diff --git a/.classpath b/.classpath index 6a5f62aa7..567febcca 100644 --- a/.classpath +++ b/.classpath @@ -1,27 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitattributes b/.gitattributes index 952a6c1ba..8ce3e61da 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,27 +1,27 @@ -# Auto detect text files and perform LF normalization -* text=auto - -# Custom for Visual Studio -*.cs diff=csharp -*.sln merge=union -*.csproj merge=union -*.vbproj merge=union -*.fsproj merge=union -*.dbproj merge=union - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain - -# Specific -*.sh text eol=lf -ENV_R66 text eol=lf - +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain + +# Specific +*.sh text eol=lf +ENV_R66 text eol=lf + diff --git a/.gitignore b/.gitignore index 8fcbb1064..fcef95b36 100644 --- a/.gitignore +++ b/.gitignore @@ -1,50 +1,50 @@ -################# -## Eclipse -################# - -*.pydevproject -.project -.metadata -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.classpath -.settings/ -.loadpath -target/ - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - - -################# -## Java -################# -*.class -*.jardesc - -############ -## Windows -############ - -# Windows image file caches -Thumbs.db - -# Folder config file -Desktop.ini - -/target +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath +target/ + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Java +################# +*.class +*.jardesc + +############ +## Windows +############ + +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + +/target /notes-divers.txt -target/ +target/ diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt index f67d82b16..07942cf2a 100644 --- a/COPYRIGHT.txt +++ b/COPYRIGHT.txt @@ -1,15 +1,15 @@ -The Waarp Project - Copyright (C) 2009, Frederic Bregier, and individual -contributors, and is licensed under the GNU GPL V (General Public License) -as published by the Free Software Foundation; either version 3.0 of the License, -or (at your option) any later version. - -A summary of the individual contributors is given below. Any omission should be -sent to Frederic Bregier . - -SVN Login(s) Name -------------------------------------------------------------------------------- -openlsd Frederic Bregier -waarp1 Frederic Bregier -fredericBregier Frederic Bregier -openr66 Frederic Bregier -------------------------------------------------------------------------------- +The Waarp Project - Copyright (C) 2009, Frederic Bregier, and individual +contributors, and is licensed under the GNU GPL V (General Public License) +as published by the Free Software Foundation; either version 3.0 of the License, +or (at your option) any later version. + +A summary of the individual contributors is given below. Any omission should be +sent to Frederic Bregier . + +SVN Login(s) Name +------------------------------------------------------------------------------- +openlsd Frederic Bregier +waarp1 Frederic Bregier +fredericBregier Frederic Bregier +openr66 Frederic Bregier +------------------------------------------------------------------------------- diff --git a/INSTALL-README.txt b/INSTALL-README.txt index ccdcd26c5..96b45b664 100644 --- a/INSTALL-README.txt +++ b/INSTALL-README.txt @@ -1,8 +1,8 @@ -The primary installation of a server is done using the following steps: - -1) Create the XML configuration files (Server, Limit, Rule, Authent, SNMP). The minimal configuration is Server and Authent (eventually limited to the created server). -2) Create the necessary GGP (GoldenGate Password files) using the des Key generated both by Waarp Password -3) Create the necessary SSL KeyStore for the HTTPS Administration interface and another one for the SSL server authentication (server only, or server AND client, depending on your choices) -4) Create the database (dependent on the one choose between Oracle, PostgreSql, MySQL or H2 database, the initial creation is out of this documentation). -5) Initialize the database (once created and the user/password and the JDBC access fill in the Server configuration XML file) -6) Now you can run the server and use the various commands or Administration interface to continue the configuration (Limit, Rule, Authent). +The primary installation of a server is done using the following steps: + +1) Create the XML configuration files (Server, Limit, Rule, Authent, SNMP). The minimal configuration is Server and Authent (eventually limited to the created server). +2) Create the necessary GGP (GoldenGate Password files) using the des Key generated both by Waarp Password +3) Create the necessary SSL KeyStore for the HTTPS Administration interface and another one for the SSL server authentication (server only, or server AND client, depending on your choices) +4) Create the database (dependent on the one choose between Oracle, PostgreSql, MySQL or H2 database, the initial creation is out of this documentation). +5) Initialize the database (once created and the user/password and the JDBC access fill in the Server configuration XML file) +6) Now you can run the server and use the various commands or Administration interface to continue the configuration (Limit, Rule, Authent). diff --git a/LICENSE.txt b/LICENSE.txt index 1de74d59d..5c72ae9ef 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,639 +1,639 @@ - Copyright (C) 2006 Frederic Bregier, and individual contributors - by the @author tags. See the COPYRIGHT.txt in the distribution for a - full listing of individual contributors. - - 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 . - - - 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 + Copyright (C) 2006 Frederic Bregier, and individual contributors + by the @author tags. See the COPYRIGHT.txt in the distribution for a + full listing of individual contributors. + + 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 . + + + 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 diff --git a/NOTICE.txt b/NOTICE.txt index 0695fc7de..d2f63e724 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,86 +1,86 @@ - - The Waarp Project - ================= - -Please visit the Waarp web site for more information: - - * http://waarp.github.com/Waarp/ - - Copyright (C) 2006 Frederic Bregier, and individual contributors - by the @author tags. See the COPYRIGHT.txt in the distribution for a - full listing of individual contributors. - - 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, please refer to each LICENSE..txt file, which is located in -the 'license' directory of the distribution file, for the license terms of the -components that this product depends on. - -------------------------------------------------------------------------------- -This product depends on 'NETTY', an asynchronous event-driven -network application framework, which can be obtained at: - - * LICENSE: - * license/LICENSE.netty.txt (Apache license) - * HOMEPAGE: - * http://netty.io/ - -This product contains a modified version of the 'Fast MD5', -a fast implementation of RSA's MD5 hash generator, -which can be obtained at: - - * LICENSE: - * license/LICENSE.fastmd5.txt (LGPL 2.1) - * HOMEPAGE: - * http://www.twmacinta.com/myjava/fast_md5.php - -This product optionally depends on 'SLF4J', a simple logging facade for Java, -which can be obtained at: - - * LICENSE: - * license/LICENSE.slf4j.txt (MIT License) - * HOMEPAGE: - * http://www.slf4j.org/ - -This product optionally depends on 'LOGBACK', a logging -framework, which can be obtained at: - - * LICENSE: - * license/LICENSE.logback.txt (LGPL 2.1) - * HOMEPAGE: - * http://logback.qos.ch/ - -This product optionally depends on 'DOM4J', open source library for working with XML, -XPath and XSLT, which can be obtained at: - - * LICENSE: - * license/LICENSE.dom4j.txt (BSD style license) - * HOMEPAGE: - * http://www.dom4j.org/ - -This product optionally depends on 'JAXEN', open source XPath library, -which can be obtained at: - - * LICENSE: - * license/LICENSE.jaxen.txt (Apache-style license) - * HOMEPAGE: - * http://jaxen.codehaus.org/ - -This product optionally depends on 'COMMONS-IO', open source XPath library, -which can be obtained at: - - * LICENSE: - * license/LICENSE.commons-io.txt (Apache license) - * HOMEPAGE: - * http://commons.apache.org/io/ + + The Waarp Project + ================= + +Please visit the Waarp web site for more information: + + * http://waarp.github.com/Waarp/ + + Copyright (C) 2006 Frederic Bregier, and individual contributors + by the @author tags. See the COPYRIGHT.txt in the distribution for a + full listing of individual contributors. + + 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, please refer to each LICENSE..txt file, which is located in +the 'license' directory of the distribution file, for the license terms of the +components that this product depends on. + +------------------------------------------------------------------------------- +This product depends on 'NETTY', an asynchronous event-driven +network application framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.netty.txt (Apache license) + * HOMEPAGE: + * http://netty.io/ + +This product contains a modified version of the 'Fast MD5', +a fast implementation of RSA's MD5 hash generator, +which can be obtained at: + + * LICENSE: + * license/LICENSE.fastmd5.txt (LGPL 2.1) + * HOMEPAGE: + * http://www.twmacinta.com/myjava/fast_md5.php + +This product optionally depends on 'SLF4J', a simple logging facade for Java, +which can be obtained at: + + * LICENSE: + * license/LICENSE.slf4j.txt (MIT License) + * HOMEPAGE: + * http://www.slf4j.org/ + +This product optionally depends on 'LOGBACK', a logging +framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.logback.txt (LGPL 2.1) + * HOMEPAGE: + * http://logback.qos.ch/ + +This product optionally depends on 'DOM4J', open source library for working with XML, +XPath and XSLT, which can be obtained at: + + * LICENSE: + * license/LICENSE.dom4j.txt (BSD style license) + * HOMEPAGE: + * http://www.dom4j.org/ + +This product optionally depends on 'JAXEN', open source XPath library, +which can be obtained at: + + * LICENSE: + * license/LICENSE.jaxen.txt (Apache-style license) + * HOMEPAGE: + * http://jaxen.codehaus.org/ + +This product optionally depends on 'COMMONS-IO', open source XPath library, +which can be obtained at: + + * LICENSE: + * license/LICENSE.commons-io.txt (Apache license) + * HOMEPAGE: + * http://commons.apache.org/io/ diff --git a/README.md b/README.md index 62bec51c0..be9187b31 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,46 @@ -Waarp R66 -============= - -You will find in this web site the sub project Waarp R66. - -There is also a Wiki available here: [Wiki](https://github.com/waarp/WaarpR66/wiki) - -The global license is GPL V3. - -Waarp is a project that provides, among other packages, -an open source massive file transfer monitor -in Java. Its goal is to unify several protocols (FTP, SSH, HTTP and proprietary -protocols) in an efficient and secured way. Its purpose is to enable bridging between -several protocols and to enable dynamic pre or post action on transfer or other commands. - -Packages --------- - - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpDigest) [Waarp Digest](http://waarp.github.com/WaarpDigest) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpCommon) [Waarp Common](http://waarp.github.com/WaarpCommon) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpExec) [Waarp Exec](http://waarp.github.com/WaarpExec) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpSnmp) [Waarp Snmp](http://waarp.github.com/WaarpSnmp) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpXmlEditor) [Waarp XmlEditor](http://waarp.github.com/WaarpXmlEditor) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpPassword) [Waarp Password Gui](http://waarp.github.com/WaarpPassword) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpR66) [Waarp R66](http://waarp.github.com/WaarpR66) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpProxyR66) [Waarp Proxy R66](http://waarp.github.com/WaarpProxyR66) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpR66Gui) [Waarp R66 Client GUI](http://waarp.github.com/WaarpR66Gui) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpFtp) [Waarp FTP](http://waarp.github.com/WaarpFtp) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpGatewayKernel) [Waarp Gateway Kernel (R66 linked)](http://waarp.github.com/WaarpGatewayKernel) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpGatewayFtp) [Waarp Gateway FTP (R66 linked)](http://waarp.github.com/WaarpGatewayFtp) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpThrift) [Waarp Thrift (R66 linked)](http://waarp.github.com/WaarpThrift) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpFtpClient) [Waarp FTP Client (Gateway and R66 linked)](http://waarp.github.com/WaarpFtpClient) - * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpAdministrator) [Waarp WaarpAdministrator (R66 linked)](http://waarp.github.com/WaarpAdministrator) - -Support -------- - -Support is available through community and also through commercial support -with the company named [Waarp](http://www.waarp.it/) - -![Waarp Company](http://waarp.github.com/Waarp/res/waarp/waarp.gif "Waarp") - - * Installation and parameters - * Integration, additional development - * Support, maintenance, phone support - +Waarp R66 +============= + +You will find in this web site the sub project Waarp R66. + +There is also a Wiki available here: [Wiki](https://github.com/waarp/WaarpR66/wiki) + +The global license is GPL V3. + +Waarp is a project that provides, among other packages, +an open source massive file transfer monitor +in Java. Its goal is to unify several protocols (FTP, SSH, HTTP and proprietary +protocols) in an efficient and secured way. Its purpose is to enable bridging between +several protocols and to enable dynamic pre or post action on transfer or other commands. + +Packages +-------- + + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpDigest) [Waarp Digest](http://waarp.github.com/WaarpDigest) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpCommon) [Waarp Common](http://waarp.github.com/WaarpCommon) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpExec) [Waarp Exec](http://waarp.github.com/WaarpExec) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpSnmp) [Waarp Snmp](http://waarp.github.com/WaarpSnmp) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpXmlEditor) [Waarp XmlEditor](http://waarp.github.com/WaarpXmlEditor) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpPassword) [Waarp Password Gui](http://waarp.github.com/WaarpPassword) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpR66) [Waarp R66](http://waarp.github.com/WaarpR66) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpProxyR66) [Waarp Proxy R66](http://waarp.github.com/WaarpProxyR66) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpR66Gui) [Waarp R66 Client GUI](http://waarp.github.com/WaarpR66Gui) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpFtp) [Waarp FTP](http://waarp.github.com/WaarpFtp) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpGatewayKernel) [Waarp Gateway Kernel (R66 linked)](http://waarp.github.com/WaarpGatewayKernel) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpGatewayFtp) [Waarp Gateway FTP (R66 linked)](http://waarp.github.com/WaarpGatewayFtp) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpThrift) [Waarp Thrift (R66 linked)](http://waarp.github.com/WaarpThrift) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpFtpClient) [Waarp FTP Client (Gateway and R66 linked)](http://waarp.github.com/WaarpFtpClient) + * [![View on GitHub](http://waarp.github.com/Waarp/res/waarp/octocaticon.png "View on GitHub")](https://www.github.com/waarp/WaarpAdministrator) [Waarp WaarpAdministrator (R66 linked)](http://waarp.github.com/WaarpAdministrator) + +Support +------- + +Support is available through community and also through commercial support +with the company named [Waarp](http://www.waarp.it/) + +![Waarp Company](http://waarp.github.com/Waarp/res/waarp/waarp.gif "Waarp") + + * Installation and parameters + * Integration, additional development + * Support, maintenance, phone support + diff --git a/license/LICENSE.commons-codec.txt b/license/LICENSE.commons-codec.txt index 29f81d812..261eeb9e9 100644 --- a/license/LICENSE.commons-codec.txt +++ b/license/LICENSE.commons-codec.txt @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/license/LICENSE.commons-exec.txt b/license/LICENSE.commons-exec.txt index 29f81d812..261eeb9e9 100644 --- a/license/LICENSE.commons-exec.txt +++ b/license/LICENSE.commons-exec.txt @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/license/LICENSE.commons-io.txt b/license/LICENSE.commons-io.txt index 43e91eb0b..6b0b1270f 100644 --- a/license/LICENSE.commons-io.txt +++ b/license/LICENSE.commons-io.txt @@ -1,203 +1,203 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/license/LICENSE.dom4j.txt b/license/LICENSE.dom4j.txt index e65c842e5..807681919 100644 --- a/license/LICENSE.dom4j.txt +++ b/license/LICENSE.dom4j.txt @@ -1,28 +1,28 @@ - Redistribution and use of this software and associated documentation ("Software"), - with or without modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain copyright statements and notices. - Redistributions must also contain a copy of this document. - 2. Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or other - materials provided with the distribution. - 3. The name "DOM4J" must not be used to endorse or promote products derived from - this Software without prior written permission of MetaStuff, Ltd. For written - permission, please contact dom4j-info@metastuff.com. - 4. Products derived from this Software may not be called "DOM4J" nor may "DOM4J" - appear in their names without prior written permission of MetaStuff, Ltd. DOM4J - is a registered trademark of MetaStuff, Ltd. - 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org - -THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY -EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT -SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT -OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. + Redistribution and use of this software and associated documentation ("Software"), + with or without modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain copyright statements and notices. + Redistributions must also contain a copy of this document. + 2. Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or other + materials provided with the distribution. + 3. The name "DOM4J" must not be used to endorse or promote products derived from + this Software without prior written permission of MetaStuff, Ltd. For written + permission, please contact dom4j-info@metastuff.com. + 4. Products derived from this Software may not be called "DOM4J" nor may "DOM4J" + appear in their names without prior written permission of MetaStuff, Ltd. DOM4J + is a registered trademark of MetaStuff, Ltd. + 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org + +THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY +EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. diff --git a/license/LICENSE.jaxen.txt b/license/LICENSE.jaxen.txt index 6c52c248d..8ba259be2 100644 --- a/license/LICENSE.jaxen.txt +++ b/license/LICENSE.jaxen.txt @@ -1,30 +1,30 @@ - $Id: LICENSE.txt,v 1.5 2006/02/05 21:49:04 elharo Exp $ - - Copyright 2003-2006 The Werken Company. All Rights Reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the Jaxen Project nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + $Id: LICENSE.txt,v 1.5 2006/02/05 21:49:04 elharo Exp $ + + Copyright 2003-2006 The Werken Company. All Rights Reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Jaxen Project nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/license/LICENSE.logback.txt b/license/LICENSE.logback.txt index 19e9843ac..b1e909165 100644 --- a/license/LICENSE.logback.txt +++ b/license/LICENSE.logback.txt @@ -1,19 +1,19 @@ -Logback: the reliable, generic, fast and flexible logging library for Java. - -Copyright (C) 2000-2008, QOS.ch - -Source code and binaries for logback, including logback-core, -logback-classic and logback-access modules, are distributed under the -GNU Lesser General Public License Version 2.1, as published by the -Free Software Foundation. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. +Logback: the reliable, generic, fast and flexible logging library for Java. + +Copyright (C) 2000-2008, QOS.ch + +Source code and binaries for logback, including logback-core, +logback-classic and logback-access modules, are distributed under the +GNU Lesser General Public License Version 2.1, as published by the +Free Software Foundation. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. \ No newline at end of file diff --git a/license/LICENSE.netty.txt b/license/LICENSE.netty.txt index 29f81d812..261eeb9e9 100644 --- a/license/LICENSE.netty.txt +++ b/license/LICENSE.netty.txt @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/license/LICENSE.slf4j.txt b/license/LICENSE.slf4j.txt index 7478d9ef5..777b1de84 100644 --- a/license/LICENSE.slf4j.txt +++ b/license/LICENSE.slf4j.txt @@ -1,23 +1,23 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ diff --git a/license/license-h2.html b/license/license-h2.html index 79191c729..54b1ee69a 100644 --- a/license/license-h2.html +++ b/license/license-h2.html @@ -1,317 +1,317 @@ - - - - -License - - - - - - - - - - - - - - + + + + +License + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index bdb20ad71..4e9bbc646 100644 --- a/pom.xml +++ b/pom.xml @@ -1,282 +1,282 @@ - - 4.0.0 - WaarpR66 - Waarp OpenR66 - 2.4.12 - - OpenR66 is a File Transfer Monitor to be used in real production to transfer files between servers. - It allows to start/restart a transfer, check the remote MD5, check status, make pre or post - actions on transfer, ... It includes Bandwidth limitation and will support SSL channel. - When multiple transfers occurs between two hosts, they use the same network channel and - multiplex their other transfers on this channel. - - http://waarp.github.com/WaarpR66 - 2009 - - Waarp - persistence-deps - 1.3 - - - GitHub - https://github.com/waarp/WaarpR66/issues/ - - - scm:git:git://github.com/waarp/WaarpR66.git - scm:git:git@github.com:YourID/WaarpR66.git - https://github.com/waarp/WaarpR66 - - - - GPL 3.0 - LICENSE.txt - - - - - waarp.releases - Waarp releases - https://raw.github.com/waarp/WaarpMaven2/master/maven2 - - true - - - false - - - - - - Waarp - WaarpCommon - 1.2.10 - - - javasysmon - javasysmon - 0.3.3 - true - - - Oracle - ojdbc6 - 6 - true - - - com.h2database - h2 - 1.3.171 - true - - - postgresql - postgresql - 9.1-901-1.jdbc4 - true - - - mysql - mysql-connector-java - 5.1.24 - true - - - commons-codec - commons-codec - 1.7 - - - Waarp - WaarpExec - 1.1.3 - - - Waarp - WaarpSnmp - 1.1.3 - - - ch.qos.logback - logback-access - 1.0.10 - - - ch.qos.logback - logback-classic - 1.0.10 - - - ch.qos.logback - logback-core - 1.0.10 - - - Waarp - WaarpThrift - 1.1.0 - true - - - commons-daemon - commons-daemon - 1.0.14 - true - - - Waarp - WaarpFtpClient - 1.0.1 - - - - UTF-8 - false - ** - - - - - maven-antrun-plugin - 1.7 - - - write-version - validate - - run - - - - - - - - - - - - - - - - - - - - add-license - package - - run - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8.1 - - - aggregate - - true - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.3.1.GA - - false - true - ${project.build.directory}/api - ${project.build.directory}/api - api - UTF-8 - UTF-8 - true - true - true - true - ${basedir}/src/javadoc/overview.html - ${project.name} ${project.version} API Reference - ${project.name} ${project.version} API Reference - - -link http://java.sun.com/javase/6/docs/api/ - -link http://static.netty.io/3.5/api/ - - -group "Waarp R66 Server package" "org.waarp.openr66.server*" - -group "Waarp R66 Client package" "org.waarp.openr66.client*" - -group "Waarp R66 Protocol package" "org.waarp.openr66.protocol*" - -group "Waarp R66 Database package" "org.waarp.openr66.database*" - -group "Waarp R66 Configuration file based loaders package" "org.waarp.openr66.configuration*" - -group "Waarp R66 Context package" "org.waarp.openr66.context*" - -group "Waarp R66 Commander package" "org.waarp.openr66.commander*" - -group "Waarp R66 Service Windows package" "org.waarp.openr66.service*" - -group "Waarp R66 Thrift Interface package" "org.waarp.openr66.thrift*" - - -sourceclasspath ${basedir}/target/classes - - UTF-8 - en_US - ${project.groupId}.test*:${project.groupId}.example*:${project.groupId}.util.internal* - - - aggregate - - - - - - + + 4.0.0 + WaarpR66 + Waarp OpenR66 + 2.4.12 + + OpenR66 is a File Transfer Monitor to be used in real production to transfer files between servers. + It allows to start/restart a transfer, check the remote MD5, check status, make pre or post + actions on transfer, ... It includes Bandwidth limitation and will support SSL channel. + When multiple transfers occurs between two hosts, they use the same network channel and + multiplex their other transfers on this channel. + + http://waarp.github.com/WaarpR66 + 2009 + + Waarp + persistence-deps + 1.3 + + + GitHub + https://github.com/waarp/WaarpR66/issues/ + + + scm:git:git://github.com/waarp/WaarpR66.git + scm:git:git@github.com:YourID/WaarpR66.git + https://github.com/waarp/WaarpR66 + + + + GPL 3.0 + LICENSE.txt + + + + + waarp.releases + Waarp releases + https://raw.github.com/waarp/WaarpMaven2/master/maven2 + + true + + + false + + + + + + Waarp + WaarpCommon + 1.2.10 + + + javasysmon + javasysmon + 0.3.3 + true + + + Oracle + ojdbc6 + 6 + true + + + com.h2database + h2 + 1.3.171 + true + + + postgresql + postgresql + 9.1-901-1.jdbc4 + true + + + mysql + mysql-connector-java + 5.1.24 + true + + + commons-codec + commons-codec + 1.7 + + + Waarp + WaarpExec + 1.1.3 + + + Waarp + WaarpSnmp + 1.1.3 + + + ch.qos.logback + logback-access + 1.0.10 + + + ch.qos.logback + logback-classic + 1.0.10 + + + ch.qos.logback + logback-core + 1.0.10 + + + Waarp + WaarpThrift + 1.1.0 + true + + + commons-daemon + commons-daemon + 1.0.14 + true + + + Waarp + WaarpFtpClient + 1.0.1 + + + + UTF-8 + false + ** + + + + + maven-antrun-plugin + 1.7 + + + write-version + validate + + run + + + + + + + + + + + + + + + + + + + + add-license + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8.1 + + + aggregate + + true + org.jboss.apiviz.APIviz + + org.jboss.apiviz + apiviz + 1.3.1.GA + + false + true + ${project.build.directory}/api + ${project.build.directory}/api + api + UTF-8 + UTF-8 + true + true + true + true + ${basedir}/src/javadoc/overview.html + ${project.name} ${project.version} API Reference + ${project.name} ${project.version} API Reference + + -link http://java.sun.com/javase/6/docs/api/ + -link http://static.netty.io/3.5/api/ + + -group "Waarp R66 Server package" "org.waarp.openr66.server*" + -group "Waarp R66 Client package" "org.waarp.openr66.client*" + -group "Waarp R66 Protocol package" "org.waarp.openr66.protocol*" + -group "Waarp R66 Database package" "org.waarp.openr66.database*" + -group "Waarp R66 Configuration file based loaders package" "org.waarp.openr66.configuration*" + -group "Waarp R66 Context package" "org.waarp.openr66.context*" + -group "Waarp R66 Commander package" "org.waarp.openr66.commander*" + -group "Waarp R66 Service Windows package" "org.waarp.openr66.service*" + -group "Waarp R66 Thrift Interface package" "org.waarp.openr66.thrift*" + + -sourceclasspath ${basedir}/target/classes + + UTF-8 + en_US + ${project.groupId}.test*:${project.groupId}.example*:${project.groupId}.util.internal* + + + aggregate + + + + + + \ No newline at end of file diff --git a/src/assembly/default.xml b/src/assembly/default.xml index 3109b678b..893df79aa 100644 --- a/src/assembly/default.xml +++ b/src/assembly/default.xml @@ -1,61 +1,61 @@ - - - dist - - tar.bz2 - tar.gz - zip - - false - - - - - **/README* - **/LICENSE* - **/NOTICE* - **/COPYRIGHT* - **/*.txt - **/*.xml - **/license/** - **/lib/** - **/src/** - - - **/target/** - **/.*/** - - - - - - target - jar - - ${project.build.finalName}*.jar - - - ${project.build.finalName}*-javadoc.jar - - - - - - target/api - doc/api - - **/** - - - - - - target/xref - doc/xref - - **/** - - - - - + + + dist + + tar.bz2 + tar.gz + zip + + false + + + + + **/README* + **/LICENSE* + **/NOTICE* + **/COPYRIGHT* + **/*.txt + **/*.xml + **/license/** + **/lib/** + **/src/** + + + **/target/** + **/.*/** + + + + + + target + jar + + ${project.build.finalName}*.jar + + + ${project.build.finalName}*-javadoc.jar + + + + + + target/api + doc/api + + **/** + + + + + + target/xref + doc/xref + + **/** + + + + + diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e83669143..c7e8f841f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -1,300 +1,300 @@ - - - - Waarp OpenR66 - Frederic Bregier - - - - Fix HTTPs log - Add final Hash check on receive operation (if not RecvThrough mode) - Add final size checking (if not Through mode) - Fix configuration files - Add support for Aliases - Add support for configuration of Business, Rules and Aliases in DB instead of files - - - Fix HTTP session checking - Add FTP task option - Allow request to itself - Fix to support R66Proxy - Fix to support future Global Admin - Update dependencies - - - Fix wildcard file as input - Add Keywords in rule helper - Add support for global Digest (optional) - Allow partially request to itself - Update Commons to have less dependency with Netty - - - Add support for Roles overriding database simple admin role - Add AllEvents level in snmp trap - Add -nossl option in ServerShutdown - Add SNMP task to enable SNMP trap/info notifications - XSD configuration files and add support for Jaxe - Add serverpasswdfile option in Server XML configuration file to enable ggp file for admin password - - - Add TRANSCODE task - Add restart time support to RequestTransfer - Fix restart of one transfer through ID in SubmitTransfer - Improve Admin GUI with Rule setting Helper - - - Thrift first stable release - Add support for Windows Service through Apache Commons Daemon - Fix Zip Task identification - Fix Log Task for File output (append mode) - Fix Netty Exception catching when starting connection - Fix execution of error tasks after any error, including pre condition before pre-tasks - Add -count option and #CPTLIMIT# to RESCHEDULE task in order to limit the number of reschedule - Netty version - - - Export configuration - Netty version - First Beta Thrift version - - - Tar and Zip tasks fix - Http get simple file fix - URL acceptance for filename argument - - - Ssl Fix - Upgrade jar dependencies - - - Fix Ssl end of channel - - - Upgrade jar dependencies - - - Upgrade jar dependencies - - - Fix hierarchy - - - Update jar dependencies - Fix Http with 1 by 1 cookie handling from Netty 3.5.1 - Add host white list for Business Requests - Handling await() instead of awaitUninterruptibly() - Fix issue on FileChannel.transferTo or transferFrom - No more SSL Renegotiation for HTTPS - Move KeepAlive message response higher in the pipeline - Optimization plus Pool DB Connection support - Add support for Extended Protocol - Fix Sleep issue and Traffic Handler - Fix Huge Concurrent connections - Fix SendThrough and RecvThrough - Add support for R66Business Interface - Add support for R66 Server with no DB at all - Add support for extension of R66 (ARK) - Add support for EXECJAVA - Add support for BusinessRequest and EXECJAVA - Fix closing issue on File - - - Database init connection fix - - - Small fix on Best practices - NPE and issue on restart while post actions on going - Change Finite State Machine to info only - - - Small fix on Logging - - - Update Dependencies - - - Add a Finite State machine to LocalServerHandler - Add possibility to use MD5 or other Digests - - - Fix on restart transfered when rule is is RECV mode - Fix on restart automatically transfer only when requester - Update to new dependent Jars - - - Clean Database model by removing double method already implemented into Commons - Add the possibility to have several Monitors on the same database with same name behind a load balancer with shared storage for HA - Update to new dependent Jars - Add the support of Multiple Servers acting as One for reliability and scalability - - - Add proactive CPU limitation through Bandwidth throttling - - - Fix Index: NEED TO UPDATE THE DATABASE MODEL (-initdb option with ServerInitDatabase command) - Cache compatibility added to HTTP and HTTPS - NOWAIT and LOCALEXEC option to ExecTask - SNMP support added as monitoring option - Update versions of used Java libraries like Netty - - - Update Digest functions - Enhance AbstractDbData - Fix Overloaded case - Fix blocksize testing - Fix and Add schedule transfer - Fix transfer submitted through id - Add support for client with a progress bar - Add ExecOuput command to get error message - Add #ERRORMSG# #ERRORCODE# #ERRORSTRCODE# support in string substitution - Fix end of request protocol - Fix LimitBandwidth for Client - Fix IdleHandler - Fix Shutdown - Fix Connection error by running error post operation - Add RescheduleTransferTask to enable reschedule of transfer in case of error in post error actions - Check explicit support of last version from H2 V2 and PostgreSQL V9 - Add /statusxml in Supervision module (HTTP) to give some useful status - - - Database support moved in GGCommon - Some String utility moved in GGCommon - Fix Doc - - - Fix xml load configuration with new module - Improve restart by testing length of received file - Fix SSL support both in HTTPS and SR66 - In SSL mode, allow client string authentication - Improve HTTP server with Html files - Password are stored and transmitted crypted - Add support for LocalExec - Add support for compression on HTTP and HTTPS - Add REMOTE and LOCAL ADDRESSIP on actions - Add Tests of address when connection occurs - Add Possibility to ignore client addressing tests (0.0.0.0) - Add Limitation on CPU and connection usage with new requests - Add support for TAR and ZIP task - Add ConfigExport and ConfigImport - - - Improve Log when a file error occurs - - - Fix MySQL, Postgre and H2 support - LIMIT instead of ROWNUM - - - - Fix MySQL support - reserved words used - - - - Fix Administrator by adding info transfer - Fix HTTP was using wrong version of codec - Fix version of Netty - - - Fix writing XML for Runner - Fix on Direct Transfer - Fix for getting correct output for GUI - Add Export Configuration in Administrator - - - Fix GG Common version used and File Support - - - Fix Transfer Task - Fix GG Common version used - Fix initialization of Request - Fix logger output - Add CloseConn Administrator method and Count of remote connections - - - Add a new function: DELETE - Fix LOG command to allow export to a FILE - - - Fix start and stop date in LogExport - Fix TEST command to LOG command - Fix EXEC command for special CommandNotFound code - Fix changing name from sender at startup should inform receiver - Add #ORIGINALFULLPATH# - - - Fix initialization of sent file - Add Version automatic in compile - Add /status url in Supervision of OpenR66 for Supervision tools - Add Multiple R66 hosts support on same database - Add #BASEHOME# support - Test correctness of external executable - - - Add ValidFilePath Task - Fix normalize path in Commons - Fix bug in bandwidth - - - Fix end of Request - - - Refactorization - Cleaning - Common to 1.0.3 - - - Fix Administrator - Fix SecureKeyStore(SunX509 vs IBMX509) - Lowering logging - Fix restarted task - Fix Common support - Fix Configuration for some options like delay for Retry - Fix Oracle DB support - Fix Shutdown, Stop and Restart - - - Add Administrator in Https - Fix shutdown - Add different actions according to receiver or sender - - - Add Information Request - - - Use NettyExtension - Fix use of AggregateChannelBuffer - Fix due to Common and Digest creation and simplification of interface - - - Add Recv through support - Add Send through support - Fix Database support - - - Add SSL and limit Bandwidth for transfer - Add Web support for monitoring status of transfers - Add Oracle, MySQL and PostGreSQL supports - Fix some bugs - - - Add licenses - Fix pom - - - Add request submission and thin clients - Fix some bugs - - - Database support continue and no database support start - Fix some bugs - - - Database support - Fix some bugs - - - Transfer implementation - Fix some bugs - - - First public version - - + + + + Waarp OpenR66 + Frederic Bregier + + + + Fix HTTPs log + Add final Hash check on receive operation (if not RecvThrough mode) + Add final size checking (if not Through mode) + Fix configuration files + Add support for Aliases + Add support for configuration of Business, Rules and Aliases in DB instead of files + + + Fix HTTP session checking + Add FTP task option + Allow request to itself + Fix to support R66Proxy + Fix to support future Global Admin + Update dependencies + + + Fix wildcard file as input + Add Keywords in rule helper + Add support for global Digest (optional) + Allow partially request to itself + Update Commons to have less dependency with Netty + + + Add support for Roles overriding database simple admin role + Add AllEvents level in snmp trap + Add -nossl option in ServerShutdown + Add SNMP task to enable SNMP trap/info notifications + XSD configuration files and add support for Jaxe + Add serverpasswdfile option in Server XML configuration file to enable ggp file for admin password + + + Add TRANSCODE task + Add restart time support to RequestTransfer + Fix restart of one transfer through ID in SubmitTransfer + Improve Admin GUI with Rule setting Helper + + + Thrift first stable release + Add support for Windows Service through Apache Commons Daemon + Fix Zip Task identification + Fix Log Task for File output (append mode) + Fix Netty Exception catching when starting connection + Fix execution of error tasks after any error, including pre condition before pre-tasks + Add -count option and #CPTLIMIT# to RESCHEDULE task in order to limit the number of reschedule + Netty version + + + Export configuration + Netty version + First Beta Thrift version + + + Tar and Zip tasks fix + Http get simple file fix + URL acceptance for filename argument + + + Ssl Fix + Upgrade jar dependencies + + + Fix Ssl end of channel + + + Upgrade jar dependencies + + + Upgrade jar dependencies + + + Fix hierarchy + + + Update jar dependencies + Fix Http with 1 by 1 cookie handling from Netty 3.5.1 + Add host white list for Business Requests + Handling await() instead of awaitUninterruptibly() + Fix issue on FileChannel.transferTo or transferFrom + No more SSL Renegotiation for HTTPS + Move KeepAlive message response higher in the pipeline + Optimization plus Pool DB Connection support + Add support for Extended Protocol + Fix Sleep issue and Traffic Handler + Fix Huge Concurrent connections + Fix SendThrough and RecvThrough + Add support for R66Business Interface + Add support for R66 Server with no DB at all + Add support for extension of R66 (ARK) + Add support for EXECJAVA + Add support for BusinessRequest and EXECJAVA + Fix closing issue on File + + + Database init connection fix + + + Small fix on Best practices + NPE and issue on restart while post actions on going + Change Finite State Machine to info only + + + Small fix on Logging + + + Update Dependencies + + + Add a Finite State machine to LocalServerHandler + Add possibility to use MD5 or other Digests + + + Fix on restart transfered when rule is is RECV mode + Fix on restart automatically transfer only when requester + Update to new dependent Jars + + + Clean Database model by removing double method already implemented into Commons + Add the possibility to have several Monitors on the same database with same name behind a load balancer with shared storage for HA + Update to new dependent Jars + Add the support of Multiple Servers acting as One for reliability and scalability + + + Add proactive CPU limitation through Bandwidth throttling + + + Fix Index: NEED TO UPDATE THE DATABASE MODEL (-initdb option with ServerInitDatabase command) + Cache compatibility added to HTTP and HTTPS + NOWAIT and LOCALEXEC option to ExecTask + SNMP support added as monitoring option + Update versions of used Java libraries like Netty + + + Update Digest functions + Enhance AbstractDbData + Fix Overloaded case + Fix blocksize testing + Fix and Add schedule transfer + Fix transfer submitted through id + Add support for client with a progress bar + Add ExecOuput command to get error message + Add #ERRORMSG# #ERRORCODE# #ERRORSTRCODE# support in string substitution + Fix end of request protocol + Fix LimitBandwidth for Client + Fix IdleHandler + Fix Shutdown + Fix Connection error by running error post operation + Add RescheduleTransferTask to enable reschedule of transfer in case of error in post error actions + Check explicit support of last version from H2 V2 and PostgreSQL V9 + Add /statusxml in Supervision module (HTTP) to give some useful status + + + Database support moved in GGCommon + Some String utility moved in GGCommon + Fix Doc + + + Fix xml load configuration with new module + Improve restart by testing length of received file + Fix SSL support both in HTTPS and SR66 + In SSL mode, allow client string authentication + Improve HTTP server with Html files + Password are stored and transmitted crypted + Add support for LocalExec + Add support for compression on HTTP and HTTPS + Add REMOTE and LOCAL ADDRESSIP on actions + Add Tests of address when connection occurs + Add Possibility to ignore client addressing tests (0.0.0.0) + Add Limitation on CPU and connection usage with new requests + Add support for TAR and ZIP task + Add ConfigExport and ConfigImport + + + Improve Log when a file error occurs + + + Fix MySQL, Postgre and H2 support - LIMIT instead of ROWNUM - + + + Fix MySQL support - reserved words used - + + + Fix Administrator by adding info transfer + Fix HTTP was using wrong version of codec + Fix version of Netty + + + Fix writing XML for Runner + Fix on Direct Transfer + Fix for getting correct output for GUI + Add Export Configuration in Administrator + + + Fix GG Common version used and File Support + + + Fix Transfer Task + Fix GG Common version used + Fix initialization of Request + Fix logger output + Add CloseConn Administrator method and Count of remote connections + + + Add a new function: DELETE + Fix LOG command to allow export to a FILE + + + Fix start and stop date in LogExport + Fix TEST command to LOG command + Fix EXEC command for special CommandNotFound code + Fix changing name from sender at startup should inform receiver + Add #ORIGINALFULLPATH# + + + Fix initialization of sent file + Add Version automatic in compile + Add /status url in Supervision of OpenR66 for Supervision tools + Add Multiple R66 hosts support on same database + Add #BASEHOME# support + Test correctness of external executable + + + Add ValidFilePath Task + Fix normalize path in Commons + Fix bug in bandwidth + + + Fix end of Request + + + Refactorization + Cleaning + Common to 1.0.3 + + + Fix Administrator + Fix SecureKeyStore(SunX509 vs IBMX509) + Lowering logging + Fix restarted task + Fix Common support + Fix Configuration for some options like delay for Retry + Fix Oracle DB support + Fix Shutdown, Stop and Restart + + + Add Administrator in Https + Fix shutdown + Add different actions according to receiver or sender + + + Add Information Request + + + Use NettyExtension + Fix use of AggregateChannelBuffer + Fix due to Common and Digest creation and simplification of interface + + + Add Recv through support + Add Send through support + Fix Database support + + + Add SSL and limit Bandwidth for transfer + Add Web support for monitoring status of transfers + Add Oracle, MySQL and PostGreSQL supports + Fix some bugs + + + Add licenses + Fix pom + + + Add request submission and thin clients + Fix some bugs + + + Database support continue and no database support start + Fix some bugs + + + Database support + Fix some bugs + + + Transfer implementation + Fix some bugs + + + First public version + + \ No newline at end of file diff --git a/src/javadoc/overview.html b/src/javadoc/overview.html index 6c58ef207..079701650 100644 --- a/src/javadoc/overview.html +++ b/src/javadoc/overview.html @@ -1,11 +1,11 @@ - - - The Waarp OpenR66 API Reference - - -
-

The Waarp - OpenR66 project contains the File Transfer Monitor made for production. It includes many features - such as secured transfers, database logs, monitoring, SNMP compliance, Administration tool, ...

- + + + The Waarp OpenR66 API Reference + + +
+

The Waarp + OpenR66 project contains the File Transfer Monitor made for production. It includes many features + such as secured transfers, database logs, monitoring, SNMP compliance, Administration tool, ...

+ \ No newline at end of file diff --git a/src/main/admin/CancelRestart_body.html b/src/main/admin/CancelRestart_body.html index 508279d9a..293852f05 100644 --- a/src/main/admin/CancelRestart_body.html +++ b/src/main/admin/CancelRestart_body.html @@ -1,26 +1,26 @@ - - XXXSpecIdXXX - XXXRulXXX - XXXFileXXX - XXXInfoXXX - XXXStepXXX - XXXActXXX - XXXStatXXX XXXRunningXXX - XXXInternXXX - XXXBloXXX - XXXisMovXXX - XXXReqrXXX - XXXReqdXXX - XXXStarXXX - XXXStopXXX - -
- - - - - - -
- + + XXXSpecIdXXX + XXXRulXXX + XXXFileXXX + XXXInfoXXX + XXXStepXXX + XXXActXXX + XXXStatXXX XXXRunningXXX + XXXInternXXX + XXXBloXXX + XXXisMovXXX + XXXReqrXXX + XXXReqdXXX + XXXStarXXX + XXXStopXXX + +
+ + + + + + +
+ \ No newline at end of file diff --git a/src/main/admin/CancelRestart_body0.html b/src/main/admin/CancelRestart_body0.html index 57f9e8efc..ca3c06d88 100644 --- a/src/main/admin/CancelRestart_body0.html +++ b/src/main/admin/CancelRestart_body0.html @@ -1,18 +1,18 @@ - - - - - - - - - - - - - - - - - +
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisMovedRequesterRequestedStartStopCancel / Stop / Restart
+ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/CancelRestart_end.html b/src/main/admin/CancelRestart_end.html index d4874d389..d228c9c25 100644 --- a/src/main/admin/CancelRestart_end.html +++ b/src/main/admin/CancelRestart_end.html @@ -1,5 +1,5 @@ -
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisMovedRequesterRequestedStartStopCancel / Stop / Restart
-
-

 

- + +
+

 

+ \ No newline at end of file diff --git a/src/main/admin/CancelRestart_head.html b/src/main/admin/CancelRestart_head.html index 998633e9a..9a4279c95 100644 --- a/src/main/admin/CancelRestart_head.html +++ b/src/main/admin/CancelRestart_head.html @@ -1,160 +1,160 @@ - - - - - - - - - - - - -Cancel-Restart - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Cancel-Restart

-

Select a Transfer - and choose the operation to do.

 

-
- From SpecialId:  - help for From SpecialId field -

- The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. -

-   To SpecialId:  - help for To SpecialId field -

- The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. -

-
From date:  - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To date:  - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

-   Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

                                                                -                -

-

                                                                -            -

-
+ + + + + + + + + + + + +Cancel-Restart + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/Hosts_body0.html b/src/main/admin/Hosts_body0.html index 3abb0cc7f..b13632cfd 100644 --- a/src/main/admin/Hosts_body0.html +++ b/src/main/admin/Hosts_body0.html @@ -1,14 +1,14 @@ -
+

 

+
Listing +Cancel-Restart +Export +
+

Cancel-Restart

+

Select a Transfer + and choose the operation to do.

 

+
+ From SpecialId:  + help for From SpecialId field +

+ The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. +

+   To SpecialId:  + help for To SpecialId field +

+ The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. +

+
From date:  + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To date:  + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+   Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

                                                                +                +

+

                                                                +            +

+

 

 

\ No newline at end of file diff --git a/src/main/admin/Export.html b/src/main/admin/Export.html index 0638d4cf1..ab5fb001b 100644 --- a/src/main/admin/Export.html +++ b/src/main/admin/Export.html @@ -1,153 +1,153 @@ - - - - - - - - - - - -Export - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Export

-
-

Export Transfers log into an XML File:

 

- From: - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To:  - - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

- Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

Warning: Purge after export - help for Purge field -

- If this option is checked, all exported logs from Transfer table will be deleted from the database. Note that running transfers are never deleted. -

            -                - -

 

-
-

 

XXXRESULTXXX

- + + + + + + + + + + + +Export + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
Listing +Cancel-Restart +Export +
+

Export

+
+

Export Transfers log into an XML File:

 

+ From: + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To:  + + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+ Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

Warning: Purge after export + help for Purge field +

+ If this option is checked, all exported logs from Transfer table will be deleted from the database. Note that running transfers are never deleted. +

            +                + +

 

+
+

 

XXXRESULTXXX

+ \ No newline at end of file diff --git a/src/main/admin/Hosts_body.html b/src/main/admin/Hosts_body.html index 0555f593b..198143a0c 100644 --- a/src/main/admin/Hosts_body.html +++ b/src/main/admin/Hosts_body.html @@ -1,26 +1,26 @@ -
- - - - - - - - - XXXCONNXXX - -
+ + + + + + + + + XXXCONNXXX + +
- - - - - - - - - - - - +
Host IDAddressPortSSLHostKeyAdmin RoleIsClientUpdateDeleteTestConnCloseConn
+ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/Hosts_end.html b/src/main/admin/Hosts_end.html index 9767e25d3..97f37f5ca 100644 --- a/src/main/admin/Hosts_end.html +++ b/src/main/admin/Hosts_end.html @@ -1,5 +1,5 @@ -

 

Host IDAddressPortSSLHostKeyAdmin RoleIsClientUpdateDeleteTestConnCloseConn
-
-

 

- +

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin/Hosts_head.html b/src/main/admin/Hosts_head.html index e14c08e26..076f9f906 100644 --- a/src/main/admin/Hosts_head.html +++ b/src/main/admin/Hosts_head.html @@ -1,177 +1,177 @@ - - - - - - - - - - - -Hosts - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Hosts

-

You can edit Hosts configuration from here.

-

 

-
- - - - - - - - - - - - - - - - - - - -
Host IDAddressPortSSLHostKeyAdmin RoleIs Client
- help for Host field -

- The host id that will be used. -

- help for Address field -

- The IP or DNS name of the host. -

- help for Port field -

- The port to be used. -

- - help for SSL field -

- If checked, this host will describe a host with SSL support. -

- help for HostKey field -

- The Key to be used when Administration action are taken. -

- - help for Admin field -

- If checked, this host can be used in local client for administration purpose (using the above key). -

- - help for IsClient field -

- If checked, this host is a client only, meaning that it can only initiate transfers but cannot receive new request of transfer. -

-

                                                                -

-
-

 

-
- Filter on Host Id:   - help for Host ID Filter field -

- Part of the Host Id to used as filter. -


- Filter on Address:  - help for Address Filter field -

- Part of the Address to used as filter. -


- Filter on SSL:  - help for SSL Filter field -

- If checked, only SSL Hosts will be listed. If not, only not SSL Hosts will be listed. -

-                                       -                -
+ + + + + + + + + + + +Hosts + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/Listing_body0.html b/src/main/admin/Listing_body0.html index 17fc585e5..2df063bfe 100644 --- a/src/main/admin/Listing_body0.html +++ b/src/main/admin/Listing_body0.html @@ -1,20 +1,20 @@ -
+

 

+
+

Hosts

+

You can edit Hosts configuration from here.

+

 

+
+ + + + + + + + + + + + + + + + + + + +
Host IDAddressPortSSLHostKeyAdmin RoleIs Client
+ help for Host field +

+ The host id that will be used. +

+ help for Address field +

+ The IP or DNS name of the host. +

+ help for Port field +

+ The port to be used. +

+ + help for SSL field +

+ If checked, this host will describe a host with SSL support. +

+ help for HostKey field +

+ The Key to be used when Administration action are taken. +

+ + help for Admin field +

+ If checked, this host can be used in local client for administration purpose (using the above key). +

+ + help for IsClient field +

+ If checked, this host is a client only, meaning that it can only initiate transfers but cannot receive new request of transfer. +

+

                                                                +

+
+

 

+
+ Filter on Host Id:   + help for Host ID Filter field +

+ Part of the Host Id to used as filter. +


+ Filter on Address:  + help for Address Filter field +

+ Part of the Address to used as filter. +


+ Filter on SSL:  + help for SSL Filter field +

+ If checked, only SSL Hosts will be listed. If not, only not SSL Hosts will be listed. +

+                                       +                +

 

\ No newline at end of file diff --git a/src/main/admin/Listing_body.html b/src/main/admin/Listing_body.html index 009f3a44c..18d58e6c5 100644 --- a/src/main/admin/Listing_body.html +++ b/src/main/admin/Listing_body.html @@ -1,19 +1,19 @@ -
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisSendXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXXXXXBandXXXXXXFreeXXX
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisSendXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXXXXXBandXXXXXXFreeXXX
- - - - - - - - - - - - - - - - - - +
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisSenderisMovedRequesterRequestedStartStopBandwidthFree Space
+ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/Listing_end.html b/src/main/admin/Listing_end.html index d4874d389..d228c9c25 100644 --- a/src/main/admin/Listing_end.html +++ b/src/main/admin/Listing_end.html @@ -1,5 +1,5 @@ -
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisSenderisMovedRequesterRequestedStartStopBandwidthFree Space
-
-

 

- +
+
+

 

+ \ No newline at end of file diff --git a/src/main/admin/Listing_head.html b/src/main/admin/Listing_head.html index 6bbb79f60..7137a254a 100644 --- a/src/main/admin/Listing_head.html +++ b/src/main/admin/Listing_head.html @@ -1,157 +1,157 @@ - - - - - - - - - - - -Listing - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Listing

-

Listing of - Transfers according to criteria.

 

-
- From SpecialId:  - help for From SpecialId field -

- The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. -

-   To SpecialId:  - help for To SpecialId field -

- The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. -

-
From date: - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To date:  - - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

-   Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

                                                                -                -

-
+ + + + + + + + + + + +Listing + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin/Rules_end.html b/src/main/admin/Rules_end.html index 9767e25d3..97f37f5ca 100644 --- a/src/main/admin/Rules_end.html +++ b/src/main/admin/Rules_end.html @@ -1,5 +1,5 @@ -

 

+

 

+
Listing +Cancel-Restart +Export +
+

Listing

+

Listing of + Transfers according to criteria.

 

+
+ From SpecialId:  + help for From SpecialId field +

+ The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. +

+   To SpecialId:  + help for To SpecialId field +

+ The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. +

+
From date: + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To date:  + + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+   Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

                                                                +                +

+

 

 

\ No newline at end of file diff --git a/src/main/admin/Logon.html b/src/main/admin/Logon.html index a03de9a34..ae8e4a927 100644 --- a/src/main/admin/Logon.html +++ b/src/main/admin/Logon.html @@ -1,93 +1,93 @@ - - - - - - - - - - - -Logon - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon
-
-

 

- -

- - - -
-

 

-
-

Logon

-

You need to login to access to the OpenR66 Administrator.

-

 

-

 

-
-

Username:

-

Password:            -       

-
-

 

-
-

 

- + + + + + + + + + + + +Logon + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon
+
+

 

+ +

+ + + +
+

 

+
+

Logon

+

You need to login to access to the OpenR66 Administrator.

+

 

+

 

+
+

Username:

+

Password:            +       

+
+

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin/Rules_body.html b/src/main/admin/Rules_body.html index 17e607e7f..50457ed8d 100644 --- a/src/main/admin/Rules_body.html +++ b/src/main/admin/Rules_body.html @@ -1,46 +1,46 @@ -
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
- SEND - RECV
- SENDMD5 - RECVMD5
- SENDTHROUGH
- RECVTHROUGH
- SENDMD5THROUGH
- RECVMD5THROUGH
Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
-

-

Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
+ SEND + RECV
+ SENDMD5 + RECVMD5
+ SENDTHROUGH
+ RECVTHROUGH
+ SENDMD5THROUGH
+ RECVMD5THROUGH
Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
+

+

-
-

 

- +

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin/Rules_head.html b/src/main/admin/Rules_head.html index 50b6b0610..e96d43900 100644 --- a/src/main/admin/Rules_head.html +++ b/src/main/admin/Rules_head.html @@ -1,294 +1,294 @@ - - - - - - - - - - - - -Rules - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Rules

-

You can edit Rules configuration from here.

-

 

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
-

SEND - RECV
- SENDMD5 - RECVMD5
- SENDTHROUGH
- RECVTHROUGH
- SENDMD5THROUGH
- RECVMD5THROUGH - help for Mode field -

- The Mode used with a transfer with this rule. For instance, if SENDMD5, the transfer will be a send of file - from the requester to the requested host where each packet will be checked by a MD5. -

help for HostIds field -

- If no Host is written, these rule is allowed for any Host. If some Hosts are specified, only those - will be accepted with this rule.

The format is as:

<hostids> - <hostid>hostid1</hostid> - <hostid>hostid2</hostid> -</hostids>

-

- help for Recv Path field -

- If not null, it specifies a sub path of server ROOT for final receive directory. -

-

- help for Send Path field -

- If not null, it specifies a sub path of server ROOT for send directory. -

-

- help for Archive Path field -

- If not null, it specifies a sub path of server ROOT for archive (export) directory. -

-

- help for Working Path field -

- If not null, it specifies a sub path of server ROOT for working (during receive) directory. -

Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
-help for Recv Pre Actions field -

- It specifies all actions to do BEFORE the transfer operation as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Recv Post Actions field -

- It specifies all actions to do AFTER the transfer operation as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Recv Error Actions field -

- It specifies all actions to do AFTER AN ERROR OCCURS as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Pre Actions field -

- It specifies all actions to do BEFORE the transfer operation as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Post Actions field -

- It specifies all actions to do AFTER the transfer operation as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Error Actions field -

- It specifies all actions to do AFTER AN ERROR OCCURS as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-

-
-

 

-
-

Filter on Rule Id:

-
- Filter on Mode: ALL - ALL SEND - ALL RECV - help for Mode Filter field -

- Either you choose "ALL SEND", "ALL RECV" or "ALL" but none of specific (SEND, RECV, ...), - or you choose some specifics types of mode (SEND, SENDMD5, ...). -

-

  - SEND - RECV - SENDMD5 - RECVMD5 - SENDTHROUGH - RECVTHROUGH - SENDMD5THROUGH - RECVMD5THROUGH

-

                                                                -                -

-
-

 

+ + + + + + + + + + + + +Rules + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/CancelRestart_body0.html b/src/main/admin2/CancelRestart_body0.html index 57f9e8efc..ca3c06d88 100644 --- a/src/main/admin2/CancelRestart_body0.html +++ b/src/main/admin2/CancelRestart_body0.html @@ -1,18 +1,18 @@ -
+

 

+
+

Rules

+

You can edit Rules configuration from here.

+

 

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
+

SEND + RECV
+ SENDMD5 + RECVMD5
+ SENDTHROUGH
+ RECVTHROUGH
+ SENDMD5THROUGH
+ RECVMD5THROUGH + help for Mode field +

+ The Mode used with a transfer with this rule. For instance, if SENDMD5, the transfer will be a send of file + from the requester to the requested host where each packet will be checked by a MD5. +

help for HostIds field +

+ If no Host is written, these rule is allowed for any Host. If some Hosts are specified, only those + will be accepted with this rule.

The format is as:

<hostids> + <hostid>hostid1</hostid> + <hostid>hostid2</hostid> +</hostids>

+

+ help for Recv Path field +

+ If not null, it specifies a sub path of server ROOT for final receive directory. +

+

+ help for Send Path field +

+ If not null, it specifies a sub path of server ROOT for send directory. +

+

+ help for Archive Path field +

+ If not null, it specifies a sub path of server ROOT for archive (export) directory. +

+

+ help for Working Path field +

+ If not null, it specifies a sub path of server ROOT for working (during receive) directory. +

Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
+help for Recv Pre Actions field +

+ It specifies all actions to do BEFORE the transfer operation as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Recv Post Actions field +

+ It specifies all actions to do AFTER the transfer operation as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Recv Error Actions field +

+ It specifies all actions to do AFTER AN ERROR OCCURS as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Pre Actions field +

+ It specifies all actions to do BEFORE the transfer operation as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Post Actions field +

+ It specifies all actions to do AFTER the transfer operation as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Error Actions field +

+ It specifies all actions to do AFTER AN ERROR OCCURS as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+

+
+

 

+
+

Filter on Rule Id:

+
+ Filter on Mode: ALL + ALL SEND + ALL RECV + help for Mode Filter field +

+ Either you choose "ALL SEND", "ALL RECV" or "ALL" but none of specific (SEND, RECV, ...), + or you choose some specifics types of mode (SEND, SENDMD5, ...). +

+

  + SEND + RECV + SENDMD5 + RECVMD5 + SENDTHROUGH + RECVTHROUGH + SENDMD5THROUGH + RECVMD5THROUGH

+

                                                                +                +

+
+

 

diff --git a/src/main/admin/System.html b/src/main/admin/System.html index 976425dd4..7da7865ec 100644 --- a/src/main/admin/System.html +++ b/src/main/admin/System.html @@ -1,179 +1,179 @@ - - - - - - - - - - - -System - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

System

-

You can edit System configuration from here, disconnect from the Administrator or even shutdown the OpenR66 server.

-

 

-
- Bandwidth Session Read Limit (B/s): - - help for Session Limit field -

- The value (in Byte per second) specifies the limit of read bandwidth (in) per session. 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Session Write Limit (B/s): - - help for Session Limit field -

- The value (in Byte per second) specifies the limit of write bandwidth (out) per session. 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Global Read Limit (B/s):   - - help for Global Limit field -

- The value (in Byte per second) specifies the limit of read bandwidth (in) globally (cumulative). 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Global Write Limit (B/s):   - - help for Global Limit field -

- The value (in Byte per second) specifies the limit of write bandwidth (out) globally (cumulative). 0 means no limit. Must be greater than 1KBs. -


- Delay for Commander (ms): - - help for Delay for Commander field -

- Delay for Commander between two acquires of new requested transfers in ms. Must be greater than 100ms. -


- Delay for Retry (ms):   - - help for Delay for Retry field -

- Delay for Retry between two retries for a currently active transfer in ms. Must be greater than 1000ms. -

-

 

-

                                                                -                -

-
-

 

-

 

-
- Export Config in Archive directory              - - help for ExportConfig -

- You can export Rules and Authentications to archive directory by clicking on this button. -

-
-

 

-

 

-
- Disconnect from OpenR66 Administrator      - - help for Disconnection -

- You can disconnect from this administrator by clicking on this button. -

-
-

 

-

 

-
- Shutdown OpenR66 Server                         - - help for Shutdown -

- By clicking on this button will result in the Shutdown process of the full OpenR66 Server (all active transfers - will be stopped in pause).. -

-
-

 

-
-

 

- + + + + + + + + + + + +System + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
+

System

+

You can edit System configuration from here, disconnect from the Administrator or even shutdown the OpenR66 server.

+

 

+
+ Bandwidth Session Read Limit (B/s): + + help for Session Limit field +

+ The value (in Byte per second) specifies the limit of read bandwidth (in) per session. 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Session Write Limit (B/s): + + help for Session Limit field +

+ The value (in Byte per second) specifies the limit of write bandwidth (out) per session. 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Global Read Limit (B/s):   + + help for Global Limit field +

+ The value (in Byte per second) specifies the limit of read bandwidth (in) globally (cumulative). 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Global Write Limit (B/s):   + + help for Global Limit field +

+ The value (in Byte per second) specifies the limit of write bandwidth (out) globally (cumulative). 0 means no limit. Must be greater than 1KBs. +


+ Delay for Commander (ms): + + help for Delay for Commander field +

+ Delay for Commander between two acquires of new requested transfers in ms. Must be greater than 100ms. +


+ Delay for Retry (ms):   + + help for Delay for Retry field +

+ Delay for Retry between two retries for a currently active transfer in ms. Must be greater than 1000ms. +

+

 

+

                                                                +                +

+
+

 

+

 

+
+ Export Config in Archive directory              + + help for ExportConfig +

+ You can export Rules and Authentications to archive directory by clicking on this button. +

+
+

 

+

 

+
+ Disconnect from OpenR66 Administrator      + + help for Disconnection +

+ You can disconnect from this administrator by clicking on this button. +

+
+

 

+

 

+
+ Shutdown OpenR66 Server                         + + help for Shutdown +

+ By clicking on this button will result in the Shutdown process of the full OpenR66 Server (all active transfers + will be stopped in pause).. +

+
+

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin/Transfers.html b/src/main/admin/Transfers.html index 2b82d45e7..344c7ecd7 100644 --- a/src/main/admin/Transfers.html +++ b/src/main/admin/Transfers.html @@ -1,116 +1,116 @@ - - - - - - - - - - - -Transfers - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Transfers

-

In this menu, you can administrate transfers.

-
    -
  • -
    Listing helps you to list all transfers according to some criteria.
  • -
  • -
    Cancel-Restart helps you to stop (cancel) active transfers or to restart pending transfers.
  • -
  • -
    Export helps you to export to an XML file the current log of the transfers.
-
-

 

- - + + + + + + + + + + + +Transfers + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
Listing +Cancel-Restart +Export +
+

Transfers

+

In this menu, you can administrate transfers.

+
    +
  • +
    Listing helps you to list all transfers according to some criteria.
  • +
  • +
    Cancel-Restart helps you to stop (cancel) active transfers or to restart pending transfers.
  • +
  • +
    Export helps you to export to an XML file the current log of the transfers.
+
+

 

+ + diff --git a/src/main/admin/error.html b/src/main/admin/error.html index d22384f2d..e44b27cd9 100644 --- a/src/main/admin/error.html +++ b/src/main/admin/error.html @@ -1,97 +1,97 @@ - - - - - - - - - - - -Start - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
-
-

 

- -

- - - -
-

 

-
-

Start

-

-

An event occurs that forces to close the connection...

-

 

-

XXXERRORMESGXXX

-

 

-
-

 

- - + + + + + + + + + + + +Start + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
+
+

 

+ +

+ + + +
+

 

+
+

Start

+

+

An event occurs that forces to close the connection...

+

 

+

XXXERRORMESGXXX

+

 

+
+

 

+ + diff --git a/src/main/admin/index.html b/src/main/admin/index.html index 4766078d0..0cd8a885b 100644 --- a/src/main/admin/index.html +++ b/src/main/admin/index.html @@ -1,112 +1,112 @@ - - - - - - - - - - - -Start - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Start

-

-

This site is the Administrator site of OpenR66.

-

 

-

The current host is:

-

XXXHOSTIDXXX

-

 

-

The current administrator is:

-

XXXADMINXXX

-

 

-

 

-

 

-

 

-

 

-

 

-

OpenR66 is part of the Waarp Project: see the Web site http://waarp.github.com/Waarp/index.html

-

Version: XXXVERSIONXXX

-

Author: Frederic Bregier

-

 

-
-

 

- - + + + + + + + + + + + +Start + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
+

Start

+

+

This site is the Administrator site of OpenR66.

+

 

+

The current host is:

+

XXXHOSTIDXXX

+

 

+

The current administrator is:

+

XXXADMINXXX

+

 

+

 

+

 

+

 

+

 

+

 

+

OpenR66 is part of the Waarp Project: see the Web site http://waarp.github.com/Waarp/index.html

+

Version: XXXVERSIONXXX

+

Author: Frederic Bregier

+

 

+
+

 

+ + diff --git a/src/main/admin/monitor/index.html b/src/main/admin/monitor/index.html index b4387fce7..0fe3aebc8 100644 --- a/src/main/admin/monitor/index.html +++ b/src/main/admin/monitor/index.html @@ -1,59 +1,59 @@ - - - OpenR66 Monitoring - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
-Default Monitoring:
- -
-Specific Monitoring:
-
-
-
One Choice Active Error Done -All:  - -
-
Number of runners (0 for all):    -               -
-
-
+ + + OpenR66 Monitoring + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+
+Default Monitoring:
+ +
+Specific Monitoring:
+
+
+
One Choice Active Error Done +All:  + +
+
Number of runners (0 for all):    +               +
+
+
\ No newline at end of file diff --git a/src/main/admin/monitor/monitoring.html b/src/main/admin/monitor/monitoring.html index c6fc4b1fe..61016f790 100644 --- a/src/main/admin/monitor/monitoring.html +++ b/src/main/admin/monitor/monitoring.html @@ -1,43 +1,43 @@ - - - OpenR66 Live Monitoring - - - - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
-

+ + + OpenR66 Live Monitoring + + + + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+
+

\ No newline at end of file diff --git a/src/main/admin/monitor/monitoring_header.html b/src/main/admin/monitor/monitoring_header.html index 3218826eb..872a6d4ac 100644 --- a/src/main/admin/monitor/monitoring_header.html +++ b/src/main/admin/monitor/monitoring_header.html @@ -1,42 +1,42 @@ - - - OpenR66 Live Monitoring - - - - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
+ + + OpenR66 Live Monitoring + + + + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+


\ No newline at end of file diff --git a/src/main/admin/res/OpenR66Admin.css b/src/main/admin/res/OpenR66Admin.css index fe6f708f0..07294611f 100644 --- a/src/main/admin/res/OpenR66Admin.css +++ b/src/main/admin/res/OpenR66Admin.css @@ -1,97 +1,97 @@ -p { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -table { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -div { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -li { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -.normal { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -.h1 { - font-family:Arial,Verdana; - font-size:20px; - color:#333333; - font-weight:bold; - margin:12px 0px 4px 0px; - padding:0px; -} -.h2 { - font-family:Verdana; - font-size:14px; - color:#333333; - font-weight:bold; - margin:8px 0px 2px 0px; - padding:0px; -} -.h3 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:normal; - margin:4px 0px 0px 0px; - padding:0px; -} -.h4 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:italic; - margin:4px 0px 0px 0px; - padding:0px; -} -.h5 { - font-family:Arial,Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:italic; - margin:4px 0px 0px 0px; - padding:0px; -} -.h6 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - letter-spacing:1px; - margin:4px 0px 0px 0px; - padding:0px; -} +p { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +table { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +div { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +li { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +.normal { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +.h1 { + font-family:Arial,Verdana; + font-size:20px; + color:#333333; + font-weight:bold; + margin:12px 0px 4px 0px; + padding:0px; +} +.h2 { + font-family:Verdana; + font-size:14px; + color:#333333; + font-weight:bold; + margin:8px 0px 2px 0px; + padding:0px; +} +.h3 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:normal; + margin:4px 0px 0px 0px; + padding:0px; +} +.h4 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:italic; + margin:4px 0px 0px 0px; + padding:0px; +} +.h5 { + font-family:Arial,Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:italic; + margin:4px 0px 0px 0px; + padding:0px; +} +.h6 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + letter-spacing:1px; + margin:4px 0px 0px 0px; + padding:0px; +} diff --git a/src/main/admin/res/OpenR66TaskOptions.html b/src/main/admin/res/OpenR66TaskOptions.html index 78f3713ba..405b3eb0a 100644 --- a/src/main/admin/res/OpenR66TaskOptions.html +++ b/src/main/admin/res/OpenR66TaskOptions.html @@ -1,421 +1,421 @@ - - - - - - - -Waarp - Waarp R66-TaskOptions - - -

Waarp R66-TaskOptions

-

We focus here on the several tasks that are possible to run before a transfer starts (pre action), after a transfer is finished correctly (post action) or after an error occurs (either in pre or post action or during transfer: error action).

-

 

-

Those actions are defined in one rule. Each rule contains 2 parts:

-
    -
  1. Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the requested on a RECV rule.
  2. - -
  3. -
    Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the requested on a SEND rule.
-

Each action could be on pre, post or error step, each step can have several actions.

-

 

-

It is defined with a unified form of XML:

-

 

-

        <tasks>

-

          <task>

-

             <type>NAME</type>

-

             <path>path</path>

-

             <delay>x</delay>

-

          </task>

-

          <task>

-

             <type>NAME</type>

-

             <path>path</path>

-

             <delay>x</delay>

-

          </task>

-

      </tasks>

-
    -
  • Type is the type of task to execute (see below the supported types)
  • - -
  • Path is a fixed argument for the task to execute. On this argument, string replacements are done when the following patterns are found:
      -
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • - -
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • - -
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • - -
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • - -
    • #FILESIZE# : File size if it exists
    • - -
    • #INPATH# : In (Receive) path 
    • - -
    • #OUTPATH# : Out (Send) path 
    • - -
    • #WORKPATH# : Working (while receiving) path 
    • - -
    • #ARCHPATH# : Archive path (for export Log)
    • - -
    • #HOMEPATH# : Home path (to enable for instance relative path commands) 
    • - -
    • #RULE# : Rule used during transfer 
    • - -
    • #DATE# : Current Date in yyyyMMdd format
    • - -
    • #HOUR# : Current Hour in HHmmss format
    • - -
    • #REMOTEHOST# : Remote host id (if not the initiator of the call)
    • - -
    • #REMOTEHOSTIP# : Remote host IP (if not the initiator of the call)
    • - -
    • #LOCALHOST# : Local host Id
    • - -
    • #LOCALHOSTIP# : Local host IP
    • - -
    • #TRANSFERID# : Transfer Id
    • - -
    • #REQUESTERHOST# : Requester host Id 
    • - -
    • #REQUESTEDHOST# : Requested host Id
    • - -
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST 
    • - -
    • #RANKTRANSFER# : Current or final RANK of block
    • - -
    • #BLOCKSIZE# : Block size used
    • - -
    • #ERRORMSG# : The current error message or NoError if no error occurs until this call
    • - -
    • #ERRORCODE# : The current error code or '-' (Unknown) if no error occurs until this call
    • - -
    • #ERRORSTRCODE# : The current error code message or "Unknown" if no error occurs until this call
    • - -
    • #NOWAIT# : Used by Exec type task to specify that the command will be executed in asynchronous mode, without waiting any result from it
    • - -
    • -
      #LOCALEXEC# : Used by Exec type task to specify that the command will be executed not locally (within the JVM) but outside using a LocalExec Daemon (specified in the global configuration)
  • - - -
  • Delay is generally the delay (if any) for execution before the execution becomes out of time.
  • - -
  • -
    Additionnaly, a task will use also the argument from the transfer itself (Transfer Information).
-

Each action is of one of the following items:

-
    -
  • -
    LOG
-
-

This task logs or writes to an external file some info:

-
    -
  • if delay is 0, no echo at all will be done
  • - -
  • if delay is 1, will echo some information in the normal log
  • - -
  • if delay is 2, will echo some information in the file (last deduced argument will be the full path for the file output)
  • - -
  • if delay is 3, will echo both in the normal log and in the file (last deduced argument will be the full path for the file output)
  • - -
  • -
    If first word of the log is one of debug, info, warn or error, this word will be used as the log level
-
    -
  • -
    MOVE
-
-

Move the file to the path designed by Path and Transfer Information arguments without renaming the filename (same basename).

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is marked as moved.

-
    -
  • -
    MOVERENAME
-
-

Move the file to the path designed by Path and Transfer Information arguments.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored. 

-

 

-

The file is marked as moved.

-
    -
  • -
    COPY
-
-

Copy the file to the path designed by Path argument without renaming the filename (same basename).

-

 

-

Delay and Transfer Information are ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    COPYRENAME
-
-

Copy the file to the path designed by Path and Transfer Information arguments.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    EXEC
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The file is not marked as moved.

-

 

-

The external command is supposed to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution
  • - -
  • exit 1, for a warned execution (but however correct)
  • - -
  • -
    other exit values for a failed execution
-
    -
  • -
    EXECMOVE
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The last line returned by the external command is interpreted as the new full file path. The external command is responsible to really move the previous file to the new one.

-

 

-

The file is marked as moved.

-

 

-

The external command is supposed to to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution

  • - -
  • exit 1, for a warned execution (but however correct)

  • - -
  • -

    other exit values for a failed execution

-
    -
  • -
    EXECOUTPUT
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

All lines returned by the external command (normal output) is interpreted as the possible error message in case of error.

-

 

-

The file is not marked as moved.

-

 

-

The external command is supposed to to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution

  • - -
  • exit 1, for a warned execution (but however correct)

  • - -
  • -

    other exit values for a failed execution, for which the output (stdout) lines are used as error message, bring back to the remote host as #ERRORMSG# and #ERRORCODE# / #ERRORSTRCODE#

-
    -
  • -
    EXECJAVA
-
-

Execute an external Java class given by Path and Transfer Information arguments.

-
-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The class name (which must implement R66Runnable) is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)). The first argument is this full classname. The allocation must be of the form new MyClass(), so an empty constructor.

-

 

-

The file is not marked as moved.

-
    -
  • -
    TRANSFER
-
-

Submit a new transfer based on the Path and Transfer Information arguments.

-

 

-

The transfer arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The result should be as r66send command except "-info" must be the last field:

-

"-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] -info transferInformation"

-

where each field is separated by blank character. Last field (transferInformation) may contain however blank character.

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    VALIDFILEPATH
-
-

Test if the current file is under one of the paths based on the Path and Transfer Information arguments.

-

 

-

The paths arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The result should be as: "path1 path2 ..." where each path is separated by blank character.

-

 

-

If Delay is not 0, a log is printed out.

-

 

-

The file is not marked as moved.

-
    -
  • -
    DELETE
-
-

This task deletes the current file.

-

 

-

The current file is no more valid.

-

 

-

No arguments are taken into account.

-
    -
  • -
    LINKRENAME
-
-

Create a link of the current file and make the file pointing to it.

-

 

-

The link first tries to be a hard link, then a soft link, and if it is really not possible (not supported by the filesystem), it does a copy and rename task.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-

 

-
    -
  • -
    RESCHEDULE
-
-

Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error code is one of the specified codes and the optional intervals of date are compatible with the new time schedule

Result of arguments will be as following options (the two first are mandatory):

-
    -
  • -
      -
    • "-delay ms" where ms is the added number of ms on current time before retry on schedule
    • - -
    • "-case errorCode,errorCode,..." where errorCode is one of the following error of the current transfer (either literal or code in 1 character):
      ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
    • - -
    • "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can be not set) and where start and stop are in the following format:
      Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
      Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, while X=n or Xn means setting exact value
      If one time specification is not set, it is based on the current date.

      If "-notbetween" is specified, the planned date must not be in the area.
      If "-between" is specified, the planned date must be found in any such specified areas (could be in any of the occurrence). If not specified, it only depends on "-notbetween".
      If none is specified, the planned date is always valid.
    • - -
    • -
      "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule as "#CPTLIMIT#newlimit#CPTLIMIT#".
-
-
-

Each time this function is called, the limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".

-

To ensure correctness, the value must be in the "info of transfer" since this value will be changed statically in the "info of transfer". If taken from the rule, it will be wrong since the value will never decrease. However, a value must be setup in the rule in order to reset the value when the count reach 0.
So in the rule, "-count resetlimit" must be present, where resetlimit will be the new value set when the limit reach 0, and in the "info on transfer", "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied.

-



-
-

Note that if a previous called to a reschedule was done for this attempt and was successful, the following calls will be ignored.

-
-

Important note: any subsequent task will be ignored and not executed once the reschedule is accepted. On the contrary, if the reschedule is not accepted, the following tasks will be executed normally.

In case start > end, end will be +1 day

-
-

In case start and end < current planned date, both will have +1 day.

-
-


Example:

-
-

"-delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0 -count 1"
And in the “file information”:

-
-

"#CPTLIMIT#3#CPTLIMIT#”

-
-

means retry in case of error during initialization of connection in 1 hour if not between 7AM to 7PM and not between 1AM to 3AM and with a limit of 3 retries (retry will be reset to 1 in case of 3 attempts).

-
    -
  • -
    TAR
-
-

Create a TAR from the argument as source and destination or UNTAR files from a TAR file.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay of 1 = UNTAR PATH="sourceFile targetDirectory"

-

 

-

Delay of 2 = TAR PATH="targetFile sourceDirectory"

-

 

-

Delay of 3 = TAR PATH="targetFile sourceFile1 sourceFile2..."

-

 

-

The current file is not touched.

-
    -
  • -
    ZIP
-
-

Create a ZIP from the argument as source and destination or UNZIP files from a ZIP file.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay of 1 = UNZIP PATH="sourceFile targetDirectory"

-

 

-

Delay of 2 = ZIP PATH="targetFile sourceDirectory"

-

 

-

Delay of 3 = ZIP PATH="targetFile sourceFile1 sourceFile2..."

-

 

-

The current file is not touched.

-
    -
  • -

    TRANSCODE

-
-

Allow to transcode a file from a Charset to another one.

-

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-
    -
  • "-from fromCharset"
  • - -
  • "-to toCharset"
  • - -
  • "-newfile filename" optional argument ; if not used, will be current filename.extension ; if used, extension is ignored
  • - -
  • -
    "-extension extension" optional argument ; if not used, will be filename.transcode
-

-

fromCharset and toCharset are string representations of the official charsets in Java.

-

 

-

A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) all the supported Charsets from your JVM. To use it, run the following command:

-

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]

-

 

-

-

-

It could also be used as a test of transcode outside R66:

-

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset

-

 

-

The current file is not touched and is not marked as moved.

-
-

 

-

 

-

 

-

Example:

-

 

-

      <tasks>

-

     <task>

-

        <type>MOVE</type>

-

        <path>/pathout/</path>

-

        <comment>move the file to /pathout/#TRUEFILENAME#</comment>

-

        <delay>0</delay>

-

     </task>

-

     <task>

-

        <type>EXEC</type>

-

        <path>#HOMEPATH#/pathexec/monscript #TRUEFULLPATH# #ORIGINALFILENAME# #FILESIZE# #RULE# %s %d #REMOTEHOST#</path>

-

        <comment>information passed by transfer is "a_string_without_blank a_number" and replaced respectively in %s and %d</comment>

-

        <delay>30000</delay>

-

        <comment>maximum 30 seconds to execute this script</comment>

-

     </task>

-

   </tasks>

-
-
-
-
-

 

- - + + + + + + + +Waarp - Waarp R66-TaskOptions + + +

Waarp R66-TaskOptions

+

We focus here on the several tasks that are possible to run before a transfer starts (pre action), after a transfer is finished correctly (post action) or after an error occurs (either in pre or post action or during transfer: error action).

+

 

+

Those actions are defined in one rule. Each rule contains 2 parts:

+
    +
  1. Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the requested on a RECV rule.
  2. + +
  3. +
    Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the requested on a SEND rule.
+

Each action could be on pre, post or error step, each step can have several actions.

+

 

+

It is defined with a unified form of XML:

+

 

+

        <tasks>

+

          <task>

+

             <type>NAME</type>

+

             <path>path</path>

+

             <delay>x</delay>

+

          </task>

+

          <task>

+

             <type>NAME</type>

+

             <path>path</path>

+

             <delay>x</delay>

+

          </task>

+

      </tasks>

+
    +
  • Type is the type of task to execute (see below the supported types)
  • + +
  • Path is a fixed argument for the task to execute. On this argument, string replacements are done when the following patterns are found:
      +
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • + +
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • + +
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • + +
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • + +
    • #FILESIZE# : File size if it exists
    • + +
    • #INPATH# : In (Receive) path 
    • + +
    • #OUTPATH# : Out (Send) path 
    • + +
    • #WORKPATH# : Working (while receiving) path 
    • + +
    • #ARCHPATH# : Archive path (for export Log)
    • + +
    • #HOMEPATH# : Home path (to enable for instance relative path commands) 
    • + +
    • #RULE# : Rule used during transfer 
    • + +
    • #DATE# : Current Date in yyyyMMdd format
    • + +
    • #HOUR# : Current Hour in HHmmss format
    • + +
    • #REMOTEHOST# : Remote host id (if not the initiator of the call)
    • + +
    • #REMOTEHOSTIP# : Remote host IP (if not the initiator of the call)
    • + +
    • #LOCALHOST# : Local host Id
    • + +
    • #LOCALHOSTIP# : Local host IP
    • + +
    • #TRANSFERID# : Transfer Id
    • + +
    • #REQUESTERHOST# : Requester host Id 
    • + +
    • #REQUESTEDHOST# : Requested host Id
    • + +
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST 
    • + +
    • #RANKTRANSFER# : Current or final RANK of block
    • + +
    • #BLOCKSIZE# : Block size used
    • + +
    • #ERRORMSG# : The current error message or NoError if no error occurs until this call
    • + +
    • #ERRORCODE# : The current error code or '-' (Unknown) if no error occurs until this call
    • + +
    • #ERRORSTRCODE# : The current error code message or "Unknown" if no error occurs until this call
    • + +
    • #NOWAIT# : Used by Exec type task to specify that the command will be executed in asynchronous mode, without waiting any result from it
    • + +
    • +
      #LOCALEXEC# : Used by Exec type task to specify that the command will be executed not locally (within the JVM) but outside using a LocalExec Daemon (specified in the global configuration)
  • + + +
  • Delay is generally the delay (if any) for execution before the execution becomes out of time.
  • + +
  • +
    Additionnaly, a task will use also the argument from the transfer itself (Transfer Information).
+

Each action is of one of the following items:

+
    +
  • +
    LOG
+
+

This task logs or writes to an external file some info:

+
    +
  • if delay is 0, no echo at all will be done
  • + +
  • if delay is 1, will echo some information in the normal log
  • + +
  • if delay is 2, will echo some information in the file (last deduced argument will be the full path for the file output)
  • + +
  • if delay is 3, will echo both in the normal log and in the file (last deduced argument will be the full path for the file output)
  • + +
  • +
    If first word of the log is one of debug, info, warn or error, this word will be used as the log level
+
    +
  • +
    MOVE
+
+

Move the file to the path designed by Path and Transfer Information arguments without renaming the filename (same basename).

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is marked as moved.

+
    +
  • +
    MOVERENAME
+
+

Move the file to the path designed by Path and Transfer Information arguments.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored. 

+

 

+

The file is marked as moved.

+
    +
  • +
    COPY
+
+

Copy the file to the path designed by Path argument without renaming the filename (same basename).

+

 

+

Delay and Transfer Information are ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    COPYRENAME
+
+

Copy the file to the path designed by Path and Transfer Information arguments.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    EXEC
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The file is not marked as moved.

+

 

+

The external command is supposed to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution
  • + +
  • exit 1, for a warned execution (but however correct)
  • + +
  • +
    other exit values for a failed execution
+
    +
  • +
    EXECMOVE
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The last line returned by the external command is interpreted as the new full file path. The external command is responsible to really move the previous file to the new one.

+

 

+

The file is marked as moved.

+

 

+

The external command is supposed to to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution

  • + +
  • exit 1, for a warned execution (but however correct)

  • + +
  • +

    other exit values for a failed execution

+
    +
  • +
    EXECOUTPUT
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

All lines returned by the external command (normal output) is interpreted as the possible error message in case of error.

+

 

+

The file is not marked as moved.

+

 

+

The external command is supposed to to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution

  • + +
  • exit 1, for a warned execution (but however correct)

  • + +
  • +

    other exit values for a failed execution, for which the output (stdout) lines are used as error message, bring back to the remote host as #ERRORMSG# and #ERRORCODE# / #ERRORSTRCODE#

+
    +
  • +
    EXECJAVA
+
+

Execute an external Java class given by Path and Transfer Information arguments.

+
+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The class name (which must implement R66Runnable) is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)). The first argument is this full classname. The allocation must be of the form new MyClass(), so an empty constructor.

+

 

+

The file is not marked as moved.

+
    +
  • +
    TRANSFER
+
+

Submit a new transfer based on the Path and Transfer Information arguments.

+

 

+

The transfer arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The result should be as r66send command except "-info" must be the last field:

+

"-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] -info transferInformation"

+

where each field is separated by blank character. Last field (transferInformation) may contain however blank character.

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    VALIDFILEPATH
+
+

Test if the current file is under one of the paths based on the Path and Transfer Information arguments.

+

 

+

The paths arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The result should be as: "path1 path2 ..." where each path is separated by blank character.

+

 

+

If Delay is not 0, a log is printed out.

+

 

+

The file is not marked as moved.

+
    +
  • +
    DELETE
+
+

This task deletes the current file.

+

 

+

The current file is no more valid.

+

 

+

No arguments are taken into account.

+
    +
  • +
    LINKRENAME
+
+

Create a link of the current file and make the file pointing to it.

+

 

+

The link first tries to be a hard link, then a soft link, and if it is really not possible (not supported by the filesystem), it does a copy and rename task.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+

 

+
    +
  • +
    RESCHEDULE
+
+

Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error code is one of the specified codes and the optional intervals of date are compatible with the new time schedule

Result of arguments will be as following options (the two first are mandatory):

+
    +
  • +
      +
    • "-delay ms" where ms is the added number of ms on current time before retry on schedule
    • + +
    • "-case errorCode,errorCode,..." where errorCode is one of the following error of the current transfer (either literal or code in 1 character):
      ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
    • + +
    • "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can be not set) and where start and stop are in the following format:
      Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
      Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, while X=n or Xn means setting exact value
      If one time specification is not set, it is based on the current date.

      If "-notbetween" is specified, the planned date must not be in the area.
      If "-between" is specified, the planned date must be found in any such specified areas (could be in any of the occurrence). If not specified, it only depends on "-notbetween".
      If none is specified, the planned date is always valid.
    • + +
    • +
      "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule as "#CPTLIMIT#newlimit#CPTLIMIT#".
+
+
+

Each time this function is called, the limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".

+

To ensure correctness, the value must be in the "info of transfer" since this value will be changed statically in the "info of transfer". If taken from the rule, it will be wrong since the value will never decrease. However, a value must be setup in the rule in order to reset the value when the count reach 0.
So in the rule, "-count resetlimit" must be present, where resetlimit will be the new value set when the limit reach 0, and in the "info on transfer", "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied.

+



+
+

Note that if a previous called to a reschedule was done for this attempt and was successful, the following calls will be ignored.

+
+

Important note: any subsequent task will be ignored and not executed once the reschedule is accepted. On the contrary, if the reschedule is not accepted, the following tasks will be executed normally.

In case start > end, end will be +1 day

+
+

In case start and end < current planned date, both will have +1 day.

+
+


Example:

+
+

"-delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0 -count 1"
And in the “file information”:

+
+

"#CPTLIMIT#3#CPTLIMIT#”

+
+

means retry in case of error during initialization of connection in 1 hour if not between 7AM to 7PM and not between 1AM to 3AM and with a limit of 3 retries (retry will be reset to 1 in case of 3 attempts).

+
    +
  • +
    TAR
+
+

Create a TAR from the argument as source and destination or UNTAR files from a TAR file.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay of 1 = UNTAR PATH="sourceFile targetDirectory"

+

 

+

Delay of 2 = TAR PATH="targetFile sourceDirectory"

+

 

+

Delay of 3 = TAR PATH="targetFile sourceFile1 sourceFile2..."

+

 

+

The current file is not touched.

+
    +
  • +
    ZIP
+
+

Create a ZIP from the argument as source and destination or UNZIP files from a ZIP file.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay of 1 = UNZIP PATH="sourceFile targetDirectory"

+

 

+

Delay of 2 = ZIP PATH="targetFile sourceDirectory"

+

 

+

Delay of 3 = ZIP PATH="targetFile sourceFile1 sourceFile2..."

+

 

+

The current file is not touched.

+
    +
  • +

    TRANSCODE

+
+

Allow to transcode a file from a Charset to another one.

+

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+
    +
  • "-from fromCharset"
  • + +
  • "-to toCharset"
  • + +
  • "-newfile filename" optional argument ; if not used, will be current filename.extension ; if used, extension is ignored
  • + +
  • +
    "-extension extension" optional argument ; if not used, will be filename.transcode
+

+

fromCharset and toCharset are string representations of the official charsets in Java.

+

 

+

A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) all the supported Charsets from your JVM. To use it, run the following command:

+

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]

+

 

+

+

+

It could also be used as a test of transcode outside R66:

+

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset

+

 

+

The current file is not touched and is not marked as moved.

+
+

 

+

 

+

 

+

Example:

+

 

+

      <tasks>

+

     <task>

+

        <type>MOVE</type>

+

        <path>/pathout/</path>

+

        <comment>move the file to /pathout/#TRUEFILENAME#</comment>

+

        <delay>0</delay>

+

     </task>

+

     <task>

+

        <type>EXEC</type>

+

        <path>#HOMEPATH#/pathexec/monscript #TRUEFULLPATH# #ORIGINALFILENAME# #FILESIZE# #RULE# %s %d #REMOTEHOST#</path>

+

        <comment>information passed by transfer is "a_string_without_blank a_number" and replaced respectively in %s and %d</comment>

+

        <delay>30000</delay>

+

        <comment>maximum 30 seconds to execute this script</comment>

+

     </task>

+

   </tasks>

+
+
+
+
+

 

+ + diff --git a/src/main/admin/res/fieldhelp.js b/src/main/admin/res/fieldhelp.js index 114576245..bf3fe7c91 100644 --- a/src/main/admin/res/fieldhelp.js +++ b/src/main/admin/res/fieldhelp.js @@ -1,77 +1,77 @@ -/* start multiple load function - allows scripts to load/register gracefully - design by Simon Willison */ -function addLoadEvent(func) { - var oldonload = window.onload; - if (typeof window.onload != 'function') { - window.onload = func; - } else { - window.onload = function() { - if (oldonload) { - oldonload(); - } - func(); - } - } -} -addLoadEvent(init); -addLoadEvent(function() { -/* more code to run on page load */ -addLoadEvent(openClose); -}); -/* end multiple load function */ - - -/* start function init() - design by Gez Lemon */ -function init() -{ - var objImage = document.getElementsByTagName('img'); - var objHelp, objAnchor, objClone; - - for (var iCounter=0; iCounter -
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXX -
- - - - - - -
-
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXX +
+ + + + + + +
+
- - - - - - - - - - - - - - - - +
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisMovedRequesterRequestedStartStopCancel / Stop / Restart
+ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/CancelRestart_end.html b/src/main/admin2/CancelRestart_end.html index d4874d389..d228c9c25 100644 --- a/src/main/admin2/CancelRestart_end.html +++ b/src/main/admin2/CancelRestart_end.html @@ -1,5 +1,5 @@ -
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisMovedRequesterRequestedStartStopCancel / Stop / Restart
-
-

 

- +
+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/CancelRestart_head.html b/src/main/admin2/CancelRestart_head.html index 998633e9a..9a4279c95 100644 --- a/src/main/admin2/CancelRestart_head.html +++ b/src/main/admin2/CancelRestart_head.html @@ -1,160 +1,160 @@ - - - - - - - - - - - - -Cancel-Restart - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Cancel-Restart

-

Select a Transfer - and choose the operation to do.

 

-
- From SpecialId:  - help for From SpecialId field -

- The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. -

-   To SpecialId:  - help for To SpecialId field -

- The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. -

-
From date:  - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To date:  - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

-   Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

                                                                -                -

-

                                                                -            -

-
+ + + + + + + + + + + + +Cancel-Restart + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/Hosts_body0.html b/src/main/admin2/Hosts_body0.html index 3abb0cc7f..b13632cfd 100644 --- a/src/main/admin2/Hosts_body0.html +++ b/src/main/admin2/Hosts_body0.html @@ -1,14 +1,14 @@ -
+

 

+
Listing +Cancel-Restart +Export +
+

Cancel-Restart

+

Select a Transfer + and choose the operation to do.

 

+
+ From SpecialId:  + help for From SpecialId field +

+ The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. +

+   To SpecialId:  + help for To SpecialId field +

+ The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. +

+
From date:  + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To date:  + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+   Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

                                                                +                +

+

                                                                +            +

+

 

 

\ No newline at end of file diff --git a/src/main/admin2/Export.html b/src/main/admin2/Export.html index 0638d4cf1..ab5fb001b 100644 --- a/src/main/admin2/Export.html +++ b/src/main/admin2/Export.html @@ -1,153 +1,153 @@ - - - - - - - - - - - -Export - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Export

-
-

Export Transfers log into an XML File:

 

- From: - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To:  - - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

- Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

Warning: Purge after export - help for Purge field -

- If this option is checked, all exported logs from Transfer table will be deleted from the database. Note that running transfers are never deleted. -

            -                - -

 

-
-

 

XXXRESULTXXX

- + + + + + + + + + + + +Export + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
Listing +Cancel-Restart +Export +
+

Export

+
+

Export Transfers log into an XML File:

 

+ From: + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To:  + + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+ Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

Warning: Purge after export + help for Purge field +

+ If this option is checked, all exported logs from Transfer table will be deleted from the database. Note that running transfers are never deleted. +

            +                + +

 

+
+

 

XXXRESULTXXX

+ \ No newline at end of file diff --git a/src/main/admin2/Hosts_body.html b/src/main/admin2/Hosts_body.html index 0555f593b..198143a0c 100644 --- a/src/main/admin2/Hosts_body.html +++ b/src/main/admin2/Hosts_body.html @@ -1,26 +1,26 @@ -
- - - - - - - - - XXXCONNXXX - -
+ + + + + + + + + XXXCONNXXX + +
- - - - - - - - - - - - +
Host IDAddressPortSSLHostKeyAdmin RoleIsClientUpdateDeleteTestConnCloseConn
+ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/Hosts_end.html b/src/main/admin2/Hosts_end.html index 9767e25d3..97f37f5ca 100644 --- a/src/main/admin2/Hosts_end.html +++ b/src/main/admin2/Hosts_end.html @@ -1,5 +1,5 @@ -

 

Host IDAddressPortSSLHostKeyAdmin RoleIsClientUpdateDeleteTestConnCloseConn
-
-

 

- +

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/Hosts_head.html b/src/main/admin2/Hosts_head.html index e14c08e26..076f9f906 100644 --- a/src/main/admin2/Hosts_head.html +++ b/src/main/admin2/Hosts_head.html @@ -1,177 +1,177 @@ - - - - - - - - - - - -Hosts - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Hosts

-

You can edit Hosts configuration from here.

-

 

-
- - - - - - - - - - - - - - - - - - - -
Host IDAddressPortSSLHostKeyAdmin RoleIs Client
- help for Host field -

- The host id that will be used. -

- help for Address field -

- The IP or DNS name of the host. -

- help for Port field -

- The port to be used. -

- - help for SSL field -

- If checked, this host will describe a host with SSL support. -

- help for HostKey field -

- The Key to be used when Administration action are taken. -

- - help for Admin field -

- If checked, this host can be used in local client for administration purpose (using the above key). -

- - help for IsClient field -

- If checked, this host is a client only, meaning that it can only initiate transfers but cannot receive new request of transfer. -

-

                                                                -

-
-

 

-
- Filter on Host Id:   - help for Host ID Filter field -

- Part of the Host Id to used as filter. -


- Filter on Address:  - help for Address Filter field -

- Part of the Address to used as filter. -


- Filter on SSL:  - help for SSL Filter field -

- If checked, only SSL Hosts will be listed. If not, only not SSL Hosts will be listed. -

-                                       -                -
+ + + + + + + + + + + +Hosts + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/Listing_body0.html b/src/main/admin2/Listing_body0.html index 17fc585e5..2df063bfe 100644 --- a/src/main/admin2/Listing_body0.html +++ b/src/main/admin2/Listing_body0.html @@ -1,20 +1,20 @@ -
+

 

+
+

Hosts

+

You can edit Hosts configuration from here.

+

 

+
+ + + + + + + + + + + + + + + + + + + +
Host IDAddressPortSSLHostKeyAdmin RoleIs Client
+ help for Host field +

+ The host id that will be used. +

+ help for Address field +

+ The IP or DNS name of the host. +

+ help for Port field +

+ The port to be used. +

+ + help for SSL field +

+ If checked, this host will describe a host with SSL support. +

+ help for HostKey field +

+ The Key to be used when Administration action are taken. +

+ + help for Admin field +

+ If checked, this host can be used in local client for administration purpose (using the above key). +

+ + help for IsClient field +

+ If checked, this host is a client only, meaning that it can only initiate transfers but cannot receive new request of transfer. +

+

                                                                +

+
+

 

+
+ Filter on Host Id:   + help for Host ID Filter field +

+ Part of the Host Id to used as filter. +


+ Filter on Address:  + help for Address Filter field +

+ Part of the Address to used as filter. +


+ Filter on SSL:  + help for SSL Filter field +

+ If checked, only SSL Hosts will be listed. If not, only not SSL Hosts will be listed. +

+                                       +                +

 

\ No newline at end of file diff --git a/src/main/admin2/Listing_body.html b/src/main/admin2/Listing_body.html index 009f3a44c..18d58e6c5 100644 --- a/src/main/admin2/Listing_body.html +++ b/src/main/admin2/Listing_body.html @@ -1,19 +1,19 @@ -
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisSendXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXXXXXBandXXXXXXFreeXXX
XXXSpecIdXXXXXXRulXXXXXXFileXXXXXXInfoXXXXXXStepXXXXXXActXXXXXXStatXXX XXXRunningXXXXXXInternXXXXXXBloXXXXXXisSendXXXXXXisMovXXXXXXReqrXXXXXXReqdXXXXXXStarXXXXXXStopXXXXXXBandXXXXXXFreeXXX
- - - - - - - - - - - - - - - - - - +
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisSenderisMovedRequesterRequestedStartStopBandwidthFree Space
+ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/Listing_end.html b/src/main/admin2/Listing_end.html index d4874d389..d228c9c25 100644 --- a/src/main/admin2/Listing_end.html +++ b/src/main/admin2/Listing_end.html @@ -1,5 +1,5 @@ -
SpecialIdRuleFilenameInfoStep (LastStep)ActionStatusInternalBlockisSenderisMovedRequesterRequestedStartStopBandwidthFree Space
-
-

 

- +
+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/Listing_head.html b/src/main/admin2/Listing_head.html index 6bbb79f60..7137a254a 100644 --- a/src/main/admin2/Listing_head.html +++ b/src/main/admin2/Listing_head.html @@ -1,157 +1,157 @@ - - - - - - - - - - - -Listing - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Listing

-

Listing of - Transfers according to criteria.

 

-
- From SpecialId:  - help for From SpecialId field -

- The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. -

-   To SpecialId:  - help for To SpecialId field -

- The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. -

-
From date: - help for From field -

- The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 -

-   To date:  - - help for To field -

- The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 -

-
Rule:  - help for Rule field -

- This field could be part of a rule name. -

-   Requested/Requester: - help for Requested/Requester field -

- This field could be part of a requester or requested host id. -

-
Pending - In Transfer - In Error - Done - All -

                                                                -                -

-
+ + + + + + + + + + + +Listing + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/admin2/Rules_end.html b/src/main/admin2/Rules_end.html index 9767e25d3..97f37f5ca 100644 --- a/src/main/admin2/Rules_end.html +++ b/src/main/admin2/Rules_end.html @@ -1,5 +1,5 @@ -

 

+

 

+
Listing +Cancel-Restart +Export +
+

Listing

+

Listing of + Transfers according to criteria.

 

+
+ From SpecialId:  + help for From SpecialId field +

+ The start SpecialId for filtering on the Special Id of transfers like id greater or equal than value. +

+   To SpecialId:  + help for To SpecialId field +

+ The stop SpecialId for filtering on the Special Id of transfers like id less or equal than value. +

+
From date: + help for From field +

+ The start date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). Example: 2009-09-19 09:54:05.492 +

+   To date:  + + help for To field +

+ The stop date for filtering in format yyyymmdd-hhmmss.SSS with or without :-/ . in it, partial or full (at least yyyymmdd). If stop date is null while start is not null, 24H is kept as interval. Example: 2009-09-19 09:54:05.492 +

+
Rule:  + help for Rule field +

+ This field could be part of a rule name. +

+   Requested/Requester: + help for Requested/Requester field +

+ This field could be part of a requester or requested host id. +

+
Pending + In Transfer + In Error + Done + All +

                                                                +                +

+

 

 

\ No newline at end of file diff --git a/src/main/admin2/Logon.html b/src/main/admin2/Logon.html index a03de9a34..ae8e4a927 100644 --- a/src/main/admin2/Logon.html +++ b/src/main/admin2/Logon.html @@ -1,93 +1,93 @@ - - - - - - - - - - - -Logon - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon
-
-

 

- -

- - - -
-

 

-
-

Logon

-

You need to login to access to the OpenR66 Administrator.

-

 

-

 

-
-

Username:

-

Password:            -       

-
-

 

-
-

 

- + + + + + + + + + + + +Logon + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon
+
+

 

+ +

+ + + +
+

 

+
+

Logon

+

You need to login to access to the OpenR66 Administrator.

+

 

+

 

+
+

Username:

+

Password:            +       

+
+

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/Rules_body.html b/src/main/admin2/Rules_body.html index 1f01eb6ab..9df6ca416 100644 --- a/src/main/admin2/Rules_body.html +++ b/src/main/admin2/Rules_body.html @@ -1,46 +1,46 @@ -
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
- SEND - RECV
- SENDMD5 - RECVMD5
- SENDTHROUGH
- RECVTHROUGH
- SENDMD5THROUGH
- RECVMD5THROUGH
Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
-

-

Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
+ SEND + RECV
+ SENDMD5 + RECVMD5
+ SENDTHROUGH
+ RECVTHROUGH
+ SENDMD5THROUGH
+ RECVMD5THROUGH
Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
+

+

-
-

 

- +

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/Rules_head.html b/src/main/admin2/Rules_head.html index 2755b4643..62d287d3b 100644 --- a/src/main/admin2/Rules_head.html +++ b/src/main/admin2/Rules_head.html @@ -1,308 +1,308 @@ - - - - - - - - - - - - - -Rules - - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Rules

-

You can edit Rules configuration from here.

- -
-
-
-
- Rule Helper -
-
-
-
- -

 

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
-

SEND - RECV
- SENDMD5 - RECVMD5
- SENDTHROUGH
- RECVTHROUGH
- SENDMD5THROUGH
- RECVMD5THROUGH - help for Mode field -

- The Mode used with a transfer with this rule. For instance, if SENDMD5, the transfer will be a send of file - from the requester to the requested host where each packet will be checked by a MD5. -

help for HostIds field -

- If no Host is written, these rule is allowed for any Host. If some Hosts are specified, only those - will be accepted with this rule.

The format is as:

<hostids> - <hostid>hostid1</hostid> - <hostid>hostid2</hostid> -</hostids>

-

- help for Recv Path field -

- If not null, it specifies a sub path of server ROOT for final receive directory. -

-

- help for Send Path field -

- If not null, it specifies a sub path of server ROOT for send directory. -

-

- help for Archive Path field -

- If not null, it specifies a sub path of server ROOT for archive (export) directory. -

-

- help for Working Path field -

- If not null, it specifies a sub path of server ROOT for working (during receive) directory. -

Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
-help for Recv Pre Actions field -

- It specifies all actions to do BEFORE the transfer operation as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Recv Post Actions field -

- It specifies all actions to do AFTER the transfer operation as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Recv Error Actions field -

- It specifies all actions to do AFTER AN ERROR OCCURS as receiver host(SEND and requested, - or RECV and requester).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Pre Actions field -

- It specifies all actions to do BEFORE the transfer operation as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Post Actions field -

- It specifies all actions to do AFTER the transfer operation as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-help for Send Error Actions field -

- It specifies all actions to do AFTER AN ERROR OCCURS as sender host(SEND and requester, - or RECV and requested).

The format is as:

<tasks> - <task> - <type>NAME</type> - <path>path</path> - <delay>x</delay> - </task> -</tasks>where
--type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
--path is a static argument where some replacement will be done
--delay is usually the maximum delay of execution
-See the API or doc for the specific conditions.

-

-
-

 

-
-

Filter on Rule Id:

-
- Filter on Mode: ALL - ALL SEND - ALL RECV - help for Mode Filter field -

- Either you choose "ALL SEND", "ALL RECV" or "ALL" but none of specific (SEND, RECV, ...), - or you choose some specifics types of mode (SEND, SENDMD5, ...). -

-

  - SEND - RECV - SENDMD5 - RECVMD5 - SENDTHROUGH - RECVTHROUGH - SENDMD5THROUGH - RECVMD5THROUGH

-

                                                                -                -

-
-

 

+ + + + + + + + + + + + + +Rules + + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + + - * transaction.transferInError(openR66Exception); - * - *
- *
- * - * @see TestSendThroughClient Class as example of usage in test part - * - * @author Frederic Bregier - * - */ -public abstract class SendThroughClient extends AbstractTransfer { - protected final NetworkTransaction networkTransaction; - protected LocalChannelReference localChannelReference; - protected DbTaskRunner taskRunner = null; - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - * @param id - */ - public SendThroughClient(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, long id, NetworkTransaction networkTransaction) { - super(SendThroughClient.class, - future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); - this.networkTransaction = networkTransaction; - } - - /** - * DO NOT CALL THIS! - */ - public void run() { - logger.error("DO NOT call this method for this class"); - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. Note that this is only - * the first part of the execution for this client. - * - * @return True if the initiate of the request is OK, else False - */ - public boolean initiateRequest() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(SendThroughClient.class); - } - DbRule rule; - try { - rule = new DbRule(DbConstant.admin.session, rulename); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Rule: " + rulename, e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; - } - int mode = rule.mode; - if (isMD5) { - mode = RequestPacket.getModeMD5(mode); - } - RequestPacket request = new RequestPacket(rulename, - mode, filename, blocksize, 0, - id, fileinfo, -1); - // Not isRecv since it is the requester, so send => isSender is true - boolean isSender = true; - try { - try { - // no starttime since immediate - taskRunner = - new DbTaskRunner(DbConstant.admin.session, rule, isSender, request, - remoteHost, null); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get task", e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; - } - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - runner.setSendThroughMode(); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - localChannelReference = runner.initRequest(); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.error("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(exc); - return false; - } - try { - localChannelReference.waitReadyForSendThrough(); - } catch (OpenR66Exception e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } - // now start the send from external data - return true; - } finally { - if (taskRunner != null) { - if (future.isFailed()) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e) { - } - } - } - } - } - - /** - * Finalize the request - */ - public void finalizeRequest() { - try { - try { - ChannelUtils.writeEndTransfer(localChannelReference); - } catch (OpenR66ProtocolPacketException e) { - // An error occurs! - try { - localChannelReference.getSession().setFinalizeTransfer( - false, - new R66Result(e, localChannelReference.getSession(), false, - ErrorCode.Internal, taskRunner)); - } catch (OpenR66RunnerErrorException e1) { - transferInError(e1); - return; - } catch (OpenR66ProtocolSystemException e1) { - transferInError(e1); - return; - } - } - localChannelReference.getFutureEndTransfer().awaitUninterruptibly(); - logger.debug("Await future End Transfer done: " + - localChannelReference.getFutureEndTransfer().isSuccess()); - if (localChannelReference.getFutureEndTransfer().isSuccess()) { - // send a validation - localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); - EndRequestPacket validPacket = new EndRequestPacket(ErrorCode.CompleteOk.ordinal()); - if (localChannelReference.getSession().getExtendedProtocol() && - localChannelReference.getSession().getBusinessObject() != null && - localChannelReference.getSession().getBusinessObject().getInfo() != null - && localChannelReference.getSession().getBusinessObject().getInfo() != null) { - validPacket.setOptional(localChannelReference.getSession().getBusinessObject() - .getInfo()); - } - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); - } catch (OpenR66ProtocolPacketException e) { - } - if (!localChannelReference.getFutureRequest().awaitUninterruptibly( - Configuration.configuration.TIMEOUTCON)) { - // valid it however - localChannelReference.validateRequest(localChannelReference - .getFutureEndTransfer().getResult()); - } - if (taskRunner != null && taskRunner.isSelfRequested()) { - ChannelUtils.close(localChannelReference.getLocalChannel()); - } - } else { - transferInError(null); - } - } finally { - if (taskRunner != null) { - if ((future.isDone() && (!future.isSuccess())) || nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e) { - } - } - } - } - } - - /** - * To be used in case of error after a correct initiate of the request - * - * @param e - */ - public void transferInError(OpenR66Exception e) { - if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { - R66Result result = new R66Result(e, localChannelReference.getSession(), true, - ErrorCode.TransferError, taskRunner); - logger.error("Transfer in error", e); - localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket("Transfer in error", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e1) { - } - localChannelReference.invalidateRequest(result); - } - ChannelUtils.close(localChannelReference.getLocalChannel()); - } - - /** - * Write the next block when the channel is ready to prevent OOM - * - * @param block - * @return the ChannelFuture on the write operation - * - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolSystemException - */ - public ChannelFuture writeWhenPossible(DataBlock block) - throws OpenR66RunnerErrorException, OpenR66ProtocolPacketException, - OpenR66ProtocolSystemException { - return RetrieveRunner.writeWhenPossible(block, localChannelReference); - } - - /** - * Utility method for send through mode - * - * @param data - * the data byte, if null it is the last block - * @return the DataBlock associated to the data - */ - public DataBlock transformToDataBlock(byte[] data) { - DataBlock block = new DataBlock(); - if (data == null) { - // last block - block.setEOF(true); - } else { - block.setBlock(ChannelBuffers.wrappedBuffer(data)); - } - return block; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.ChannelFuture; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.RetrieveRunner; +import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Class for Send Through client + * + * This class does not included the real file transfer since it is up to the business project to + * implement how to read new data to be sent to the remote host. If an error occurs, no transfer log + * is kept. + * + * 1) Configuration must have been loaded
+ *
+ * 2) Pipeline and NetworkTransaction must have been initiated:
+ * Configuration.configuration.pipelineInit();
+ * NetworkTransaction networkTransaction = new NetworkTransaction();
+ *
+ * 3) Prepare the request of transfer:
+ * R66Future futureReq = new R66Future(true);
+ * SendThroughClient transaction = new SendThroughClient(futureReq,...);
+ * if (! transaction.initiateRequest()) { error }
+ *
+ * 4) Once initiateRequest() gives true, you are ready to send the data in through mode like:
+ * byte[] data = readOrGetInSomeWayData();
+ * DataBlock block = transaction.transformToDataBlock(data);
+ * futureWrite = transaction.writeWhenPossible(block);
+ *
+ * 5) Once you have finished, so this is the last block, you have to do the following:
+ * If the last block is not empty:
+ * DataBlock block = transaction.transformToDataBlock(data);
+ * block.setEOF(true);
+ * Or if the last block is empty:
+ * DataBlock block = transaction.transformToDataBlock(null);
+ * Then
+ * futureWrite = transaction.writeWhenPossible(block);
+ * futureWrite.awaitUninterruptibly();
+ *
+ * 6) If everything is in success:
+ * transaction.finalizeRequest();
+ *
+ * And now wait for the transfer to finish:
+ * futureReq.awaitUninterruptibly();
+ * R66Result result = futureReq.getResult();
+ *
+ * 7) If there is the need to re-do, just re-execute the steps from 3 to 6.
+ * Don't forget at the very end to finish the global structure (steps 3 to 6 no more executed):
+ * networkTransaction.closeAll();
+ *
+ * 8) In case of errors during steps 4 or 5 (and only those), call the following:
+ *
+ * transaction.transferInError(openR66Exception); + * + *
+ *
+ * + * @see TestSendThroughClient Class as example of usage in test part + * + * @author Frederic Bregier + * + */ +public abstract class SendThroughClient extends AbstractTransfer { + protected final NetworkTransaction networkTransaction; + protected LocalChannelReference localChannelReference; + protected DbTaskRunner taskRunner = null; + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + * @param id + */ + public SendThroughClient(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, long id, NetworkTransaction networkTransaction) { + super(SendThroughClient.class, + future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); + this.networkTransaction = networkTransaction; + } + + /** + * DO NOT CALL THIS! + */ + public void run() { + logger.error("DO NOT call this method for this class"); + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. Note that this is only + * the first part of the execution for this client. + * + * @return True if the initiate of the request is OK, else False + */ + public boolean initiateRequest() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(SendThroughClient.class); + } + DbRule rule; + try { + rule = new DbRule(DbConstant.admin.session, rulename); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Rule: " + rulename, e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; + } + int mode = rule.mode; + if (isMD5) { + mode = RequestPacket.getModeMD5(mode); + } + RequestPacket request = new RequestPacket(rulename, + mode, filename, blocksize, 0, + id, fileinfo, -1); + // Not isRecv since it is the requester, so send => isSender is true + boolean isSender = true; + try { + try { + // no starttime since immediate + taskRunner = + new DbTaskRunner(DbConstant.admin.session, rule, isSender, request, + remoteHost, null); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get task", e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; + } + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); + runner.setSendThroughMode(); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + localChannelReference = runner.initRequest(); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; + } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.error("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(exc); + return false; + } + try { + localChannelReference.waitReadyForSendThrough(); + } catch (OpenR66Exception e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } + // now start the send from external data + return true; + } finally { + if (taskRunner != null) { + if (future.isFailed()) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e) { + } + } + } + } + } + + /** + * Finalize the request + */ + public void finalizeRequest() { + try { + try { + ChannelUtils.writeEndTransfer(localChannelReference); + } catch (OpenR66ProtocolPacketException e) { + // An error occurs! + try { + localChannelReference.getSession().setFinalizeTransfer( + false, + new R66Result(e, localChannelReference.getSession(), false, + ErrorCode.Internal, taskRunner)); + } catch (OpenR66RunnerErrorException e1) { + transferInError(e1); + return; + } catch (OpenR66ProtocolSystemException e1) { + transferInError(e1); + return; + } + } + localChannelReference.getFutureEndTransfer().awaitUninterruptibly(); + logger.debug("Await future End Transfer done: " + + localChannelReference.getFutureEndTransfer().isSuccess()); + if (localChannelReference.getFutureEndTransfer().isSuccess()) { + // send a validation + localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); + EndRequestPacket validPacket = new EndRequestPacket(ErrorCode.CompleteOk.ordinal()); + if (localChannelReference.getSession().getExtendedProtocol() && + localChannelReference.getSession().getBusinessObject() != null && + localChannelReference.getSession().getBusinessObject().getInfo() != null + && localChannelReference.getSession().getBusinessObject().getInfo() != null) { + validPacket.setOptional(localChannelReference.getSession().getBusinessObject() + .getInfo()); + } + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); + } catch (OpenR66ProtocolPacketException e) { + } + if (!localChannelReference.getFutureRequest().awaitUninterruptibly( + Configuration.configuration.TIMEOUTCON)) { + // valid it however + localChannelReference.validateRequest(localChannelReference + .getFutureEndTransfer().getResult()); + } + if (taskRunner != null && taskRunner.isSelfRequested()) { + ChannelUtils.close(localChannelReference.getLocalChannel()); + } + } else { + transferInError(null); + } + } finally { + if (taskRunner != null) { + if ((future.isDone() && (!future.isSuccess())) || nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e) { + } + } + } + } + } + + /** + * To be used in case of error after a correct initiate of the request + * + * @param e + */ + public void transferInError(OpenR66Exception e) { + if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { + R66Result result = new R66Result(e, localChannelReference.getSession(), true, + ErrorCode.TransferError, taskRunner); + logger.error("Transfer in error", e); + localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket("Transfer in error", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e1) { + } + localChannelReference.invalidateRequest(result); + } + ChannelUtils.close(localChannelReference.getLocalChannel()); + } + + /** + * Write the next block when the channel is ready to prevent OOM + * + * @param block + * @return the ChannelFuture on the write operation + * + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolSystemException + */ + public ChannelFuture writeWhenPossible(DataBlock block) + throws OpenR66RunnerErrorException, OpenR66ProtocolPacketException, + OpenR66ProtocolSystemException { + return RetrieveRunner.writeWhenPossible(block, localChannelReference); + } + + /** + * Utility method for send through mode + * + * @param data + * the data byte, if null it is the last block + * @return the DataBlock associated to the data + */ + public DataBlock transformToDataBlock(byte[] data) { + DataBlock block = new DataBlock(); + if (data == null) { + // last block + block.setEOF(true); + } else { + block.setBlock(ChannelBuffers.wrappedBuffer(data)); + } + return block; + } +} diff --git a/src/main/java/org/waarp/openr66/client/SubmitTransfer.java b/src/main/java/org/waarp/openr66/client/SubmitTransfer.java index d8aea40b1..edb4e3eb7 100644 --- a/src/main/java/org/waarp/openr66/client/SubmitTransfer.java +++ b/src/main/java/org/waarp/openr66/client/SubmitTransfer.java @@ -1,137 +1,137 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.sql.Timestamp; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Client to submit a transfer - * - * @author Frederic Bregier - * - */ -public class SubmitTransfer extends AbstractTransfer { - - public SubmitTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - long id, - Timestamp starttime) { - super(SubmitTransfer.class, - future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, starttime); - } - - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); - } - long srcId = id; - DbTaskRunner taskRunner = this.initRequest(); - if (taskRunner == null) { - logger.debug("Cannot prepare task"); - R66Result result = new R66Result(new OpenR66DatabaseGlobalException(), null, true, - ErrorCode.Internal, taskRunner); - future.setResult(result); - future.setFailure(result.exception); - return; - } - if (srcId != DbConstant.ILLEGALVALUE) { - // Resubmit call, some checks are needed - if (! taskRunner.restart(true)) { - // cannot be done from there => must be done through IHM - logger.debug("Cannot prepare task from there. IHM must be used"); - R66Result result = new R66Result( - new OpenR66DatabaseGlobalException("Cannot prepare task from there. IHM must be used"), - null, true, - ErrorCode.Internal, taskRunner); - future.setResult(result); - future.setFailure(result.exception); - return; - } - } else { - taskRunner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.TOSUBMIT); - } - if (!taskRunner.forceSaveStatus()) { - logger.debug("Cannot prepare task"); - R66Result result = new R66Result(new OpenR66DatabaseGlobalException("Cannot prepare Task"), null, true, - ErrorCode.Internal, taskRunner); - future.setResult(result); - future.setFailure(result.exception); - return; - } - R66Result result = new R66Result(null, false, ErrorCode.InitOk, taskRunner); - future.setResult(result); - future.setSuccess(); - } - - /** - * - * @param args - * configuration file, the remoteHost Id, the file to transfer, the rule, file - * transfer information as arguments and optionally isMD5=1 for true or 0 for - * false(default) and the blocksize if different than default - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); - } - if (!getParams(args, true)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - } - R66Future future = new R66Future(true); - SubmitTransfer transaction = new SubmitTransfer(future, - rhost, localFilename, rule, fileInfo, ismd5, block, idt, - ttimestart); - transaction.run(); - future.awaitUninterruptibly(); - DbTaskRunner runner = future.getResult().runner; - if (future.isSuccess()) { - logger.warn("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + - "" + rhost + ""); - } else { - if (runner != null) { - logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + - "" + rhost + "", future.getCause()); - } else { - logger.error("Prepare transfer in\n FAILURE\n ", future.getCause()); - } - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(future.getResult().code.ordinal()); - } - DbConstant.admin.close(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.sql.Timestamp; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Client to submit a transfer + * + * @author Frederic Bregier + * + */ +public class SubmitTransfer extends AbstractTransfer { + + public SubmitTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, + long id, + Timestamp starttime) { + super(SubmitTransfer.class, + future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, starttime); + } + + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); + } + long srcId = id; + DbTaskRunner taskRunner = this.initRequest(); + if (taskRunner == null) { + logger.debug("Cannot prepare task"); + R66Result result = new R66Result(new OpenR66DatabaseGlobalException(), null, true, + ErrorCode.Internal, taskRunner); + future.setResult(result); + future.setFailure(result.exception); + return; + } + if (srcId != DbConstant.ILLEGALVALUE) { + // Resubmit call, some checks are needed + if (! taskRunner.restart(true)) { + // cannot be done from there => must be done through IHM + logger.debug("Cannot prepare task from there. IHM must be used"); + R66Result result = new R66Result( + new OpenR66DatabaseGlobalException("Cannot prepare task from there. IHM must be used"), + null, true, + ErrorCode.Internal, taskRunner); + future.setResult(result); + future.setFailure(result.exception); + return; + } + } else { + taskRunner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.TOSUBMIT); + } + if (!taskRunner.forceSaveStatus()) { + logger.debug("Cannot prepare task"); + R66Result result = new R66Result(new OpenR66DatabaseGlobalException("Cannot prepare Task"), null, true, + ErrorCode.Internal, taskRunner); + future.setResult(result); + future.setFailure(result.exception); + return; + } + R66Result result = new R66Result(null, false, ErrorCode.InitOk, taskRunner); + future.setResult(result); + future.setSuccess(); + } + + /** + * + * @param args + * configuration file, the remoteHost Id, the file to transfer, the rule, file + * transfer information as arguments and optionally isMD5=1 for true or 0 for + * false(default) and the blocksize if different than default + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); + } + if (!getParams(args, true)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + } + R66Future future = new R66Future(true); + SubmitTransfer transaction = new SubmitTransfer(future, + rhost, localFilename, rule, fileInfo, ismd5, block, idt, + ttimestart); + transaction.run(); + future.awaitUninterruptibly(); + DbTaskRunner runner = future.getResult().runner; + if (future.isSuccess()) { + logger.warn("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + + "" + rhost + ""); + } else { + if (runner != null) { + logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + + "" + rhost + "", future.getCause()); + } else { + logger.error("Prepare transfer in\n FAILURE\n ", future.getCause()); + } + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(future.getResult().code.ordinal()); + } + DbConstant.admin.close(); + } + +} diff --git a/src/main/java/org/waarp/openr66/client/package-info.java b/src/main/java/org/waarp/openr66/client/package-info.java index 011b3ae08..bfd59120c 100644 --- a/src/main/java/org/waarp/openr66/client/package-info.java +++ b/src/main/java/org/waarp/openr66/client/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Clients - * - * @apiviz.landmark - */ -package org.waarp.openr66.client; - +/** + * Classes implementing Clients + * + * @apiviz.landmark + */ +package org.waarp.openr66.client; + diff --git a/src/main/java/org/waarp/openr66/commander/ClientRunner.java b/src/main/java/org/waarp/openr66/commander/ClientRunner.java index 108e77345..86da88389 100644 --- a/src/main/java/org/waarp/openr66/commander/ClientRunner.java +++ b/src/main/java/org/waarp/openr66/commander/ClientRunner.java @@ -1,600 +1,600 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp. If not, see - * . - */ -package org.waarp.openr66.commander; - -import java.net.SocketAddress; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.jboss.netty.channel.Channels; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.RecvThroughHandler; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; -import org.waarp.openr66.protocol.utils.TransferUtils; - -/** - * Client Runner from a TaskRunner - * - * @author Frederic Bregier - * - */ -public class ClientRunner extends Thread { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ClientRunner.class); - - private static final ConcurrentHashMap taskRunnerRetryHashMap = new ConcurrentHashMap(); - - public static ConcurrentLinkedQueue activeRunners = null; - - private final NetworkTransaction networkTransaction; - - private final DbTaskRunner taskRunner; - - private final R66Future futureRequest; - - private RecvThroughHandler handler = null; - - private boolean isSendThroughMode = false; - - private LocalChannelReference localChannelReference = null; - - public ClientRunner(NetworkTransaction networkTransaction, - DbTaskRunner taskRunner, R66Future futureRequest) { - this.networkTransaction = networkTransaction; - this.taskRunner = taskRunner; - this.futureRequest = futureRequest; - } - - /** - * @return the networkTransaction - */ - public NetworkTransaction getNetworkTransaction() { - return networkTransaction; - } - - /** - * @return the taskRunner - */ - public DbTaskRunner getTaskRunner() { - return taskRunner; - } - - /** - * @return the localChannelReference - */ - public LocalChannelReference getLocalChannelReference() { - return localChannelReference; - } - - /* - * (non-Javadoc) - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - if (Configuration.configuration.isShutdown) { - taskRunner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - taskRunner.forceSaveStatus(); - return; - } - try { - if (activeRunners != null) { - activeRunners.add(this); - } - // fix for SelfRequest - if (taskRunner.isSelfRequest()) { - taskRunner.setSenderByRequestToValidate(false); - } - R66Future transfer; - try { - transfer = this.runTransfer(); - } catch (OpenR66RunnerErrorException e) { - logger.error("Runner Error: {} {}", e.getMessage(), - taskRunner.toShortString()); - return; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("No connection Error {}", e.getMessage()); - if (localChannelReference != null) { - localChannelReference.setErrorMessage( - ErrorCode.ConnectionImpossible.mesg, - ErrorCode.ConnectionImpossible); - } - taskRunner.setErrorTask(localChannelReference); - try { - taskRunner.forceSaveStatus(); - taskRunner.run(); - } catch (OpenR66RunnerErrorException e1) { - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ConnectionImpossible, true); - } - return; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Protocol Error", e); - return; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.warn("No connection warning {}", e.getMessage()); - return; - } - R66Result result = transfer.getResult(); - if (result != null) { - if (result.code == ErrorCode.QueryAlreadyFinished) { - logger.warn("TRANSFER RESULT:\n " + - (transfer.isSuccess() ? "SUCCESS" : "FAILURE") + - "\n " + ErrorCode.QueryAlreadyFinished.mesg + - ":" + - (result != null ? result.toString() : "no result")); - } else { - if (transfer.isSuccess()) { - logger.info("TRANSFER RESULT:\n SUCCESS\n " + - (result != null ? result.toString() - : "no result")); - } else { - logger.error("TRANSFER RESULT:\n FAILURE\n " + - (result != null ? result.toString() - : "no result")); - } - } - } else { - if (transfer.isSuccess()) { - logger.warn("TRANSFER REQUESTED RESULT:\n SUCCESS\n no result"); - } else { - logger.error("TRANSFER REQUESTED RESULT:\n FAILURE\n no result"); - } - } - transfer = null; - Thread.currentThread().setName( - "Finished_" + Thread.currentThread().getName()); - } finally { - if (activeRunners != null) { - activeRunners.remove(this); - } - } - } - - /** - * - * @param runner - * @param limit - * @return True if the task was run less than limit, else False - */ - public boolean incrementTaskRunerTry(DbTaskRunner runner, int limit) { - String key = runner.getKey(); - Integer tries = taskRunnerRetryHashMap.get(key); - logger.debug("try to find integer: " + tries); - if (tries == null) { - tries = new Integer(1); - } else { - tries = tries + 1; - } - if (limit <= tries) { - taskRunnerRetryHashMap.remove(key); - return false; - } else { - taskRunnerRetryHashMap.put(key, tries); - return true; - } - } - - /** - * True transfer run (can be called directly to enable exception outside any executors) - * - * @return The R66Future of the transfer operation - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolNoConnectionException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolNotYetConnectionException - */ - public R66Future runTransfer() throws OpenR66RunnerErrorException, - OpenR66ProtocolNoConnectionException, - OpenR66ProtocolPacketException, - OpenR66ProtocolNotYetConnectionException { - logger.debug("Start attempt Transfer"); - localChannelReference = initRequest(); - try { - localChannelReference.getFutureValidRequest().await(); - } catch (InterruptedException e) { - } - if (localChannelReference.getFutureValidRequest().isSuccess()) { - return finishTransfer(true, localChannelReference); - } else if (localChannelReference.getFutureValidRequest().getResult().code == ErrorCode.ServerOverloaded) { - return tryAgainTransferOnOverloaded(true, localChannelReference); - } else - return finishTransfer(true, localChannelReference); - } - - /** - * In case an overloaded signal is returned by the requested - * - * @param retry - * if True, it will retry in case of overloaded remote server, else it just stops - * @param localChannelReference - * @return The R66Future of the transfer operation - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolNoConnectionException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolNotYetConnectionException - */ - public R66Future tryAgainTransferOnOverloaded(boolean retry, - LocalChannelReference localChannelReference) - throws OpenR66RunnerErrorException, - OpenR66ProtocolNoConnectionException, - OpenR66ProtocolPacketException, - OpenR66ProtocolNotYetConnectionException { - if (this.localChannelReference == null) { - this.localChannelReference = localChannelReference; - } - boolean incRetry = incrementTaskRunerTry(taskRunner, - Configuration.RETRYNB); - logger.debug("tryAgainTransferOnOverloaded: " + retry + ":" + incRetry); - switch (taskRunner.getUpdatedInfo()) { - case DONE: - case INERROR: - case INTERRUPTED: - break; - default: - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ServerOverloaded, true); - } - // redo if possible - if (retry && incRetry) { - try { - Thread.sleep(Configuration.configuration.constraintLimitHandler - .getSleepTime()); - } catch (InterruptedException e) { - } - return runTransfer(); - } else { - if (localChannelReference == null) { - taskRunner - .setLocalChannelReference(new LocalChannelReference()); - } - taskRunner.getLocalChannelReference().setErrorMessage( - ErrorCode.ConnectionImpossible.mesg, - ErrorCode.ConnectionImpossible); - this.taskRunner.setErrorTask(localChannelReference); - this.taskRunner.run(); - throw new OpenR66ProtocolNoConnectionException( - "End of retry on ServerOverloaded"); - } - } - - /** - * Finish the transfer (called at the end of runTransfer) - * - * @param retry - * if True, it will retry in case of overloaded remote server, else it just stops - * @param localChannelReference - * @return The R66Future of the transfer operation - * @throws OpenR66ProtocolNotYetConnectionException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolNoConnectionException - * @throws OpenR66RunnerErrorException - */ - public R66Future finishTransfer(boolean retry, - LocalChannelReference localChannelReference) - throws OpenR66RunnerErrorException { - if (this.localChannelReference == null) { - this.localChannelReference = localChannelReference; - } - R66Future transfer = localChannelReference.getFutureRequest(); - try { - transfer.await(); - } catch (InterruptedException e1) { - } - taskRunnerRetryHashMap.remove(taskRunner.getKey()); - logger.info("Request done with {}", (transfer.isSuccess() ? "success" - : "error")); - Channels.close(localChannelReference.getLocalChannel()); - // now reload TaskRunner if it still exists (light client can forget it) - boolean isSender = taskRunner.isSender(); - if (transfer.isSuccess()) { - try { - taskRunner.select(); - } catch (WaarpDatabaseException e) { - logger.debug("Not a problem but cannot find at the end the task"); - taskRunner.setFrom(transfer.runner); - } - taskRunner.setSender(isSender); - this.changeUpdatedInfo(UpdatedInfo.DONE, ErrorCode.CompleteOk, false); - } else { - try { - taskRunner.select(); - } catch (WaarpDatabaseException e) { - logger.debug("Not a problem but cannot find at the end the task"); - taskRunner.setFrom(transfer.runner); - } - taskRunner.setSender(isSender); - // Case when we were interrupted - if (transfer.getResult() == null) { - switch (taskRunner.getUpdatedInfo()) { - case DONE: - R66Result ok = new R66Result(null, true, - ErrorCode.CompleteOk, taskRunner); - transfer.setResult(ok); - transfer.setSuccess(); - this.changeUpdatedInfo(UpdatedInfo.DONE, - ErrorCode.CompleteOk, false); - break; - case INERROR: - case INTERRUPTED: - default: - R66Result error = new R66Result(null, true, - ErrorCode.Internal, taskRunner); - transfer.setResult(error); - transfer.cancel(); - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.Internal, false); - } - return transfer; - } - if (transfer.getResult().code == ErrorCode.QueryAlreadyFinished) { - // check if post task to execute - logger.warn("WARN QueryAlreadyFinished:\n " + - transfer.toString() + "\n " + - taskRunner.toShortString()); - try { - TransferUtils.finalizeTaskWithNoSession(taskRunner, - localChannelReference); - } catch (OpenR66RunnerErrorException e) { - this.taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); - this.taskRunner.forceSaveStatus(); - } - } else { - switch (taskRunner.getUpdatedInfo()) { - case DONE: - case INERROR: - case INTERRUPTED: - case TOSUBMIT: - break; - default: - this.changeUpdatedInfo(UpdatedInfo.INERROR, - transfer.getResult().code, false); - } - } - } - return transfer; - } - - /** - * Initialize the request - * - * @return the localChannelReference holding the transfer request - * @throws OpenR66ProtocolNoConnectionException - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolNotYetConnectionException - */ - public LocalChannelReference initRequest() - throws OpenR66ProtocolNoConnectionException, - OpenR66RunnerErrorException, OpenR66ProtocolPacketException, - OpenR66ProtocolNotYetConnectionException { - this.changeUpdatedInfo(UpdatedInfo.RUNNING, ErrorCode.Running, true); - long id = taskRunner.getSpecialId(); - String tid; - if (id == DbConstant.ILLEGALVALUE) { - tid = taskRunner.getRuleId() + "_" + taskRunner.getMode() + - "_NEWTRANSFER"; - } else { - tid = taskRunner.getRuleId() + "_" + taskRunner.getMode() + "_" + - id; - } - Thread.currentThread().setName(tid); - logger.debug("Will run {}", this.taskRunner); - boolean restartPost = false; - if (taskRunner.getGloballaststep() == TASKSTEP.POSTTASK.ordinal()) { - // Send a validation to requested - if (!taskRunner.isSelfRequested()) { - // restart - restartPost = true; - } - } - if (taskRunner.isSelfRequested()) { - // Don't have to restart a task for itself (or should use requester) - logger.warn("Requested host cannot initiate itself the request"); - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.LoopSelfRequestedHost, true); - throw new OpenR66ProtocolNoConnectionException( - "Requested host cannot initiate itself the request"); - } - DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, - taskRunner.getRequested()); - if (host == null) { - logger.error("Requested host cannot be found: " + - taskRunner.getRequested()); - this.changeUpdatedInfo(UpdatedInfo.INERROR, ErrorCode.NotKnownHost, true); - throw new OpenR66ProtocolNoConnectionException( - "Requested host cannot be found " + - taskRunner.getRequested()); - } - if (host.isClient()) { - logger.debug("Cannot initiate a connection with a client: {}", host); - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ConnectionImpossible, true); - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to client " + host.toString()); - } - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, futureRequest); - taskRunner.setLocalChannelReference(localChannelReference); - socketAddress = null; - if (localChannelReference == null) { - // propose to redo - // See if reprogramming is ok (not too many tries) - String retry; - if (incrementTaskRunerTry(taskRunner, Configuration.RETRYNB)) { - logger.debug("Will retry since Cannot connect to {}", host); - retry = " but will retry"; - // now wait - try { - Thread.sleep(Configuration.configuration.delayRetry); - } catch (InterruptedException e) { - logger.debug( - "Will not retry since limit of connection attemtps is reached for {}", - host); - retry = " and retries limit is reached so stop here"; - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ConnectionImpossible, true); - taskRunner - .setLocalChannelReference(new LocalChannelReference()); - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to server " + host.toString() + retry); - } - this.changeUpdatedInfo(UpdatedInfo.TOSUBMIT, - ErrorCode.ConnectionImpossible, true); - throw new OpenR66ProtocolNotYetConnectionException( - "Cannot connect to server " + host.toString() + retry); - } else { - logger.debug( - "Will not retry since limit of connection attemtps is reached for {}", - host); - retry = " and retries limit is reached so stop here"; - this.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ConnectionImpossible, true); - taskRunner - .setLocalChannelReference(new LocalChannelReference()); - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to server " + host.toString() + retry); - } - } - if (handler != null) { - localChannelReference.setRecvThroughHandler(handler); - } - localChannelReference.setSendThroughMode(isSendThroughMode); - if (restartPost) { - RequestPacket request = taskRunner.getRequest(); - logger.debug("Will send request {} ", request); - localChannelReference.setClientRunner(this); - localChannelReference.sessionNewState(R66FiniteDualStates.REQUESTR); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - request, false); - } catch (OpenR66ProtocolPacketException e) { - // propose to redo - logger.warn("Cannot transfer request to " + host.toString()); - this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED, - ErrorCode.Internal, true); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - host = null; - request = null; - throw e; - } - logger.debug("Wait for request to {}", host); - request = null; - host = null; - return localChannelReference; - } - // If Requester is NOT Sender, and if TransferTask then decrease now if - // possible the rank - if (!taskRunner.isSender() && - (taskRunner.getGloballaststep() == TASKSTEP.TRANSFERTASK - .ordinal())) { - logger.debug( - "Requester is not Sender so decrease if possible the rank {}", - taskRunner); - taskRunner.restartRank(); - taskRunner.forceSaveStatus(); - logger.debug( - "Requester is not Sender so new rank is " + - taskRunner.getRank() + " {}", taskRunner); - } - RequestPacket request = taskRunner.getRequest(); - logger.debug("Will send request {} {}", request, localChannelReference); - localChannelReference.setClientRunner(this); - localChannelReference.sessionNewState(R66FiniteDualStates.REQUESTR); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - request, false); - } catch (OpenR66ProtocolPacketException e) { - // propose to redo - logger.warn("Cannot transfer request to " + host.toString()); - this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED, ErrorCode.Internal, true); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - host = null; - request = null; - throw e; - } - logger.debug("Wait for request to {}", host); - request = null; - host = null; - return localChannelReference; - } - - /** - * Change the UpdatedInfo of the current runner - * - * @param info - */ - public void changeUpdatedInfo(AbstractDbData.UpdatedInfo info, - ErrorCode code, boolean force) { - this.taskRunner.changeUpdatedInfo(info); - this.taskRunner.setErrorExecutionStatus(code); - if (force) { - this.taskRunner.forceSaveStatus(); - } else { - try { - this.taskRunner.saveStatus(); - } catch (OpenR66RunnerErrorException e) { - } - } - } - - /** - * @param handler - * the handler to set - */ - public void setRecvThroughHandler(RecvThroughHandler handler) { - this.handler = handler; - } - - public void setSendThroughMode() { - isSendThroughMode = true; - } - - public boolean getSendThroughMode() { - return isSendThroughMode; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp. If not, see + * . + */ +package org.waarp.openr66.commander; + +import java.net.SocketAddress; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.jboss.netty.channel.Channels; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.RecvThroughHandler; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.openr66.protocol.utils.TransferUtils; + +/** + * Client Runner from a TaskRunner + * + * @author Frederic Bregier + * + */ +public class ClientRunner extends Thread { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ClientRunner.class); + + private static final ConcurrentHashMap taskRunnerRetryHashMap = new ConcurrentHashMap(); + + public static ConcurrentLinkedQueue activeRunners = null; + + private final NetworkTransaction networkTransaction; + + private final DbTaskRunner taskRunner; + + private final R66Future futureRequest; + + private RecvThroughHandler handler = null; + + private boolean isSendThroughMode = false; + + private LocalChannelReference localChannelReference = null; + + public ClientRunner(NetworkTransaction networkTransaction, + DbTaskRunner taskRunner, R66Future futureRequest) { + this.networkTransaction = networkTransaction; + this.taskRunner = taskRunner; + this.futureRequest = futureRequest; + } + + /** + * @return the networkTransaction + */ + public NetworkTransaction getNetworkTransaction() { + return networkTransaction; + } + + /** + * @return the taskRunner + */ + public DbTaskRunner getTaskRunner() { + return taskRunner; + } + + /** + * @return the localChannelReference + */ + public LocalChannelReference getLocalChannelReference() { + return localChannelReference; + } + + /* + * (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + if (Configuration.configuration.isShutdown) { + taskRunner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + taskRunner.forceSaveStatus(); + return; + } + try { + if (activeRunners != null) { + activeRunners.add(this); + } + // fix for SelfRequest + if (taskRunner.isSelfRequest()) { + taskRunner.setSenderByRequestToValidate(false); + } + R66Future transfer; + try { + transfer = this.runTransfer(); + } catch (OpenR66RunnerErrorException e) { + logger.error("Runner Error: {} {}", e.getMessage(), + taskRunner.toShortString()); + return; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("No connection Error {}", e.getMessage()); + if (localChannelReference != null) { + localChannelReference.setErrorMessage( + ErrorCode.ConnectionImpossible.mesg, + ErrorCode.ConnectionImpossible); + } + taskRunner.setErrorTask(localChannelReference); + try { + taskRunner.forceSaveStatus(); + taskRunner.run(); + } catch (OpenR66RunnerErrorException e1) { + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ConnectionImpossible, true); + } + return; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Protocol Error", e); + return; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.warn("No connection warning {}", e.getMessage()); + return; + } + R66Result result = transfer.getResult(); + if (result != null) { + if (result.code == ErrorCode.QueryAlreadyFinished) { + logger.warn("TRANSFER RESULT:\n " + + (transfer.isSuccess() ? "SUCCESS" : "FAILURE") + + "\n " + ErrorCode.QueryAlreadyFinished.mesg + + ":" + + (result != null ? result.toString() : "no result")); + } else { + if (transfer.isSuccess()) { + logger.info("TRANSFER RESULT:\n SUCCESS\n " + + (result != null ? result.toString() + : "no result")); + } else { + logger.error("TRANSFER RESULT:\n FAILURE\n " + + (result != null ? result.toString() + : "no result")); + } + } + } else { + if (transfer.isSuccess()) { + logger.warn("TRANSFER REQUESTED RESULT:\n SUCCESS\n no result"); + } else { + logger.error("TRANSFER REQUESTED RESULT:\n FAILURE\n no result"); + } + } + transfer = null; + Thread.currentThread().setName( + "Finished_" + Thread.currentThread().getName()); + } finally { + if (activeRunners != null) { + activeRunners.remove(this); + } + } + } + + /** + * + * @param runner + * @param limit + * @return True if the task was run less than limit, else False + */ + public boolean incrementTaskRunerTry(DbTaskRunner runner, int limit) { + String key = runner.getKey(); + Integer tries = taskRunnerRetryHashMap.get(key); + logger.debug("try to find integer: " + tries); + if (tries == null) { + tries = new Integer(1); + } else { + tries = tries + 1; + } + if (limit <= tries) { + taskRunnerRetryHashMap.remove(key); + return false; + } else { + taskRunnerRetryHashMap.put(key, tries); + return true; + } + } + + /** + * True transfer run (can be called directly to enable exception outside any executors) + * + * @return The R66Future of the transfer operation + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolNoConnectionException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolNotYetConnectionException + */ + public R66Future runTransfer() throws OpenR66RunnerErrorException, + OpenR66ProtocolNoConnectionException, + OpenR66ProtocolPacketException, + OpenR66ProtocolNotYetConnectionException { + logger.debug("Start attempt Transfer"); + localChannelReference = initRequest(); + try { + localChannelReference.getFutureValidRequest().await(); + } catch (InterruptedException e) { + } + if (localChannelReference.getFutureValidRequest().isSuccess()) { + return finishTransfer(true, localChannelReference); + } else if (localChannelReference.getFutureValidRequest().getResult().code == ErrorCode.ServerOverloaded) { + return tryAgainTransferOnOverloaded(true, localChannelReference); + } else + return finishTransfer(true, localChannelReference); + } + + /** + * In case an overloaded signal is returned by the requested + * + * @param retry + * if True, it will retry in case of overloaded remote server, else it just stops + * @param localChannelReference + * @return The R66Future of the transfer operation + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolNoConnectionException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolNotYetConnectionException + */ + public R66Future tryAgainTransferOnOverloaded(boolean retry, + LocalChannelReference localChannelReference) + throws OpenR66RunnerErrorException, + OpenR66ProtocolNoConnectionException, + OpenR66ProtocolPacketException, + OpenR66ProtocolNotYetConnectionException { + if (this.localChannelReference == null) { + this.localChannelReference = localChannelReference; + } + boolean incRetry = incrementTaskRunerTry(taskRunner, + Configuration.RETRYNB); + logger.debug("tryAgainTransferOnOverloaded: " + retry + ":" + incRetry); + switch (taskRunner.getUpdatedInfo()) { + case DONE: + case INERROR: + case INTERRUPTED: + break; + default: + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ServerOverloaded, true); + } + // redo if possible + if (retry && incRetry) { + try { + Thread.sleep(Configuration.configuration.constraintLimitHandler + .getSleepTime()); + } catch (InterruptedException e) { + } + return runTransfer(); + } else { + if (localChannelReference == null) { + taskRunner + .setLocalChannelReference(new LocalChannelReference()); + } + taskRunner.getLocalChannelReference().setErrorMessage( + ErrorCode.ConnectionImpossible.mesg, + ErrorCode.ConnectionImpossible); + this.taskRunner.setErrorTask(localChannelReference); + this.taskRunner.run(); + throw new OpenR66ProtocolNoConnectionException( + "End of retry on ServerOverloaded"); + } + } + + /** + * Finish the transfer (called at the end of runTransfer) + * + * @param retry + * if True, it will retry in case of overloaded remote server, else it just stops + * @param localChannelReference + * @return The R66Future of the transfer operation + * @throws OpenR66ProtocolNotYetConnectionException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolNoConnectionException + * @throws OpenR66RunnerErrorException + */ + public R66Future finishTransfer(boolean retry, + LocalChannelReference localChannelReference) + throws OpenR66RunnerErrorException { + if (this.localChannelReference == null) { + this.localChannelReference = localChannelReference; + } + R66Future transfer = localChannelReference.getFutureRequest(); + try { + transfer.await(); + } catch (InterruptedException e1) { + } + taskRunnerRetryHashMap.remove(taskRunner.getKey()); + logger.info("Request done with {}", (transfer.isSuccess() ? "success" + : "error")); + Channels.close(localChannelReference.getLocalChannel()); + // now reload TaskRunner if it still exists (light client can forget it) + boolean isSender = taskRunner.isSender(); + if (transfer.isSuccess()) { + try { + taskRunner.select(); + } catch (WaarpDatabaseException e) { + logger.debug("Not a problem but cannot find at the end the task"); + taskRunner.setFrom(transfer.runner); + } + taskRunner.setSender(isSender); + this.changeUpdatedInfo(UpdatedInfo.DONE, ErrorCode.CompleteOk, false); + } else { + try { + taskRunner.select(); + } catch (WaarpDatabaseException e) { + logger.debug("Not a problem but cannot find at the end the task"); + taskRunner.setFrom(transfer.runner); + } + taskRunner.setSender(isSender); + // Case when we were interrupted + if (transfer.getResult() == null) { + switch (taskRunner.getUpdatedInfo()) { + case DONE: + R66Result ok = new R66Result(null, true, + ErrorCode.CompleteOk, taskRunner); + transfer.setResult(ok); + transfer.setSuccess(); + this.changeUpdatedInfo(UpdatedInfo.DONE, + ErrorCode.CompleteOk, false); + break; + case INERROR: + case INTERRUPTED: + default: + R66Result error = new R66Result(null, true, + ErrorCode.Internal, taskRunner); + transfer.setResult(error); + transfer.cancel(); + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.Internal, false); + } + return transfer; + } + if (transfer.getResult().code == ErrorCode.QueryAlreadyFinished) { + // check if post task to execute + logger.warn("WARN QueryAlreadyFinished:\n " + + transfer.toString() + "\n " + + taskRunner.toShortString()); + try { + TransferUtils.finalizeTaskWithNoSession(taskRunner, + localChannelReference); + } catch (OpenR66RunnerErrorException e) { + this.taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); + this.taskRunner.forceSaveStatus(); + } + } else { + switch (taskRunner.getUpdatedInfo()) { + case DONE: + case INERROR: + case INTERRUPTED: + case TOSUBMIT: + break; + default: + this.changeUpdatedInfo(UpdatedInfo.INERROR, + transfer.getResult().code, false); + } + } + } + return transfer; + } + + /** + * Initialize the request + * + * @return the localChannelReference holding the transfer request + * @throws OpenR66ProtocolNoConnectionException + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolNotYetConnectionException + */ + public LocalChannelReference initRequest() + throws OpenR66ProtocolNoConnectionException, + OpenR66RunnerErrorException, OpenR66ProtocolPacketException, + OpenR66ProtocolNotYetConnectionException { + this.changeUpdatedInfo(UpdatedInfo.RUNNING, ErrorCode.Running, true); + long id = taskRunner.getSpecialId(); + String tid; + if (id == DbConstant.ILLEGALVALUE) { + tid = taskRunner.getRuleId() + "_" + taskRunner.getMode() + + "_NEWTRANSFER"; + } else { + tid = taskRunner.getRuleId() + "_" + taskRunner.getMode() + "_" + + id; + } + Thread.currentThread().setName(tid); + logger.debug("Will run {}", this.taskRunner); + boolean restartPost = false; + if (taskRunner.getGloballaststep() == TASKSTEP.POSTTASK.ordinal()) { + // Send a validation to requested + if (!taskRunner.isSelfRequested()) { + // restart + restartPost = true; + } + } + if (taskRunner.isSelfRequested()) { + // Don't have to restart a task for itself (or should use requester) + logger.warn("Requested host cannot initiate itself the request"); + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.LoopSelfRequestedHost, true); + throw new OpenR66ProtocolNoConnectionException( + "Requested host cannot initiate itself the request"); + } + DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, + taskRunner.getRequested()); + if (host == null) { + logger.error("Requested host cannot be found: " + + taskRunner.getRequested()); + this.changeUpdatedInfo(UpdatedInfo.INERROR, ErrorCode.NotKnownHost, true); + throw new OpenR66ProtocolNoConnectionException( + "Requested host cannot be found " + + taskRunner.getRequested()); + } + if (host.isClient()) { + logger.debug("Cannot initiate a connection with a client: {}", host); + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ConnectionImpossible, true); + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to client " + host.toString()); + } + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, futureRequest); + taskRunner.setLocalChannelReference(localChannelReference); + socketAddress = null; + if (localChannelReference == null) { + // propose to redo + // See if reprogramming is ok (not too many tries) + String retry; + if (incrementTaskRunerTry(taskRunner, Configuration.RETRYNB)) { + logger.debug("Will retry since Cannot connect to {}", host); + retry = " but will retry"; + // now wait + try { + Thread.sleep(Configuration.configuration.delayRetry); + } catch (InterruptedException e) { + logger.debug( + "Will not retry since limit of connection attemtps is reached for {}", + host); + retry = " and retries limit is reached so stop here"; + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ConnectionImpossible, true); + taskRunner + .setLocalChannelReference(new LocalChannelReference()); + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to server " + host.toString() + retry); + } + this.changeUpdatedInfo(UpdatedInfo.TOSUBMIT, + ErrorCode.ConnectionImpossible, true); + throw new OpenR66ProtocolNotYetConnectionException( + "Cannot connect to server " + host.toString() + retry); + } else { + logger.debug( + "Will not retry since limit of connection attemtps is reached for {}", + host); + retry = " and retries limit is reached so stop here"; + this.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ConnectionImpossible, true); + taskRunner + .setLocalChannelReference(new LocalChannelReference()); + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to server " + host.toString() + retry); + } + } + if (handler != null) { + localChannelReference.setRecvThroughHandler(handler); + } + localChannelReference.setSendThroughMode(isSendThroughMode); + if (restartPost) { + RequestPacket request = taskRunner.getRequest(); + logger.debug("Will send request {} ", request); + localChannelReference.setClientRunner(this); + localChannelReference.sessionNewState(R66FiniteDualStates.REQUESTR); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + request, false); + } catch (OpenR66ProtocolPacketException e) { + // propose to redo + logger.warn("Cannot transfer request to " + host.toString()); + this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED, + ErrorCode.Internal, true); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + host = null; + request = null; + throw e; + } + logger.debug("Wait for request to {}", host); + request = null; + host = null; + return localChannelReference; + } + // If Requester is NOT Sender, and if TransferTask then decrease now if + // possible the rank + if (!taskRunner.isSender() && + (taskRunner.getGloballaststep() == TASKSTEP.TRANSFERTASK + .ordinal())) { + logger.debug( + "Requester is not Sender so decrease if possible the rank {}", + taskRunner); + taskRunner.restartRank(); + taskRunner.forceSaveStatus(); + logger.debug( + "Requester is not Sender so new rank is " + + taskRunner.getRank() + " {}", taskRunner); + } + RequestPacket request = taskRunner.getRequest(); + logger.debug("Will send request {} {}", request, localChannelReference); + localChannelReference.setClientRunner(this); + localChannelReference.sessionNewState(R66FiniteDualStates.REQUESTR); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + request, false); + } catch (OpenR66ProtocolPacketException e) { + // propose to redo + logger.warn("Cannot transfer request to " + host.toString()); + this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED, ErrorCode.Internal, true); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + host = null; + request = null; + throw e; + } + logger.debug("Wait for request to {}", host); + request = null; + host = null; + return localChannelReference; + } + + /** + * Change the UpdatedInfo of the current runner + * + * @param info + */ + public void changeUpdatedInfo(AbstractDbData.UpdatedInfo info, + ErrorCode code, boolean force) { + this.taskRunner.changeUpdatedInfo(info); + this.taskRunner.setErrorExecutionStatus(code); + if (force) { + this.taskRunner.forceSaveStatus(); + } else { + try { + this.taskRunner.saveStatus(); + } catch (OpenR66RunnerErrorException e) { + } + } + } + + /** + * @param handler + * the handler to set + */ + public void setRecvThroughHandler(RecvThroughHandler handler) { + this.handler = handler; + } + + public void setSendThroughMode() { + isSendThroughMode = true; + } + + public boolean getSendThroughMode() { + return isSendThroughMode; + } +} diff --git a/src/main/java/org/waarp/openr66/commander/Commander.java b/src/main/java/org/waarp/openr66/commander/Commander.java index 386b714f5..f3f36e4d1 100644 --- a/src/main/java/org/waarp/openr66/commander/Commander.java +++ b/src/main/java/org/waarp/openr66/commander/Commander.java @@ -1,526 +1,526 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.commander; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.database.model.DbModelFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.data.DbMultipleMonitor; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; - -/** - * Commander is responsible to read from database updated data from time to time in order to achieve - * new runner or new configuration updates. - * - * @author Frederic Bregier - * - */ -public class Commander implements CommanderInterface { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(Commander.class); - - private static final int LIMITSUBMIT = 100; - - private InternalRunner internalRunner = null; - private DbPreparedStatement preparedStatementLock = null; - private DbPreparedStatement preparedStatementConfig = null; - private DbPreparedStatement preparedStatementHostConfig = null; - private DbPreparedStatement preparedStatementHost = null; - private DbPreparedStatement preparedStatementRule = null; - private DbPreparedStatement preparedStatementRunner = null; - - /** - * Prepare requests that will be executed from time to time - * - * @param runner - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public Commander(InternalRunner runner) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - this.internalConstructor(runner); - } - - /** - * Prepare requests that will be executed from time to time - * - * @param runner - * @param fromStartup - * True if call from startup of the server - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public Commander(InternalRunner runner, boolean fromStartup) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - this.internalConstructor(runner); - if (fromStartup) { - // Change RUNNING or INTERRUPTED to TOSUBMIT since they should be ready - DbTaskRunner.resetToSubmit(DbConstant.admin.session); - } - } - - private void internalConstructor(InternalRunner runner) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - try { - if (Configuration.configuration.multipleMonitors > 1) { - preparedStatementLock = - DbMultipleMonitor - .getUpdatedPrepareStament(DbConstant.noCommitAdmin.session); - } else { - preparedStatementLock = null; - } - preparedStatementConfig = - DbConfiguration.getUpdatedPrepareStament(DbConstant.admin.session); - preparedStatementHostConfig = - DbHostConfiguration.getUpdatedPrepareStament(DbConstant.admin.session); - preparedStatementHost = - DbHostAuth.getUpdatedPrepareStament(DbConstant.admin.session); - preparedStatementRule = - DbRule.getUpdatedPrepareStament(DbConstant.admin.session); - preparedStatementRunner = - DbTaskRunner.getSelectFromInfoPrepareStatement(DbConstant.admin.session, - UpdatedInfo.TOSUBMIT, false, LIMITSUBMIT); - - // Clean tasks (CompleteOK and ALLDONE => DONE) - DbTaskRunner.changeFinishedToDone(DbConstant.admin.session); - internalRunner = runner; - } finally { - if (internalRunner == null) { - // An error occurs - if (preparedStatementLock != null) { - preparedStatementLock.realClose(); - } - if (preparedStatementConfig != null) { - preparedStatementConfig.realClose(); - } - if (preparedStatementHostConfig != null) { - preparedStatementHostConfig.realClose(); - } - if (preparedStatementHost != null) { - preparedStatementHost.realClose(); - } - if (preparedStatementRule != null) { - preparedStatementRule.realClose(); - } - if (preparedStatementRunner != null) { - preparedStatementRunner.realClose(); - } - } else { - if (preparedStatementLock != null) { - DbConstant.noCommitAdmin.session - .addLongTermPreparedStatement(preparedStatementLock); - } - if (preparedStatementConfig != null) { - DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementConfig); - } - if (preparedStatementHostConfig != null) { - DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementHostConfig); - } - if (preparedStatementHost != null) { - DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementHost); - } - if (preparedStatementRule != null) { - DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementRule); - } - if (preparedStatementRunner != null) { - DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementRunner); - } - } - } - } - - /** - * Finalize internal data - */ - public void finalize() { - if (preparedStatementLock != null) { - try { - DbConstant.noCommitAdmin.session.commit(); - } catch (WaarpDatabaseSqlException e) { - } catch (WaarpDatabaseNoConnectionException e) { - } - preparedStatementLock.realClose(); - DbConstant.noCommitAdmin.session - .removeLongTermPreparedStatements(preparedStatementLock); - // DbConstant.noCommitAdmin.session.removeLongTermPreparedStatements(); - } - if (preparedStatementConfig != null) { - preparedStatementConfig.realClose(); - DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementConfig); - } - if (preparedStatementHostConfig != null) { - preparedStatementHostConfig.realClose(); - DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementHostConfig); - } - if (preparedStatementHost != null) { - preparedStatementHost.realClose(); - DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementHost); - } - if (preparedStatementRule != null) { - preparedStatementRule.realClose(); - DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementRule); - } - if (preparedStatementRunner != null) { - preparedStatementRunner.realClose(); - DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementRunner); - } - // DbConstant.admin.session.removeLongTermPreparedStatements(); - } - - public void run() { - Thread.currentThread().setName("OpenR66Commander"); - // each time it is runned, it parses all database for updates - DbMultipleMonitor multipleMonitor = null; - // Open a lock to prevent other "HA" monitors to retrieve access as Commander - try { - try { - if (preparedStatementLock != null) { - preparedStatementLock.executeQuery(); - preparedStatementLock.getNext(); - multipleMonitor = - DbMultipleMonitor.getFromStatement(preparedStatementLock); - } - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Database No Connection Error: Cannot execute Commander", e); - try { - DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - return; - } catch (WaarpDatabaseSqlException e) { - logger.error("Database SQL Error: Cannot execute Commander", e); - try { - DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - return; - } - logger.debug("Before " + multipleMonitor); - // First check Configuration - try { - preparedStatementConfig.executeQuery(); - while (preparedStatementConfig.getNext()) { - // should be only one... - DbConfiguration configuration = DbConfiguration - .getFromStatement(preparedStatementConfig); - if (configuration.isOwnConfiguration()) { - configuration.updateConfiguration(); - } - if (multipleMonitor != null) { - // update the configuration in HA mode - if (multipleMonitor.checkUpdateConfig()) { - configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - configuration.update(); - logger.debug("Config " + multipleMonitor); - } else { - configuration.update(); - logger.debug("Config " + multipleMonitor); - } - } else { - configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - configuration.update(); - } - configuration = null; - } - preparedStatementConfig.close(); - } catch (WaarpDatabaseNoConnectionException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } finally { - preparedStatementConfig.close(); - } - // check HostConfiguration - try { - preparedStatementHostConfig.executeQuery(); - while (preparedStatementHostConfig.getNext()) { - // should be only one... - DbHostConfiguration configuration = DbHostConfiguration - .getFromStatement(preparedStatementHostConfig); - if (configuration.isOwnConfiguration()) { - configuration.updateConfiguration(); - } - if (multipleMonitor != null) { - // update the configuration in HA mode - if (multipleMonitor.checkUpdateConfig()) { - configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - configuration.update(); - logger.debug("Config " + multipleMonitor); - } else { - configuration.update(); - logger.debug("Config " + multipleMonitor); - } - } else { - configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - configuration.update(); - } - configuration = null; - } - preparedStatementHostConfig.close(); - } catch (WaarpDatabaseNoConnectionException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } finally { - preparedStatementHostConfig.close(); - } - // Check HostAuthent - try { - preparedStatementHost.executeQuery(); - boolean mm = false; - boolean lastUpdate = false; - while (preparedStatementHost.getNext()) { - // Maybe multiple - DbHostAuth hostAuth = DbHostAuth.getFromStatement(preparedStatementHost); - if (multipleMonitor != null) { - if (!mm) { - // not already set from a previous hostAuth - mm = true; - lastUpdate = multipleMonitor.checkUpdateHost(); - } // else already set so no action on multipleMonitor - - // Update the Host configuration in HA mode - if (lastUpdate) { - hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - hostAuth.update(); - logger.debug("Host " + multipleMonitor); - } else { - // Nothing to do except validate - hostAuth.update(); - logger.debug("Host " + multipleMonitor); - } - } else { - // Nothing to do except validate - hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - hostAuth.update(); - } - hostAuth = null; - } - } catch (WaarpDatabaseNoConnectionException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } finally { - preparedStatementHost.close(); - } - // Check Rules - try { - preparedStatementRule.executeQuery(); - boolean mm = false; - boolean lastUpdate = false; - while (preparedStatementRule.getNext()) { - DbRule rule = DbRule.getFromStatement(preparedStatementRule); - if (multipleMonitor != null) { - if (!mm) { - // not already set from a previous hostAuth - mm = true; - lastUpdate = multipleMonitor.checkUpdateRule(); - } // else already set so no action on multipleMonitor - // Update the Rules in HA mode - if (lastUpdate) { - rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - rule.update(); - logger.debug("Rule " + multipleMonitor); - } else { - // Nothing to do except validate - rule.update(); - logger.debug("Rule " + multipleMonitor); - } - } else { - // Nothing to do except validate - rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - rule.update(); - } - rule = null; - } - } catch (WaarpDatabaseNoConnectionException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseNoDataException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } finally { - preparedStatementRule.close(); - } - if (R66ShutdownHook.isInShutdown()) { - // no more task to submit - return; - } - logger.debug("start runner"); - // Check TaskRunner - try { - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatementRunner); - // No specific HA mode since the other servers will wait for the commit on Lock - preparedStatementRunner.executeQuery(); - while (preparedStatementRunner.getNext()) { - DbTaskRunner taskRunner = DbTaskRunner - .getFromStatement(preparedStatementRunner); - logger.debug("get a task: {}", taskRunner); - // Launch if possible this task - String key = taskRunner.getRequested() + " " + taskRunner.getRequester() + - " " + taskRunner.getSpecialId(); - if (Configuration.configuration.getLocalTransaction(). - getFromRequest(key) != null) { - // already running - continue; - } - if (taskRunner.isSelfRequested()) { - // cannot schedule a request where the host is the requested host - taskRunner.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); - taskRunner.update(); - continue; - } - taskRunner.changeUpdatedInfo(UpdatedInfo.RUNNING); - taskRunner.forceSaveStatus(); - internalRunner.submitTaskRunner(taskRunner); - taskRunner = null; - } - } catch (WaarpDatabaseNoConnectionException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - logger.error("Database Error: Cannot execute Commander", e); - return; - } finally { - preparedStatementRunner.close(); - } - logger.debug("end commander"); - } finally { - if (multipleMonitor != null) { - try { - // Now update and Commit so releasing the lock - logger.debug("Update " + multipleMonitor); - multipleMonitor.update(); - DbConstant.noCommitAdmin.session.commit(); - } catch (WaarpDatabaseException e) { - try { - DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); - } catch (WaarpDatabaseNoConnectionException e1) { - } - } - multipleMonitor = null; - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.commander; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.database.model.DbModelFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.data.DbMultipleMonitor; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; + +/** + * Commander is responsible to read from database updated data from time to time in order to achieve + * new runner or new configuration updates. + * + * @author Frederic Bregier + * + */ +public class Commander implements CommanderInterface { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(Commander.class); + + private static final int LIMITSUBMIT = 100; + + private InternalRunner internalRunner = null; + private DbPreparedStatement preparedStatementLock = null; + private DbPreparedStatement preparedStatementConfig = null; + private DbPreparedStatement preparedStatementHostConfig = null; + private DbPreparedStatement preparedStatementHost = null; + private DbPreparedStatement preparedStatementRule = null; + private DbPreparedStatement preparedStatementRunner = null; + + /** + * Prepare requests that will be executed from time to time + * + * @param runner + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public Commander(InternalRunner runner) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + this.internalConstructor(runner); + } + + /** + * Prepare requests that will be executed from time to time + * + * @param runner + * @param fromStartup + * True if call from startup of the server + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public Commander(InternalRunner runner, boolean fromStartup) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + this.internalConstructor(runner); + if (fromStartup) { + // Change RUNNING or INTERRUPTED to TOSUBMIT since they should be ready + DbTaskRunner.resetToSubmit(DbConstant.admin.session); + } + } + + private void internalConstructor(InternalRunner runner) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + try { + if (Configuration.configuration.multipleMonitors > 1) { + preparedStatementLock = + DbMultipleMonitor + .getUpdatedPrepareStament(DbConstant.noCommitAdmin.session); + } else { + preparedStatementLock = null; + } + preparedStatementConfig = + DbConfiguration.getUpdatedPrepareStament(DbConstant.admin.session); + preparedStatementHostConfig = + DbHostConfiguration.getUpdatedPrepareStament(DbConstant.admin.session); + preparedStatementHost = + DbHostAuth.getUpdatedPrepareStament(DbConstant.admin.session); + preparedStatementRule = + DbRule.getUpdatedPrepareStament(DbConstant.admin.session); + preparedStatementRunner = + DbTaskRunner.getSelectFromInfoPrepareStatement(DbConstant.admin.session, + UpdatedInfo.TOSUBMIT, false, LIMITSUBMIT); + + // Clean tasks (CompleteOK and ALLDONE => DONE) + DbTaskRunner.changeFinishedToDone(DbConstant.admin.session); + internalRunner = runner; + } finally { + if (internalRunner == null) { + // An error occurs + if (preparedStatementLock != null) { + preparedStatementLock.realClose(); + } + if (preparedStatementConfig != null) { + preparedStatementConfig.realClose(); + } + if (preparedStatementHostConfig != null) { + preparedStatementHostConfig.realClose(); + } + if (preparedStatementHost != null) { + preparedStatementHost.realClose(); + } + if (preparedStatementRule != null) { + preparedStatementRule.realClose(); + } + if (preparedStatementRunner != null) { + preparedStatementRunner.realClose(); + } + } else { + if (preparedStatementLock != null) { + DbConstant.noCommitAdmin.session + .addLongTermPreparedStatement(preparedStatementLock); + } + if (preparedStatementConfig != null) { + DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementConfig); + } + if (preparedStatementHostConfig != null) { + DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementHostConfig); + } + if (preparedStatementHost != null) { + DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementHost); + } + if (preparedStatementRule != null) { + DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementRule); + } + if (preparedStatementRunner != null) { + DbConstant.admin.session.addLongTermPreparedStatement(preparedStatementRunner); + } + } + } + } + + /** + * Finalize internal data + */ + public void finalize() { + if (preparedStatementLock != null) { + try { + DbConstant.noCommitAdmin.session.commit(); + } catch (WaarpDatabaseSqlException e) { + } catch (WaarpDatabaseNoConnectionException e) { + } + preparedStatementLock.realClose(); + DbConstant.noCommitAdmin.session + .removeLongTermPreparedStatements(preparedStatementLock); + // DbConstant.noCommitAdmin.session.removeLongTermPreparedStatements(); + } + if (preparedStatementConfig != null) { + preparedStatementConfig.realClose(); + DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementConfig); + } + if (preparedStatementHostConfig != null) { + preparedStatementHostConfig.realClose(); + DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementHostConfig); + } + if (preparedStatementHost != null) { + preparedStatementHost.realClose(); + DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementHost); + } + if (preparedStatementRule != null) { + preparedStatementRule.realClose(); + DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementRule); + } + if (preparedStatementRunner != null) { + preparedStatementRunner.realClose(); + DbConstant.admin.session.removeLongTermPreparedStatements(preparedStatementRunner); + } + // DbConstant.admin.session.removeLongTermPreparedStatements(); + } + + public void run() { + Thread.currentThread().setName("OpenR66Commander"); + // each time it is runned, it parses all database for updates + DbMultipleMonitor multipleMonitor = null; + // Open a lock to prevent other "HA" monitors to retrieve access as Commander + try { + try { + if (preparedStatementLock != null) { + preparedStatementLock.executeQuery(); + preparedStatementLock.getNext(); + multipleMonitor = + DbMultipleMonitor.getFromStatement(preparedStatementLock); + } + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Database No Connection Error: Cannot execute Commander", e); + try { + DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + return; + } catch (WaarpDatabaseSqlException e) { + logger.error("Database SQL Error: Cannot execute Commander", e); + try { + DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + return; + } + logger.debug("Before " + multipleMonitor); + // First check Configuration + try { + preparedStatementConfig.executeQuery(); + while (preparedStatementConfig.getNext()) { + // should be only one... + DbConfiguration configuration = DbConfiguration + .getFromStatement(preparedStatementConfig); + if (configuration.isOwnConfiguration()) { + configuration.updateConfiguration(); + } + if (multipleMonitor != null) { + // update the configuration in HA mode + if (multipleMonitor.checkUpdateConfig()) { + configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + configuration.update(); + logger.debug("Config " + multipleMonitor); + } else { + configuration.update(); + logger.debug("Config " + multipleMonitor); + } + } else { + configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + configuration.update(); + } + configuration = null; + } + preparedStatementConfig.close(); + } catch (WaarpDatabaseNoConnectionException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } finally { + preparedStatementConfig.close(); + } + // check HostConfiguration + try { + preparedStatementHostConfig.executeQuery(); + while (preparedStatementHostConfig.getNext()) { + // should be only one... + DbHostConfiguration configuration = DbHostConfiguration + .getFromStatement(preparedStatementHostConfig); + if (configuration.isOwnConfiguration()) { + configuration.updateConfiguration(); + } + if (multipleMonitor != null) { + // update the configuration in HA mode + if (multipleMonitor.checkUpdateConfig()) { + configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + configuration.update(); + logger.debug("Config " + multipleMonitor); + } else { + configuration.update(); + logger.debug("Config " + multipleMonitor); + } + } else { + configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + configuration.update(); + } + configuration = null; + } + preparedStatementHostConfig.close(); + } catch (WaarpDatabaseNoConnectionException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } finally { + preparedStatementHostConfig.close(); + } + // Check HostAuthent + try { + preparedStatementHost.executeQuery(); + boolean mm = false; + boolean lastUpdate = false; + while (preparedStatementHost.getNext()) { + // Maybe multiple + DbHostAuth hostAuth = DbHostAuth.getFromStatement(preparedStatementHost); + if (multipleMonitor != null) { + if (!mm) { + // not already set from a previous hostAuth + mm = true; + lastUpdate = multipleMonitor.checkUpdateHost(); + } // else already set so no action on multipleMonitor + + // Update the Host configuration in HA mode + if (lastUpdate) { + hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + hostAuth.update(); + logger.debug("Host " + multipleMonitor); + } else { + // Nothing to do except validate + hostAuth.update(); + logger.debug("Host " + multipleMonitor); + } + } else { + // Nothing to do except validate + hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + hostAuth.update(); + } + hostAuth = null; + } + } catch (WaarpDatabaseNoConnectionException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } finally { + preparedStatementHost.close(); + } + // Check Rules + try { + preparedStatementRule.executeQuery(); + boolean mm = false; + boolean lastUpdate = false; + while (preparedStatementRule.getNext()) { + DbRule rule = DbRule.getFromStatement(preparedStatementRule); + if (multipleMonitor != null) { + if (!mm) { + // not already set from a previous hostAuth + mm = true; + lastUpdate = multipleMonitor.checkUpdateRule(); + } // else already set so no action on multipleMonitor + // Update the Rules in HA mode + if (lastUpdate) { + rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + rule.update(); + logger.debug("Rule " + multipleMonitor); + } else { + // Nothing to do except validate + rule.update(); + logger.debug("Rule " + multipleMonitor); + } + } else { + // Nothing to do except validate + rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + rule.update(); + } + rule = null; + } + } catch (WaarpDatabaseNoConnectionException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseNoDataException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } finally { + preparedStatementRule.close(); + } + if (R66ShutdownHook.isInShutdown()) { + // no more task to submit + return; + } + logger.debug("start runner"); + // Check TaskRunner + try { + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatementRunner); + // No specific HA mode since the other servers will wait for the commit on Lock + preparedStatementRunner.executeQuery(); + while (preparedStatementRunner.getNext()) { + DbTaskRunner taskRunner = DbTaskRunner + .getFromStatement(preparedStatementRunner); + logger.debug("get a task: {}", taskRunner); + // Launch if possible this task + String key = taskRunner.getRequested() + " " + taskRunner.getRequester() + + " " + taskRunner.getSpecialId(); + if (Configuration.configuration.getLocalTransaction(). + getFromRequest(key) != null) { + // already running + continue; + } + if (taskRunner.isSelfRequested()) { + // cannot schedule a request where the host is the requested host + taskRunner.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); + taskRunner.update(); + continue; + } + taskRunner.changeUpdatedInfo(UpdatedInfo.RUNNING); + taskRunner.forceSaveStatus(); + internalRunner.submitTaskRunner(taskRunner); + taskRunner = null; + } + } catch (WaarpDatabaseNoConnectionException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + logger.error("Database Error: Cannot execute Commander", e); + return; + } finally { + preparedStatementRunner.close(); + } + logger.debug("end commander"); + } finally { + if (multipleMonitor != null) { + try { + // Now update and Commit so releasing the lock + logger.debug("Update " + multipleMonitor); + multipleMonitor.update(); + DbConstant.noCommitAdmin.session.commit(); + } catch (WaarpDatabaseException e) { + try { + DbModelFactory.dbModel.validConnection(DbConstant.noCommitAdmin.session); + } catch (WaarpDatabaseNoConnectionException e1) { + } + } + multipleMonitor = null; + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/commander/CommanderInterface.java b/src/main/java/org/waarp/openr66/commander/CommanderInterface.java index a635c08e2..2714a56d6 100644 --- a/src/main/java/org/waarp/openr66/commander/CommanderInterface.java +++ b/src/main/java/org/waarp/openr66/commander/CommanderInterface.java @@ -1,29 +1,29 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.commander; - -/** - * @author Frederic Bregier - * - */ -public interface CommanderInterface extends Runnable { - /** - * Finalize internal data - */ - public void finalize(); -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.commander; + +/** + * @author Frederic Bregier + * + */ +public interface CommanderInterface extends Runnable { + /** + * Finalize internal data + */ + public void finalize(); +} diff --git a/src/main/java/org/waarp/openr66/commander/CommanderNoDb.java b/src/main/java/org/waarp/openr66/commander/CommanderNoDb.java index 1bd99171d..df5b3bb74 100644 --- a/src/main/java/org/waarp/openr66/commander/CommanderNoDb.java +++ b/src/main/java/org/waarp/openr66/commander/CommanderNoDb.java @@ -1,194 +1,194 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.commander; - -import java.io.File; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.configuration.ExtensionFilter; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.utils.FileUtils; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; - -/** - * Commander is responsible to read list of updated data from time to time in order to achieve new - * runner or new configuration updates. - * - * Based on no Database support - * - * @author Frederic Bregier - * - */ -public class CommanderNoDb implements CommanderInterface { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(CommanderNoDb.class); - - private InternalRunner internalRunner = null; - public static final ConcurrentLinkedQueue todoList = new ConcurrentLinkedQueue(); - - /** - * Prepare requests that will be executed from time to time - * - * @param runner - */ - public CommanderNoDb(InternalRunner runner) { - this.internalConstructor(runner); - } - - /** - * Prepare requests that will be executed from time to time - * - * @param runner - * @param fromStartup - * True if call from startup of the server - */ - public CommanderNoDb(InternalRunner runner, boolean fromStartup) { - this.internalConstructor(runner); - if (fromStartup) { - ClientRunner.activeRunners = new ConcurrentLinkedQueue(); - // Change RUNNING or INTERRUPTED to TOSUBMIT since they should be ready - /* - * Configuration.configuration.baseDirectory+ - * Configuration.configuration.archivePath+R66Dir.SEPARATOR+ - * this.requesterHostId+"_"+this.requestedHostId+"_"+this.ruleId+"_"+this.specialId - * +XMLEXTENSION; - */ - File directory = new File(Configuration.configuration.baseDirectory + - Configuration.configuration.archivePath); - File[] files = FileUtils.getFiles(directory, - new ExtensionFilter(DbTaskRunner.XMLEXTENSION)); - for (File file : files) { - String shortname = file.getName(); - String[] info = shortname.split("_"); - if (info.length < 5) { - continue; - } - DbRule rule; - try { - rule = new DbRule(null, info[2]); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot find the rule named: " + info[2]); - continue; - } - long id = Long.parseLong(info[3]); - try { - DbTaskRunner task = new DbTaskRunner(null, null, rule, id, info[0], info[1]); - UpdatedInfo status = task.getUpdatedInfo(); - if (status == UpdatedInfo.RUNNING || status == UpdatedInfo.INTERRUPTED) { - task.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - task.update(); - } - } catch (WaarpDatabaseException e) { - logger.warn("Cannot reload the task named: " + shortname); - continue; - } - } - } - } - - private void internalConstructor(InternalRunner runner) { - internalRunner = runner; - } - - /** - * Finalize internal data - */ - public void finalize() { - // no since it will be reloaded - // todoList.clear(); - } - - public void run() { - Thread.currentThread().setName("OpenR66Commander"); - while (!todoList.isEmpty()) { - try { - AbstractDbData data = todoList.poll(); - // First check Configuration - if (data instanceof DbConfiguration) { - // should be only one... - DbConfiguration configuration = (DbConfiguration) data; - if (configuration.isOwnConfiguration()) { - configuration.updateConfiguration(); - } - configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - configuration.update(); - } - // Check HostAuthent - else if (data instanceof DbHostAuth) { - DbHostAuth hostAuth = (DbHostAuth) data; - // Nothing to do except validate - hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - hostAuth.update(); - } - // Check Rules - else if (data instanceof DbRule) { - // Nothing to do except validate - DbRule rule = (DbRule) data; - rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); - rule.update(); - } - // Check TaskRunner - else if (data instanceof DbTaskRunner) { - DbTaskRunner taskRunner = (DbTaskRunner) data; - logger.debug("get a task: {}", taskRunner); - // Launch if possible this task - String key = taskRunner.getRequested() + " " + taskRunner.getRequester() + - " " + taskRunner.getSpecialId(); - if (Configuration.configuration.getLocalTransaction(). - getFromRequest(key) != null) { - // already running - continue; - } - if (taskRunner.isSelfRequested()) { - // cannot schedule a request where the host is the requested host - taskRunner.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); - taskRunner.update(); - continue; - } - taskRunner.changeUpdatedInfo(UpdatedInfo.RUNNING); - taskRunner.update(); - internalRunner.submitTaskRunner(taskRunner); - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - taskRunner = null; - } - if (R66ShutdownHook.isInShutdown()) { - // no more task to submit - return; - } - } catch (WaarpDatabaseException e) { - logger.error("Error in Commander", e); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.commander; + +import java.io.File; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.configuration.ExtensionFilter; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.utils.FileUtils; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; + +/** + * Commander is responsible to read list of updated data from time to time in order to achieve new + * runner or new configuration updates. + * + * Based on no Database support + * + * @author Frederic Bregier + * + */ +public class CommanderNoDb implements CommanderInterface { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(CommanderNoDb.class); + + private InternalRunner internalRunner = null; + public static final ConcurrentLinkedQueue todoList = new ConcurrentLinkedQueue(); + + /** + * Prepare requests that will be executed from time to time + * + * @param runner + */ + public CommanderNoDb(InternalRunner runner) { + this.internalConstructor(runner); + } + + /** + * Prepare requests that will be executed from time to time + * + * @param runner + * @param fromStartup + * True if call from startup of the server + */ + public CommanderNoDb(InternalRunner runner, boolean fromStartup) { + this.internalConstructor(runner); + if (fromStartup) { + ClientRunner.activeRunners = new ConcurrentLinkedQueue(); + // Change RUNNING or INTERRUPTED to TOSUBMIT since they should be ready + /* + * Configuration.configuration.baseDirectory+ + * Configuration.configuration.archivePath+R66Dir.SEPARATOR+ + * this.requesterHostId+"_"+this.requestedHostId+"_"+this.ruleId+"_"+this.specialId + * +XMLEXTENSION; + */ + File directory = new File(Configuration.configuration.baseDirectory + + Configuration.configuration.archivePath); + File[] files = FileUtils.getFiles(directory, + new ExtensionFilter(DbTaskRunner.XMLEXTENSION)); + for (File file : files) { + String shortname = file.getName(); + String[] info = shortname.split("_"); + if (info.length < 5) { + continue; + } + DbRule rule; + try { + rule = new DbRule(null, info[2]); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot find the rule named: " + info[2]); + continue; + } + long id = Long.parseLong(info[3]); + try { + DbTaskRunner task = new DbTaskRunner(null, null, rule, id, info[0], info[1]); + UpdatedInfo status = task.getUpdatedInfo(); + if (status == UpdatedInfo.RUNNING || status == UpdatedInfo.INTERRUPTED) { + task.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + task.update(); + } + } catch (WaarpDatabaseException e) { + logger.warn("Cannot reload the task named: " + shortname); + continue; + } + } + } + } + + private void internalConstructor(InternalRunner runner) { + internalRunner = runner; + } + + /** + * Finalize internal data + */ + public void finalize() { + // no since it will be reloaded + // todoList.clear(); + } + + public void run() { + Thread.currentThread().setName("OpenR66Commander"); + while (!todoList.isEmpty()) { + try { + AbstractDbData data = todoList.poll(); + // First check Configuration + if (data instanceof DbConfiguration) { + // should be only one... + DbConfiguration configuration = (DbConfiguration) data; + if (configuration.isOwnConfiguration()) { + configuration.updateConfiguration(); + } + configuration.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + configuration.update(); + } + // Check HostAuthent + else if (data instanceof DbHostAuth) { + DbHostAuth hostAuth = (DbHostAuth) data; + // Nothing to do except validate + hostAuth.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + hostAuth.update(); + } + // Check Rules + else if (data instanceof DbRule) { + // Nothing to do except validate + DbRule rule = (DbRule) data; + rule.changeUpdatedInfo(AbstractDbData.UpdatedInfo.NOTUPDATED); + rule.update(); + } + // Check TaskRunner + else if (data instanceof DbTaskRunner) { + DbTaskRunner taskRunner = (DbTaskRunner) data; + logger.debug("get a task: {}", taskRunner); + // Launch if possible this task + String key = taskRunner.getRequested() + " " + taskRunner.getRequester() + + " " + taskRunner.getSpecialId(); + if (Configuration.configuration.getLocalTransaction(). + getFromRequest(key) != null) { + // already running + continue; + } + if (taskRunner.isSelfRequested()) { + // cannot schedule a request where the host is the requested host + taskRunner.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); + taskRunner.update(); + continue; + } + taskRunner.changeUpdatedInfo(UpdatedInfo.RUNNING); + taskRunner.update(); + internalRunner.submitTaskRunner(taskRunner); + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + taskRunner = null; + } + if (R66ShutdownHook.isInShutdown()) { + // no more task to submit + return; + } + } catch (WaarpDatabaseException e) { + logger.error("Error in Commander", e); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/commander/InternalRunner.java b/src/main/java/org/waarp/openr66/commander/InternalRunner.java index 26c56623a..41f19c33c 100644 --- a/src/main/java/org/waarp/openr66/commander/InternalRunner.java +++ b/src/main/java/org/waarp/openr66/commander/InternalRunner.java @@ -1,155 +1,155 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.commander; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; - -/** - * This class launch and control the Commander and enable TaskRunner job submissions - * - * @author Frederic Bregier - * - */ -public class InternalRunner { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(InternalRunner.class); - - private final ScheduledExecutorService scheduledExecutorService; - private ScheduledFuture scheduledFuture; - private CommanderInterface commander = null; - private volatile boolean isRunning = true; - private final ThreadPoolExecutor threadPoolExecutor; - private final BlockingQueue workQueue; - private final NetworkTransaction networkTransaction; - - /** - * Create the structure to enable submission by database - * - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public InternalRunner() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - if (DbConstant.admin.isConnected) { - commander = new Commander(this, true); - } else { - commander = new CommanderNoDb(this, true); - } - scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); - isRunning = true; - workQueue = new ArrayBlockingQueue(10); - threadPoolExecutor = new ThreadPoolExecutor(10, Configuration.configuration.RUNNER_THREAD, - 1000, TimeUnit.MILLISECONDS, workQueue); - scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(commander, - Configuration.configuration.delayCommander, - Configuration.configuration.delayCommander, TimeUnit.MILLISECONDS); - networkTransaction = new NetworkTransaction(); - } - - public NetworkTransaction getNetworkTransaction() { - return networkTransaction; - } - - /** - * Submit a task - * - * @param taskRunner - */ - public void submitTaskRunner(DbTaskRunner taskRunner) { - if (isRunning || !Configuration.configuration.isShutdown) { - if (threadPoolExecutor.getActiveCount() + 5 > Configuration.configuration.RUNNER_THREAD) { - // too many current active threads - taskRunner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - taskRunner.forceSaveStatus(); - return; - } - logger.debug("Will run {}", taskRunner); - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, null); - if (taskRunner.isSendThrough() && (taskRunner.isRescheduledTransfer() - || taskRunner.isPreTaskStarting())) { - runner.setSendThroughMode(); - taskRunner.checkThroughMode(); - } - runner.setDaemon(true); - // create the client, connect and run - threadPoolExecutor.execute(runner); - runner = null; - } - } - - /** - * First step while shutting down the service - */ - public void prepareStopInternalRunner() { - isRunning = false; - scheduledFuture.cancel(false); - scheduledExecutorService.shutdown(); - threadPoolExecutor.shutdown(); - } - - /** - * This should be called when the server is shutting down, after stopping active requests if - * possible. - */ - public void stopInternalRunner() { - isRunning = false; - logger.info("Stopping Commander and Runner Tasks"); - scheduledFuture.cancel(false); - scheduledExecutorService.shutdownNow(); - threadPoolExecutor.shutdownNow(); - networkTransaction.closeAll(); - } - - public int nbInternalRunner() { - return threadPoolExecutor.getActiveCount(); - } - - public void reloadInternalRunner() - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - scheduledFuture.cancel(false); - if (commander != null) { - commander.finalize(); - } - if (DbConstant.admin.isConnected) { - commander = new Commander(this); - } else { - commander = new CommanderNoDb(this); - } - scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(commander, - Configuration.configuration.delayCommander, - Configuration.configuration.delayCommander, TimeUnit.MILLISECONDS); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.commander; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; + +/** + * This class launch and control the Commander and enable TaskRunner job submissions + * + * @author Frederic Bregier + * + */ +public class InternalRunner { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(InternalRunner.class); + + private final ScheduledExecutorService scheduledExecutorService; + private ScheduledFuture scheduledFuture; + private CommanderInterface commander = null; + private volatile boolean isRunning = true; + private final ThreadPoolExecutor threadPoolExecutor; + private final BlockingQueue workQueue; + private final NetworkTransaction networkTransaction; + + /** + * Create the structure to enable submission by database + * + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public InternalRunner() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + if (DbConstant.admin.isConnected) { + commander = new Commander(this, true); + } else { + commander = new CommanderNoDb(this, true); + } + scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); + isRunning = true; + workQueue = new ArrayBlockingQueue(10); + threadPoolExecutor = new ThreadPoolExecutor(10, Configuration.configuration.RUNNER_THREAD, + 1000, TimeUnit.MILLISECONDS, workQueue); + scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(commander, + Configuration.configuration.delayCommander, + Configuration.configuration.delayCommander, TimeUnit.MILLISECONDS); + networkTransaction = new NetworkTransaction(); + } + + public NetworkTransaction getNetworkTransaction() { + return networkTransaction; + } + + /** + * Submit a task + * + * @param taskRunner + */ + public void submitTaskRunner(DbTaskRunner taskRunner) { + if (isRunning || !Configuration.configuration.isShutdown) { + if (threadPoolExecutor.getActiveCount() + 5 > Configuration.configuration.RUNNER_THREAD) { + // too many current active threads + taskRunner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + taskRunner.forceSaveStatus(); + return; + } + logger.debug("Will run {}", taskRunner); + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, null); + if (taskRunner.isSendThrough() && (taskRunner.isRescheduledTransfer() + || taskRunner.isPreTaskStarting())) { + runner.setSendThroughMode(); + taskRunner.checkThroughMode(); + } + runner.setDaemon(true); + // create the client, connect and run + threadPoolExecutor.execute(runner); + runner = null; + } + } + + /** + * First step while shutting down the service + */ + public void prepareStopInternalRunner() { + isRunning = false; + scheduledFuture.cancel(false); + scheduledExecutorService.shutdown(); + threadPoolExecutor.shutdown(); + } + + /** + * This should be called when the server is shutting down, after stopping active requests if + * possible. + */ + public void stopInternalRunner() { + isRunning = false; + logger.info("Stopping Commander and Runner Tasks"); + scheduledFuture.cancel(false); + scheduledExecutorService.shutdownNow(); + threadPoolExecutor.shutdownNow(); + networkTransaction.closeAll(); + } + + public int nbInternalRunner() { + return threadPoolExecutor.getActiveCount(); + } + + public void reloadInternalRunner() + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + scheduledFuture.cancel(false); + if (commander != null) { + commander.finalize(); + } + if (DbConstant.admin.isConnected) { + commander = new Commander(this); + } else { + commander = new CommanderNoDb(this); + } + scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(commander, + Configuration.configuration.delayCommander, + Configuration.configuration.delayCommander, TimeUnit.MILLISECONDS); + } +} diff --git a/src/main/java/org/waarp/openr66/commander/ThreadPoolRunnerExecutor.java b/src/main/java/org/waarp/openr66/commander/ThreadPoolRunnerExecutor.java index 08904d0bb..09e0d05a0 100644 --- a/src/main/java/org/waarp/openr66/commander/ThreadPoolRunnerExecutor.java +++ b/src/main/java/org/waarp/openr66/commander/ThreadPoolRunnerExecutor.java @@ -1,116 +1,116 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.commander; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.openr66.context.ErrorCode; - -/** - * Thread Pool Executor for ClientRunner - * - * @author Frederic Bregier - * - */ -public class ThreadPoolRunnerExecutor extends ThreadPoolExecutor { - - /** - * RejectedExecutionHandler for this ThreadPoolRunnerExecutor - * - * @author Frederic Bregier - * - */ - private class RunnerRejectedExecutionHandler implements RejectedExecutionHandler { - - public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) { - ClientRunner runner = (ClientRunner) arg0; - runner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.INERROR, - ErrorCode.Unknown, true); - } - - } - - /** - * @param corePoolSize - * @param maximumPoolSize - * @param keepAliveTime - * @param unit - * @param workQueue - */ - public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, - long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); - this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); - } - - /** - * @param corePoolSize - * @param maximumPoolSize - * @param keepAliveTime - * @param unit - * @param workQueue - * @param threadFactory - */ - public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, - long keepAliveTime, TimeUnit unit, - BlockingQueue workQueue, ThreadFactory threadFactory) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, - threadFactory); - this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); - } - - /** - * @param corePoolSize - * @param maximumPoolSize - * @param keepAliveTime - * @param unit - * @param workQueue - * @param handler - */ - public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, - long keepAliveTime, TimeUnit unit, - BlockingQueue workQueue, RejectedExecutionHandler handler) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, - handler); - this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); - } - - /** - * @param corePoolSize - * @param maximumPoolSize - * @param keepAliveTime - * @param unit - * @param workQueue - * @param threadFactory - * @param handler - */ - public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, - long keepAliveTime, TimeUnit unit, - BlockingQueue workQueue, ThreadFactory threadFactory, - RejectedExecutionHandler handler) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, - threadFactory, handler); - this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.commander; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.openr66.context.ErrorCode; + +/** + * Thread Pool Executor for ClientRunner + * + * @author Frederic Bregier + * + */ +public class ThreadPoolRunnerExecutor extends ThreadPoolExecutor { + + /** + * RejectedExecutionHandler for this ThreadPoolRunnerExecutor + * + * @author Frederic Bregier + * + */ + private class RunnerRejectedExecutionHandler implements RejectedExecutionHandler { + + public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) { + ClientRunner runner = (ClientRunner) arg0; + runner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.INERROR, + ErrorCode.Unknown, true); + } + + } + + /** + * @param corePoolSize + * @param maximumPoolSize + * @param keepAliveTime + * @param unit + * @param workQueue + */ + public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); + this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); + } + + /** + * @param corePoolSize + * @param maximumPoolSize + * @param keepAliveTime + * @param unit + * @param workQueue + * @param threadFactory + */ + public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, ThreadFactory threadFactory) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, + threadFactory); + this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); + } + + /** + * @param corePoolSize + * @param maximumPoolSize + * @param keepAliveTime + * @param unit + * @param workQueue + * @param handler + */ + public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, RejectedExecutionHandler handler) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, + handler); + this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); + } + + /** + * @param corePoolSize + * @param maximumPoolSize + * @param keepAliveTime + * @param unit + * @param workQueue + * @param threadFactory + * @param handler + */ + public ThreadPoolRunnerExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, ThreadFactory threadFactory, + RejectedExecutionHandler handler) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, + threadFactory, handler); + this.setRejectedExecutionHandler(new RunnerRejectedExecutionHandler()); + } + +} diff --git a/src/main/java/org/waarp/openr66/commander/package-info.java b/src/main/java/org/waarp/openr66/commander/package-info.java index eeb41f006..ac3f82352 100644 --- a/src/main/java/org/waarp/openr66/commander/package-info.java +++ b/src/main/java/org/waarp/openr66/commander/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Commander, reader of database updates from clients - * - * @apiviz.landmark - */ -package org.waarp.openr66.commander; - +/** + * Classes implementing Commander, reader of database updates from clients + * + * @apiviz.landmark + */ +package org.waarp.openr66.commander; + diff --git a/src/main/java/org/waarp/openr66/configuration/AuthenticationFileBasedConfiguration.java b/src/main/java/org/waarp/openr66/configuration/AuthenticationFileBasedConfiguration.java index ccafd329c..550a34303 100644 --- a/src/main/java/org/waarp/openr66/configuration/AuthenticationFileBasedConfiguration.java +++ b/src/main/java/org/waarp/openr66/configuration/AuthenticationFileBasedConfiguration.java @@ -1,310 +1,310 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.configuration; - -import java.io.File; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.dom4j.tree.DefaultElement; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.xml.XmlDecl; -import org.waarp.common.xml.XmlHash; -import org.waarp.common.xml.XmlType; -import org.waarp.common.xml.XmlUtil; -import org.waarp.common.xml.XmlValue; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * Authentication from File support - * - * @author Frederic Bregier - * - */ -public class AuthenticationFileBasedConfiguration { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(AuthenticationFileBasedConfiguration.class); - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ROOT = "authent"; - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ENTRY = "entry"; - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_BASED = "/" - + - XML_AUTHENTIFICATION_ROOT - + "/" - + XML_AUTHENTIFICATION_ENTRY; - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_HOSTID = "hostid"; - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_KEYFILE = "keyfile"; - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_KEY = "key"; - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ADMIN = "admin"; - - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ADDRESS = "address"; - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_PORT = "port"; - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ISSSL = "isssl"; - /** - * Authentication Fields - */ - private static final String XML_AUTHENTIFICATION_ISCLIENT = "isclient"; - - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configAuthenticationDecls = { - // identity - new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_HOSTID), - new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_KEYFILE), - new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_KEY), - new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ADMIN), - new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_ADDRESS), - new XmlDecl(XmlType.INTEGER, XML_AUTHENTIFICATION_PORT), - new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ISSSL), - new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ISCLIENT) - }; - /** - * Global Structure for Server Configuration - */ - private static final XmlDecl[] authentElements = { - new XmlDecl( - XML_AUTHENTIFICATION_ENTRY, - XmlType.XVAL, - XML_AUTHENTIFICATION_BASED, - configAuthenticationDecls, - true) - }; - - /** - * Load Authentication from File - * - * @param filename - * @return True if OK - */ - @SuppressWarnings("unchecked") - public static boolean loadAuthentication(Configuration config, String filename) { - Document document = null; - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Authentication file: " + - filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Authentication file: " + - filename); - return false; - } - XmlValue[] values = XmlUtil.read(document, authentElements); - XmlHash hash = new XmlHash(values); - XmlValue value = hash.get(XML_AUTHENTIFICATION_ENTRY); - List list = (List) value.getList(); - Iterator iterator = list.iterator(); - File key; - byte[] byteKeys; - while (iterator.hasNext()) { - XmlValue[] subvalues = iterator.next(); - XmlHash subHash = new XmlHash(subvalues); - value = subHash.get(XML_AUTHENTIFICATION_HOSTID); - if (value == null || (value.isEmpty())) { - continue; - } - String refHostId = value.getString(); - value = subHash.get(XML_AUTHENTIFICATION_KEYFILE); - if (value == null || (value.isEmpty())) { - value = subHash.get(XML_AUTHENTIFICATION_KEY); - if (value == null || (value.isEmpty())) { - // Allow empty key - byteKeys = null; - } else { - String skey = value.getString(); - // key is crypted - if (skey.length() > 0) { - try { - byteKeys = config.cryptoKey.decryptHexInBytes(skey); - } catch (Exception e) { - logger.error("Cannot read key for hostId " + refHostId + ":" + skey); - continue; - } - } else { - byteKeys = null; - } - } - } else { - String skey = value.getString(); - // load key from file - key = new File(skey); - if (!key.canRead()) { - logger.error("Cannot read key for hostId " + refHostId + ":" + skey); - continue; - } - try { - byteKeys = config.cryptoKey.decryptHexFile(key); - } catch (Exception e2) { - logger.error("Cannot read key for hostId " + refHostId, e2); - continue; - } - } - boolean isAdmin = false; - value = subHash.get(XML_AUTHENTIFICATION_ADMIN); - if (value != null && (!value.isEmpty())) { - isAdmin = value.getBoolean(); - } - value = subHash.get(XML_AUTHENTIFICATION_ADDRESS); - if (value == null || (value.isEmpty())) { - continue; - } - String address = value.getString(); - int port; - value = subHash.get(XML_AUTHENTIFICATION_PORT); - if (value != null && (!value.isEmpty())) { - port = value.getInteger(); - } else { - continue; - } - boolean isSsl = false; - value = subHash.get(XML_AUTHENTIFICATION_ISSSL); - if (value != null && (!value.isEmpty())) { - isSsl = value.getBoolean(); - } - boolean isClient = false; - value = subHash.get(XML_AUTHENTIFICATION_ISCLIENT); - if (value != null && (!value.isEmpty())) { - isClient = value.getBoolean(); - } - DbHostAuth auth = new DbHostAuth(DbConstant.admin.session, - refHostId, address, port, isSsl, byteKeys, isAdmin, isClient); - try { - if (auth.exist()) { - auth.update(); - } else { - auth.insert(); - } - } catch (WaarpDatabaseException e) { - logger.error("Cannot create Authentication for hostId {}", refHostId); - continue; - } - logger.debug("Add {} {}", refHostId, auth); - } - document = null; - hash.clear(); - values = null; - return true; - } - - /** - * Construct a new Element with value - * - * @param name - * @param value - * @return the new Element - */ - private static Element newElement(String name, String value) { - Element node = new DefaultElement(name); - node.addText(value); - return node; - } - - /** - * Write all authentication to a file with filename - * - * @param filename - * @throws OpenR66ProtocolSystemException - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static void writeXML(Configuration config, String filename) - throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - Document document = DocumentHelper.createDocument(); - Element root = document.addElement(XML_AUTHENTIFICATION_ROOT); - DbHostAuth[] hosts = DbHostAuth.getAllHosts(DbConstant.admin.session); - logger.debug("Will write DbHostAuth: "+hosts.length+" in "+filename); - for (DbHostAuth auth : hosts) { - logger.debug("Will write DbHostAuth: "+auth.getHostid()); - Element entry = new DefaultElement(XML_AUTHENTIFICATION_ENTRY); - entry.add(newElement(XML_AUTHENTIFICATION_HOSTID, auth.getHostid())); - byte[] key = auth.getHostkey(); - String encode; - try { - encode = config.cryptoKey.cryptToHex(key); - } catch (Exception e) { - encode = ""; - } - entry.add(newElement(XML_AUTHENTIFICATION_KEY, encode)); - entry.add(newElement(XML_AUTHENTIFICATION_ADMIN, Boolean.toString(auth.isAdminrole()))); - entry.add(newElement(XML_AUTHENTIFICATION_ADDRESS, auth.getAddress())); - entry.add(newElement(XML_AUTHENTIFICATION_PORT, Integer.toString(auth.getPort()))); - entry.add(newElement(XML_AUTHENTIFICATION_ISSSL, Boolean.toString(auth.isSsl()))); - root.add(entry); - } - try { - XmlUtil.writeXML(filename, null, document); - } catch (IOException e) { - throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.configuration; + +import java.io.File; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.dom4j.tree.DefaultElement; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.xml.XmlDecl; +import org.waarp.common.xml.XmlHash; +import org.waarp.common.xml.XmlType; +import org.waarp.common.xml.XmlUtil; +import org.waarp.common.xml.XmlValue; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * Authentication from File support + * + * @author Frederic Bregier + * + */ +public class AuthenticationFileBasedConfiguration { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(AuthenticationFileBasedConfiguration.class); + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ROOT = "authent"; + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ENTRY = "entry"; + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_BASED = "/" + + + XML_AUTHENTIFICATION_ROOT + + "/" + + XML_AUTHENTIFICATION_ENTRY; + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_HOSTID = "hostid"; + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_KEYFILE = "keyfile"; + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_KEY = "key"; + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ADMIN = "admin"; + + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ADDRESS = "address"; + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_PORT = "port"; + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ISSSL = "isssl"; + /** + * Authentication Fields + */ + private static final String XML_AUTHENTIFICATION_ISCLIENT = "isclient"; + + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configAuthenticationDecls = { + // identity + new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_HOSTID), + new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_KEYFILE), + new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_KEY), + new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ADMIN), + new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_ADDRESS), + new XmlDecl(XmlType.INTEGER, XML_AUTHENTIFICATION_PORT), + new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ISSSL), + new XmlDecl(XmlType.BOOLEAN, XML_AUTHENTIFICATION_ISCLIENT) + }; + /** + * Global Structure for Server Configuration + */ + private static final XmlDecl[] authentElements = { + new XmlDecl( + XML_AUTHENTIFICATION_ENTRY, + XmlType.XVAL, + XML_AUTHENTIFICATION_BASED, + configAuthenticationDecls, + true) + }; + + /** + * Load Authentication from File + * + * @param filename + * @return True if OK + */ + @SuppressWarnings("unchecked") + public static boolean loadAuthentication(Configuration config, String filename) { + Document document = null; + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Authentication file: " + + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Authentication file: " + + filename); + return false; + } + XmlValue[] values = XmlUtil.read(document, authentElements); + XmlHash hash = new XmlHash(values); + XmlValue value = hash.get(XML_AUTHENTIFICATION_ENTRY); + List list = (List) value.getList(); + Iterator iterator = list.iterator(); + File key; + byte[] byteKeys; + while (iterator.hasNext()) { + XmlValue[] subvalues = iterator.next(); + XmlHash subHash = new XmlHash(subvalues); + value = subHash.get(XML_AUTHENTIFICATION_HOSTID); + if (value == null || (value.isEmpty())) { + continue; + } + String refHostId = value.getString(); + value = subHash.get(XML_AUTHENTIFICATION_KEYFILE); + if (value == null || (value.isEmpty())) { + value = subHash.get(XML_AUTHENTIFICATION_KEY); + if (value == null || (value.isEmpty())) { + // Allow empty key + byteKeys = null; + } else { + String skey = value.getString(); + // key is crypted + if (skey.length() > 0) { + try { + byteKeys = config.cryptoKey.decryptHexInBytes(skey); + } catch (Exception e) { + logger.error("Cannot read key for hostId " + refHostId + ":" + skey); + continue; + } + } else { + byteKeys = null; + } + } + } else { + String skey = value.getString(); + // load key from file + key = new File(skey); + if (!key.canRead()) { + logger.error("Cannot read key for hostId " + refHostId + ":" + skey); + continue; + } + try { + byteKeys = config.cryptoKey.decryptHexFile(key); + } catch (Exception e2) { + logger.error("Cannot read key for hostId " + refHostId, e2); + continue; + } + } + boolean isAdmin = false; + value = subHash.get(XML_AUTHENTIFICATION_ADMIN); + if (value != null && (!value.isEmpty())) { + isAdmin = value.getBoolean(); + } + value = subHash.get(XML_AUTHENTIFICATION_ADDRESS); + if (value == null || (value.isEmpty())) { + continue; + } + String address = value.getString(); + int port; + value = subHash.get(XML_AUTHENTIFICATION_PORT); + if (value != null && (!value.isEmpty())) { + port = value.getInteger(); + } else { + continue; + } + boolean isSsl = false; + value = subHash.get(XML_AUTHENTIFICATION_ISSSL); + if (value != null && (!value.isEmpty())) { + isSsl = value.getBoolean(); + } + boolean isClient = false; + value = subHash.get(XML_AUTHENTIFICATION_ISCLIENT); + if (value != null && (!value.isEmpty())) { + isClient = value.getBoolean(); + } + DbHostAuth auth = new DbHostAuth(DbConstant.admin.session, + refHostId, address, port, isSsl, byteKeys, isAdmin, isClient); + try { + if (auth.exist()) { + auth.update(); + } else { + auth.insert(); + } + } catch (WaarpDatabaseException e) { + logger.error("Cannot create Authentication for hostId {}", refHostId); + continue; + } + logger.debug("Add {} {}", refHostId, auth); + } + document = null; + hash.clear(); + values = null; + return true; + } + + /** + * Construct a new Element with value + * + * @param name + * @param value + * @return the new Element + */ + private static Element newElement(String name, String value) { + Element node = new DefaultElement(name); + node.addText(value); + return node; + } + + /** + * Write all authentication to a file with filename + * + * @param filename + * @throws OpenR66ProtocolSystemException + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static void writeXML(Configuration config, String filename) + throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + Document document = DocumentHelper.createDocument(); + Element root = document.addElement(XML_AUTHENTIFICATION_ROOT); + DbHostAuth[] hosts = DbHostAuth.getAllHosts(DbConstant.admin.session); + logger.debug("Will write DbHostAuth: "+hosts.length+" in "+filename); + for (DbHostAuth auth : hosts) { + logger.debug("Will write DbHostAuth: "+auth.getHostid()); + Element entry = new DefaultElement(XML_AUTHENTIFICATION_ENTRY); + entry.add(newElement(XML_AUTHENTIFICATION_HOSTID, auth.getHostid())); + byte[] key = auth.getHostkey(); + String encode; + try { + encode = config.cryptoKey.cryptToHex(key); + } catch (Exception e) { + encode = ""; + } + entry.add(newElement(XML_AUTHENTIFICATION_KEY, encode)); + entry.add(newElement(XML_AUTHENTIFICATION_ADMIN, Boolean.toString(auth.isAdminrole()))); + entry.add(newElement(XML_AUTHENTIFICATION_ADDRESS, auth.getAddress())); + entry.add(newElement(XML_AUTHENTIFICATION_PORT, Integer.toString(auth.getPort()))); + entry.add(newElement(XML_AUTHENTIFICATION_ISSSL, Boolean.toString(auth.isSsl()))); + root.add(entry); + } + try { + XmlUtil.writeXML(filename, null, document); + } catch (IOException e) { + throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); + } + } +} diff --git a/src/main/java/org/waarp/openr66/configuration/ExtensionFilter.java b/src/main/java/org/waarp/openr66/configuration/ExtensionFilter.java index 5daea01fc..0666268d8 100644 --- a/src/main/java/org/waarp/openr66/configuration/ExtensionFilter.java +++ b/src/main/java/org/waarp/openr66/configuration/ExtensionFilter.java @@ -1,23 +1,23 @@ -package org.waarp.openr66.configuration; - -import java.io.File; -import java.io.FilenameFilter; - -/** - * Extension Filter based on extension - * - * @author Frederic Bregier - * - */ -public class ExtensionFilter implements FilenameFilter { - String filter = RuleFileBasedConfiguration.EXT_RULE; - - public ExtensionFilter(String filter) { - this.filter = filter; - } - - public boolean accept(File arg0, String arg1) { - return arg1.endsWith(filter); - } - -} +package org.waarp.openr66.configuration; + +import java.io.File; +import java.io.FilenameFilter; + +/** + * Extension Filter based on extension + * + * @author Frederic Bregier + * + */ +public class ExtensionFilter implements FilenameFilter { + String filter = RuleFileBasedConfiguration.EXT_RULE; + + public ExtensionFilter(String filter) { + this.filter = filter; + } + + public boolean accept(File arg0, String arg1) { + return arg1.endsWith(filter); + } + +} diff --git a/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java b/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java index d4b8eed54..9b3ea5d75 100644 --- a/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java +++ b/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java @@ -1,2197 +1,2197 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.configuration; - -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.util.List; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler; -import org.waarp.common.crypto.Des; -import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; -import org.waarp.common.crypto.ssl.WaarpSslContextFactory; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; -import org.waarp.common.exception.CryptoException; -import org.waarp.common.file.DirInterface; -import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; -import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.role.RoleDefault; -import org.waarp.common.role.RoleDefault.ROLE; -import org.waarp.common.xml.XmlDecl; -import org.waarp.common.xml.XmlHash; -import org.waarp.common.xml.XmlType; -import org.waarp.common.xml.XmlUtil; -import org.waarp.common.xml.XmlValue; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.model.DbModelFactory; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.networkhandler.R66ConstraintLimitHandler; -import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; -import org.waarp.openr66.protocol.utils.FileUtils; -import org.waarp.snmp.SnmpConfiguration; - -/** - * File Based Configuration - * - * @author frederic bregier - * - */ -public class FileBasedConfiguration { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(FileBasedConfiguration.class); - - /** - * SERVER HOSTID - */ - private static final String XML_SERVER_HOSTID = "hostid"; - - /** - * SERVER SSL HOSTID - */ - private static final String XML_SERVER_SSLHOSTID = "sslhostid"; - - /** - * ADMINISTRATOR SERVER NAME (shutdown) - */ - private static final String XML_SERVER_ADMIN = "serveradmin"; - - /** - * SERVER PASSWORD (shutdown) - */ - private static final String XML_SERVER_PASSWD = "serverpasswd"; - /** - * SERVER PASSWORD FILE (shutdown) - */ - private static final String XML_SERVER_PASSWD_FILE = "serverpasswdfile"; - /** - * Authentication - */ - private static final String XML_AUTHENTIFICATION_FILE = "authentfile"; - - /** - * SERVER PORT - */ - private static final String XML_SERVER_PORT = "serverport"; - - /** - * SERVER SSL PORT - */ - private static final String XML_SERVER_SSLPORT = "serversslport"; - - /** - * SERVER HTTP PORT - */ - private static final String XML_SERVER_HTTPPORT = "serverhttpport"; - - /** - * SERVER HTTP PORT - */ - private static final String XML_SERVER_HTTPSPORT = "serverhttpsport"; - - /** - * SERVER SSL STOREKEY PATH - */ - private static final String XML_PATH_KEYPATH = "keypath"; - - /** - * SERVER SSL KEY PASS - */ - private static final String XML_PATH_KEYPASS = "keypass"; - - /** - * SERVER SSL STOREKEY PASS - */ - private static final String XML_PATH_KEYSTOREPASS = "keystorepass"; - - /** - * SERVER SSL TRUSTSTOREKEY PATH - */ - private static final String XML_PATH_TRUSTKEYPATH = "trustkeypath"; - - /** - * SERVER SSL TRUSTSTOREKEY PASS - */ - private static final String XML_PATH_TRUSTKEYSTOREPASS = "trustkeystorepass"; - - /** - * SERVER SSL STOREKEY PATH ADMIN - */ - private static final String XML_PATH_ADMIN_KEYPATH = "admkeypath"; - - /** - * SERVER SSL KEY PASS ADMIN - */ - private static final String XML_PATH_ADMIN_KEYPASS = "admkeypass"; - - /** - * SERVER SSL STOREKEY PASS ADMIN - */ - private static final String XML_PATH_ADMIN_KEYSTOREPASS = "admkeystorepass"; - - /** - * SERVER CRYPTO for Password - */ - private static final String XML_PATH_CRYPTOKEY = "cryptokey"; - /** - * Base Directory - */ - private static final String XML_SERVER_HOME = "serverhome"; - - /** - * IN Directory - */ - private static final String XML_INPATH = "in"; - - /** - * OUT Directory - */ - private static final String XML_OUTPATH = "out"; - - /** - * ARCHIVE Directory - */ - private static final String XML_ARCHIVEPATH = "arch"; - - /** - * WORKING Directory - */ - private static final String XML_WORKINGPATH = "work"; - - /** - * CONFIG Directory - */ - private static final String XML_CONFIGPATH = "conf"; - - /** - * HTTP Admin Directory - */ - private static final String XML_HTTPADMINPATH = "httpadmin"; - /** - * Use SSL for R66 connection - */ - private static final String XML_USESSL = "usessl"; - - /** - * Use non SSL for R66 connection - */ - private static final String XML_USENOSSL = "usenossl"; - - /** - * Use HTTP compression for R66 HTTP connection - */ - private static final String XML_USEHTTPCOMP = "usehttpcomp"; - - /** - * SERVER SSL Use TrustStore for Client Authentication - */ - private static final String XML_USECLIENT_AUTHENT = "trustuseclientauthenticate"; - - /** - * Limit per session - */ - private static final String XML_LIMITSESSION = "sessionlimit"; - - /** - * Limit global - */ - private static final String XML_LIMITGLOBAL = "globallimit"; - - /** - * Delay between two checks for Limit - */ - private static final String XML_LIMITDELAY = "delaylimit"; - /** - * Monitoring: how long in ms to get back in monitoring - */ - private static final String XML_MONITOR_PASTLIMIT = "pastlimit"; - /** - * Monitoring: minimal interval in ms before redo real monitoring - */ - private static final String XML_MONITOR_MINIMALDELAY = "minimaldelay"; - /** - * Monitoring: snmp configuration file (if empty, no snmp support) - */ - private static final String XML_MONITOR_SNMP_CONFIG = "snmpconfig"; - /** - * In case of multiple OpenR66 Monitors behing a loadbalancer (ha config) - */ - private static final String XML_MULTIPLE_MONITORS = "multiplemonitors"; - /** - * Usage of CPU Limit - */ - private static final String XML_CSTRT_USECPULIMIT = "usecpulimit"; - - /** - * Usage of JDK CPU Limit (True) or SysMon CPU Limit - */ - private static final String XML_CSTRT_USECPUJDKLIMIT = "usejdkcpulimit"; - - /** - * CPU LIMIT between 0 and 1, where 1 stands for no limit - */ - private static final String XML_CSTRT_CPULIMIT = "cpulimit"; - /** - * Connection limit where 0 stands for no limit - */ - private static final String XML_CSTRT_CONNLIMIT = "connlimit"; - /** - * CPU LOW limit to apply increase of throttle - */ - private static final String XML_CSTRT_LOWCPULIMIT = "lowcpulimit"; - /** - * CPU HIGH limit to apply decrease of throttle, 0 meaning no throttle activated - */ - private static final String XML_CSTRT_HIGHCPULIMIT = "highcpulimit"; - /** - * PERCENTAGE DECREASE of Bandwidth - */ - private static final String XML_CSTRT_PERCENTDECREASE = "percentdecrease"; - /** - * Delay between 2 checks of throttle test - */ - private static final String XML_CSTRT_DELAYTHROTTLE = "delaythrottle"; - /** - * Bandwidth low limit to not got below - */ - private static final String XML_CSTRT_LIMITLOWBANDWIDTH = "limitlowbandwidth"; - /** - * Usage of checking remote address with the DbHost definition - */ - private static final String XML_CHECK_ADDRESS = "checkaddress"; - /** - * Usage of checking remote address also for Client - */ - private static final String XML_CHECK_CLIENTADDRESS = "checkclientaddress"; - - /** - * In case of No Db Client, Usage of saving TaskRunner into independent XML file - */ - private static final String XML_SAVE_TASKRUNNERNODB = "taskrunnernodb"; - - /** - * Use external Waarp Local Exec for ExecTask and ExecMoveTask - */ - private static final String XML_USELOCALEXEC = "uselocalexec"; - - /** - * Address of Waarp Local Exec for ExecTask and ExecMoveTask - */ - private static final String XML_LEXECADDR = "lexecaddr"; - - /** - * Port of Waarp Local Exec for ExecTask and ExecMoveTask - */ - private static final String XML_LEXECPORT = "lexecport"; - - /** - * Default number of threads in pool for Server. - */ - private static final String XML_SERVER_THREAD = "serverthread"; - - /** - * Default number of threads in pool for Client (truly concurrent). - */ - private static final String XML_CLIENT_THREAD = "clientthread"; - - /** - * Memory Limit to use. - */ - private static final String XML_MEMORY_LIMIT = "memorylimit"; - - /** - * Limit of number of active Runner from Commander - */ - private static final String XML_LIMITRUNNING = "runlimit"; - - /** - * Delay between two checks for Commander - */ - private static final String XML_DELAYCOMMANDER = "delaycommand"; - - /** - * Delay between two retry after bad connection - */ - private static final String XML_DELAYRETRY = "delayretry"; - - /** - * Nb of milliseconds after connection is in timeout - */ - private static final String XML_TIMEOUTCON = "timeoutcon"; - - /** - * Should a file MD5 SHA1 be computed using NIO - */ - private static final String XML_USENIO = "usenio"; - - /** - * What Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 - */ - private static final String XML_DIGEST = "digest"; - /** - * Should a file MD5 be computed using FastMD5 - */ - private static final String XML_USEFASTMD5 = "usefastmd5"; - - /** - * If using Fast MD5, should we used the binary JNI library, empty meaning no - */ - private static final String XML_FASTMD5 = "fastmd5"; - - /** - * number of rank to go back when a transfer is restarted. restart is gaprestart*blocksize - */ - private static final String XML_GAPRESTART = "gaprestart"; - /** - * Size by default of block size for receive/sending files. Should be a multiple of 8192 - * (maximum = 64K due to block limitation to 2 bytes) - */ - private static final String XML_BLOCKSIZE = "blocksize"; - /** - * If set to <=0, will not use Thrift support, if set >0 (preferably > 1024) will enable - * Thrift support on the TCP port specified by this number - */ - private static final String XML_USETHRIFT = "usethrift"; - /** - * Database Driver as of oracle, mysql, postgresql, h2 - */ - private static final String XML_DBDRIVER = "dbdriver"; - - /** - * Database Server connection string as of jdbc:type://[host:port],[failoverhost:port] - * .../[database][?propertyName1][ =propertyValue1][&propertyName2][=propertyValue2]... - */ - private static final String XML_DBSERVER = "dbserver"; - - /** - * Database User - */ - private static final String XML_DBUSER = "dbuser"; - - /** - * Database Password - */ - private static final String XML_DBPASSWD = "dbpasswd"; - - /** - * Check version in protocol - */ - private static final String XML_CHECKVERSION = "checkversion"; - /** - * Global digest by transfer enable - */ - private static final String XML_GLOBALDIGEST = "globaldigest"; - /** - * Check version in protocol - */ - private static final String XML_BUSINESSID = "businessid"; - /** - * Role Main entry - */ - private static final String XML_ROLE = "role"; - /** - * ID in role - */ - private static final String XML_ROLEID = "roleid"; - /** - * Role set - */ - private static final String XML_ROLESET = "roleset"; - /** - * Alias - */ - private static final String XML_ALIAS = "alias"; - /** - * Main ID in alias - */ - private static final String XML_REALID = "realid"; - /** - * Alias Id - */ - private static final String XML_ALIASID = "aliasid"; - - - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configIdentityDecls = { - // identity - new XmlDecl(XmlType.STRING, XML_SERVER_HOSTID), - new XmlDecl(XmlType.STRING, XML_SERVER_SSLHOSTID), - new XmlDecl(XmlType.STRING, XML_PATH_CRYPTOKEY), - new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_FILE) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configServerParamDecls = { - // server - new XmlDecl(XmlType.BOOLEAN, XML_USESSL), - new XmlDecl(XmlType.BOOLEAN, XML_USENOSSL), - new XmlDecl(XmlType.BOOLEAN, XML_USEHTTPCOMP), - new XmlDecl(XmlType.BOOLEAN, XML_USELOCALEXEC), - new XmlDecl(XmlType.STRING, XML_LEXECADDR), - new XmlDecl(XmlType.INTEGER, XML_LEXECPORT), - new XmlDecl(XmlType.BOOLEAN, XML_CHECK_ADDRESS), - new XmlDecl(XmlType.BOOLEAN, XML_CHECK_CLIENTADDRESS), - new XmlDecl(XmlType.STRING, XML_SERVER_ADMIN), - new XmlDecl(XmlType.STRING, XML_SERVER_PASSWD), - new XmlDecl(XmlType.STRING, XML_SERVER_PASSWD_FILE), - new XmlDecl(XmlType.STRING, XML_HTTPADMINPATH), - new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYPATH), - new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYSTOREPASS), - new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYPASS), - new XmlDecl(XmlType.LONG, XML_MONITOR_PASTLIMIT), - new XmlDecl(XmlType.LONG, XML_MONITOR_MINIMALDELAY), - new XmlDecl(XmlType.STRING, XML_MONITOR_SNMP_CONFIG), - new XmlDecl(XmlType.INTEGER, XML_MULTIPLE_MONITORS) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configNetworkServerDecls = { - // network - new XmlDecl(XmlType.INTEGER, XML_SERVER_PORT), - new XmlDecl(XmlType.INTEGER, XML_SERVER_SSLPORT), - new XmlDecl(XmlType.INTEGER, XML_SERVER_HTTPPORT), - new XmlDecl(XmlType.INTEGER, XML_SERVER_HTTPSPORT) - }; - - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configSslDecls = { - // ssl - new XmlDecl(XmlType.STRING, XML_PATH_KEYPATH), - new XmlDecl(XmlType.STRING, XML_PATH_KEYSTOREPASS), - new XmlDecl(XmlType.STRING, XML_PATH_KEYPASS), - new XmlDecl(XmlType.STRING, XML_PATH_TRUSTKEYPATH), - new XmlDecl(XmlType.STRING, XML_PATH_TRUSTKEYSTOREPASS), - new XmlDecl(XmlType.BOOLEAN, XML_USECLIENT_AUTHENT) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configDbDecls = { - // db - new XmlDecl(XmlType.STRING, XML_DBDRIVER), - new XmlDecl(XmlType.STRING, XML_DBSERVER), - new XmlDecl(XmlType.STRING, XML_DBUSER), - new XmlDecl(XmlType.STRING, XML_DBPASSWD), - new XmlDecl(XmlType.BOOLEAN, XML_SAVE_TASKRUNNERNODB) - }; - - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configLimitDecls = { - // limit - new XmlDecl(XmlType.LONG, XML_LIMITSESSION), - new XmlDecl(XmlType.LONG, XML_LIMITGLOBAL), - new XmlDecl(XmlType.LONG, XML_LIMITDELAY), - new XmlDecl(XmlType.INTEGER, XML_LIMITRUNNING), - new XmlDecl(XmlType.LONG, XML_DELAYCOMMANDER), - new XmlDecl(XmlType.LONG, XML_DELAYRETRY), - new XmlDecl(XmlType.INTEGER, XML_SERVER_THREAD), - new XmlDecl(XmlType.INTEGER, XML_CLIENT_THREAD), - new XmlDecl(XmlType.LONG, XML_MEMORY_LIMIT), - new XmlDecl(XmlType.BOOLEAN, XML_CSTRT_USECPULIMIT), - new XmlDecl(XmlType.BOOLEAN, XML_CSTRT_USECPUJDKLIMIT), - new XmlDecl(XmlType.DOUBLE, XML_CSTRT_CPULIMIT), - new XmlDecl(XmlType.INTEGER, XML_CSTRT_CONNLIMIT), - new XmlDecl(XmlType.DOUBLE, XML_CSTRT_LOWCPULIMIT), - new XmlDecl(XmlType.DOUBLE, XML_CSTRT_HIGHCPULIMIT), - new XmlDecl(XmlType.DOUBLE, XML_CSTRT_PERCENTDECREASE), - new XmlDecl(XmlType.LONG, XML_CSTRT_LIMITLOWBANDWIDTH), - new XmlDecl(XmlType.LONG, XML_CSTRT_DELAYTHROTTLE), - new XmlDecl(XmlType.LONG, XML_TIMEOUTCON), - new XmlDecl(XmlType.BOOLEAN, XML_USENIO), - new XmlDecl(XmlType.INTEGER, XML_DIGEST), - new XmlDecl(XmlType.BOOLEAN, XML_USEFASTMD5), - new XmlDecl(XmlType.STRING, XML_FASTMD5), - new XmlDecl(XmlType.INTEGER, XML_GAPRESTART), - new XmlDecl(XmlType.INTEGER, XML_BLOCKSIZE), - new XmlDecl(XmlType.INTEGER, XML_USETHRIFT), - new XmlDecl(XmlType.BOOLEAN, XML_CHECKVERSION), - new XmlDecl(XmlType.BOOLEAN, XML_GLOBALDIGEST) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configSubmitLimitDecls = { - // limit - new XmlDecl( - XmlType.INTEGER, - XML_BLOCKSIZE) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configClientParamDecls = { - // client - new XmlDecl( - XmlType.BOOLEAN, - XML_SAVE_TASKRUNNERNODB), - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configDirectoryDecls = { - // directory - new XmlDecl(XmlType.STRING, XML_SERVER_HOME), - new XmlDecl(XmlType.STRING, XML_INPATH), - new XmlDecl(XmlType.STRING, XML_OUTPATH), - new XmlDecl(XmlType.STRING, XML_ARCHIVEPATH), - new XmlDecl(XmlType.STRING, XML_WORKINGPATH), - new XmlDecl(XmlType.STRING, XML_CONFIGPATH) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configRoleDecls = { - // roles - new XmlDecl(XmlType.STRING, XML_ROLEID), - new XmlDecl(XmlType.STRING, XML_ROLESET) - }; - /** - * Structure of the Configuration file - * - */ - private static final XmlDecl[] configAliasDecls = { - // roles - new XmlDecl(XmlType.STRING, XML_REALID), - new XmlDecl(XmlType.STRING, XML_ALIASID) - }; - - /** - * Overall structure of the Configuration file - */ - private static final String XML_ROOT = "/config/"; - private static final String XML_IDENTITY = "identity"; - private static final String XML_SERVER = "server"; - private static final String XML_CLIENT = "client"; - private static final String XML_DIRECTORY = "directory"; - private static final String XML_LIMIT = "limit"; - private static final String XML_NETWORK = "network"; - private static final String XML_SSL = "ssl"; - private static final String XML_DB = "db"; - private static final String XML_BUSINESS = "business"; - private static final String XML_ROLES = "roles"; - private static final String XML_ALIASES = "aliases"; - - /** - * Global Structure for Server Configuration - */ - private static final XmlDecl[] configServer = { - new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, - false), - new XmlDecl(XML_SERVER, XmlType.XVAL, XML_ROOT + XML_SERVER, configServerParamDecls, - false), - new XmlDecl(XML_NETWORK, XmlType.XVAL, XML_ROOT + XML_NETWORK, - configNetworkServerDecls, false), - new XmlDecl(XML_SSL, XmlType.XVAL, XML_ROOT + XML_SSL, configSslDecls, false), - new XmlDecl(XML_DIRECTORY, XmlType.XVAL, XML_ROOT + XML_DIRECTORY, - configDirectoryDecls, false), - new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configLimitDecls, false), - new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), - new XmlDecl(XML_BUSINESS, XmlType.STRING, XML_ROOT + XML_BUSINESS + "/" - + XML_BUSINESSID, true), - new XmlDecl(XML_ROLES, XmlType.XVAL, XML_ROOT + XML_ROLES + "/" - + XML_ROLE, configRoleDecls, true), - new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" - + XML_ALIAS, configAliasDecls, true) - }; - /** - * Global Structure for Client Configuration - */ - private static final XmlDecl[] configClient = { - new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, - false), - new XmlDecl(XML_CLIENT, XmlType.XVAL, XML_ROOT + XML_CLIENT, configClientParamDecls, - false), - new XmlDecl(XML_SSL, XmlType.XVAL, XML_ROOT + XML_SSL, configSslDecls, false), - new XmlDecl(XML_DIRECTORY, XmlType.XVAL, XML_ROOT + XML_DIRECTORY, - configDirectoryDecls, false), - new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configLimitDecls, false), - new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), - new XmlDecl(XML_BUSINESS, XmlType.STRING, XML_ROOT + XML_BUSINESS + "/" - + XML_BUSINESSID, true), - new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" - + XML_ALIAS, configAliasDecls, true) - }; - /** - * Global Structure for Submit only Client Configuration - */ - private static final XmlDecl[] configSubmitClient = { - new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, - false), - new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configSubmitLimitDecls, - false), - new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), - new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" - + XML_ALIAS, configAliasDecls, true) - }; - private static XmlValue[] configuration = null; - private static XmlHash hashConfig = null; - - private static boolean loadIdentity(Configuration config) { - XmlValue value = hashConfig.get(XML_SERVER_HOSTID); - if (value != null && (!value.isEmpty())) { - config.HOST_ID = value.getString(); - config.REQER_HOST_ID = config.HOST_ID + "__rd__"; - config.REQED_HOST_ID = config.HOST_ID + "__rr__"; - } else { - logger.error("Unable to find Host ID in Config file"); - return false; - } - value = hashConfig.get(XML_SERVER_SSLHOSTID); - if (value != null && (!value.isEmpty())) { - config.HOST_SSLID = value.getString(); - } else { - logger - .warn("Unable to find Host SSL ID in Config file so no SSL support will be used"); - config.useSSL = false; - config.HOST_SSLID = null; - } - return setCryptoKey(config); - } - - private static boolean loadAuthentication(Configuration config) { - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - XmlValue value = hashConfig.get(XML_AUTHENTIFICATION_FILE); - if (value != null && (!value.isEmpty())) { - String fileauthent = value.getString(); - if (!AuthenticationFileBasedConfiguration - .loadAuthentication(config, fileauthent)) { - return false; - } - } else { - logger.warn("Unable to find Authentication file in Config file"); - return false; - } - } - return true; - } - - private static boolean loadServerParam(Configuration config) { - XmlValue value = hashConfig.get(XML_USESSL); - if (value != null && (!value.isEmpty())) { - config.useSSL = value.getBoolean(); - } - value = hashConfig.get(XML_USENOSSL); - if (value != null && (!value.isEmpty())) { - config.useNOSSL = value.getBoolean(); - } - value = hashConfig.get(XML_USEHTTPCOMP); - if (value != null && (!value.isEmpty())) { - config.useHttpCompression = value.getBoolean(); - } - value = hashConfig.get(XML_USELOCALEXEC); - if (value != null && (!value.isEmpty())) { - config.useLocalExec = value.getBoolean(); - if (config.useLocalExec) { - value = hashConfig.get(XML_LEXECADDR); - String saddr; - InetAddress addr; - if (value != null && (!value.isEmpty())) { - saddr = value.getString(); - try { - addr = InetAddress.getByName(saddr); - } catch (UnknownHostException e) { - logger.error("Unable to find LocalExec Address in Config file"); - return false; - } - } else { - logger.warn("Unable to find LocalExec Address in Config file"); - try { - addr = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); - } catch (UnknownHostException e) { - logger.error("Unable to find LocalExec Address in Config file"); - return false; - } - } - value = hashConfig.get(XML_LEXECPORT); - int port; - if (value != null && (!value.isEmpty())) { - port = value.getInteger(); - } else { - port = 9999; - } - LocalExecClient.address = new InetSocketAddress(addr, port); - } - } - value = hashConfig.get(XML_CHECK_ADDRESS); - if (value != null && (!value.isEmpty())) { - config.checkRemoteAddress = value.getBoolean(); - } - value = hashConfig.get(XML_CHECK_CLIENTADDRESS); - if (value != null && (!value.isEmpty())) { - config.checkClientAddress = value.getBoolean(); - } - value = hashConfig.get(XML_SERVER_ADMIN); - if (value != null && (!value.isEmpty())) { - config.ADMINNAME = value.getString(); - } else { - logger.error("Unable to find Administrator name in Config file"); - return false; - } - if (config.cryptoKey == null) { - if (!setCryptoKey(config)) { - logger.error("Unable to find Crypto Key in Config file"); - return false; - } - } - byte[] decodedByteKeys = null; - value = hashConfig.get(XML_SERVER_PASSWD_FILE); - if (value == null || (value.isEmpty())) { - String passwd; - value = hashConfig.get(XML_SERVER_PASSWD); - if (value != null && (!value.isEmpty())) { - passwd = value.getString(); - } else { - logger.error("Unable to find Password in Config file"); - return false; - } - try { - decodedByteKeys = - config.cryptoKey.decryptHexInBytes(passwd); - } catch (Exception e) { - logger.error( - "Unable to Decrypt Server Password in Config file from: " + - passwd, e); - return false; - } - } else { - String skey = value.getString(); - // load key from file - config.serverKeyFile = skey; - File key = new File(skey); - if (!key.canRead()) { - logger.error("Unable to read Password in Config file from " + skey); - return false; - } - try { - decodedByteKeys = config.cryptoKey.decryptHexFile(key); - } catch (Exception e2) { - logger.error( - "Unable to Decrypt Server Password in Config file from: " + - skey, e2); - return false; - } - } - config.setSERVERKEY(decodedByteKeys); - value = hashConfig.get(XML_HTTPADMINPATH); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find Http Admin Base in Config file"); - return false; - } - String path = value.getString(); - if (path == null || path.length() == 0) { - logger.error("Unable to set correct Http Admin Base in Config file"); - return false; - } - File file = new File(path); - if (!file.isDirectory()) { - logger.error("Http Admin is not a directory in Config file"); - return false; - } - try { - config.httpBasePath = - FilesystemBasedDirImpl.normalizePath(file.getCanonicalPath()) + - DirInterface.SEPARATOR; - } catch (IOException e1) { - logger.error("Unable to set Http Admin Path in Config file"); - return false; - } - - // Key for HTTPS - value = hashConfig.get(XML_PATH_ADMIN_KEYPATH); - if (value != null && (!value.isEmpty())) { - String keypath = value.getString(); - if ((keypath == null) || (keypath.length() == 0)) { - logger.error("Bad Key Path"); - return false; - } - value = hashConfig.get(XML_PATH_ADMIN_KEYSTOREPASS); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find KeyStore Passwd"); - return false; - } - String keystorepass = value.getString(); - if ((keystorepass == null) || (keystorepass.length() == 0)) { - logger.error("Bad KeyStore Passwd"); - return false; - } - value = hashConfig.get(XML_PATH_ADMIN_KEYPASS); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find Key Passwd"); - return false; - } - String keypass = value.getString(); - if ((keypass == null) || (keypass.length() == 0)) { - logger.error("Bad Key Passwd"); - return false; - } - try { - Configuration.WaarpSecureKeyStore = - new WaarpSecureKeyStore(keypath, keystorepass, - keypass); - } catch (CryptoException e) { - logger.error("Bad SecureKeyStore construction for AdminSsl"); - return false; - } - // No client authentication - Configuration.WaarpSecureKeyStore.initEmptyTrustStore(); - Configuration.waarpSslContextFactory = - new WaarpSslContextFactory( - Configuration.WaarpSecureKeyStore, true); - } - value = hashConfig.get(XML_MONITOR_PASTLIMIT); - if (value != null && (!value.isEmpty())) { - config.pastLimit = (value.getLong() / 10) * 10; - } - value = hashConfig.get(XML_MONITOR_MINIMALDELAY); - if (value != null && (!value.isEmpty())) { - config.minimalDelay = (value.getLong() / 10) * 10; - } - value = hashConfig.get(XML_MONITOR_SNMP_CONFIG); - if (value != null && (!value.isEmpty())) { - config.snmpConfig = value.getString(); - File snmpfile = new File(config.snmpConfig); - if (snmpfile.canRead()) { - if (!SnmpConfiguration.setConfigurationFromXml(snmpfile)) { - config.snmpConfig = null; - } - } else { - config.snmpConfig = null; - } - } - value = hashConfig.get(XML_MULTIPLE_MONITORS); - if (value != null && (!value.isEmpty())) { - config.multipleMonitors = value.getInteger(); - logger.warn("Multiple Monitor configuration active for " - + config.multipleMonitors - + " servers in HA behind a Load Balancer in TCP"); - } else { - config.multipleMonitors = 1; - logger.warn("Multiple Monitor configuration unactive"); - } - return true; - } - - private static boolean loadClientParam(Configuration config) { - XmlValue value = hashConfig.get(XML_SAVE_TASKRUNNERNODB); - if (value != null && (!value.isEmpty())) { - config.saveTaskRunnerWithNoDb = value.getBoolean(); - } - return true; - } - - private static boolean loadDirectory(Configuration config) { - XmlValue value = hashConfig.get(XML_SERVER_HOME); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find Home in Config file"); - return false; - } - String path = value.getString(); - File file = new File(path); - if (!file.isDirectory()) { - logger.error("Home is not a directory in Config file"); - return false; - } - try { - config.baseDirectory = FilesystemBasedDirImpl - .normalizePath(file.getCanonicalPath()); - } catch (IOException e1) { - logger.error("Unable to set Home in Config file"); - return false; - } - try { - config.configPath = FilesystemBasedDirImpl - .normalizePath(getSubPath(config, XML_CONFIGPATH)); - } catch (OpenR66ProtocolSystemException e2) { - logger.error("Unable to set Config in Config file"); - return false; - } - try { - config.inPath = FilesystemBasedDirImpl - .normalizePath(getSubPath(config, XML_INPATH)); - } catch (OpenR66ProtocolSystemException e2) { - logger.error("Unable to set In in Config file"); - return false; - } - try { - config.outPath = FilesystemBasedDirImpl - .normalizePath(getSubPath(config, XML_OUTPATH)); - } catch (OpenR66ProtocolSystemException e2) { - logger.error("Unable to set Out in Config file"); - return false; - } - try { - config.workingPath = FilesystemBasedDirImpl - .normalizePath(getSubPath(config, XML_WORKINGPATH)); - } catch (OpenR66ProtocolSystemException e2) { - logger.error("Unable to set Working in Config file"); - return false; - } - try { - config.archivePath = FilesystemBasedDirImpl - .normalizePath(getSubPath(config, XML_ARCHIVEPATH)); - } catch (OpenR66ProtocolSystemException e2) { - logger.error("Unable to set Archive in Config file"); - return false; - } - return true; - } - - private static boolean alreadySetLimit = false; - - private static boolean loadLimit(Configuration config, boolean updateLimit) { - if (alreadySetLimit) { - return true; - } - XmlValue value = hashConfig.get(XML_LIMITGLOBAL); - if (value != null && (!value.isEmpty())) { - config.serverGlobalReadLimit = value.getLong(); - if (config.serverGlobalReadLimit <= 0) { - config.serverGlobalReadLimit = 0; - } - config.serverGlobalWriteLimit = config.serverGlobalReadLimit; - logger.info("Global Limit: {}", - config.serverGlobalReadLimit); - } - value = hashConfig.get(XML_LIMITSESSION); - if (value != null && (!value.isEmpty())) { - config.serverChannelReadLimit = value.getLong(); - if (config.serverChannelReadLimit <= 0) { - config.serverChannelReadLimit = 0; - } - config.serverChannelWriteLimit = config.serverChannelReadLimit; - logger.info("SessionInterface Limit: {}", - config.serverChannelReadLimit); - } - config.anyBandwidthLimitation = - (config.serverGlobalReadLimit > 0 || config.serverGlobalWriteLimit > 0 || - config.serverChannelReadLimit > 0 || config.serverChannelWriteLimit > 0); - config.delayLimit = AbstractTrafficShapingHandler.DEFAULT_CHECK_INTERVAL; - value = hashConfig.get(XML_LIMITDELAY); - if (value != null && (!value.isEmpty())) { - config.delayLimit = (value.getLong() / 10) * 10; - if (config.delayLimit <= 0) { - config.delayLimit = 0; - } - logger.info("Delay Limit: {}", - config.delayLimit); - } - value = hashConfig.get(XML_LIMITRUNNING); - if (value != null && (!value.isEmpty())) { - config.RUNNER_THREAD = value.getInteger(); - } - if (config.RUNNER_THREAD < 10) { - config.RUNNER_THREAD = 10; - } - logger.info("Limit of Runner: {}", - config.RUNNER_THREAD); - value = hashConfig.get(XML_DELAYCOMMANDER); - if (value != null && (!value.isEmpty())) { - config.delayCommander = (value.getLong() / 10) * 10; - if (config.delayCommander <= 100) { - config.delayCommander = 100; - } - logger.info("Delay Commander: {}", - config.delayCommander); - } - value = hashConfig.get(XML_DELAYRETRY); - if (value != null && (!value.isEmpty())) { - config.delayRetry = (value.getLong() / 10) * 10; - if (config.delayRetry <= 1000) { - config.delayRetry = 1000; - } - logger.info("Delay Retry: {}", - config.delayRetry); - } - if (DbConstant.admin.isConnected && updateLimit) { - value = hashConfig.get(XML_SERVER_HOSTID); - if (value != null && (!value.isEmpty())) { - config.HOST_ID = value.getString(); - DbConfiguration configuration = new DbConfiguration( - DbConstant.admin.session, - config.HOST_ID, - config.serverGlobalReadLimit, - config.serverGlobalWriteLimit, - config.serverChannelReadLimit, - config.serverChannelWriteLimit, - config.delayLimit); - configuration.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - try { - if (configuration.exist()) { - configuration.update(); - } else { - configuration.insert(); - } - } catch (WaarpDatabaseException e) { - } - } - } - boolean useCpuLimit = false; - boolean useCpuLimitJDK = false; - double cpulimit = 1.0; - value = hashConfig.get(XML_CSTRT_USECPULIMIT); - if (value != null && (!value.isEmpty())) { - useCpuLimit = value.getBoolean(); - value = hashConfig.get(XML_CSTRT_USECPUJDKLIMIT); - if (value != null && (!value.isEmpty())) { - useCpuLimitJDK = value.getBoolean(); - } - value = hashConfig.get(XML_CSTRT_CPULIMIT); - if (value != null && (!value.isEmpty())) { - cpulimit = value.getDouble(); - } - } - int connlimit = 0; - value = hashConfig.get(XML_CSTRT_CONNLIMIT); - if (value != null && (!value.isEmpty())) { - connlimit = value.getInteger(); - } - double lowcpuLimit = 0; - double highcpuLimit = 0; - double percentageDecrease = 0; - long delay = 1000000; - long limitLowBandwidth = 4096; - value = hashConfig.get(XML_CSTRT_LOWCPULIMIT); - if (value != null && (!value.isEmpty())) { - lowcpuLimit = value.getDouble(); - } - value = hashConfig.get(XML_CSTRT_HIGHCPULIMIT); - if (value != null && (!value.isEmpty())) { - highcpuLimit = value.getDouble(); - } - value = hashConfig.get(XML_CSTRT_PERCENTDECREASE); - if (value != null && (!value.isEmpty())) { - percentageDecrease = value.getDouble(); - } - value = hashConfig.get(XML_CSTRT_DELAYTHROTTLE); - if (value != null && (!value.isEmpty())) { - delay = (value.getLong() / 10) * 10; - } - value = hashConfig.get(XML_CSTRT_LIMITLOWBANDWIDTH); - if (value != null && (!value.isEmpty())) { - limitLowBandwidth = value.getLong(); - } - if (highcpuLimit > 0) { - config.constraintLimitHandler = - new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit, connlimit, - lowcpuLimit, highcpuLimit, percentageDecrease, null, delay, - limitLowBandwidth); - } else { - config.constraintLimitHandler = - new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit, connlimit); - } - value = hashConfig.get(XML_SERVER_THREAD); - if (value != null && (!value.isEmpty())) { - config.SERVER_THREAD = value.getInteger(); - } - value = hashConfig.get(XML_CLIENT_THREAD); - if (value != null && (!value.isEmpty())) { - config.CLIENT_THREAD = value.getInteger(); - } - value = hashConfig.get(XML_MEMORY_LIMIT); - if (value != null && (!value.isEmpty())) { - config.maxGlobalMemory = value.getLong(); - } - Configuration.getFileParameter().deleteOnAbort = false; - value = hashConfig.get(XML_USENIO); - if (value != null && (!value.isEmpty())) { - FilesystemBasedFileParameterImpl.useNio = value.getBoolean(); - } - value = hashConfig.get(XML_DIGEST); - if (value != null && (!value.isEmpty())) { - int val = value.getInteger(); - if (val < 0 || val >= DigestAlgo.values().length) { - val = 0; - } - config.digest = DigestAlgo.values()[val]; - } - logger.warn("DigestAlgo used: {}", config.digest); - value = hashConfig.get(XML_USEFASTMD5); - if (value != null && (!value.isEmpty())) { - FilesystemBasedDigest.useFastMd5 = value.getBoolean(); - } else { - FilesystemBasedDigest.useFastMd5 = false; - } - value = hashConfig.get(XML_GAPRESTART); - if (value != null && (!value.isEmpty())) { - Configuration.RANKRESTART = value.getInteger(); - if (Configuration.RANKRESTART <= 0) { - Configuration.RANKRESTART = 1; - } - } - value = hashConfig.get(XML_BLOCKSIZE); - if (value != null && (!value.isEmpty())) { - config.BLOCKSIZE = value.getInteger(); - } - value = hashConfig.get(XML_USETHRIFT); - if (value != null && (!value.isEmpty())) { - config.thriftport = value.getInteger(); - } - value = hashConfig.get(XML_TIMEOUTCON); - if (value != null && (!value.isEmpty())) { - config.TIMEOUTCON = (value.getLong() / 10) * 10; - config.shutdownConfiguration.timeout = config.TIMEOUTCON; - } - value = hashConfig.get(XML_CHECKVERSION); - if (value != null && (!value.isEmpty())) { - config.extendedProtocol = value.getBoolean(); - logger.warn("ExtendedProtocol= " + config.extendedProtocol); - } - value = hashConfig.get(XML_GLOBALDIGEST); - if (value != null && (!value.isEmpty())) { - config.globalDigest = value.getBoolean(); - } - alreadySetLimit = true; - return true; - } - - private static boolean loadSsl(Configuration config) { - // StoreKey for Server - XmlValue value = hashConfig.get(XML_PATH_KEYPATH); - if (value == null || (value.isEmpty())) { - logger.info("Unable to find Key Path"); - try { - NetworkSslServerPipelineFactory.WaarpSecureKeyStore = - new WaarpSecureKeyStore("secret", "secret"); - } catch (CryptoException e) { - logger.error("Bad SecureKeyStore construction"); - return false; - } - } else { - String keypath = value.getString(); - if ((keypath == null) || (keypath.length() == 0)) { - logger.error("Bad Key Path"); - return false; - } - value = hashConfig.get(XML_PATH_KEYSTOREPASS); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find KeyStore Passwd"); - return false; - } - String keystorepass = value.getString(); - if ((keystorepass == null) || (keystorepass.length() == 0)) { - logger.error("Bad KeyStore Passwd"); - return false; - } - value = hashConfig.get(XML_PATH_KEYPASS); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find Key Passwd"); - return false; - } - String keypass = value.getString(); - if ((keypass == null) || (keypass.length() == 0)) { - logger.error("Bad Key Passwd"); - return false; - } - try { - NetworkSslServerPipelineFactory.WaarpSecureKeyStore = - new WaarpSecureKeyStore(keypath, keystorepass, - keypass); - } catch (CryptoException e) { - logger.error("Bad SecureKeyStore construction"); - return false; - } - - } - // TrustedKey for OpenR66 server - value = hashConfig.get(XML_PATH_TRUSTKEYPATH); - if (value == null || (value.isEmpty())) { - logger.info("Unable to find TRUST Key Path"); - NetworkSslServerPipelineFactory.WaarpSecureKeyStore.initEmptyTrustStore(); - } else { - String keypath = value.getString(); - if ((keypath == null) || (keypath.length() == 0)) { - logger.error("Bad TRUST Key Path"); - return false; - } - value = hashConfig.get(XML_PATH_TRUSTKEYSTOREPASS); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find TRUST KeyStore Passwd"); - return false; - } - String keystorepass = value.getString(); - if ((keystorepass == null) || (keystorepass.length() == 0)) { - logger.error("Bad TRUST KeyStore Passwd"); - return false; - } - boolean useClientAuthent = false; - value = hashConfig.get(XML_USECLIENT_AUTHENT); - if (value != null && (!value.isEmpty())) { - useClientAuthent = value.getBoolean(); - } - try { - NetworkSslServerPipelineFactory.WaarpSecureKeyStore.initTrustStore(keypath, - keystorepass, useClientAuthent); - } catch (CryptoException e) { - logger.error("Bad TrustKeyStore construction"); - return false; - } - } - NetworkSslServerPipelineFactory.waarpSslContextFactory = - new WaarpSslContextFactory( - NetworkSslServerPipelineFactory.WaarpSecureKeyStore); - return true; - } - - private static boolean loadNetworkServer(Configuration config) { - XmlValue value = hashConfig.get(XML_SERVER_PORT); - int port = 6666; - if (value != null && (!value.isEmpty())) { - port = value.getInteger(); - } else { - port = 6666; - } - config.SERVER_PORT = port; - value = hashConfig.get(XML_SERVER_SSLPORT); - int sslport = 6667; - if (value != null && (!value.isEmpty())) { - sslport = value.getInteger(); - } else { - sslport = 6667; - } - config.SERVER_SSLPORT = sslport; - value = hashConfig.get(XML_SERVER_HTTPPORT); - int httpport = 8066; - if (value != null && (!value.isEmpty())) { - httpport = value.getInteger(); - } - config.SERVER_HTTPPORT = httpport; - value = hashConfig.get(XML_SERVER_HTTPSPORT); - int httpsport = 8067; - if (value != null && (!value.isEmpty())) { - httpsport = value.getInteger(); - } - config.SERVER_HTTPSPORT = httpsport; - return true; - } - - /** - * Set the Crypto Key from the Document - * - * @param document - * @return True if OK - */ - private static boolean setCryptoKey(Configuration config) { - XmlValue value = hashConfig.get(XML_PATH_CRYPTOKEY); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find CryptoKey in Config file"); - return false; - } - String filename = value.getString(); - config.cryptoFile = filename; - File key = new File(filename); - Des des = new Des(); - try { - des.setSecretKey(key); - } catch (CryptoException e) { - logger.error("Unable to load CryptoKey from Config file"); - return false; - } catch (IOException e) { - logger.error("Unable to load CryptoKey from Config file"); - return false; - } - config.cryptoKey = des; - return true; - } - - /** - * Load data from database or from files if not connected - * - * @param document - * @return True if OK - */ - private static boolean loadFromDatabase(Configuration config) { - if (DbConstant.admin.isConnected) { - // load from database the limit to apply - try { - DbConfiguration configuration = new DbConfiguration( - DbConstant.admin.session, - config.HOST_ID); - configuration.updateConfiguration(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot load configuration from database", e); - } - } else { - if (config.baseDirectory != null && - config.configPath != null) { - // load Rules from files - File dirConfig = new File( - config.baseDirectory + - config.configPath); - if (dirConfig.isDirectory()) { - try { - RuleFileBasedConfiguration.importRules(dirConfig); - } catch (OpenR66ProtocolSystemException e) { - logger.error("Cannot load Rules", e); - return false; - } catch (WaarpDatabaseException e) { - logger.error("Cannot load Rules", e); - return false; - } - } else { - logger.error("Config Directory is not a directory: " + - config.baseDirectory + - config.configPath); - return false; - } - } - // load if possible the limit to apply - loadLimit(config, false); - } - return true; - } - - /** - * Load database parameter - * - * @param document - * @return True if OK - */ - private static boolean loadDatabase(Configuration config) { - XmlValue value = hashConfig.get(XML_DBDRIVER); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find DBDriver in Config file"); - DbConstant.admin = new DbAdmin(); // no database support - DbConstant.noCommitAdmin = DbConstant.admin; - } else { - String dbdriver = value.getString(); - value = hashConfig.get(XML_DBSERVER); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find DBServer in Config file"); - return false; - } - String dbserver = value.getString(); - value = hashConfig.get(XML_DBUSER); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find DBUser in Config file"); - return false; - } - String dbuser = value.getString(); - value = hashConfig.get(XML_DBPASSWD); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find DBPassword in Config file"); - return false; - } - String dbpasswd = value.getString(); - if (dbdriver == null || dbserver == null || dbuser == null || - dbpasswd == null || dbdriver.length() == 0 || - dbserver.length() == 0 || dbuser.length() == 0 || - dbpasswd.length() == 0) { - logger.error("Unable to find Correct DB data in Config file"); - return false; - } - try { - DbConstant.admin = - DbModelFactory.initialize(dbdriver, dbserver, dbuser, dbpasswd, - true); - if (config.multipleMonitors > 1) { - DbConstant.noCommitAdmin = - DbModelFactory.initialize(dbdriver, dbserver, dbuser, dbpasswd, - true); - DbConstant.noCommitAdmin.session.setAutoCommit(false); - } else { - DbConstant.noCommitAdmin = DbConstant.admin; - } - logger.info("Database connection: " + (DbConstant.admin != null) + ":" - + (DbConstant.noCommitAdmin != null)); - } catch (WaarpDatabaseNoConnectionException e2) { - logger.error("Unable to Connect to DB", e2); - return false; - } - } - value = hashConfig.get(XML_SAVE_TASKRUNNERNODB); - if (value != null && (!value.isEmpty())) { - config.saveTaskRunnerWithNoDb = value.getBoolean(); - } - return true; - } - - /** - * Load white list for Business if any - * - * @param document - */ - private static void loadBusinessWhiteList(Configuration config) { - XmlValue value = hashConfig.get(XML_BUSINESS); - if (value != null && (value.getList() != null)) { - @SuppressWarnings("unchecked") - List ids = (List) value.getList(); - if (ids != null) { - for (String sval : ids) { - if (sval.isEmpty()) { - continue; - } - logger.warn("Business Allow: " + sval); - config.businessWhiteSet.add(sval.trim()); - } - ids.clear(); - ids = null; - } - } - loadAliases(config); - // now check in DB - if (DbConstant.admin != null) { - try { - DbHostConfiguration hostconfiguration = new DbHostConfiguration(DbConstant.admin.session, config.HOST_ID); - if (hostconfiguration != null) { - updateHostConfiguration(config, hostconfiguration); - } - } catch (WaarpDatabaseException e) { - // ignore - } - - } - } - @SuppressWarnings("unchecked") - public static void loadAliases(Configuration config) { - XmlValue value = hashConfig.get(XML_ALIASES); - if (value != null && (value.getList() != null)) { - for (XmlValue[] xml : (List) value.getList()) { - XmlHash subHash = new XmlHash(xml); - value = subHash.get(XML_REALID); - if (value == null || (value.isEmpty())) { - continue; - } - String refHostId = value.getString(); - value = subHash.get(XML_ALIASID); - if (value == null || (value.isEmpty())) { - continue; - } - String aliasset = value.getString(); - String [] alias = aliasset.split(" |\\|"); - for (String namealias : alias) { - config.aliases.put(namealias, refHostId); - } - logger.warn("Aliases for: " + refHostId +" = "+ aliasset); - } - } - } - @SuppressWarnings("unchecked") - public static void updateHostConfiguration(Configuration config, DbHostConfiguration hostConfiguration) { - String business = hostConfiguration.getBusiness(); - Document document = null; - // Open config file - StringReader reader = null; - try { - reader = new StringReader(business); - document = new SAXReader().read(reader); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config Business string: " + business, e); - if (reader != null) { - reader.close(); - } - return; - } - if (document == null) { - logger.error("Unable to read the XML Config Business string: " + business); - if (reader != null) { - reader.close(); - } - return; - } - // XXX FIXME - List list = document.selectNodes(XML_BUSINESS + "/" + XML_BUSINESSID); - for (Element element : list) { - String sval = element.getText(); - if (sval.isEmpty()) { - continue; - } - logger.warn("Business Allow: " + sval); - config.businessWhiteSet.add(sval.trim()); - } - list.clear(); - document.clearContent(); - document = null; - if (reader != null) { - reader.close(); - reader = null; - } - - String aliases = hostConfiguration.getAliases(); - try { - reader = new StringReader(aliases); - document = new SAXReader().read(reader); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config Aliases string: " + business, e); - if (reader != null) { - reader.close(); - } - return; - } - if (document == null) { - logger.error("Unable to read the XML Config Aliases string: " + business); - if (reader != null) { - reader.close(); - } - return; - } - // XXX FIXME - list = document.selectNodes(XML_ALIASES + "/" + XML_ALIAS); - for (Element element : list) { - Element nodeid = (Element) element.selectSingleNode(XML_REALID); - if (nodeid == null) { - continue; - } - Element nodeset = (Element) element.selectSingleNode(XML_ALIASID); - if (nodeset == null) { - continue; - } - String refHostId = nodeid.getText(); - String aliasesid = nodeset.getText(); - String [] aliasid = aliasesid.split(" |\\|"); - for (String namealias : aliasid) { - config.aliases.put(namealias, refHostId); - } - logger.warn("Aliases for: " + refHostId +" = "+ aliasesid); - } - list.clear(); - document.clearContent(); - document = null; - if (reader != null) { - reader.close(); - } - - String xroles = hostConfiguration.getRoles(); - try { - reader = new StringReader(xroles); - document = new SAXReader().read(reader); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config Roles string: " + business, e); - if (reader != null) { - reader.close(); - } - return; - } - if (document == null) { - logger.error("Unable to read the XML Config Roles string: " + business); - if (reader != null) { - reader.close(); - } - return; - } - // XXX FIXME - list = document.selectNodes(XML_ROLES + "/" + XML_ROLE); - for (Element element : list) { - Element nodeid = (Element) element.selectSingleNode(XML_ROLEID); - if (nodeid == null) { - continue; - } - Element nodeset = (Element) element.selectSingleNode(XML_ROLESET); - if (nodeset == null) { - continue; - } - String refHostId = nodeid.getText(); - String roleset = nodeset.getText(); - String [] roles = roleset.split(" |\\|"); - RoleDefault newrole = new RoleDefault(); - for (String role : roles) { - try { - RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(role.toUpperCase()); - if (roletype == ROLE.NOACCESS) { - // reset - newrole.setRole(roletype); - } else { - newrole.addRole(roletype); - } - } catch (IllegalArgumentException e) { - // ignore - } - } - logger.warn("New Role: " + refHostId + ":" + newrole); - config.roles.put(refHostId, newrole); - } - list.clear(); - document.clearContent(); - document = null; - if (reader != null) { - reader.close(); - } - } - /** - * Load Role list if any - * - * @param document - */ - @SuppressWarnings("unchecked") - private static void loadRolesList(Configuration config) { - XmlValue value = hashConfig.get(XML_ROLES); - if (value != null && (value.getList() != null)) { - for (XmlValue[] xml : (List) value.getList()) { - XmlHash subHash = new XmlHash(xml); - value = subHash.get(XML_ROLEID); - if (value == null || (value.isEmpty())) { - continue; - } - String refHostId = value.getString(); - value = subHash.get(XML_ROLESET); - if (value == null || (value.isEmpty())) { - continue; - } - String roleset = value.getString(); - String [] roles = roleset.split(" |\\|"); - RoleDefault newrole = new RoleDefault(); - for (String role : roles) { - try { - RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(role.toUpperCase()); - if (roletype == ROLE.NOACCESS) { - // reset - newrole.setRole(roletype); - } else { - newrole.addRole(roletype); - } - } catch (IllegalArgumentException e) { - // ignore - } - } - logger.warn("New Role: " + refHostId + ":" + newrole); - config.roles.put(refHostId, newrole); - } - } - } - - /** - * - * @param document - * @param fromXML - * @return the new subpath - * @throws OpenR66ProtocolSystemException - */ - private static String getSubPath(Configuration config, String fromXML) - throws OpenR66ProtocolSystemException { - XmlValue value = hashConfig.get(fromXML); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find a Path in Config file: " + fromXML); - throw new OpenR66ProtocolSystemException( - "Unable to find a Path in Config file: " + fromXML); - } - - String path = value.getString(); - if (path == null || path.length() == 0) { - throw new OpenR66ProtocolSystemException( - "Unable to find a correct Path in Config file: " + fromXML); - } - path = DirInterface.SEPARATOR + path; - String newpath = config.baseDirectory + path; - File file = new File(newpath); - if (!file.isDirectory()) { - FileUtils.createDir(file); - } - return path; - } - - /** - * Load minimalistic Limit configuration - * - * @param filename - * @return True if OK - */ - public static boolean setConfigurationLoadLimitFromXml(Configuration config, String filename) { - Document document = null; - alreadySetLimit = false; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configServer); - hashConfig = new XmlHash(configuration); - if (!loadLimit(config, true)) { - logger.error("Unable to read Limitation config file: " + filename); - return false; - } - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Load configuration for init database - * - * @param filename - * @return True if OK - */ - public static boolean setConfigurationInitDatabase(Configuration config, String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configServer); - hashConfig = new XmlHash(configuration); - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - if (!loadDirectory(config)) { - logger.error("Cannot load Directory configuration"); - return false; - } - if (!loadLimit(config, false)) { - logger.error("Cannot load Limit configuration"); - return false; - } - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - if (!loadAuthentication(config)) { - logger.error("Cannot load Authentication configuration"); - return false; - } - } - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Load minimalistic configuration - * - * @param filename - * @return True if OK - */ - public static boolean setConfigurationServerMinimalFromXml(Configuration config, String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configServer); - hashConfig = new XmlHash(configuration); - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - if (!loadDirectory(config)) { - logger.error("Cannot load Directory configuration"); - return false; - } - if (!loadLimit(config, false)) { - logger.error("Cannot load Limit configuration"); - return false; - } - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - if (!loadAuthentication(config)) { - logger.error("Cannot load Authentication configuration"); - return false; - } - } - config.HOST_AUTH = R66Auth.getServerAuth( - DbConstant.admin.session, config.HOST_ID); - if (config.HOST_AUTH == null && - config.useNOSSL) { - logger.error("Cannot find Authentication for current host"); - return false; - } - if (config.HOST_SSLID != null) { - config.HOST_SSLAUTH = R66Auth.getServerAuth( - DbConstant.admin.session, - config.HOST_SSLID); - if (config.HOST_SSLAUTH == null && - config.useSSL) { - logger.error("Cannot find SSL Authentication for current host"); - return false; - } - } - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Initiate the configuration from the xml file for server shutdown - * - * @param filename - * @return True if OK - */ - public static boolean setConfigurationServerShutdownFromXml(Configuration config, - String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configServer); - hashConfig = new XmlHash(configuration); - // Now read the configuration - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - if (!loadServerParam(config)) { - logger.error("Cannot load Server Parameters"); - return false; - } - if (!loadDirectory(config)) { - logger.error("Cannot load Directory configuration"); - return false; - } - if (!loadLimit(config, false)) { - logger.error("Cannot load Limit configuration"); - return false; - } - if (config.useSSL) { - if (!loadSsl(config)) { - logger.error("Cannot load SSL configuration"); - return false; - } - } - if (!loadNetworkServer(config)) { - logger.error("Cannot load Network configuration"); - return false; - } - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - if (!loadAuthentication(config)) { - logger.error("Cannot load Authentication configuration"); - return false; - } - } - config.HOST_AUTH = R66Auth.getServerAuth( - DbConstant.admin.session, config.HOST_ID); - if (config.HOST_AUTH == null && - config.useNOSSL) { - logger.error("Cannot find Authentication for current host"); - return false; - } - if (config.HOST_SSLID != null) { - config.HOST_SSLAUTH = R66Auth.getServerAuth( - DbConstant.admin.session, - config.HOST_SSLID); - if (config.HOST_SSLAUTH == null && - config.useSSL) { - logger.error("Cannot find SSL Authentication for current host"); - return false; - } - } - loadBusinessWhiteList(config); - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Initiate the configuration from the xml file for server - * - * @param filename - * @return True if OK - */ - public static boolean setConfigurationServerFromXml(Configuration config, String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configServer); - hashConfig = new XmlHash(configuration); - // Now read the configuration - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - if (!loadServerParam(config)) { - logger.error("Cannot load Server Parameters"); - return false; - } - if (!loadDirectory(config)) { - logger.error("Cannot load Directory configuration"); - return false; - } - if (!loadLimit(config, false)) { - logger.error("Cannot load Limit configuration"); - return false; - } - if (config.useSSL) { - if (!loadSsl(config)) { - logger.error("Cannot load SSL configuration"); - return false; - } - } - if (!loadNetworkServer(config)) { - logger.error("Cannot load Network configuration"); - return false; - } - if (!loadFromDatabase(config)) { - logger.error("Cannot load configuration from Database"); - return false; - } - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - if (!loadAuthentication(config)) { - logger.error("Cannot load Authentication configuration"); - return false; - } - } - config.HOST_AUTH = R66Auth.getServerAuth( - DbConstant.admin.session, config.HOST_ID); - if (config.HOST_AUTH == null && - config.useNOSSL) { - logger.error("Cannot find Authentication for current host"); - return false; - } - if (config.HOST_SSLID != null) { - config.HOST_SSLAUTH = R66Auth.getServerAuth( - DbConstant.admin.session, - config.HOST_SSLID); - if (config.HOST_SSLAUTH == null && - config.useSSL) { - logger.error("Cannot find SSL Authentication for current host"); - return false; - } - } - loadBusinessWhiteList(config); - loadRolesList(config); - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Initiate the configuration from the xml file for database client - * - * @param filename - * @return True if OK - */ - public static boolean setClientConfigurationFromXml(Configuration config, String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configClient); - hashConfig = new XmlHash(configuration); - // Client enables SSL by default but could be reverted later on - config.useSSL = true; - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - if (!loadClientParam(config)) { - logger.error("Cannot load Client Parameters"); - return false; - } - if (!loadDirectory(config)) { - logger.error("Cannot load Directory configuration"); - return false; - } - if (!loadLimit(config, false)) { - logger.error("Cannot load Limit configuration"); - return false; - } - if (config.useSSL) { - if (!loadSsl(config)) { - logger.error("Cannot load SSL configuration"); - return false; - } - } - if (!loadFromDatabase(config)) { - logger.error("Cannot load configuration from Database"); - return false; - } - if (!DbConstant.admin.isConnected) { - // if no database, must load authentication from file - if (!loadAuthentication(config)) { - logger.error("Cannot load Authentication configuration"); - return false; - } - } - config.HOST_AUTH = R66Auth.getServerAuth( - DbConstant.admin.session, config.HOST_ID); - if (config.HOST_AUTH == null) { - logger.error("Cannot find Authentication for current host"); - return false; - } - if (config.HOST_SSLID != null) { - config.HOST_SSLAUTH = R66Auth.getServerAuth( - DbConstant.admin.session, - config.HOST_SSLID); - if (config.HOST_SSLAUTH == null) { - logger.error("Cannot find SSL Authentication for current host"); - return false; - } - } - loadBusinessWhiteList(config); - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } - - /** - * Initiate the configuration from the xml file for submit database client - * - * @param config - * @param filename - * @return True if OK - */ - public static boolean setSubmitClientConfigurationFromXml(Configuration config, String filename) { - Document document = null; - // Open config file - try { - document = new SAXReader().read(filename); - } catch (DocumentException e) { - logger.error("Unable to read the XML Config file: " + filename, e); - return false; - } - if (document == null) { - logger.error("Unable to read the XML Config file: " + filename); - return false; - } - configuration = XmlUtil.read(document, configSubmitClient); - hashConfig = new XmlHash(configuration); - // Client enables SSL by default but could be reverted later on - config.useSSL = true; - if (!loadIdentity(config)) { - logger.error("Cannot load Identity"); - return false; - } - if (!loadDatabase(config)) { - logger.error("Cannot load Database configuration"); - return false; - } - XmlValue value = hashConfig.get(XML_BLOCKSIZE); - if (value != null && (!value.isEmpty())) { - config.BLOCKSIZE = value.getInteger(); - } - config.HOST_AUTH = R66Auth.getServerAuth( - DbConstant.admin.session, config.HOST_ID); - if (config.HOST_AUTH == null) { - logger.error("Cannot find Authentication for current host"); - return false; - } - if (config.HOST_SSLID != null) { - config.HOST_SSLAUTH = R66Auth.getServerAuth( - DbConstant.admin.session, - config.HOST_SSLID); - if (config.HOST_SSLAUTH == null) { - logger.error("Cannot find SSL Authentication for current host"); - return false; - } - } - loadBusinessWhiteList(config); - hashConfig.clear(); - hashConfig = null; - configuration = null; - return true; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.configuration; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.List; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler; +import org.waarp.common.crypto.Des; +import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; +import org.waarp.common.crypto.ssl.WaarpSslContextFactory; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; +import org.waarp.common.exception.CryptoException; +import org.waarp.common.file.DirInterface; +import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; +import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.role.RoleDefault; +import org.waarp.common.role.RoleDefault.ROLE; +import org.waarp.common.xml.XmlDecl; +import org.waarp.common.xml.XmlHash; +import org.waarp.common.xml.XmlType; +import org.waarp.common.xml.XmlUtil; +import org.waarp.common.xml.XmlValue; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.model.DbModelFactory; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.networkhandler.R66ConstraintLimitHandler; +import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; +import org.waarp.openr66.protocol.utils.FileUtils; +import org.waarp.snmp.SnmpConfiguration; + +/** + * File Based Configuration + * + * @author frederic bregier + * + */ +public class FileBasedConfiguration { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(FileBasedConfiguration.class); + + /** + * SERVER HOSTID + */ + private static final String XML_SERVER_HOSTID = "hostid"; + + /** + * SERVER SSL HOSTID + */ + private static final String XML_SERVER_SSLHOSTID = "sslhostid"; + + /** + * ADMINISTRATOR SERVER NAME (shutdown) + */ + private static final String XML_SERVER_ADMIN = "serveradmin"; + + /** + * SERVER PASSWORD (shutdown) + */ + private static final String XML_SERVER_PASSWD = "serverpasswd"; + /** + * SERVER PASSWORD FILE (shutdown) + */ + private static final String XML_SERVER_PASSWD_FILE = "serverpasswdfile"; + /** + * Authentication + */ + private static final String XML_AUTHENTIFICATION_FILE = "authentfile"; + + /** + * SERVER PORT + */ + private static final String XML_SERVER_PORT = "serverport"; + + /** + * SERVER SSL PORT + */ + private static final String XML_SERVER_SSLPORT = "serversslport"; + + /** + * SERVER HTTP PORT + */ + private static final String XML_SERVER_HTTPPORT = "serverhttpport"; + + /** + * SERVER HTTP PORT + */ + private static final String XML_SERVER_HTTPSPORT = "serverhttpsport"; + + /** + * SERVER SSL STOREKEY PATH + */ + private static final String XML_PATH_KEYPATH = "keypath"; + + /** + * SERVER SSL KEY PASS + */ + private static final String XML_PATH_KEYPASS = "keypass"; + + /** + * SERVER SSL STOREKEY PASS + */ + private static final String XML_PATH_KEYSTOREPASS = "keystorepass"; + + /** + * SERVER SSL TRUSTSTOREKEY PATH + */ + private static final String XML_PATH_TRUSTKEYPATH = "trustkeypath"; + + /** + * SERVER SSL TRUSTSTOREKEY PASS + */ + private static final String XML_PATH_TRUSTKEYSTOREPASS = "trustkeystorepass"; + + /** + * SERVER SSL STOREKEY PATH ADMIN + */ + private static final String XML_PATH_ADMIN_KEYPATH = "admkeypath"; + + /** + * SERVER SSL KEY PASS ADMIN + */ + private static final String XML_PATH_ADMIN_KEYPASS = "admkeypass"; + + /** + * SERVER SSL STOREKEY PASS ADMIN + */ + private static final String XML_PATH_ADMIN_KEYSTOREPASS = "admkeystorepass"; + + /** + * SERVER CRYPTO for Password + */ + private static final String XML_PATH_CRYPTOKEY = "cryptokey"; + /** + * Base Directory + */ + private static final String XML_SERVER_HOME = "serverhome"; + + /** + * IN Directory + */ + private static final String XML_INPATH = "in"; + + /** + * OUT Directory + */ + private static final String XML_OUTPATH = "out"; + + /** + * ARCHIVE Directory + */ + private static final String XML_ARCHIVEPATH = "arch"; + + /** + * WORKING Directory + */ + private static final String XML_WORKINGPATH = "work"; + + /** + * CONFIG Directory + */ + private static final String XML_CONFIGPATH = "conf"; + + /** + * HTTP Admin Directory + */ + private static final String XML_HTTPADMINPATH = "httpadmin"; + /** + * Use SSL for R66 connection + */ + private static final String XML_USESSL = "usessl"; + + /** + * Use non SSL for R66 connection + */ + private static final String XML_USENOSSL = "usenossl"; + + /** + * Use HTTP compression for R66 HTTP connection + */ + private static final String XML_USEHTTPCOMP = "usehttpcomp"; + + /** + * SERVER SSL Use TrustStore for Client Authentication + */ + private static final String XML_USECLIENT_AUTHENT = "trustuseclientauthenticate"; + + /** + * Limit per session + */ + private static final String XML_LIMITSESSION = "sessionlimit"; + + /** + * Limit global + */ + private static final String XML_LIMITGLOBAL = "globallimit"; + + /** + * Delay between two checks for Limit + */ + private static final String XML_LIMITDELAY = "delaylimit"; + /** + * Monitoring: how long in ms to get back in monitoring + */ + private static final String XML_MONITOR_PASTLIMIT = "pastlimit"; + /** + * Monitoring: minimal interval in ms before redo real monitoring + */ + private static final String XML_MONITOR_MINIMALDELAY = "minimaldelay"; + /** + * Monitoring: snmp configuration file (if empty, no snmp support) + */ + private static final String XML_MONITOR_SNMP_CONFIG = "snmpconfig"; + /** + * In case of multiple OpenR66 Monitors behing a loadbalancer (ha config) + */ + private static final String XML_MULTIPLE_MONITORS = "multiplemonitors"; + /** + * Usage of CPU Limit + */ + private static final String XML_CSTRT_USECPULIMIT = "usecpulimit"; + + /** + * Usage of JDK CPU Limit (True) or SysMon CPU Limit + */ + private static final String XML_CSTRT_USECPUJDKLIMIT = "usejdkcpulimit"; + + /** + * CPU LIMIT between 0 and 1, where 1 stands for no limit + */ + private static final String XML_CSTRT_CPULIMIT = "cpulimit"; + /** + * Connection limit where 0 stands for no limit + */ + private static final String XML_CSTRT_CONNLIMIT = "connlimit"; + /** + * CPU LOW limit to apply increase of throttle + */ + private static final String XML_CSTRT_LOWCPULIMIT = "lowcpulimit"; + /** + * CPU HIGH limit to apply decrease of throttle, 0 meaning no throttle activated + */ + private static final String XML_CSTRT_HIGHCPULIMIT = "highcpulimit"; + /** + * PERCENTAGE DECREASE of Bandwidth + */ + private static final String XML_CSTRT_PERCENTDECREASE = "percentdecrease"; + /** + * Delay between 2 checks of throttle test + */ + private static final String XML_CSTRT_DELAYTHROTTLE = "delaythrottle"; + /** + * Bandwidth low limit to not got below + */ + private static final String XML_CSTRT_LIMITLOWBANDWIDTH = "limitlowbandwidth"; + /** + * Usage of checking remote address with the DbHost definition + */ + private static final String XML_CHECK_ADDRESS = "checkaddress"; + /** + * Usage of checking remote address also for Client + */ + private static final String XML_CHECK_CLIENTADDRESS = "checkclientaddress"; + + /** + * In case of No Db Client, Usage of saving TaskRunner into independent XML file + */ + private static final String XML_SAVE_TASKRUNNERNODB = "taskrunnernodb"; + + /** + * Use external Waarp Local Exec for ExecTask and ExecMoveTask + */ + private static final String XML_USELOCALEXEC = "uselocalexec"; + + /** + * Address of Waarp Local Exec for ExecTask and ExecMoveTask + */ + private static final String XML_LEXECADDR = "lexecaddr"; + + /** + * Port of Waarp Local Exec for ExecTask and ExecMoveTask + */ + private static final String XML_LEXECPORT = "lexecport"; + + /** + * Default number of threads in pool for Server. + */ + private static final String XML_SERVER_THREAD = "serverthread"; + + /** + * Default number of threads in pool for Client (truly concurrent). + */ + private static final String XML_CLIENT_THREAD = "clientthread"; + + /** + * Memory Limit to use. + */ + private static final String XML_MEMORY_LIMIT = "memorylimit"; + + /** + * Limit of number of active Runner from Commander + */ + private static final String XML_LIMITRUNNING = "runlimit"; + + /** + * Delay between two checks for Commander + */ + private static final String XML_DELAYCOMMANDER = "delaycommand"; + + /** + * Delay between two retry after bad connection + */ + private static final String XML_DELAYRETRY = "delayretry"; + + /** + * Nb of milliseconds after connection is in timeout + */ + private static final String XML_TIMEOUTCON = "timeoutcon"; + + /** + * Should a file MD5 SHA1 be computed using NIO + */ + private static final String XML_USENIO = "usenio"; + + /** + * What Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 + */ + private static final String XML_DIGEST = "digest"; + /** + * Should a file MD5 be computed using FastMD5 + */ + private static final String XML_USEFASTMD5 = "usefastmd5"; + + /** + * If using Fast MD5, should we used the binary JNI library, empty meaning no + */ + private static final String XML_FASTMD5 = "fastmd5"; + + /** + * number of rank to go back when a transfer is restarted. restart is gaprestart*blocksize + */ + private static final String XML_GAPRESTART = "gaprestart"; + /** + * Size by default of block size for receive/sending files. Should be a multiple of 8192 + * (maximum = 64K due to block limitation to 2 bytes) + */ + private static final String XML_BLOCKSIZE = "blocksize"; + /** + * If set to <=0, will not use Thrift support, if set >0 (preferably > 1024) will enable + * Thrift support on the TCP port specified by this number + */ + private static final String XML_USETHRIFT = "usethrift"; + /** + * Database Driver as of oracle, mysql, postgresql, h2 + */ + private static final String XML_DBDRIVER = "dbdriver"; + + /** + * Database Server connection string as of jdbc:type://[host:port],[failoverhost:port] + * .../[database][?propertyName1][ =propertyValue1][&propertyName2][=propertyValue2]... + */ + private static final String XML_DBSERVER = "dbserver"; + + /** + * Database User + */ + private static final String XML_DBUSER = "dbuser"; + + /** + * Database Password + */ + private static final String XML_DBPASSWD = "dbpasswd"; + + /** + * Check version in protocol + */ + private static final String XML_CHECKVERSION = "checkversion"; + /** + * Global digest by transfer enable + */ + private static final String XML_GLOBALDIGEST = "globaldigest"; + /** + * Check version in protocol + */ + private static final String XML_BUSINESSID = "businessid"; + /** + * Role Main entry + */ + private static final String XML_ROLE = "role"; + /** + * ID in role + */ + private static final String XML_ROLEID = "roleid"; + /** + * Role set + */ + private static final String XML_ROLESET = "roleset"; + /** + * Alias + */ + private static final String XML_ALIAS = "alias"; + /** + * Main ID in alias + */ + private static final String XML_REALID = "realid"; + /** + * Alias Id + */ + private static final String XML_ALIASID = "aliasid"; + + + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configIdentityDecls = { + // identity + new XmlDecl(XmlType.STRING, XML_SERVER_HOSTID), + new XmlDecl(XmlType.STRING, XML_SERVER_SSLHOSTID), + new XmlDecl(XmlType.STRING, XML_PATH_CRYPTOKEY), + new XmlDecl(XmlType.STRING, XML_AUTHENTIFICATION_FILE) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configServerParamDecls = { + // server + new XmlDecl(XmlType.BOOLEAN, XML_USESSL), + new XmlDecl(XmlType.BOOLEAN, XML_USENOSSL), + new XmlDecl(XmlType.BOOLEAN, XML_USEHTTPCOMP), + new XmlDecl(XmlType.BOOLEAN, XML_USELOCALEXEC), + new XmlDecl(XmlType.STRING, XML_LEXECADDR), + new XmlDecl(XmlType.INTEGER, XML_LEXECPORT), + new XmlDecl(XmlType.BOOLEAN, XML_CHECK_ADDRESS), + new XmlDecl(XmlType.BOOLEAN, XML_CHECK_CLIENTADDRESS), + new XmlDecl(XmlType.STRING, XML_SERVER_ADMIN), + new XmlDecl(XmlType.STRING, XML_SERVER_PASSWD), + new XmlDecl(XmlType.STRING, XML_SERVER_PASSWD_FILE), + new XmlDecl(XmlType.STRING, XML_HTTPADMINPATH), + new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYPATH), + new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYSTOREPASS), + new XmlDecl(XmlType.STRING, XML_PATH_ADMIN_KEYPASS), + new XmlDecl(XmlType.LONG, XML_MONITOR_PASTLIMIT), + new XmlDecl(XmlType.LONG, XML_MONITOR_MINIMALDELAY), + new XmlDecl(XmlType.STRING, XML_MONITOR_SNMP_CONFIG), + new XmlDecl(XmlType.INTEGER, XML_MULTIPLE_MONITORS) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configNetworkServerDecls = { + // network + new XmlDecl(XmlType.INTEGER, XML_SERVER_PORT), + new XmlDecl(XmlType.INTEGER, XML_SERVER_SSLPORT), + new XmlDecl(XmlType.INTEGER, XML_SERVER_HTTPPORT), + new XmlDecl(XmlType.INTEGER, XML_SERVER_HTTPSPORT) + }; + + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configSslDecls = { + // ssl + new XmlDecl(XmlType.STRING, XML_PATH_KEYPATH), + new XmlDecl(XmlType.STRING, XML_PATH_KEYSTOREPASS), + new XmlDecl(XmlType.STRING, XML_PATH_KEYPASS), + new XmlDecl(XmlType.STRING, XML_PATH_TRUSTKEYPATH), + new XmlDecl(XmlType.STRING, XML_PATH_TRUSTKEYSTOREPASS), + new XmlDecl(XmlType.BOOLEAN, XML_USECLIENT_AUTHENT) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configDbDecls = { + // db + new XmlDecl(XmlType.STRING, XML_DBDRIVER), + new XmlDecl(XmlType.STRING, XML_DBSERVER), + new XmlDecl(XmlType.STRING, XML_DBUSER), + new XmlDecl(XmlType.STRING, XML_DBPASSWD), + new XmlDecl(XmlType.BOOLEAN, XML_SAVE_TASKRUNNERNODB) + }; + + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configLimitDecls = { + // limit + new XmlDecl(XmlType.LONG, XML_LIMITSESSION), + new XmlDecl(XmlType.LONG, XML_LIMITGLOBAL), + new XmlDecl(XmlType.LONG, XML_LIMITDELAY), + new XmlDecl(XmlType.INTEGER, XML_LIMITRUNNING), + new XmlDecl(XmlType.LONG, XML_DELAYCOMMANDER), + new XmlDecl(XmlType.LONG, XML_DELAYRETRY), + new XmlDecl(XmlType.INTEGER, XML_SERVER_THREAD), + new XmlDecl(XmlType.INTEGER, XML_CLIENT_THREAD), + new XmlDecl(XmlType.LONG, XML_MEMORY_LIMIT), + new XmlDecl(XmlType.BOOLEAN, XML_CSTRT_USECPULIMIT), + new XmlDecl(XmlType.BOOLEAN, XML_CSTRT_USECPUJDKLIMIT), + new XmlDecl(XmlType.DOUBLE, XML_CSTRT_CPULIMIT), + new XmlDecl(XmlType.INTEGER, XML_CSTRT_CONNLIMIT), + new XmlDecl(XmlType.DOUBLE, XML_CSTRT_LOWCPULIMIT), + new XmlDecl(XmlType.DOUBLE, XML_CSTRT_HIGHCPULIMIT), + new XmlDecl(XmlType.DOUBLE, XML_CSTRT_PERCENTDECREASE), + new XmlDecl(XmlType.LONG, XML_CSTRT_LIMITLOWBANDWIDTH), + new XmlDecl(XmlType.LONG, XML_CSTRT_DELAYTHROTTLE), + new XmlDecl(XmlType.LONG, XML_TIMEOUTCON), + new XmlDecl(XmlType.BOOLEAN, XML_USENIO), + new XmlDecl(XmlType.INTEGER, XML_DIGEST), + new XmlDecl(XmlType.BOOLEAN, XML_USEFASTMD5), + new XmlDecl(XmlType.STRING, XML_FASTMD5), + new XmlDecl(XmlType.INTEGER, XML_GAPRESTART), + new XmlDecl(XmlType.INTEGER, XML_BLOCKSIZE), + new XmlDecl(XmlType.INTEGER, XML_USETHRIFT), + new XmlDecl(XmlType.BOOLEAN, XML_CHECKVERSION), + new XmlDecl(XmlType.BOOLEAN, XML_GLOBALDIGEST) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configSubmitLimitDecls = { + // limit + new XmlDecl( + XmlType.INTEGER, + XML_BLOCKSIZE) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configClientParamDecls = { + // client + new XmlDecl( + XmlType.BOOLEAN, + XML_SAVE_TASKRUNNERNODB), + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configDirectoryDecls = { + // directory + new XmlDecl(XmlType.STRING, XML_SERVER_HOME), + new XmlDecl(XmlType.STRING, XML_INPATH), + new XmlDecl(XmlType.STRING, XML_OUTPATH), + new XmlDecl(XmlType.STRING, XML_ARCHIVEPATH), + new XmlDecl(XmlType.STRING, XML_WORKINGPATH), + new XmlDecl(XmlType.STRING, XML_CONFIGPATH) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configRoleDecls = { + // roles + new XmlDecl(XmlType.STRING, XML_ROLEID), + new XmlDecl(XmlType.STRING, XML_ROLESET) + }; + /** + * Structure of the Configuration file + * + */ + private static final XmlDecl[] configAliasDecls = { + // roles + new XmlDecl(XmlType.STRING, XML_REALID), + new XmlDecl(XmlType.STRING, XML_ALIASID) + }; + + /** + * Overall structure of the Configuration file + */ + private static final String XML_ROOT = "/config/"; + private static final String XML_IDENTITY = "identity"; + private static final String XML_SERVER = "server"; + private static final String XML_CLIENT = "client"; + private static final String XML_DIRECTORY = "directory"; + private static final String XML_LIMIT = "limit"; + private static final String XML_NETWORK = "network"; + private static final String XML_SSL = "ssl"; + private static final String XML_DB = "db"; + private static final String XML_BUSINESS = "business"; + private static final String XML_ROLES = "roles"; + private static final String XML_ALIASES = "aliases"; + + /** + * Global Structure for Server Configuration + */ + private static final XmlDecl[] configServer = { + new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, + false), + new XmlDecl(XML_SERVER, XmlType.XVAL, XML_ROOT + XML_SERVER, configServerParamDecls, + false), + new XmlDecl(XML_NETWORK, XmlType.XVAL, XML_ROOT + XML_NETWORK, + configNetworkServerDecls, false), + new XmlDecl(XML_SSL, XmlType.XVAL, XML_ROOT + XML_SSL, configSslDecls, false), + new XmlDecl(XML_DIRECTORY, XmlType.XVAL, XML_ROOT + XML_DIRECTORY, + configDirectoryDecls, false), + new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configLimitDecls, false), + new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), + new XmlDecl(XML_BUSINESS, XmlType.STRING, XML_ROOT + XML_BUSINESS + "/" + + XML_BUSINESSID, true), + new XmlDecl(XML_ROLES, XmlType.XVAL, XML_ROOT + XML_ROLES + "/" + + XML_ROLE, configRoleDecls, true), + new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" + + XML_ALIAS, configAliasDecls, true) + }; + /** + * Global Structure for Client Configuration + */ + private static final XmlDecl[] configClient = { + new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, + false), + new XmlDecl(XML_CLIENT, XmlType.XVAL, XML_ROOT + XML_CLIENT, configClientParamDecls, + false), + new XmlDecl(XML_SSL, XmlType.XVAL, XML_ROOT + XML_SSL, configSslDecls, false), + new XmlDecl(XML_DIRECTORY, XmlType.XVAL, XML_ROOT + XML_DIRECTORY, + configDirectoryDecls, false), + new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configLimitDecls, false), + new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), + new XmlDecl(XML_BUSINESS, XmlType.STRING, XML_ROOT + XML_BUSINESS + "/" + + XML_BUSINESSID, true), + new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" + + XML_ALIAS, configAliasDecls, true) + }; + /** + * Global Structure for Submit only Client Configuration + */ + private static final XmlDecl[] configSubmitClient = { + new XmlDecl(XML_IDENTITY, XmlType.XVAL, XML_ROOT + XML_IDENTITY, configIdentityDecls, + false), + new XmlDecl(XML_LIMIT, XmlType.XVAL, XML_ROOT + XML_LIMIT, configSubmitLimitDecls, + false), + new XmlDecl(XML_DB, XmlType.XVAL, XML_ROOT + XML_DB, configDbDecls, false), + new XmlDecl(XML_ALIASES, XmlType.XVAL, XML_ROOT + XML_ALIASES + "/" + + XML_ALIAS, configAliasDecls, true) + }; + private static XmlValue[] configuration = null; + private static XmlHash hashConfig = null; + + private static boolean loadIdentity(Configuration config) { + XmlValue value = hashConfig.get(XML_SERVER_HOSTID); + if (value != null && (!value.isEmpty())) { + config.HOST_ID = value.getString(); + config.REQER_HOST_ID = config.HOST_ID + "__rd__"; + config.REQED_HOST_ID = config.HOST_ID + "__rr__"; + } else { + logger.error("Unable to find Host ID in Config file"); + return false; + } + value = hashConfig.get(XML_SERVER_SSLHOSTID); + if (value != null && (!value.isEmpty())) { + config.HOST_SSLID = value.getString(); + } else { + logger + .warn("Unable to find Host SSL ID in Config file so no SSL support will be used"); + config.useSSL = false; + config.HOST_SSLID = null; + } + return setCryptoKey(config); + } + + private static boolean loadAuthentication(Configuration config) { + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + XmlValue value = hashConfig.get(XML_AUTHENTIFICATION_FILE); + if (value != null && (!value.isEmpty())) { + String fileauthent = value.getString(); + if (!AuthenticationFileBasedConfiguration + .loadAuthentication(config, fileauthent)) { + return false; + } + } else { + logger.warn("Unable to find Authentication file in Config file"); + return false; + } + } + return true; + } + + private static boolean loadServerParam(Configuration config) { + XmlValue value = hashConfig.get(XML_USESSL); + if (value != null && (!value.isEmpty())) { + config.useSSL = value.getBoolean(); + } + value = hashConfig.get(XML_USENOSSL); + if (value != null && (!value.isEmpty())) { + config.useNOSSL = value.getBoolean(); + } + value = hashConfig.get(XML_USEHTTPCOMP); + if (value != null && (!value.isEmpty())) { + config.useHttpCompression = value.getBoolean(); + } + value = hashConfig.get(XML_USELOCALEXEC); + if (value != null && (!value.isEmpty())) { + config.useLocalExec = value.getBoolean(); + if (config.useLocalExec) { + value = hashConfig.get(XML_LEXECADDR); + String saddr; + InetAddress addr; + if (value != null && (!value.isEmpty())) { + saddr = value.getString(); + try { + addr = InetAddress.getByName(saddr); + } catch (UnknownHostException e) { + logger.error("Unable to find LocalExec Address in Config file"); + return false; + } + } else { + logger.warn("Unable to find LocalExec Address in Config file"); + try { + addr = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); + } catch (UnknownHostException e) { + logger.error("Unable to find LocalExec Address in Config file"); + return false; + } + } + value = hashConfig.get(XML_LEXECPORT); + int port; + if (value != null && (!value.isEmpty())) { + port = value.getInteger(); + } else { + port = 9999; + } + LocalExecClient.address = new InetSocketAddress(addr, port); + } + } + value = hashConfig.get(XML_CHECK_ADDRESS); + if (value != null && (!value.isEmpty())) { + config.checkRemoteAddress = value.getBoolean(); + } + value = hashConfig.get(XML_CHECK_CLIENTADDRESS); + if (value != null && (!value.isEmpty())) { + config.checkClientAddress = value.getBoolean(); + } + value = hashConfig.get(XML_SERVER_ADMIN); + if (value != null && (!value.isEmpty())) { + config.ADMINNAME = value.getString(); + } else { + logger.error("Unable to find Administrator name in Config file"); + return false; + } + if (config.cryptoKey == null) { + if (!setCryptoKey(config)) { + logger.error("Unable to find Crypto Key in Config file"); + return false; + } + } + byte[] decodedByteKeys = null; + value = hashConfig.get(XML_SERVER_PASSWD_FILE); + if (value == null || (value.isEmpty())) { + String passwd; + value = hashConfig.get(XML_SERVER_PASSWD); + if (value != null && (!value.isEmpty())) { + passwd = value.getString(); + } else { + logger.error("Unable to find Password in Config file"); + return false; + } + try { + decodedByteKeys = + config.cryptoKey.decryptHexInBytes(passwd); + } catch (Exception e) { + logger.error( + "Unable to Decrypt Server Password in Config file from: " + + passwd, e); + return false; + } + } else { + String skey = value.getString(); + // load key from file + config.serverKeyFile = skey; + File key = new File(skey); + if (!key.canRead()) { + logger.error("Unable to read Password in Config file from " + skey); + return false; + } + try { + decodedByteKeys = config.cryptoKey.decryptHexFile(key); + } catch (Exception e2) { + logger.error( + "Unable to Decrypt Server Password in Config file from: " + + skey, e2); + return false; + } + } + config.setSERVERKEY(decodedByteKeys); + value = hashConfig.get(XML_HTTPADMINPATH); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find Http Admin Base in Config file"); + return false; + } + String path = value.getString(); + if (path == null || path.length() == 0) { + logger.error("Unable to set correct Http Admin Base in Config file"); + return false; + } + File file = new File(path); + if (!file.isDirectory()) { + logger.error("Http Admin is not a directory in Config file"); + return false; + } + try { + config.httpBasePath = + FilesystemBasedDirImpl.normalizePath(file.getCanonicalPath()) + + DirInterface.SEPARATOR; + } catch (IOException e1) { + logger.error("Unable to set Http Admin Path in Config file"); + return false; + } + + // Key for HTTPS + value = hashConfig.get(XML_PATH_ADMIN_KEYPATH); + if (value != null && (!value.isEmpty())) { + String keypath = value.getString(); + if ((keypath == null) || (keypath.length() == 0)) { + logger.error("Bad Key Path"); + return false; + } + value = hashConfig.get(XML_PATH_ADMIN_KEYSTOREPASS); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find KeyStore Passwd"); + return false; + } + String keystorepass = value.getString(); + if ((keystorepass == null) || (keystorepass.length() == 0)) { + logger.error("Bad KeyStore Passwd"); + return false; + } + value = hashConfig.get(XML_PATH_ADMIN_KEYPASS); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find Key Passwd"); + return false; + } + String keypass = value.getString(); + if ((keypass == null) || (keypass.length() == 0)) { + logger.error("Bad Key Passwd"); + return false; + } + try { + Configuration.WaarpSecureKeyStore = + new WaarpSecureKeyStore(keypath, keystorepass, + keypass); + } catch (CryptoException e) { + logger.error("Bad SecureKeyStore construction for AdminSsl"); + return false; + } + // No client authentication + Configuration.WaarpSecureKeyStore.initEmptyTrustStore(); + Configuration.waarpSslContextFactory = + new WaarpSslContextFactory( + Configuration.WaarpSecureKeyStore, true); + } + value = hashConfig.get(XML_MONITOR_PASTLIMIT); + if (value != null && (!value.isEmpty())) { + config.pastLimit = (value.getLong() / 10) * 10; + } + value = hashConfig.get(XML_MONITOR_MINIMALDELAY); + if (value != null && (!value.isEmpty())) { + config.minimalDelay = (value.getLong() / 10) * 10; + } + value = hashConfig.get(XML_MONITOR_SNMP_CONFIG); + if (value != null && (!value.isEmpty())) { + config.snmpConfig = value.getString(); + File snmpfile = new File(config.snmpConfig); + if (snmpfile.canRead()) { + if (!SnmpConfiguration.setConfigurationFromXml(snmpfile)) { + config.snmpConfig = null; + } + } else { + config.snmpConfig = null; + } + } + value = hashConfig.get(XML_MULTIPLE_MONITORS); + if (value != null && (!value.isEmpty())) { + config.multipleMonitors = value.getInteger(); + logger.warn("Multiple Monitor configuration active for " + + config.multipleMonitors + + " servers in HA behind a Load Balancer in TCP"); + } else { + config.multipleMonitors = 1; + logger.warn("Multiple Monitor configuration unactive"); + } + return true; + } + + private static boolean loadClientParam(Configuration config) { + XmlValue value = hashConfig.get(XML_SAVE_TASKRUNNERNODB); + if (value != null && (!value.isEmpty())) { + config.saveTaskRunnerWithNoDb = value.getBoolean(); + } + return true; + } + + private static boolean loadDirectory(Configuration config) { + XmlValue value = hashConfig.get(XML_SERVER_HOME); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find Home in Config file"); + return false; + } + String path = value.getString(); + File file = new File(path); + if (!file.isDirectory()) { + logger.error("Home is not a directory in Config file"); + return false; + } + try { + config.baseDirectory = FilesystemBasedDirImpl + .normalizePath(file.getCanonicalPath()); + } catch (IOException e1) { + logger.error("Unable to set Home in Config file"); + return false; + } + try { + config.configPath = FilesystemBasedDirImpl + .normalizePath(getSubPath(config, XML_CONFIGPATH)); + } catch (OpenR66ProtocolSystemException e2) { + logger.error("Unable to set Config in Config file"); + return false; + } + try { + config.inPath = FilesystemBasedDirImpl + .normalizePath(getSubPath(config, XML_INPATH)); + } catch (OpenR66ProtocolSystemException e2) { + logger.error("Unable to set In in Config file"); + return false; + } + try { + config.outPath = FilesystemBasedDirImpl + .normalizePath(getSubPath(config, XML_OUTPATH)); + } catch (OpenR66ProtocolSystemException e2) { + logger.error("Unable to set Out in Config file"); + return false; + } + try { + config.workingPath = FilesystemBasedDirImpl + .normalizePath(getSubPath(config, XML_WORKINGPATH)); + } catch (OpenR66ProtocolSystemException e2) { + logger.error("Unable to set Working in Config file"); + return false; + } + try { + config.archivePath = FilesystemBasedDirImpl + .normalizePath(getSubPath(config, XML_ARCHIVEPATH)); + } catch (OpenR66ProtocolSystemException e2) { + logger.error("Unable to set Archive in Config file"); + return false; + } + return true; + } + + private static boolean alreadySetLimit = false; + + private static boolean loadLimit(Configuration config, boolean updateLimit) { + if (alreadySetLimit) { + return true; + } + XmlValue value = hashConfig.get(XML_LIMITGLOBAL); + if (value != null && (!value.isEmpty())) { + config.serverGlobalReadLimit = value.getLong(); + if (config.serverGlobalReadLimit <= 0) { + config.serverGlobalReadLimit = 0; + } + config.serverGlobalWriteLimit = config.serverGlobalReadLimit; + logger.info("Global Limit: {}", + config.serverGlobalReadLimit); + } + value = hashConfig.get(XML_LIMITSESSION); + if (value != null && (!value.isEmpty())) { + config.serverChannelReadLimit = value.getLong(); + if (config.serverChannelReadLimit <= 0) { + config.serverChannelReadLimit = 0; + } + config.serverChannelWriteLimit = config.serverChannelReadLimit; + logger.info("SessionInterface Limit: {}", + config.serverChannelReadLimit); + } + config.anyBandwidthLimitation = + (config.serverGlobalReadLimit > 0 || config.serverGlobalWriteLimit > 0 || + config.serverChannelReadLimit > 0 || config.serverChannelWriteLimit > 0); + config.delayLimit = AbstractTrafficShapingHandler.DEFAULT_CHECK_INTERVAL; + value = hashConfig.get(XML_LIMITDELAY); + if (value != null && (!value.isEmpty())) { + config.delayLimit = (value.getLong() / 10) * 10; + if (config.delayLimit <= 0) { + config.delayLimit = 0; + } + logger.info("Delay Limit: {}", + config.delayLimit); + } + value = hashConfig.get(XML_LIMITRUNNING); + if (value != null && (!value.isEmpty())) { + config.RUNNER_THREAD = value.getInteger(); + } + if (config.RUNNER_THREAD < 10) { + config.RUNNER_THREAD = 10; + } + logger.info("Limit of Runner: {}", + config.RUNNER_THREAD); + value = hashConfig.get(XML_DELAYCOMMANDER); + if (value != null && (!value.isEmpty())) { + config.delayCommander = (value.getLong() / 10) * 10; + if (config.delayCommander <= 100) { + config.delayCommander = 100; + } + logger.info("Delay Commander: {}", + config.delayCommander); + } + value = hashConfig.get(XML_DELAYRETRY); + if (value != null && (!value.isEmpty())) { + config.delayRetry = (value.getLong() / 10) * 10; + if (config.delayRetry <= 1000) { + config.delayRetry = 1000; + } + logger.info("Delay Retry: {}", + config.delayRetry); + } + if (DbConstant.admin.isConnected && updateLimit) { + value = hashConfig.get(XML_SERVER_HOSTID); + if (value != null && (!value.isEmpty())) { + config.HOST_ID = value.getString(); + DbConfiguration configuration = new DbConfiguration( + DbConstant.admin.session, + config.HOST_ID, + config.serverGlobalReadLimit, + config.serverGlobalWriteLimit, + config.serverChannelReadLimit, + config.serverChannelWriteLimit, + config.delayLimit); + configuration.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + try { + if (configuration.exist()) { + configuration.update(); + } else { + configuration.insert(); + } + } catch (WaarpDatabaseException e) { + } + } + } + boolean useCpuLimit = false; + boolean useCpuLimitJDK = false; + double cpulimit = 1.0; + value = hashConfig.get(XML_CSTRT_USECPULIMIT); + if (value != null && (!value.isEmpty())) { + useCpuLimit = value.getBoolean(); + value = hashConfig.get(XML_CSTRT_USECPUJDKLIMIT); + if (value != null && (!value.isEmpty())) { + useCpuLimitJDK = value.getBoolean(); + } + value = hashConfig.get(XML_CSTRT_CPULIMIT); + if (value != null && (!value.isEmpty())) { + cpulimit = value.getDouble(); + } + } + int connlimit = 0; + value = hashConfig.get(XML_CSTRT_CONNLIMIT); + if (value != null && (!value.isEmpty())) { + connlimit = value.getInteger(); + } + double lowcpuLimit = 0; + double highcpuLimit = 0; + double percentageDecrease = 0; + long delay = 1000000; + long limitLowBandwidth = 4096; + value = hashConfig.get(XML_CSTRT_LOWCPULIMIT); + if (value != null && (!value.isEmpty())) { + lowcpuLimit = value.getDouble(); + } + value = hashConfig.get(XML_CSTRT_HIGHCPULIMIT); + if (value != null && (!value.isEmpty())) { + highcpuLimit = value.getDouble(); + } + value = hashConfig.get(XML_CSTRT_PERCENTDECREASE); + if (value != null && (!value.isEmpty())) { + percentageDecrease = value.getDouble(); + } + value = hashConfig.get(XML_CSTRT_DELAYTHROTTLE); + if (value != null && (!value.isEmpty())) { + delay = (value.getLong() / 10) * 10; + } + value = hashConfig.get(XML_CSTRT_LIMITLOWBANDWIDTH); + if (value != null && (!value.isEmpty())) { + limitLowBandwidth = value.getLong(); + } + if (highcpuLimit > 0) { + config.constraintLimitHandler = + new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit, connlimit, + lowcpuLimit, highcpuLimit, percentageDecrease, null, delay, + limitLowBandwidth); + } else { + config.constraintLimitHandler = + new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit, connlimit); + } + value = hashConfig.get(XML_SERVER_THREAD); + if (value != null && (!value.isEmpty())) { + config.SERVER_THREAD = value.getInteger(); + } + value = hashConfig.get(XML_CLIENT_THREAD); + if (value != null && (!value.isEmpty())) { + config.CLIENT_THREAD = value.getInteger(); + } + value = hashConfig.get(XML_MEMORY_LIMIT); + if (value != null && (!value.isEmpty())) { + config.maxGlobalMemory = value.getLong(); + } + Configuration.getFileParameter().deleteOnAbort = false; + value = hashConfig.get(XML_USENIO); + if (value != null && (!value.isEmpty())) { + FilesystemBasedFileParameterImpl.useNio = value.getBoolean(); + } + value = hashConfig.get(XML_DIGEST); + if (value != null && (!value.isEmpty())) { + int val = value.getInteger(); + if (val < 0 || val >= DigestAlgo.values().length) { + val = 0; + } + config.digest = DigestAlgo.values()[val]; + } + logger.warn("DigestAlgo used: {}", config.digest); + value = hashConfig.get(XML_USEFASTMD5); + if (value != null && (!value.isEmpty())) { + FilesystemBasedDigest.useFastMd5 = value.getBoolean(); + } else { + FilesystemBasedDigest.useFastMd5 = false; + } + value = hashConfig.get(XML_GAPRESTART); + if (value != null && (!value.isEmpty())) { + Configuration.RANKRESTART = value.getInteger(); + if (Configuration.RANKRESTART <= 0) { + Configuration.RANKRESTART = 1; + } + } + value = hashConfig.get(XML_BLOCKSIZE); + if (value != null && (!value.isEmpty())) { + config.BLOCKSIZE = value.getInteger(); + } + value = hashConfig.get(XML_USETHRIFT); + if (value != null && (!value.isEmpty())) { + config.thriftport = value.getInteger(); + } + value = hashConfig.get(XML_TIMEOUTCON); + if (value != null && (!value.isEmpty())) { + config.TIMEOUTCON = (value.getLong() / 10) * 10; + config.shutdownConfiguration.timeout = config.TIMEOUTCON; + } + value = hashConfig.get(XML_CHECKVERSION); + if (value != null && (!value.isEmpty())) { + config.extendedProtocol = value.getBoolean(); + logger.warn("ExtendedProtocol= " + config.extendedProtocol); + } + value = hashConfig.get(XML_GLOBALDIGEST); + if (value != null && (!value.isEmpty())) { + config.globalDigest = value.getBoolean(); + } + alreadySetLimit = true; + return true; + } + + private static boolean loadSsl(Configuration config) { + // StoreKey for Server + XmlValue value = hashConfig.get(XML_PATH_KEYPATH); + if (value == null || (value.isEmpty())) { + logger.info("Unable to find Key Path"); + try { + NetworkSslServerPipelineFactory.WaarpSecureKeyStore = + new WaarpSecureKeyStore("secret", "secret"); + } catch (CryptoException e) { + logger.error("Bad SecureKeyStore construction"); + return false; + } + } else { + String keypath = value.getString(); + if ((keypath == null) || (keypath.length() == 0)) { + logger.error("Bad Key Path"); + return false; + } + value = hashConfig.get(XML_PATH_KEYSTOREPASS); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find KeyStore Passwd"); + return false; + } + String keystorepass = value.getString(); + if ((keystorepass == null) || (keystorepass.length() == 0)) { + logger.error("Bad KeyStore Passwd"); + return false; + } + value = hashConfig.get(XML_PATH_KEYPASS); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find Key Passwd"); + return false; + } + String keypass = value.getString(); + if ((keypass == null) || (keypass.length() == 0)) { + logger.error("Bad Key Passwd"); + return false; + } + try { + NetworkSslServerPipelineFactory.WaarpSecureKeyStore = + new WaarpSecureKeyStore(keypath, keystorepass, + keypass); + } catch (CryptoException e) { + logger.error("Bad SecureKeyStore construction"); + return false; + } + + } + // TrustedKey for OpenR66 server + value = hashConfig.get(XML_PATH_TRUSTKEYPATH); + if (value == null || (value.isEmpty())) { + logger.info("Unable to find TRUST Key Path"); + NetworkSslServerPipelineFactory.WaarpSecureKeyStore.initEmptyTrustStore(); + } else { + String keypath = value.getString(); + if ((keypath == null) || (keypath.length() == 0)) { + logger.error("Bad TRUST Key Path"); + return false; + } + value = hashConfig.get(XML_PATH_TRUSTKEYSTOREPASS); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find TRUST KeyStore Passwd"); + return false; + } + String keystorepass = value.getString(); + if ((keystorepass == null) || (keystorepass.length() == 0)) { + logger.error("Bad TRUST KeyStore Passwd"); + return false; + } + boolean useClientAuthent = false; + value = hashConfig.get(XML_USECLIENT_AUTHENT); + if (value != null && (!value.isEmpty())) { + useClientAuthent = value.getBoolean(); + } + try { + NetworkSslServerPipelineFactory.WaarpSecureKeyStore.initTrustStore(keypath, + keystorepass, useClientAuthent); + } catch (CryptoException e) { + logger.error("Bad TrustKeyStore construction"); + return false; + } + } + NetworkSslServerPipelineFactory.waarpSslContextFactory = + new WaarpSslContextFactory( + NetworkSslServerPipelineFactory.WaarpSecureKeyStore); + return true; + } + + private static boolean loadNetworkServer(Configuration config) { + XmlValue value = hashConfig.get(XML_SERVER_PORT); + int port = 6666; + if (value != null && (!value.isEmpty())) { + port = value.getInteger(); + } else { + port = 6666; + } + config.SERVER_PORT = port; + value = hashConfig.get(XML_SERVER_SSLPORT); + int sslport = 6667; + if (value != null && (!value.isEmpty())) { + sslport = value.getInteger(); + } else { + sslport = 6667; + } + config.SERVER_SSLPORT = sslport; + value = hashConfig.get(XML_SERVER_HTTPPORT); + int httpport = 8066; + if (value != null && (!value.isEmpty())) { + httpport = value.getInteger(); + } + config.SERVER_HTTPPORT = httpport; + value = hashConfig.get(XML_SERVER_HTTPSPORT); + int httpsport = 8067; + if (value != null && (!value.isEmpty())) { + httpsport = value.getInteger(); + } + config.SERVER_HTTPSPORT = httpsport; + return true; + } + + /** + * Set the Crypto Key from the Document + * + * @param document + * @return True if OK + */ + private static boolean setCryptoKey(Configuration config) { + XmlValue value = hashConfig.get(XML_PATH_CRYPTOKEY); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find CryptoKey in Config file"); + return false; + } + String filename = value.getString(); + config.cryptoFile = filename; + File key = new File(filename); + Des des = new Des(); + try { + des.setSecretKey(key); + } catch (CryptoException e) { + logger.error("Unable to load CryptoKey from Config file"); + return false; + } catch (IOException e) { + logger.error("Unable to load CryptoKey from Config file"); + return false; + } + config.cryptoKey = des; + return true; + } + + /** + * Load data from database or from files if not connected + * + * @param document + * @return True if OK + */ + private static boolean loadFromDatabase(Configuration config) { + if (DbConstant.admin.isConnected) { + // load from database the limit to apply + try { + DbConfiguration configuration = new DbConfiguration( + DbConstant.admin.session, + config.HOST_ID); + configuration.updateConfiguration(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot load configuration from database", e); + } + } else { + if (config.baseDirectory != null && + config.configPath != null) { + // load Rules from files + File dirConfig = new File( + config.baseDirectory + + config.configPath); + if (dirConfig.isDirectory()) { + try { + RuleFileBasedConfiguration.importRules(dirConfig); + } catch (OpenR66ProtocolSystemException e) { + logger.error("Cannot load Rules", e); + return false; + } catch (WaarpDatabaseException e) { + logger.error("Cannot load Rules", e); + return false; + } + } else { + logger.error("Config Directory is not a directory: " + + config.baseDirectory + + config.configPath); + return false; + } + } + // load if possible the limit to apply + loadLimit(config, false); + } + return true; + } + + /** + * Load database parameter + * + * @param document + * @return True if OK + */ + private static boolean loadDatabase(Configuration config) { + XmlValue value = hashConfig.get(XML_DBDRIVER); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find DBDriver in Config file"); + DbConstant.admin = new DbAdmin(); // no database support + DbConstant.noCommitAdmin = DbConstant.admin; + } else { + String dbdriver = value.getString(); + value = hashConfig.get(XML_DBSERVER); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find DBServer in Config file"); + return false; + } + String dbserver = value.getString(); + value = hashConfig.get(XML_DBUSER); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find DBUser in Config file"); + return false; + } + String dbuser = value.getString(); + value = hashConfig.get(XML_DBPASSWD); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find DBPassword in Config file"); + return false; + } + String dbpasswd = value.getString(); + if (dbdriver == null || dbserver == null || dbuser == null || + dbpasswd == null || dbdriver.length() == 0 || + dbserver.length() == 0 || dbuser.length() == 0 || + dbpasswd.length() == 0) { + logger.error("Unable to find Correct DB data in Config file"); + return false; + } + try { + DbConstant.admin = + DbModelFactory.initialize(dbdriver, dbserver, dbuser, dbpasswd, + true); + if (config.multipleMonitors > 1) { + DbConstant.noCommitAdmin = + DbModelFactory.initialize(dbdriver, dbserver, dbuser, dbpasswd, + true); + DbConstant.noCommitAdmin.session.setAutoCommit(false); + } else { + DbConstant.noCommitAdmin = DbConstant.admin; + } + logger.info("Database connection: " + (DbConstant.admin != null) + ":" + + (DbConstant.noCommitAdmin != null)); + } catch (WaarpDatabaseNoConnectionException e2) { + logger.error("Unable to Connect to DB", e2); + return false; + } + } + value = hashConfig.get(XML_SAVE_TASKRUNNERNODB); + if (value != null && (!value.isEmpty())) { + config.saveTaskRunnerWithNoDb = value.getBoolean(); + } + return true; + } + + /** + * Load white list for Business if any + * + * @param document + */ + private static void loadBusinessWhiteList(Configuration config) { + XmlValue value = hashConfig.get(XML_BUSINESS); + if (value != null && (value.getList() != null)) { + @SuppressWarnings("unchecked") + List ids = (List) value.getList(); + if (ids != null) { + for (String sval : ids) { + if (sval.isEmpty()) { + continue; + } + logger.warn("Business Allow: " + sval); + config.businessWhiteSet.add(sval.trim()); + } + ids.clear(); + ids = null; + } + } + loadAliases(config); + // now check in DB + if (DbConstant.admin != null) { + try { + DbHostConfiguration hostconfiguration = new DbHostConfiguration(DbConstant.admin.session, config.HOST_ID); + if (hostconfiguration != null) { + updateHostConfiguration(config, hostconfiguration); + } + } catch (WaarpDatabaseException e) { + // ignore + } + + } + } + @SuppressWarnings("unchecked") + public static void loadAliases(Configuration config) { + XmlValue value = hashConfig.get(XML_ALIASES); + if (value != null && (value.getList() != null)) { + for (XmlValue[] xml : (List) value.getList()) { + XmlHash subHash = new XmlHash(xml); + value = subHash.get(XML_REALID); + if (value == null || (value.isEmpty())) { + continue; + } + String refHostId = value.getString(); + value = subHash.get(XML_ALIASID); + if (value == null || (value.isEmpty())) { + continue; + } + String aliasset = value.getString(); + String [] alias = aliasset.split(" |\\|"); + for (String namealias : alias) { + config.aliases.put(namealias, refHostId); + } + logger.warn("Aliases for: " + refHostId +" = "+ aliasset); + } + } + } + @SuppressWarnings("unchecked") + public static void updateHostConfiguration(Configuration config, DbHostConfiguration hostConfiguration) { + String business = hostConfiguration.getBusiness(); + Document document = null; + // Open config file + StringReader reader = null; + try { + reader = new StringReader(business); + document = new SAXReader().read(reader); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config Business string: " + business, e); + if (reader != null) { + reader.close(); + } + return; + } + if (document == null) { + logger.error("Unable to read the XML Config Business string: " + business); + if (reader != null) { + reader.close(); + } + return; + } + // XXX FIXME + List list = document.selectNodes(XML_BUSINESS + "/" + XML_BUSINESSID); + for (Element element : list) { + String sval = element.getText(); + if (sval.isEmpty()) { + continue; + } + logger.warn("Business Allow: " + sval); + config.businessWhiteSet.add(sval.trim()); + } + list.clear(); + document.clearContent(); + document = null; + if (reader != null) { + reader.close(); + reader = null; + } + + String aliases = hostConfiguration.getAliases(); + try { + reader = new StringReader(aliases); + document = new SAXReader().read(reader); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config Aliases string: " + business, e); + if (reader != null) { + reader.close(); + } + return; + } + if (document == null) { + logger.error("Unable to read the XML Config Aliases string: " + business); + if (reader != null) { + reader.close(); + } + return; + } + // XXX FIXME + list = document.selectNodes(XML_ALIASES + "/" + XML_ALIAS); + for (Element element : list) { + Element nodeid = (Element) element.selectSingleNode(XML_REALID); + if (nodeid == null) { + continue; + } + Element nodeset = (Element) element.selectSingleNode(XML_ALIASID); + if (nodeset == null) { + continue; + } + String refHostId = nodeid.getText(); + String aliasesid = nodeset.getText(); + String [] aliasid = aliasesid.split(" |\\|"); + for (String namealias : aliasid) { + config.aliases.put(namealias, refHostId); + } + logger.warn("Aliases for: " + refHostId +" = "+ aliasesid); + } + list.clear(); + document.clearContent(); + document = null; + if (reader != null) { + reader.close(); + } + + String xroles = hostConfiguration.getRoles(); + try { + reader = new StringReader(xroles); + document = new SAXReader().read(reader); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config Roles string: " + business, e); + if (reader != null) { + reader.close(); + } + return; + } + if (document == null) { + logger.error("Unable to read the XML Config Roles string: " + business); + if (reader != null) { + reader.close(); + } + return; + } + // XXX FIXME + list = document.selectNodes(XML_ROLES + "/" + XML_ROLE); + for (Element element : list) { + Element nodeid = (Element) element.selectSingleNode(XML_ROLEID); + if (nodeid == null) { + continue; + } + Element nodeset = (Element) element.selectSingleNode(XML_ROLESET); + if (nodeset == null) { + continue; + } + String refHostId = nodeid.getText(); + String roleset = nodeset.getText(); + String [] roles = roleset.split(" |\\|"); + RoleDefault newrole = new RoleDefault(); + for (String role : roles) { + try { + RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(role.toUpperCase()); + if (roletype == ROLE.NOACCESS) { + // reset + newrole.setRole(roletype); + } else { + newrole.addRole(roletype); + } + } catch (IllegalArgumentException e) { + // ignore + } + } + logger.warn("New Role: " + refHostId + ":" + newrole); + config.roles.put(refHostId, newrole); + } + list.clear(); + document.clearContent(); + document = null; + if (reader != null) { + reader.close(); + } + } + /** + * Load Role list if any + * + * @param document + */ + @SuppressWarnings("unchecked") + private static void loadRolesList(Configuration config) { + XmlValue value = hashConfig.get(XML_ROLES); + if (value != null && (value.getList() != null)) { + for (XmlValue[] xml : (List) value.getList()) { + XmlHash subHash = new XmlHash(xml); + value = subHash.get(XML_ROLEID); + if (value == null || (value.isEmpty())) { + continue; + } + String refHostId = value.getString(); + value = subHash.get(XML_ROLESET); + if (value == null || (value.isEmpty())) { + continue; + } + String roleset = value.getString(); + String [] roles = roleset.split(" |\\|"); + RoleDefault newrole = new RoleDefault(); + for (String role : roles) { + try { + RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(role.toUpperCase()); + if (roletype == ROLE.NOACCESS) { + // reset + newrole.setRole(roletype); + } else { + newrole.addRole(roletype); + } + } catch (IllegalArgumentException e) { + // ignore + } + } + logger.warn("New Role: " + refHostId + ":" + newrole); + config.roles.put(refHostId, newrole); + } + } + } + + /** + * + * @param document + * @param fromXML + * @return the new subpath + * @throws OpenR66ProtocolSystemException + */ + private static String getSubPath(Configuration config, String fromXML) + throws OpenR66ProtocolSystemException { + XmlValue value = hashConfig.get(fromXML); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find a Path in Config file: " + fromXML); + throw new OpenR66ProtocolSystemException( + "Unable to find a Path in Config file: " + fromXML); + } + + String path = value.getString(); + if (path == null || path.length() == 0) { + throw new OpenR66ProtocolSystemException( + "Unable to find a correct Path in Config file: " + fromXML); + } + path = DirInterface.SEPARATOR + path; + String newpath = config.baseDirectory + path; + File file = new File(newpath); + if (!file.isDirectory()) { + FileUtils.createDir(file); + } + return path; + } + + /** + * Load minimalistic Limit configuration + * + * @param filename + * @return True if OK + */ + public static boolean setConfigurationLoadLimitFromXml(Configuration config, String filename) { + Document document = null; + alreadySetLimit = false; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configServer); + hashConfig = new XmlHash(configuration); + if (!loadLimit(config, true)) { + logger.error("Unable to read Limitation config file: " + filename); + return false; + } + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Load configuration for init database + * + * @param filename + * @return True if OK + */ + public static boolean setConfigurationInitDatabase(Configuration config, String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configServer); + hashConfig = new XmlHash(configuration); + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + if (!loadDirectory(config)) { + logger.error("Cannot load Directory configuration"); + return false; + } + if (!loadLimit(config, false)) { + logger.error("Cannot load Limit configuration"); + return false; + } + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + if (!loadAuthentication(config)) { + logger.error("Cannot load Authentication configuration"); + return false; + } + } + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Load minimalistic configuration + * + * @param filename + * @return True if OK + */ + public static boolean setConfigurationServerMinimalFromXml(Configuration config, String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configServer); + hashConfig = new XmlHash(configuration); + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + if (!loadDirectory(config)) { + logger.error("Cannot load Directory configuration"); + return false; + } + if (!loadLimit(config, false)) { + logger.error("Cannot load Limit configuration"); + return false; + } + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + if (!loadAuthentication(config)) { + logger.error("Cannot load Authentication configuration"); + return false; + } + } + config.HOST_AUTH = R66Auth.getServerAuth( + DbConstant.admin.session, config.HOST_ID); + if (config.HOST_AUTH == null && + config.useNOSSL) { + logger.error("Cannot find Authentication for current host"); + return false; + } + if (config.HOST_SSLID != null) { + config.HOST_SSLAUTH = R66Auth.getServerAuth( + DbConstant.admin.session, + config.HOST_SSLID); + if (config.HOST_SSLAUTH == null && + config.useSSL) { + logger.error("Cannot find SSL Authentication for current host"); + return false; + } + } + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Initiate the configuration from the xml file for server shutdown + * + * @param filename + * @return True if OK + */ + public static boolean setConfigurationServerShutdownFromXml(Configuration config, + String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configServer); + hashConfig = new XmlHash(configuration); + // Now read the configuration + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + if (!loadServerParam(config)) { + logger.error("Cannot load Server Parameters"); + return false; + } + if (!loadDirectory(config)) { + logger.error("Cannot load Directory configuration"); + return false; + } + if (!loadLimit(config, false)) { + logger.error("Cannot load Limit configuration"); + return false; + } + if (config.useSSL) { + if (!loadSsl(config)) { + logger.error("Cannot load SSL configuration"); + return false; + } + } + if (!loadNetworkServer(config)) { + logger.error("Cannot load Network configuration"); + return false; + } + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + if (!loadAuthentication(config)) { + logger.error("Cannot load Authentication configuration"); + return false; + } + } + config.HOST_AUTH = R66Auth.getServerAuth( + DbConstant.admin.session, config.HOST_ID); + if (config.HOST_AUTH == null && + config.useNOSSL) { + logger.error("Cannot find Authentication for current host"); + return false; + } + if (config.HOST_SSLID != null) { + config.HOST_SSLAUTH = R66Auth.getServerAuth( + DbConstant.admin.session, + config.HOST_SSLID); + if (config.HOST_SSLAUTH == null && + config.useSSL) { + logger.error("Cannot find SSL Authentication for current host"); + return false; + } + } + loadBusinessWhiteList(config); + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Initiate the configuration from the xml file for server + * + * @param filename + * @return True if OK + */ + public static boolean setConfigurationServerFromXml(Configuration config, String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configServer); + hashConfig = new XmlHash(configuration); + // Now read the configuration + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + if (!loadServerParam(config)) { + logger.error("Cannot load Server Parameters"); + return false; + } + if (!loadDirectory(config)) { + logger.error("Cannot load Directory configuration"); + return false; + } + if (!loadLimit(config, false)) { + logger.error("Cannot load Limit configuration"); + return false; + } + if (config.useSSL) { + if (!loadSsl(config)) { + logger.error("Cannot load SSL configuration"); + return false; + } + } + if (!loadNetworkServer(config)) { + logger.error("Cannot load Network configuration"); + return false; + } + if (!loadFromDatabase(config)) { + logger.error("Cannot load configuration from Database"); + return false; + } + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + if (!loadAuthentication(config)) { + logger.error("Cannot load Authentication configuration"); + return false; + } + } + config.HOST_AUTH = R66Auth.getServerAuth( + DbConstant.admin.session, config.HOST_ID); + if (config.HOST_AUTH == null && + config.useNOSSL) { + logger.error("Cannot find Authentication for current host"); + return false; + } + if (config.HOST_SSLID != null) { + config.HOST_SSLAUTH = R66Auth.getServerAuth( + DbConstant.admin.session, + config.HOST_SSLID); + if (config.HOST_SSLAUTH == null && + config.useSSL) { + logger.error("Cannot find SSL Authentication for current host"); + return false; + } + } + loadBusinessWhiteList(config); + loadRolesList(config); + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Initiate the configuration from the xml file for database client + * + * @param filename + * @return True if OK + */ + public static boolean setClientConfigurationFromXml(Configuration config, String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configClient); + hashConfig = new XmlHash(configuration); + // Client enables SSL by default but could be reverted later on + config.useSSL = true; + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + if (!loadClientParam(config)) { + logger.error("Cannot load Client Parameters"); + return false; + } + if (!loadDirectory(config)) { + logger.error("Cannot load Directory configuration"); + return false; + } + if (!loadLimit(config, false)) { + logger.error("Cannot load Limit configuration"); + return false; + } + if (config.useSSL) { + if (!loadSsl(config)) { + logger.error("Cannot load SSL configuration"); + return false; + } + } + if (!loadFromDatabase(config)) { + logger.error("Cannot load configuration from Database"); + return false; + } + if (!DbConstant.admin.isConnected) { + // if no database, must load authentication from file + if (!loadAuthentication(config)) { + logger.error("Cannot load Authentication configuration"); + return false; + } + } + config.HOST_AUTH = R66Auth.getServerAuth( + DbConstant.admin.session, config.HOST_ID); + if (config.HOST_AUTH == null) { + logger.error("Cannot find Authentication for current host"); + return false; + } + if (config.HOST_SSLID != null) { + config.HOST_SSLAUTH = R66Auth.getServerAuth( + DbConstant.admin.session, + config.HOST_SSLID); + if (config.HOST_SSLAUTH == null) { + logger.error("Cannot find SSL Authentication for current host"); + return false; + } + } + loadBusinessWhiteList(config); + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } + + /** + * Initiate the configuration from the xml file for submit database client + * + * @param config + * @param filename + * @return True if OK + */ + public static boolean setSubmitClientConfigurationFromXml(Configuration config, String filename) { + Document document = null; + // Open config file + try { + document = new SAXReader().read(filename); + } catch (DocumentException e) { + logger.error("Unable to read the XML Config file: " + filename, e); + return false; + } + if (document == null) { + logger.error("Unable to read the XML Config file: " + filename); + return false; + } + configuration = XmlUtil.read(document, configSubmitClient); + hashConfig = new XmlHash(configuration); + // Client enables SSL by default but could be reverted later on + config.useSSL = true; + if (!loadIdentity(config)) { + logger.error("Cannot load Identity"); + return false; + } + if (!loadDatabase(config)) { + logger.error("Cannot load Database configuration"); + return false; + } + XmlValue value = hashConfig.get(XML_BLOCKSIZE); + if (value != null && (!value.isEmpty())) { + config.BLOCKSIZE = value.getInteger(); + } + config.HOST_AUTH = R66Auth.getServerAuth( + DbConstant.admin.session, config.HOST_ID); + if (config.HOST_AUTH == null) { + logger.error("Cannot find Authentication for current host"); + return false; + } + if (config.HOST_SSLID != null) { + config.HOST_SSLAUTH = R66Auth.getServerAuth( + DbConstant.admin.session, + config.HOST_SSLID); + if (config.HOST_SSLAUTH == null) { + logger.error("Cannot find SSL Authentication for current host"); + return false; + } + } + loadBusinessWhiteList(config); + hashConfig.clear(); + hashConfig = null; + configuration = null; + return true; + } +} diff --git a/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java b/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java index 2cf8cd3f7..a81c52606 100644 --- a/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java +++ b/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java @@ -1,664 +1,664 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.configuration; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.dom4j.tree.DefaultElement; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.file.DirInterface; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.xml.XmlDecl; -import org.waarp.common.xml.XmlHash; -import org.waarp.common.xml.XmlType; -import org.waarp.common.xml.XmlUtil; -import org.waarp.common.xml.XmlValue; -import org.waarp.openr66.context.task.TaskType; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Rule File Based Configuration - * - * @author Frederic Bregier - * - */ -public class RuleFileBasedConfiguration { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(RuleFileBasedConfiguration.class); - - private static final String MULTIPLEROOT = "rules"; - private static final String ROOT = "rule"; - private static final String XIDRULE = "idrule"; - public static final String XHOSTIDS = "hostids"; - public static final String XHOSTID = "hostid"; - private static final String XMODE = "mode"; - private static final String XRECVPATH = "recvpath"; - private static final String XSENDPATH = "sendpath"; - private static final String XARCHIVEPATH = "archivepath"; - private static final String XWORKPATH = "workpath"; - private static final String XRPRETASKS = "rpretasks"; - private static final String XRPOSTTASKS = "rposttasks"; - private static final String XRERRORTASKS = "rerrortasks"; - private static final String XSPRETASKS = "spretasks"; - private static final String XSPOSTTASKS = "sposttasks"; - private static final String XSERRORTASKS = "serrortasks"; - public static final String XTASKS = "tasks"; - public static final String XTASK = "task"; - - private static final String HOSTIDS_HOSTID = "/" + XHOSTIDS + "/" - + XHOSTID; - - private static final String TASK = "/tasks/task"; - - private static final XmlDecl[] taskDecl = { - new XmlDecl(XmlType.STRING, DbRule.TASK_TYPE), - new XmlDecl(XmlType.STRING, DbRule.TASK_PATH), - new XmlDecl(XmlType.LONG, DbRule.TASK_DELAY), - }; - public static final XmlDecl[] tasksDecl = { - new XmlDecl(XTASK, - XmlType.XVAL, TASK, - taskDecl, true) - }; - private static final XmlDecl[] subruleDecls = { - new XmlDecl(XmlType.STRING, XIDRULE), - new XmlDecl(XHOSTIDS, XmlType.STRING, HOSTIDS_HOSTID, true), - new XmlDecl(XmlType.INTEGER, XMODE), - new XmlDecl(XmlType.STRING, XRECVPATH), - new XmlDecl(XmlType.STRING, XSENDPATH), - new XmlDecl(XmlType.STRING, XARCHIVEPATH), - new XmlDecl(XmlType.STRING, XWORKPATH), - new XmlDecl(XRPRETASKS, XmlType.XVAL, XRPRETASKS, tasksDecl, false), - new XmlDecl(XRPOSTTASKS, XmlType.XVAL, XRPOSTTASKS, tasksDecl, false), - new XmlDecl(XRERRORTASKS, XmlType.XVAL, XRERRORTASKS, tasksDecl, false), - new XmlDecl(XSPRETASKS, XmlType.XVAL, XSPRETASKS, tasksDecl, false), - new XmlDecl(XSPOSTTASKS, XmlType.XVAL, XSPOSTTASKS, tasksDecl, false), - new XmlDecl(XSERRORTASKS, XmlType.XVAL, XSERRORTASKS, tasksDecl, false) - }; - private static final XmlDecl[] ruleDecls = { - new XmlDecl(ROOT, XmlType.XVAL, - ROOT, subruleDecls, - false) - }; - private static final XmlDecl[] multipleruleDecls = { - new XmlDecl(MULTIPLEROOT, - XmlType.XVAL, "/" - + MULTIPLEROOT - + "/" + ROOT, - subruleDecls, true) - }; - public static final XmlDecl[] hostsDecls = { - new XmlDecl(XHOSTIDS, - XmlType.STRING, - HOSTIDS_HOSTID, true), - }; - - /** - * Extension of rule files - */ - public static final String EXT_RULE = ".rule.xml"; - /** - * Extension of multiple rules in one file - */ - public static final String EXT_RULES = ".rules.xml"; - - /** - * Import all Rule files into the HashTable of Rules - * - * @param configDirectory - * @throws OpenR66ProtocolSystemException - * @throws WaarpDatabaseException - */ - public static void importRules(File configDirectory) - throws OpenR66ProtocolSystemException, WaarpDatabaseException { - File[] files = FileUtils.getFiles(configDirectory, - new ExtensionFilter(EXT_RULE)); - for (File file : files) { - DbRule rule = getFromFile(file); - logger.debug(rule.toString()); - } - files = FileUtils.getFiles(configDirectory, - new ExtensionFilter(EXT_RULES)); - for (File file : files) { - getMultipleFromFile(file); - } - } - - /** - * Utility function - * - * @param value - * @return the array of tasks or empty array if in error. - */ - @SuppressWarnings("unchecked") - public static String[][] getTasksRule(XmlValue value) { - List list = (List) value.getList(); - if (list == null || list.isEmpty()) { - logger.debug("NoRule for " + value.getName()); - // Unable to find the tasks for Rule, setting to the default - return new String[0][0]; - } - String[][] taskArray = new String[list.size()][3]; - for (int i = 0; i < list.size(); i++) { - taskArray[i][0] = null; - taskArray[i][1] = null; - taskArray[i][2] = null; - } - int rank = 0; - for (XmlValue[] subvals : list) { - XmlHash hash = new XmlHash(subvals); - XmlValue valtype = hash.get(DbRule.TASK_TYPE); - if (valtype == null || (valtype.isEmpty()) || valtype.getString().isEmpty()) { - continue; - } - XmlValue valpath = hash.get(DbRule.TASK_PATH); - if (valpath == null || (valpath.isEmpty()) || valtype.getString().isEmpty()) { - continue; - } - XmlValue valdelay = hash.get(DbRule.TASK_DELAY); - String delay; - if (valdelay == null || (valdelay.isEmpty())) { - delay = Long - .toString(Configuration.configuration.TIMEOUTCON); - } else { - delay = valdelay.getIntoString(); - } - taskArray[rank][0] = valtype.getString().toUpperCase(); - // CHECK TASK_TYPE - try { - TaskType.valueOf(taskArray[rank][0]); - } catch (IllegalArgumentException e) { - // Bad Type - logger.warn("Bad Type of Task: " + taskArray[rank][0]); - continue; - } - taskArray[rank][1] = valpath.getString(); - taskArray[rank][2] = delay; - rank++; - hash.clear(); - } - list.clear(); - list = null; - return taskArray; - } - - /** - * - * @param value - * the XmlValue hosting hostids/hostid - * @return the array of HostIds allowed for the current rule - */ - public static String[] getHostIds(XmlValue value) { - String[] idsArray = null; - if (value == null || (value.getList() == null) || value.getList().isEmpty()) { - logger - .info("Unable to find the id for Rule, setting to the default"); - } else { - @SuppressWarnings("unchecked") - List ids = (List) value.getList(); - idsArray = new String[ids.size()]; - int i = 0; - for (String sval : ids) { - if (sval.isEmpty()) { - continue; - } - idsArray[i] = sval; - i++; - } - ids.clear(); - ids = null; - } - return idsArray; - } - - /** - * Load and update a Rule from a file - * - * @param file - * @return the newly created R66Rule from XML File - * @throws OpenR66ProtocolSystemException - * @throws WaarpDatabaseException - * @throws WaarpDatabaseNoDataException - * @throws WaarpDatabaseSqlException - * @throws WaarpDatabaseNoConnectionException - * @throws OpenR66ProtocolNoDataException - */ - public static DbRule getFromFile(File file) - throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { - DbRule newRule = null; - Document document = null; - // Open config file - try { - document = new SAXReader().read(file); - } catch (DocumentException e) { - logger.error("Unable to read the XML Rule file: " + file.getName(), - e); - throw new OpenR66ProtocolSystemException( - "Unable to read the XML Rule file", e); - } - if (document == null) { - logger.error("Unable to read the XML Rule file: " + file.getName()); - throw new OpenR66ProtocolSystemException( - "Unable to read the XML Rule file"); - } - XmlValue[] values = XmlUtil.read(document, ruleDecls); - newRule = getFromXmlValue(values); - values = null; - return newRule; - } - - /** - * Load and update multiple Rules from one file - * - * @param file - * @return a list of newly created R66Rule from XML File - * @throws OpenR66ProtocolSystemException - * @throws WaarpDatabaseException - * @throws WaarpDatabaseNoDataException - * @throws WaarpDatabaseSqlException - * @throws WaarpDatabaseNoConnectionException - * @throws OpenR66ProtocolNoDataException - */ - public static List getMultipleFromFile(File file) - throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { - Document document = null; - // Open config file - try { - document = new SAXReader().read(file); - } catch (DocumentException e) { - logger.error("Unable to read the XML Rule file: " + file.getName(), - e); - throw new OpenR66ProtocolSystemException( - "Unable to read the XML Rule file", e); - } - if (document == null) { - logger.error("Unable to read the XML Rule file: " + file.getName()); - throw new OpenR66ProtocolSystemException( - "Unable to read the XML Rule file"); - } - XmlValue[] values = XmlUtil.read(document, multipleruleDecls); - if (values.length <= 0) { - return new ArrayList(0); - } - XmlValue value = values[0]; - @SuppressWarnings("unchecked") - List list = (List) value.getList(); - List result = new ArrayList(list.size()); - for (XmlValue[] xmlValue : list) { - result.add(getFromXmlValue(xmlValue)); - } - values = null; - return result; - } - - /** - * Load and update one Rule from a XmlValue - * - * @param root - * @return the newly created R66Rule from XML File - * @throws OpenR66ProtocolSystemException - * @throws WaarpDatabaseException - * @throws WaarpDatabaseNoDataException - * @throws WaarpDatabaseSqlException - * @throws WaarpDatabaseNoConnectionException - * @throws OpenR66ProtocolNoDataException - */ - private static DbRule getFromXmlValue(XmlValue[] root) - throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { - DbRule newRule = null; - XmlHash hash = new XmlHash(root); - XmlValue value = hash.get(XIDRULE); - if (value == null || (value.isEmpty()) || value.getString().length() == 0) { - logger.error("Unable to find in Rule field: " + XIDRULE); - throw new OpenR66ProtocolSystemException(); - } - String idrule = value.getString(); - value = hash.get(XMODE); - if (value == null || (value.isEmpty())) { - logger.error("Unable to find in Rule field: " + XMODE); - throw new OpenR66ProtocolSystemException(); - } - int mode = value.getInteger(); - String recvpath; - value = hash.get(XRECVPATH); - if (value == null || (value.isEmpty()) || value.getString().length() == 0) { - recvpath = Configuration.configuration.inPath; - } else { - recvpath = DirInterface.SEPARATOR + value.getString(); - } - String sendpath; - value = hash.get(XSENDPATH); - if (value == null || (value.isEmpty()) || value.getString().length() == 0) { - sendpath = Configuration.configuration.outPath; - } else { - sendpath = DirInterface.SEPARATOR + value.getString(); - } - String archivepath; - value = hash.get(XARCHIVEPATH); - if (value == null || (value.isEmpty()) || value.getString().length() == 0) { - archivepath = Configuration.configuration.archivePath; - } else { - archivepath = DirInterface.SEPARATOR + value.getString(); - } - String workpath; - value = hash.get(XWORKPATH); - if (value == null || (value.isEmpty()) || value.getString().length() == 0) { - workpath = Configuration.configuration.workingPath; - } else { - workpath = DirInterface.SEPARATOR + value.getString(); - } - String[] idsArray = null; - value = hash.get(XHOSTIDS); - idsArray = getHostIds(value); - String[][] rpretasks = new String[0][0]; - value = hash.get(XRPRETASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - rpretasks = getTasksRule(subvalues[0]); - } - } - String[][] rposttasks = new String[0][0]; - value = hash.get(XRPOSTTASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - rposttasks = getTasksRule(subvalues[0]); - } - } - String[][] rerrortasks = new String[0][0]; - value = hash.get(XRERRORTASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - rerrortasks = getTasksRule(subvalues[0]); - } - } - String[][] spretasks = new String[0][0]; - value = hash.get(XSPRETASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - spretasks = getTasksRule(subvalues[0]); - } - } - String[][] sposttasks = new String[0][0]; - value = hash.get(XSPOSTTASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - sposttasks = getTasksRule(subvalues[0]); - } - } - String[][] serrortasks = new String[0][0]; - value = hash.get(XSERRORTASKS); - if (value != null && (!value.isEmpty())) { - XmlValue[] subvalues = value.getSubXml(); - if (subvalues.length > 0) { - serrortasks = getTasksRule(subvalues[0]); - } - } - - newRule = new DbRule(DbConstant.admin.session, idrule, idsArray, mode, recvpath, sendpath, - archivepath, workpath, rpretasks, rposttasks, rerrortasks, - spretasks, sposttasks, serrortasks); - if (DbConstant.admin != null && DbConstant.admin.session != null) { - if (newRule.exist()) { - newRule.update(); - } else { - newRule.insert(); - } - } else { - // put in hashtable - newRule.insert(); - } - hash.clear(); - return newRule; - } - - /** - * Construct a new Element with value - * - * @param name - * @param value - * @return the new Element - */ - private static final Element newElement(String name, String value) { - Element node = new DefaultElement(name); - node.addText(value); - return node; - } - - /** - * Add a rule from root element (ROOT = rule) - * - * @param element - * @param rule - */ - private static void addToElement(Element element, DbRule rule) { - Element root = element; - root.add(newElement(XIDRULE, rule.idRule)); - Element hosts = new DefaultElement(XHOSTIDS); - if (rule.idsArray != null) { - for (String host : rule.idsArray) { - hosts.add(newElement(XHOSTID, host)); - } - } - root.add(hosts); - root.add(newElement(XMODE, Integer.toString(rule.mode))); - if (rule.recvPath != null) { - root.add(newElement(XRECVPATH, rule.recvPath.substring(1))); - } - if (rule.sendPath != null) { - root.add(newElement(XSENDPATH, rule.sendPath.substring(1))); - } - if (rule.archivePath != null) { - root.add(newElement(XARCHIVEPATH, rule.archivePath.substring(1))); - } - if (rule.workPath != null) { - root.add(newElement(XWORKPATH, rule.workPath.substring(1))); - } - Element tasks = new DefaultElement(XRPRETASKS); - Element roottasks = new DefaultElement(XTASKS); - int rank = 0; - String[][] array = rule.rpreTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - tasks = new DefaultElement(XRPOSTTASKS); - roottasks = new DefaultElement(XTASKS); - array = rule.rpostTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - tasks = new DefaultElement(XRERRORTASKS); - roottasks = new DefaultElement(XTASKS); - array = rule.rerrorTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - tasks = new DefaultElement(XSPRETASKS); - roottasks = new DefaultElement(XTASKS); - array = rule.spreTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - tasks = new DefaultElement(XSPOSTTASKS); - roottasks = new DefaultElement(XTASKS); - array = rule.spostTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - tasks = new DefaultElement(XSERRORTASKS); - roottasks = new DefaultElement(XTASKS); - array = rule.serrorTasksArray; - if (array != null) { - for (rank = 0; rank < array.length; rank++) { - Element task = new DefaultElement(XTASK); - task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); - task.add(newElement(DbRule.TASK_PATH, array[rank][1])); - task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - roottasks.add(task); - } - } - tasks.add(roottasks); - root.add(tasks); - } - - /** - * Write the rule to a file from filename - * - * @param filename - * @param rule - * @throws OpenR66ProtocolSystemException - */ - private static final void writeXML(String filename, DbRule rule) - throws OpenR66ProtocolSystemException { - Document document = DocumentHelper.createDocument(); - Element root = document.addElement(ROOT); - addToElement(root, rule); - try { - XmlUtil.writeXML(filename, null, document); - } catch (IOException e) { - throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); - } - } - - /** - * Write to directory files prefixed by hostname all Rules from database - * - * @param directory - * @param hostname - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - * @throws OpenR66ProtocolSystemException - */ - public static final void writeXml(String directory, String hostname) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, - OpenR66ProtocolSystemException { - File dir = new File(directory); - if (!dir.isDirectory()) { - dir.mkdirs(); - } - DbRule[] rules = DbRule.getAllRules(DbConstant.admin.session); - for (DbRule rule : rules) { - String filename = dir.getAbsolutePath() + File.separator + hostname + "_" + rule.idRule - + - RuleFileBasedConfiguration.EXT_RULE; - logger.debug("Will write Rule: "+rule.idRule+" in "+filename); - RuleFileBasedConfiguration.writeXML(filename, rule); - } - } - - /** - * Write to directory 1 file prefixed by hostname all Rules from database - * - * @param directory - * @param hostname - * @return the filename - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - * @throws OpenR66ProtocolSystemException - */ - public static String writeOneXml(String directory, String hostname) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, - OpenR66ProtocolSystemException { - File dir = new File(directory); - if (!dir.isDirectory()) { - dir.mkdirs(); - } - DbRule[] rules = DbRule.getAllRules(DbConstant.admin.session); - String filename = dir.getAbsolutePath() + File.separator + hostname + - RuleFileBasedConfiguration.EXT_RULES; - Document document = DocumentHelper.createDocument(); - Element root = document.addElement(MULTIPLEROOT); - for (DbRule rule : rules) { - Element element = root.addElement(ROOT); - addToElement(element, rule); - } - try { - XmlUtil.writeXML(filename, null, document); - } catch (IOException e) { - throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); - } - return filename; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.configuration; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.dom4j.tree.DefaultElement; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.file.DirInterface; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.xml.XmlDecl; +import org.waarp.common.xml.XmlHash; +import org.waarp.common.xml.XmlType; +import org.waarp.common.xml.XmlUtil; +import org.waarp.common.xml.XmlValue; +import org.waarp.openr66.context.task.TaskType; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Rule File Based Configuration + * + * @author Frederic Bregier + * + */ +public class RuleFileBasedConfiguration { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(RuleFileBasedConfiguration.class); + + private static final String MULTIPLEROOT = "rules"; + private static final String ROOT = "rule"; + private static final String XIDRULE = "idrule"; + public static final String XHOSTIDS = "hostids"; + public static final String XHOSTID = "hostid"; + private static final String XMODE = "mode"; + private static final String XRECVPATH = "recvpath"; + private static final String XSENDPATH = "sendpath"; + private static final String XARCHIVEPATH = "archivepath"; + private static final String XWORKPATH = "workpath"; + private static final String XRPRETASKS = "rpretasks"; + private static final String XRPOSTTASKS = "rposttasks"; + private static final String XRERRORTASKS = "rerrortasks"; + private static final String XSPRETASKS = "spretasks"; + private static final String XSPOSTTASKS = "sposttasks"; + private static final String XSERRORTASKS = "serrortasks"; + public static final String XTASKS = "tasks"; + public static final String XTASK = "task"; + + private static final String HOSTIDS_HOSTID = "/" + XHOSTIDS + "/" + + XHOSTID; + + private static final String TASK = "/tasks/task"; + + private static final XmlDecl[] taskDecl = { + new XmlDecl(XmlType.STRING, DbRule.TASK_TYPE), + new XmlDecl(XmlType.STRING, DbRule.TASK_PATH), + new XmlDecl(XmlType.LONG, DbRule.TASK_DELAY), + }; + public static final XmlDecl[] tasksDecl = { + new XmlDecl(XTASK, + XmlType.XVAL, TASK, + taskDecl, true) + }; + private static final XmlDecl[] subruleDecls = { + new XmlDecl(XmlType.STRING, XIDRULE), + new XmlDecl(XHOSTIDS, XmlType.STRING, HOSTIDS_HOSTID, true), + new XmlDecl(XmlType.INTEGER, XMODE), + new XmlDecl(XmlType.STRING, XRECVPATH), + new XmlDecl(XmlType.STRING, XSENDPATH), + new XmlDecl(XmlType.STRING, XARCHIVEPATH), + new XmlDecl(XmlType.STRING, XWORKPATH), + new XmlDecl(XRPRETASKS, XmlType.XVAL, XRPRETASKS, tasksDecl, false), + new XmlDecl(XRPOSTTASKS, XmlType.XVAL, XRPOSTTASKS, tasksDecl, false), + new XmlDecl(XRERRORTASKS, XmlType.XVAL, XRERRORTASKS, tasksDecl, false), + new XmlDecl(XSPRETASKS, XmlType.XVAL, XSPRETASKS, tasksDecl, false), + new XmlDecl(XSPOSTTASKS, XmlType.XVAL, XSPOSTTASKS, tasksDecl, false), + new XmlDecl(XSERRORTASKS, XmlType.XVAL, XSERRORTASKS, tasksDecl, false) + }; + private static final XmlDecl[] ruleDecls = { + new XmlDecl(ROOT, XmlType.XVAL, + ROOT, subruleDecls, + false) + }; + private static final XmlDecl[] multipleruleDecls = { + new XmlDecl(MULTIPLEROOT, + XmlType.XVAL, "/" + + MULTIPLEROOT + + "/" + ROOT, + subruleDecls, true) + }; + public static final XmlDecl[] hostsDecls = { + new XmlDecl(XHOSTIDS, + XmlType.STRING, + HOSTIDS_HOSTID, true), + }; + + /** + * Extension of rule files + */ + public static final String EXT_RULE = ".rule.xml"; + /** + * Extension of multiple rules in one file + */ + public static final String EXT_RULES = ".rules.xml"; + + /** + * Import all Rule files into the HashTable of Rules + * + * @param configDirectory + * @throws OpenR66ProtocolSystemException + * @throws WaarpDatabaseException + */ + public static void importRules(File configDirectory) + throws OpenR66ProtocolSystemException, WaarpDatabaseException { + File[] files = FileUtils.getFiles(configDirectory, + new ExtensionFilter(EXT_RULE)); + for (File file : files) { + DbRule rule = getFromFile(file); + logger.debug(rule.toString()); + } + files = FileUtils.getFiles(configDirectory, + new ExtensionFilter(EXT_RULES)); + for (File file : files) { + getMultipleFromFile(file); + } + } + + /** + * Utility function + * + * @param value + * @return the array of tasks or empty array if in error. + */ + @SuppressWarnings("unchecked") + public static String[][] getTasksRule(XmlValue value) { + List list = (List) value.getList(); + if (list == null || list.isEmpty()) { + logger.debug("NoRule for " + value.getName()); + // Unable to find the tasks for Rule, setting to the default + return new String[0][0]; + } + String[][] taskArray = new String[list.size()][3]; + for (int i = 0; i < list.size(); i++) { + taskArray[i][0] = null; + taskArray[i][1] = null; + taskArray[i][2] = null; + } + int rank = 0; + for (XmlValue[] subvals : list) { + XmlHash hash = new XmlHash(subvals); + XmlValue valtype = hash.get(DbRule.TASK_TYPE); + if (valtype == null || (valtype.isEmpty()) || valtype.getString().isEmpty()) { + continue; + } + XmlValue valpath = hash.get(DbRule.TASK_PATH); + if (valpath == null || (valpath.isEmpty()) || valtype.getString().isEmpty()) { + continue; + } + XmlValue valdelay = hash.get(DbRule.TASK_DELAY); + String delay; + if (valdelay == null || (valdelay.isEmpty())) { + delay = Long + .toString(Configuration.configuration.TIMEOUTCON); + } else { + delay = valdelay.getIntoString(); + } + taskArray[rank][0] = valtype.getString().toUpperCase(); + // CHECK TASK_TYPE + try { + TaskType.valueOf(taskArray[rank][0]); + } catch (IllegalArgumentException e) { + // Bad Type + logger.warn("Bad Type of Task: " + taskArray[rank][0]); + continue; + } + taskArray[rank][1] = valpath.getString(); + taskArray[rank][2] = delay; + rank++; + hash.clear(); + } + list.clear(); + list = null; + return taskArray; + } + + /** + * + * @param value + * the XmlValue hosting hostids/hostid + * @return the array of HostIds allowed for the current rule + */ + public static String[] getHostIds(XmlValue value) { + String[] idsArray = null; + if (value == null || (value.getList() == null) || value.getList().isEmpty()) { + logger + .info("Unable to find the id for Rule, setting to the default"); + } else { + @SuppressWarnings("unchecked") + List ids = (List) value.getList(); + idsArray = new String[ids.size()]; + int i = 0; + for (String sval : ids) { + if (sval.isEmpty()) { + continue; + } + idsArray[i] = sval; + i++; + } + ids.clear(); + ids = null; + } + return idsArray; + } + + /** + * Load and update a Rule from a file + * + * @param file + * @return the newly created R66Rule from XML File + * @throws OpenR66ProtocolSystemException + * @throws WaarpDatabaseException + * @throws WaarpDatabaseNoDataException + * @throws WaarpDatabaseSqlException + * @throws WaarpDatabaseNoConnectionException + * @throws OpenR66ProtocolNoDataException + */ + public static DbRule getFromFile(File file) + throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { + DbRule newRule = null; + Document document = null; + // Open config file + try { + document = new SAXReader().read(file); + } catch (DocumentException e) { + logger.error("Unable to read the XML Rule file: " + file.getName(), + e); + throw new OpenR66ProtocolSystemException( + "Unable to read the XML Rule file", e); + } + if (document == null) { + logger.error("Unable to read the XML Rule file: " + file.getName()); + throw new OpenR66ProtocolSystemException( + "Unable to read the XML Rule file"); + } + XmlValue[] values = XmlUtil.read(document, ruleDecls); + newRule = getFromXmlValue(values); + values = null; + return newRule; + } + + /** + * Load and update multiple Rules from one file + * + * @param file + * @return a list of newly created R66Rule from XML File + * @throws OpenR66ProtocolSystemException + * @throws WaarpDatabaseException + * @throws WaarpDatabaseNoDataException + * @throws WaarpDatabaseSqlException + * @throws WaarpDatabaseNoConnectionException + * @throws OpenR66ProtocolNoDataException + */ + public static List getMultipleFromFile(File file) + throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { + Document document = null; + // Open config file + try { + document = new SAXReader().read(file); + } catch (DocumentException e) { + logger.error("Unable to read the XML Rule file: " + file.getName(), + e); + throw new OpenR66ProtocolSystemException( + "Unable to read the XML Rule file", e); + } + if (document == null) { + logger.error("Unable to read the XML Rule file: " + file.getName()); + throw new OpenR66ProtocolSystemException( + "Unable to read the XML Rule file"); + } + XmlValue[] values = XmlUtil.read(document, multipleruleDecls); + if (values.length <= 0) { + return new ArrayList(0); + } + XmlValue value = values[0]; + @SuppressWarnings("unchecked") + List list = (List) value.getList(); + List result = new ArrayList(list.size()); + for (XmlValue[] xmlValue : list) { + result.add(getFromXmlValue(xmlValue)); + } + values = null; + return result; + } + + /** + * Load and update one Rule from a XmlValue + * + * @param root + * @return the newly created R66Rule from XML File + * @throws OpenR66ProtocolSystemException + * @throws WaarpDatabaseException + * @throws WaarpDatabaseNoDataException + * @throws WaarpDatabaseSqlException + * @throws WaarpDatabaseNoConnectionException + * @throws OpenR66ProtocolNoDataException + */ + private static DbRule getFromXmlValue(XmlValue[] root) + throws OpenR66ProtocolSystemException, WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException, WaarpDatabaseException { + DbRule newRule = null; + XmlHash hash = new XmlHash(root); + XmlValue value = hash.get(XIDRULE); + if (value == null || (value.isEmpty()) || value.getString().length() == 0) { + logger.error("Unable to find in Rule field: " + XIDRULE); + throw new OpenR66ProtocolSystemException(); + } + String idrule = value.getString(); + value = hash.get(XMODE); + if (value == null || (value.isEmpty())) { + logger.error("Unable to find in Rule field: " + XMODE); + throw new OpenR66ProtocolSystemException(); + } + int mode = value.getInteger(); + String recvpath; + value = hash.get(XRECVPATH); + if (value == null || (value.isEmpty()) || value.getString().length() == 0) { + recvpath = Configuration.configuration.inPath; + } else { + recvpath = DirInterface.SEPARATOR + value.getString(); + } + String sendpath; + value = hash.get(XSENDPATH); + if (value == null || (value.isEmpty()) || value.getString().length() == 0) { + sendpath = Configuration.configuration.outPath; + } else { + sendpath = DirInterface.SEPARATOR + value.getString(); + } + String archivepath; + value = hash.get(XARCHIVEPATH); + if (value == null || (value.isEmpty()) || value.getString().length() == 0) { + archivepath = Configuration.configuration.archivePath; + } else { + archivepath = DirInterface.SEPARATOR + value.getString(); + } + String workpath; + value = hash.get(XWORKPATH); + if (value == null || (value.isEmpty()) || value.getString().length() == 0) { + workpath = Configuration.configuration.workingPath; + } else { + workpath = DirInterface.SEPARATOR + value.getString(); + } + String[] idsArray = null; + value = hash.get(XHOSTIDS); + idsArray = getHostIds(value); + String[][] rpretasks = new String[0][0]; + value = hash.get(XRPRETASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + rpretasks = getTasksRule(subvalues[0]); + } + } + String[][] rposttasks = new String[0][0]; + value = hash.get(XRPOSTTASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + rposttasks = getTasksRule(subvalues[0]); + } + } + String[][] rerrortasks = new String[0][0]; + value = hash.get(XRERRORTASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + rerrortasks = getTasksRule(subvalues[0]); + } + } + String[][] spretasks = new String[0][0]; + value = hash.get(XSPRETASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + spretasks = getTasksRule(subvalues[0]); + } + } + String[][] sposttasks = new String[0][0]; + value = hash.get(XSPOSTTASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + sposttasks = getTasksRule(subvalues[0]); + } + } + String[][] serrortasks = new String[0][0]; + value = hash.get(XSERRORTASKS); + if (value != null && (!value.isEmpty())) { + XmlValue[] subvalues = value.getSubXml(); + if (subvalues.length > 0) { + serrortasks = getTasksRule(subvalues[0]); + } + } + + newRule = new DbRule(DbConstant.admin.session, idrule, idsArray, mode, recvpath, sendpath, + archivepath, workpath, rpretasks, rposttasks, rerrortasks, + spretasks, sposttasks, serrortasks); + if (DbConstant.admin != null && DbConstant.admin.session != null) { + if (newRule.exist()) { + newRule.update(); + } else { + newRule.insert(); + } + } else { + // put in hashtable + newRule.insert(); + } + hash.clear(); + return newRule; + } + + /** + * Construct a new Element with value + * + * @param name + * @param value + * @return the new Element + */ + private static final Element newElement(String name, String value) { + Element node = new DefaultElement(name); + node.addText(value); + return node; + } + + /** + * Add a rule from root element (ROOT = rule) + * + * @param element + * @param rule + */ + private static void addToElement(Element element, DbRule rule) { + Element root = element; + root.add(newElement(XIDRULE, rule.idRule)); + Element hosts = new DefaultElement(XHOSTIDS); + if (rule.idsArray != null) { + for (String host : rule.idsArray) { + hosts.add(newElement(XHOSTID, host)); + } + } + root.add(hosts); + root.add(newElement(XMODE, Integer.toString(rule.mode))); + if (rule.recvPath != null) { + root.add(newElement(XRECVPATH, rule.recvPath.substring(1))); + } + if (rule.sendPath != null) { + root.add(newElement(XSENDPATH, rule.sendPath.substring(1))); + } + if (rule.archivePath != null) { + root.add(newElement(XARCHIVEPATH, rule.archivePath.substring(1))); + } + if (rule.workPath != null) { + root.add(newElement(XWORKPATH, rule.workPath.substring(1))); + } + Element tasks = new DefaultElement(XRPRETASKS); + Element roottasks = new DefaultElement(XTASKS); + int rank = 0; + String[][] array = rule.rpreTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + tasks = new DefaultElement(XRPOSTTASKS); + roottasks = new DefaultElement(XTASKS); + array = rule.rpostTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + tasks = new DefaultElement(XRERRORTASKS); + roottasks = new DefaultElement(XTASKS); + array = rule.rerrorTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + tasks = new DefaultElement(XSPRETASKS); + roottasks = new DefaultElement(XTASKS); + array = rule.spreTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + tasks = new DefaultElement(XSPOSTTASKS); + roottasks = new DefaultElement(XTASKS); + array = rule.spostTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + tasks = new DefaultElement(XSERRORTASKS); + roottasks = new DefaultElement(XTASKS); + array = rule.serrorTasksArray; + if (array != null) { + for (rank = 0; rank < array.length; rank++) { + Element task = new DefaultElement(XTASK); + task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); + task.add(newElement(DbRule.TASK_PATH, array[rank][1])); + task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); + roottasks.add(task); + } + } + tasks.add(roottasks); + root.add(tasks); + } + + /** + * Write the rule to a file from filename + * + * @param filename + * @param rule + * @throws OpenR66ProtocolSystemException + */ + private static final void writeXML(String filename, DbRule rule) + throws OpenR66ProtocolSystemException { + Document document = DocumentHelper.createDocument(); + Element root = document.addElement(ROOT); + addToElement(root, rule); + try { + XmlUtil.writeXML(filename, null, document); + } catch (IOException e) { + throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); + } + } + + /** + * Write to directory files prefixed by hostname all Rules from database + * + * @param directory + * @param hostname + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + * @throws OpenR66ProtocolSystemException + */ + public static final void writeXml(String directory, String hostname) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, + OpenR66ProtocolSystemException { + File dir = new File(directory); + if (!dir.isDirectory()) { + dir.mkdirs(); + } + DbRule[] rules = DbRule.getAllRules(DbConstant.admin.session); + for (DbRule rule : rules) { + String filename = dir.getAbsolutePath() + File.separator + hostname + "_" + rule.idRule + + + RuleFileBasedConfiguration.EXT_RULE; + logger.debug("Will write Rule: "+rule.idRule+" in "+filename); + RuleFileBasedConfiguration.writeXML(filename, rule); + } + } + + /** + * Write to directory 1 file prefixed by hostname all Rules from database + * + * @param directory + * @param hostname + * @return the filename + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + * @throws OpenR66ProtocolSystemException + */ + public static String writeOneXml(String directory, String hostname) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, + OpenR66ProtocolSystemException { + File dir = new File(directory); + if (!dir.isDirectory()) { + dir.mkdirs(); + } + DbRule[] rules = DbRule.getAllRules(DbConstant.admin.session); + String filename = dir.getAbsolutePath() + File.separator + hostname + + RuleFileBasedConfiguration.EXT_RULES; + Document document = DocumentHelper.createDocument(); + Element root = document.addElement(MULTIPLEROOT); + for (DbRule rule : rules) { + Element element = root.addElement(ROOT); + addToElement(element, rule); + } + try { + XmlUtil.writeXML(filename, null, document); + } catch (IOException e) { + throw new OpenR66ProtocolSystemException("Cannot write file: " + filename, e); + } + return filename; + } +} diff --git a/src/main/java/org/waarp/openr66/configuration/package-info.java b/src/main/java/org/waarp/openr66/configuration/package-info.java index ce360b882..c10d4e48e 100644 --- a/src/main/java/org/waarp/openr66/configuration/package-info.java +++ b/src/main/java/org/waarp/openr66/configuration/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Configuration loading from database or files - * - * @apiviz.landmark - */ -package org.waarp.openr66.configuration; - +/** + * Classes implementing Configuration loading from database or files + * + * @apiviz.landmark + */ +package org.waarp.openr66.configuration; + diff --git a/src/main/java/org/waarp/openr66/context/ErrorCode.java b/src/main/java/org/waarp/openr66/context/ErrorCode.java index 80dc0fb50..5aafc9b71 100644 --- a/src/main/java/org/waarp/openr66/context/ErrorCode.java +++ b/src/main/java/org/waarp/openr66/context/ErrorCode.java @@ -1,311 +1,311 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -/** - * This enum class keeps all code that will be returned into the result and store (char - * representation) into the runner. - * - * @author Frederic Bregier - * - */ -public enum ErrorCode { - /** - * Code stands for initialization ok (internal connection, authentication) - */ - InitOk("Initialization step ok", 'i'), - /** - * Code stands for pre processing ok - */ - PreProcessingOk( - "PreProcessing step ok", - 'B'), - /** - * Code stands for transfer OK - */ - TransferOk("Transfer step ok", 'X'), - /** - * Code stands for post processing ok - */ - PostProcessingOk( - "PostProcessing step ok", - 'P'), - /** - * Code stands for All action are completed ok - */ - CompleteOk("Operation completed", 'O'), - /** - * Code stands for connection is impossible (remote or local reason) - */ - ConnectionImpossible( - "Connection Impossible", - 'C'), - /** - * Code stands for connection is impossible now due to limits(remote or local reason) - */ - ServerOverloaded( - "Connection delayed due to exceed of capacity", - 'l'), - /** - * Code stands for bad authentication (remote or local) - */ - BadAuthent("Bad Authentication", 'A'), - /** - * Code stands for External operation in error (pre, post or error processing) - */ - ExternalOp( - "External Operation as Task in error", - 'E'), - /** - * Code stands for Transfer is in error - */ - TransferError("Bad Transfer", 'T'), - /** - * Code stands for Transfer in error due to MD5 - */ - MD5Error( - "MD5 during transfer in error", - 'M'), - /** - * Code stands for Network disconnection - */ - Disconnection("Disconnection before end", 'D'), - /** - * Code stands for Remote Shutdown - */ - RemoteShutdown("Disconnection before end due to a remote shutdown", 'r'), - /** - * Code stands for final action (like moving file) is in error - */ - FinalOp( - "Final Operation on the result file in error", - 'F'), - /** - * Code stands for unimplemented feature - */ - Unimplemented("Function not implemented", 'U'), - /** - * Code stands for shutdown is in progress - */ - Shutdown( - "Shutdown order", - 'S'), - /** - * Code stands for a remote error is received - */ - RemoteError("Error due to remote", 'R'), - /** - * Code stands for an internal error - */ - Internal( - "Internal Error", - 'I'), - /** - * Code stands for a request of stopping transfer - */ - StoppedTransfer("Stopped Transfer", 'H'), - /** - * Code stands for a request of canceling transfer - */ - CanceledTransfer("Canceled Transfer", 'K'), - /** - * Warning in execution - */ - Warning("Warning during pre or post execution", 'W'), - /** - * Code stands for unknown type of error - */ - Unknown("Unknown status", '-'), - /** - * Code stands for a request that is already remotely finished - */ - QueryAlreadyFinished("Restart Query for a transfer already finished", 'Q'), - /** - * Code stands for request that is still running - */ - QueryStillRunning("Restart Query for a transfer still running", 's'), - /** - * Code stands for not known host - */ - NotKnownHost("Not known remote host", 'N'), - /** - * Code stands for self requested host starting request is invalid - */ - LoopSelfRequestedHost("Host tries to start a self requested transfer", 'N'), - /** - * Code stands for request should exist but is not found on remote host - */ - QueryRemotelyUnknown("Not known remote asked query", 'u'), - /** - * Code stands for File not found error - */ - FileNotFound("File not found", 'f'), - /** - * Code stands for Command not found error - */ - CommandNotFound("Command not found", 'c'), - /** - * Code stands for a request in PassThroughMode and required action is incompatible with this - * mode - */ - PassThroughMode("Error since action cannot be taken on PassThroughMode", 'p'), - /** - * Code stands for running step - */ - Running("Current step in running", 'z'); - - /** - * Literal for this code - */ - public String mesg; - /** - * Code could be used to switch case operations - */ - public char code; - - private ErrorCode(String mesg, char code) { - this.mesg = mesg; - this.code = code; - } - - public String getCode() { - return String.valueOf(code); - } - - /** - * Code is either the 1 char code or the exact name in Enum - * - * @param code - * @return the ErrorCode according to the code - */ - public static ErrorCode getFromCode(String code) { - switch (code.charAt(0)) { - case 'i': - return InitOk; - case 'B': - return PreProcessingOk; - case 'P': - return PostProcessingOk; - case 'X': - return TransferOk; - case 'O': - return CompleteOk; - case 'C': - return ConnectionImpossible; - case 'A': - return BadAuthent; - case 'E': - return ExternalOp; - case 'T': - return TransferError; - case 'M': - return MD5Error; - case 'D': - return Disconnection; - case 'r': - return RemoteShutdown; - case 'F': - return FinalOp; - case 'U': - return Unimplemented; - case 'S': - return Shutdown; - case 'R': - return RemoteError; - case 'I': - return Internal; - case 'H': - return StoppedTransfer; - case 'K': - return CanceledTransfer; - case 'W': - return Warning; - case '-': - return Unknown; - case 'Q': - return QueryAlreadyFinished; - case 's': - return QueryStillRunning; - case 'N': - return NotKnownHost; - case 'L': - return LoopSelfRequestedHost; - case 'u': - return QueryRemotelyUnknown; - case 'f': - return FileNotFound; - case 'z': - return Running; - case 'c': - return CommandNotFound; - case 'p': - return PassThroughMode; - case 'l': - return ServerOverloaded; - default: - ErrorCode ecode = Unknown; - try { - ecode = ErrorCode.valueOf(code.trim()); - } catch (IllegalArgumentException e) { - return Unknown; - } - return ecode; - } - } - - public static boolean isErrorCode(ErrorCode code) { - switch (code) { - case BadAuthent: - case CanceledTransfer: - case CommandNotFound: - case ConnectionImpossible: - case Disconnection: - case ExternalOp: - case FileNotFound: - case FinalOp: - case Internal: - case LoopSelfRequestedHost: - case MD5Error: - case NotKnownHost: - case PassThroughMode: - case QueryAlreadyFinished: - case QueryRemotelyUnknown: - case QueryStillRunning: - case RemoteError: - case RemoteShutdown: - case ServerOverloaded: - case Shutdown: - case StoppedTransfer: - case TransferError: - case Unimplemented: - return true; - case CompleteOk: - case InitOk: - case PostProcessingOk: - case PreProcessingOk: - case Running: - case TransferOk: - case Unknown: - case Warning: - return false; - default: - break; - } - return true; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +/** + * This enum class keeps all code that will be returned into the result and store (char + * representation) into the runner. + * + * @author Frederic Bregier + * + */ +public enum ErrorCode { + /** + * Code stands for initialization ok (internal connection, authentication) + */ + InitOk("Initialization step ok", 'i'), + /** + * Code stands for pre processing ok + */ + PreProcessingOk( + "PreProcessing step ok", + 'B'), + /** + * Code stands for transfer OK + */ + TransferOk("Transfer step ok", 'X'), + /** + * Code stands for post processing ok + */ + PostProcessingOk( + "PostProcessing step ok", + 'P'), + /** + * Code stands for All action are completed ok + */ + CompleteOk("Operation completed", 'O'), + /** + * Code stands for connection is impossible (remote or local reason) + */ + ConnectionImpossible( + "Connection Impossible", + 'C'), + /** + * Code stands for connection is impossible now due to limits(remote or local reason) + */ + ServerOverloaded( + "Connection delayed due to exceed of capacity", + 'l'), + /** + * Code stands for bad authentication (remote or local) + */ + BadAuthent("Bad Authentication", 'A'), + /** + * Code stands for External operation in error (pre, post or error processing) + */ + ExternalOp( + "External Operation as Task in error", + 'E'), + /** + * Code stands for Transfer is in error + */ + TransferError("Bad Transfer", 'T'), + /** + * Code stands for Transfer in error due to MD5 + */ + MD5Error( + "MD5 during transfer in error", + 'M'), + /** + * Code stands for Network disconnection + */ + Disconnection("Disconnection before end", 'D'), + /** + * Code stands for Remote Shutdown + */ + RemoteShutdown("Disconnection before end due to a remote shutdown", 'r'), + /** + * Code stands for final action (like moving file) is in error + */ + FinalOp( + "Final Operation on the result file in error", + 'F'), + /** + * Code stands for unimplemented feature + */ + Unimplemented("Function not implemented", 'U'), + /** + * Code stands for shutdown is in progress + */ + Shutdown( + "Shutdown order", + 'S'), + /** + * Code stands for a remote error is received + */ + RemoteError("Error due to remote", 'R'), + /** + * Code stands for an internal error + */ + Internal( + "Internal Error", + 'I'), + /** + * Code stands for a request of stopping transfer + */ + StoppedTransfer("Stopped Transfer", 'H'), + /** + * Code stands for a request of canceling transfer + */ + CanceledTransfer("Canceled Transfer", 'K'), + /** + * Warning in execution + */ + Warning("Warning during pre or post execution", 'W'), + /** + * Code stands for unknown type of error + */ + Unknown("Unknown status", '-'), + /** + * Code stands for a request that is already remotely finished + */ + QueryAlreadyFinished("Restart Query for a transfer already finished", 'Q'), + /** + * Code stands for request that is still running + */ + QueryStillRunning("Restart Query for a transfer still running", 's'), + /** + * Code stands for not known host + */ + NotKnownHost("Not known remote host", 'N'), + /** + * Code stands for self requested host starting request is invalid + */ + LoopSelfRequestedHost("Host tries to start a self requested transfer", 'N'), + /** + * Code stands for request should exist but is not found on remote host + */ + QueryRemotelyUnknown("Not known remote asked query", 'u'), + /** + * Code stands for File not found error + */ + FileNotFound("File not found", 'f'), + /** + * Code stands for Command not found error + */ + CommandNotFound("Command not found", 'c'), + /** + * Code stands for a request in PassThroughMode and required action is incompatible with this + * mode + */ + PassThroughMode("Error since action cannot be taken on PassThroughMode", 'p'), + /** + * Code stands for running step + */ + Running("Current step in running", 'z'); + + /** + * Literal for this code + */ + public String mesg; + /** + * Code could be used to switch case operations + */ + public char code; + + private ErrorCode(String mesg, char code) { + this.mesg = mesg; + this.code = code; + } + + public String getCode() { + return String.valueOf(code); + } + + /** + * Code is either the 1 char code or the exact name in Enum + * + * @param code + * @return the ErrorCode according to the code + */ + public static ErrorCode getFromCode(String code) { + switch (code.charAt(0)) { + case 'i': + return InitOk; + case 'B': + return PreProcessingOk; + case 'P': + return PostProcessingOk; + case 'X': + return TransferOk; + case 'O': + return CompleteOk; + case 'C': + return ConnectionImpossible; + case 'A': + return BadAuthent; + case 'E': + return ExternalOp; + case 'T': + return TransferError; + case 'M': + return MD5Error; + case 'D': + return Disconnection; + case 'r': + return RemoteShutdown; + case 'F': + return FinalOp; + case 'U': + return Unimplemented; + case 'S': + return Shutdown; + case 'R': + return RemoteError; + case 'I': + return Internal; + case 'H': + return StoppedTransfer; + case 'K': + return CanceledTransfer; + case 'W': + return Warning; + case '-': + return Unknown; + case 'Q': + return QueryAlreadyFinished; + case 's': + return QueryStillRunning; + case 'N': + return NotKnownHost; + case 'L': + return LoopSelfRequestedHost; + case 'u': + return QueryRemotelyUnknown; + case 'f': + return FileNotFound; + case 'z': + return Running; + case 'c': + return CommandNotFound; + case 'p': + return PassThroughMode; + case 'l': + return ServerOverloaded; + default: + ErrorCode ecode = Unknown; + try { + ecode = ErrorCode.valueOf(code.trim()); + } catch (IllegalArgumentException e) { + return Unknown; + } + return ecode; + } + } + + public static boolean isErrorCode(ErrorCode code) { + switch (code) { + case BadAuthent: + case CanceledTransfer: + case CommandNotFound: + case ConnectionImpossible: + case Disconnection: + case ExternalOp: + case FileNotFound: + case FinalOp: + case Internal: + case LoopSelfRequestedHost: + case MD5Error: + case NotKnownHost: + case PassThroughMode: + case QueryAlreadyFinished: + case QueryRemotelyUnknown: + case QueryStillRunning: + case RemoteError: + case RemoteShutdown: + case ServerOverloaded: + case Shutdown: + case StoppedTransfer: + case TransferError: + case Unimplemented: + return true; + case CompleteOk: + case InitOk: + case PostProcessingOk: + case PreProcessingOk: + case Running: + case TransferOk: + case Unknown: + case Warning: + return false; + default: + break; + } + return true; + } +} diff --git a/src/main/java/org/waarp/openr66/context/R66BusinessFactoryInterface.java b/src/main/java/org/waarp/openr66/context/R66BusinessFactoryInterface.java index 9b787186a..995a995d7 100644 --- a/src/main/java/org/waarp/openr66/context/R66BusinessFactoryInterface.java +++ b/src/main/java/org/waarp/openr66/context/R66BusinessFactoryInterface.java @@ -1,33 +1,33 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -/** - * @author Frederic Bregier - * - */ -public interface R66BusinessFactoryInterface { - /** - * - * @param session - * @return a Business object (new or same, depending on the implementation), maybe null - */ - public R66BusinessInterface getBusinessInterface(R66Session session); - - public void releaseResources(); -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +/** + * @author Frederic Bregier + * + */ +public interface R66BusinessFactoryInterface { + /** + * + * @param session + * @return a Business object (new or same, depending on the implementation), maybe null + */ + public R66BusinessInterface getBusinessInterface(R66Session session); + + public void releaseResources(); +} diff --git a/src/main/java/org/waarp/openr66/context/R66BusinessInterface.java b/src/main/java/org/waarp/openr66/context/R66BusinessInterface.java index 84f74923d..d4712fb87 100644 --- a/src/main/java/org/waarp/openr66/context/R66BusinessInterface.java +++ b/src/main/java/org/waarp/openr66/context/R66BusinessInterface.java @@ -1,46 +1,46 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; - -/** - * @author Frederic Bregier - * - */ -public interface R66BusinessInterface { - - public void checkAtStartup(R66Session session) throws OpenR66RunnerErrorException; - - public void checkAfterPreCommand(R66Session session) throws OpenR66RunnerErrorException; - - public void checkAfterTransfer(R66Session session) throws OpenR66RunnerErrorException; - - public void checkAfterPost(R66Session session) throws OpenR66RunnerErrorException; - - public void checkAtError(R66Session session) throws OpenR66RunnerErrorException; - - public void checkAtChangeFilename(R66Session session) throws OpenR66RunnerErrorException; - - public void releaseResources(); - - public String getInfo(); - - public void setInfo(String info); - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; + +/** + * @author Frederic Bregier + * + */ +public interface R66BusinessInterface { + + public void checkAtStartup(R66Session session) throws OpenR66RunnerErrorException; + + public void checkAfterPreCommand(R66Session session) throws OpenR66RunnerErrorException; + + public void checkAfterTransfer(R66Session session) throws OpenR66RunnerErrorException; + + public void checkAfterPost(R66Session session) throws OpenR66RunnerErrorException; + + public void checkAtError(R66Session session) throws OpenR66RunnerErrorException; + + public void checkAtChangeFilename(R66Session session) throws OpenR66RunnerErrorException; + + public void releaseResources(); + + public String getInfo(); + + public void setInfo(String info); + +} diff --git a/src/main/java/org/waarp/openr66/context/R66DefaultBusinessFactory.java b/src/main/java/org/waarp/openr66/context/R66DefaultBusinessFactory.java index 7d3bd8bdc..6d71dfe0a 100644 --- a/src/main/java/org/waarp/openr66/context/R66DefaultBusinessFactory.java +++ b/src/main/java/org/waarp/openr66/context/R66DefaultBusinessFactory.java @@ -1,44 +1,44 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; - -/** - * Empty Business factory - * - * @author Frederic Bregier - * - */ -public class R66DefaultBusinessFactory implements R66BusinessFactoryInterface { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66DefaultBusinessFactory.class); - - public R66BusinessInterface getBusinessInterface(R66Session session) { - logger.debug("No Business"); - return null; - } - - public void releaseResources() { - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; + +/** + * Empty Business factory + * + * @author Frederic Bregier + * + */ +public class R66DefaultBusinessFactory implements R66BusinessFactoryInterface { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66DefaultBusinessFactory.class); + + public R66BusinessInterface getBusinessInterface(R66Session session) { + logger.debug("No Business"); + return null; + } + + public void releaseResources() { + } + +} diff --git a/src/main/java/org/waarp/openr66/context/R66FiniteDualStates.java b/src/main/java/org/waarp/openr66/context/R66FiniteDualStates.java index 8db090782..7e1bdb31a 100644 --- a/src/main/java/org/waarp/openr66/context/R66FiniteDualStates.java +++ b/src/main/java/org/waarp/openr66/context/R66FiniteDualStates.java @@ -1,107 +1,107 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -import java.util.EnumSet; -import java.util.concurrent.ConcurrentHashMap; - -import org.waarp.common.state.MachineState; -import org.waarp.common.state.Transition; - -/** - * Finite Dual State Machine for OpenR66 (Requester=R, requesteD=D, Sender=S, Receive=R) - * - * @author Frederic Bregier - * - */ -public enum R66FiniteDualStates { - OPENEDCHANNEL, CLOSEDCHANNEL, ERROR, - STARTUP, - AUTHENTR, AUTHENTD, - REQUESTR, REQUESTD, VALID, - DATAR, DATAS, - ENDTRANSFERR, ENDREQUESTR, - ENDTRANSFERS, ENDREQUESTS, - TEST, INFORMATION, VALIDOTHER, - SHUTDOWN, BUSINESSR, BUSINESSD; - // not used in LSH - // CONNECTERROR, - // KEEPALIVEPACKET; - - private enum R66Transition { - tOPENEDCHANNEL(OPENEDCHANNEL, EnumSet.of(STARTUP, CLOSEDCHANNEL, ERROR)), - tSTARTUP(STARTUP, EnumSet.of(AUTHENTR, AUTHENTD, CLOSEDCHANNEL, ERROR)), - tAUTHENTR(AUTHENTR, EnumSet.of(AUTHENTD, CLOSEDCHANNEL, ERROR)), - tAUTHENTD(AUTHENTD, EnumSet.of(REQUESTR, VALIDOTHER, INFORMATION, SHUTDOWN, TEST, - BUSINESSR, BUSINESSD, ENDREQUESTS, CLOSEDCHANNEL, ERROR)), - tREQUESTR(REQUESTR, EnumSet.of(VALID, REQUESTD, CLOSEDCHANNEL, ERROR)), - tREQUESTD(REQUESTD, EnumSet.of(VALID, DATAS, DATAR, CLOSEDCHANNEL, ERROR)), - tVALID(VALID, EnumSet.of(REQUESTD, DATAR, CLOSEDCHANNEL, ERROR)), - tDATAS(DATAS, EnumSet.of(DATAS, ENDTRANSFERS, CLOSEDCHANNEL, ERROR)), - tDATAR(DATAR, EnumSet.of(DATAR, ENDTRANSFERS, CLOSEDCHANNEL, ERROR)), - tENDTRANSFERS(ENDTRANSFERS, EnumSet.of(ENDTRANSFERR, CLOSEDCHANNEL, ERROR)), - tENDTRANSFERR(ENDTRANSFERR, EnumSet.of(ENDREQUESTS, CLOSEDCHANNEL, ERROR)), - tENDREQUESTS(ENDREQUESTS, EnumSet.of(ENDREQUESTR, CLOSEDCHANNEL, ERROR)), - tENDREQUESTR(ENDREQUESTR, EnumSet.of(CLOSEDCHANNEL, ERROR)), - tINFORMATION(INFORMATION, EnumSet.of(VALIDOTHER, CLOSEDCHANNEL, ERROR)), - tTEST(TEST, EnumSet.of(TEST, VALIDOTHER)), - tVALIDOTHER(VALIDOTHER, EnumSet.of(VALIDOTHER, CLOSEDCHANNEL, ERROR)), - tSHUTDOWN(SHUTDOWN, EnumSet.of(CLOSEDCHANNEL, SHUTDOWN, ERROR)), - tERROR(ERROR, EnumSet.of(ERROR, CLOSEDCHANNEL)), - tCLOSEDCHANNEL(CLOSEDCHANNEL, EnumSet.noneOf(R66FiniteDualStates.class)), - tBUSINESSR(BUSINESSR, EnumSet.of(ERROR, BUSINESSD, CLOSEDCHANNEL, VALIDOTHER)), - tBUSINESSD(BUSINESSD, EnumSet.of(ERROR, BUSINESSD, BUSINESSR, CLOSEDCHANNEL, VALIDOTHER)); - - public Transition elt; - - private R66Transition(R66FiniteDualStates state, EnumSet set) { - this.elt = new Transition(state, set); - } - } - - private static ConcurrentHashMap> stateMap = - new ConcurrentHashMap>(); - - /** - * This method should be called once at startup to initialize the Finite States association. - */ - public static void initR66FiniteStates() { - for (R66Transition trans : R66Transition.values()) { - stateMap.put(trans.elt.state, trans.elt.set); - } - } - - /** - * - * @return a new Session MachineState for OpenR66 - */ - public static MachineState newSessionMachineState() { - MachineState machine = - new MachineState(OPENEDCHANNEL, stateMap); - return machine; - } - - /** - * - * @param machine - * the Session MachineState to release - */ - public static void endSessionMachineSate(MachineState machine) { - machine.release(); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +import java.util.EnumSet; +import java.util.concurrent.ConcurrentHashMap; + +import org.waarp.common.state.MachineState; +import org.waarp.common.state.Transition; + +/** + * Finite Dual State Machine for OpenR66 (Requester=R, requesteD=D, Sender=S, Receive=R) + * + * @author Frederic Bregier + * + */ +public enum R66FiniteDualStates { + OPENEDCHANNEL, CLOSEDCHANNEL, ERROR, + STARTUP, + AUTHENTR, AUTHENTD, + REQUESTR, REQUESTD, VALID, + DATAR, DATAS, + ENDTRANSFERR, ENDREQUESTR, + ENDTRANSFERS, ENDREQUESTS, + TEST, INFORMATION, VALIDOTHER, + SHUTDOWN, BUSINESSR, BUSINESSD; + // not used in LSH + // CONNECTERROR, + // KEEPALIVEPACKET; + + private enum R66Transition { + tOPENEDCHANNEL(OPENEDCHANNEL, EnumSet.of(STARTUP, CLOSEDCHANNEL, ERROR)), + tSTARTUP(STARTUP, EnumSet.of(AUTHENTR, AUTHENTD, CLOSEDCHANNEL, ERROR)), + tAUTHENTR(AUTHENTR, EnumSet.of(AUTHENTD, CLOSEDCHANNEL, ERROR)), + tAUTHENTD(AUTHENTD, EnumSet.of(REQUESTR, VALIDOTHER, INFORMATION, SHUTDOWN, TEST, + BUSINESSR, BUSINESSD, ENDREQUESTS, CLOSEDCHANNEL, ERROR)), + tREQUESTR(REQUESTR, EnumSet.of(VALID, REQUESTD, CLOSEDCHANNEL, ERROR)), + tREQUESTD(REQUESTD, EnumSet.of(VALID, DATAS, DATAR, CLOSEDCHANNEL, ERROR)), + tVALID(VALID, EnumSet.of(REQUESTD, DATAR, CLOSEDCHANNEL, ERROR)), + tDATAS(DATAS, EnumSet.of(DATAS, ENDTRANSFERS, CLOSEDCHANNEL, ERROR)), + tDATAR(DATAR, EnumSet.of(DATAR, ENDTRANSFERS, CLOSEDCHANNEL, ERROR)), + tENDTRANSFERS(ENDTRANSFERS, EnumSet.of(ENDTRANSFERR, CLOSEDCHANNEL, ERROR)), + tENDTRANSFERR(ENDTRANSFERR, EnumSet.of(ENDREQUESTS, CLOSEDCHANNEL, ERROR)), + tENDREQUESTS(ENDREQUESTS, EnumSet.of(ENDREQUESTR, CLOSEDCHANNEL, ERROR)), + tENDREQUESTR(ENDREQUESTR, EnumSet.of(CLOSEDCHANNEL, ERROR)), + tINFORMATION(INFORMATION, EnumSet.of(VALIDOTHER, CLOSEDCHANNEL, ERROR)), + tTEST(TEST, EnumSet.of(TEST, VALIDOTHER)), + tVALIDOTHER(VALIDOTHER, EnumSet.of(VALIDOTHER, CLOSEDCHANNEL, ERROR)), + tSHUTDOWN(SHUTDOWN, EnumSet.of(CLOSEDCHANNEL, SHUTDOWN, ERROR)), + tERROR(ERROR, EnumSet.of(ERROR, CLOSEDCHANNEL)), + tCLOSEDCHANNEL(CLOSEDCHANNEL, EnumSet.noneOf(R66FiniteDualStates.class)), + tBUSINESSR(BUSINESSR, EnumSet.of(ERROR, BUSINESSD, CLOSEDCHANNEL, VALIDOTHER)), + tBUSINESSD(BUSINESSD, EnumSet.of(ERROR, BUSINESSD, BUSINESSR, CLOSEDCHANNEL, VALIDOTHER)); + + public Transition elt; + + private R66Transition(R66FiniteDualStates state, EnumSet set) { + this.elt = new Transition(state, set); + } + } + + private static ConcurrentHashMap> stateMap = + new ConcurrentHashMap>(); + + /** + * This method should be called once at startup to initialize the Finite States association. + */ + public static void initR66FiniteStates() { + for (R66Transition trans : R66Transition.values()) { + stateMap.put(trans.elt.state, trans.elt.set); + } + } + + /** + * + * @return a new Session MachineState for OpenR66 + */ + public static MachineState newSessionMachineState() { + MachineState machine = + new MachineState(OPENEDCHANNEL, stateMap); + return machine; + } + + /** + * + * @param machine + * the Session MachineState to release + */ + public static void endSessionMachineSate(MachineState machine) { + machine.release(); + } +} diff --git a/src/main/java/org/waarp/openr66/context/R66Result.java b/src/main/java/org/waarp/openr66/context/R66Result.java index 424d3f2fd..cd3ff6bfd 100644 --- a/src/main/java/org/waarp/openr66/context/R66Result.java +++ b/src/main/java/org/waarp/openr66/context/R66Result.java @@ -1,111 +1,111 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.exception.OpenR66Exception; - -/** - * This class is the result for every operations in OpenR66. - * - * @author Frederic Bregier - * - */ -public class R66Result { - /** - * The exception associated in case of error (if any exception) - */ - public OpenR66Exception exception = null; - /** - * The file if any - */ - public R66File file = null; - /** - * The runner if any - */ - public DbTaskRunner runner = null; - /** - * Does this result already have been transfered to the remote server - */ - public boolean isAnswered = false; - /** - * The code (error or not) - */ - public ErrorCode code; - /** - * Any other object for special operations (test or shutdown for instance) - */ - public Object other = null; - - /** - * @param exception - * @param session - * @param isAnswered - * @param code - * @param runner - */ - public R66Result(OpenR66Exception exception, R66Session session, - boolean isAnswered, ErrorCode code, DbTaskRunner runner) { - this.exception = exception; - this.runner = runner; - if (session != null) { - file = session.getFile(); - this.runner = session.getRunner(); - } - this.isAnswered = isAnswered; - this.code = code; - } - - /** - * @param session - * @param isAnswered - * @param code - * @param runner - */ - public R66Result(R66Session session, boolean isAnswered, ErrorCode code, - DbTaskRunner runner) { - this.runner = runner; - if (session != null) { - file = session.getFile(); - this.runner = session.getRunner(); - } - this.isAnswered = isAnswered; - this.code = code; - } - - @Override - public String toString() { - return (exception != null ? "Exception: " + exception.toString() : "") + - (file != null ? file.toString() : " no file") + "\n " + - (runner != null ? runner.toShortString() : " no runner") + - " isAnswered: " + isAnswered + " Code: " + code.mesg; - } - - /** - * - * @return the associated message with this Result - */ - public String getMessage() { - if (exception != null) { - return exception.getMessage(); - } else { - return code.mesg; - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.exception.OpenR66Exception; + +/** + * This class is the result for every operations in OpenR66. + * + * @author Frederic Bregier + * + */ +public class R66Result { + /** + * The exception associated in case of error (if any exception) + */ + public OpenR66Exception exception = null; + /** + * The file if any + */ + public R66File file = null; + /** + * The runner if any + */ + public DbTaskRunner runner = null; + /** + * Does this result already have been transfered to the remote server + */ + public boolean isAnswered = false; + /** + * The code (error or not) + */ + public ErrorCode code; + /** + * Any other object for special operations (test or shutdown for instance) + */ + public Object other = null; + + /** + * @param exception + * @param session + * @param isAnswered + * @param code + * @param runner + */ + public R66Result(OpenR66Exception exception, R66Session session, + boolean isAnswered, ErrorCode code, DbTaskRunner runner) { + this.exception = exception; + this.runner = runner; + if (session != null) { + file = session.getFile(); + this.runner = session.getRunner(); + } + this.isAnswered = isAnswered; + this.code = code; + } + + /** + * @param session + * @param isAnswered + * @param code + * @param runner + */ + public R66Result(R66Session session, boolean isAnswered, ErrorCode code, + DbTaskRunner runner) { + this.runner = runner; + if (session != null) { + file = session.getFile(); + this.runner = session.getRunner(); + } + this.isAnswered = isAnswered; + this.code = code; + } + + @Override + public String toString() { + return (exception != null ? "Exception: " + exception.toString() : "") + + (file != null ? file.toString() : " no file") + "\n " + + (runner != null ? runner.toShortString() : " no runner") + + " isAnswered: " + isAnswered + " Code: " + code.mesg; + } + + /** + * + * @return the associated message with this Result + */ + public String getMessage() { + if (exception != null) { + return exception.getMessage(); + } else { + return code.mesg; + } + } +} diff --git a/src/main/java/org/waarp/openr66/context/R66Session.java b/src/main/java/org/waarp/openr66/context/R66Session.java index 813811f25..ed6f41034 100644 --- a/src/main/java/org/waarp/openr66/context/R66Session.java +++ b/src/main/java/org/waarp/openr66/context/R66Session.java @@ -1,906 +1,906 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context; - -import java.io.UnsupportedEncodingException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.URLDecoder; -import java.util.HashMap; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.exception.IllegalFiniteStateException; -import org.waarp.common.exception.NoRestartException; -import org.waarp.common.file.SessionInterface; -import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.state.MachineState; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.filesystem.R66Restart; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; - -/** - * The global object session in OpenR66, a session by local channel - * - * @author frederic bregier - * - */ -public class R66Session implements SessionInterface { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66Session.class); - - /** - * Block size used during file transfer - */ - private int blockSize = Configuration.configuration.BLOCKSIZE; - /** - * The local channel reference - */ - private LocalChannelReference localChannelReference; - /** - * Authentication - */ - private final R66Auth auth; - /** - * Remote Address - */ - private SocketAddress raddress; - /** - * Local Address - */ - private SocketAddress laddress; - - /** - * Current directory - */ - private final R66Dir dir; - /** - * Current file - */ - private R66File file; - /** - * Does this session is Ready to server a request - */ - private volatile boolean isReady = false; - - /** - * Current Restart information - */ - private final R66Restart restart; - - /** - * DbTaskRunner - */ - private DbTaskRunner runner = null; - - private String status = "NoStatus"; - - /** - * The Finite Machine State - */ - private final MachineState state; - /** - * Business Object if used - */ - private R66BusinessInterface businessObject = null; - /** - * Extended protocol or not - */ - private boolean extendedProtocol = Configuration.configuration.extendedProtocol; - - public HashMap dirsFromSession = new HashMap(); - /** - * Create the session - */ - public R66Session() { - isReady = false; - auth = new R66Auth(this); - dir = new R66Dir(this); - restart = new R66Restart(this); - state = R66FiniteDualStates.newSessionMachineState(); - } - - /** - * @return extendedProtocol - */ - public boolean getExtendedProtocol() { - return extendedProtocol; - } - - /** - * @return the businessObject - */ - public R66BusinessInterface getBusinessObject() { - return businessObject; - } - - /** - * @param businessObject - * the businessObject to set - */ - public void setBusinessObject(R66BusinessInterface businessObject) { - this.businessObject = businessObject; - } - - /** - * Propose a new State - * - * @param desiredstate - * @throws IllegalFiniteStateException - * if the new status if not ok - */ - public void newState(R66FiniteDualStates desiredstate) { - try { - state.setCurrent(desiredstate); - } catch (IllegalFiniteStateException e) { - logger.warn("Should not changed of State: {} {}", this, e.getMessage()); - state.setDryCurrent(desiredstate); - } - } - - /** - * Debugging purpose - * - * @param stat - */ - public void setStatus(int stat) { - StackTraceElement elt = Thread.currentThread().getStackTrace()[2]; - this.status = "(" + elt.getFileName() + ":" + elt.getLineNumber() + "):" + stat; - } - - public void clear() { - // First check if a transfer was on going - if (runner != null && (!runner.isFinished()) && (!runner.continueTransfer())) { - if (localChannelReference != null) { - if (!localChannelReference.getFutureRequest().isDone()) { - R66Result result = new R66Result(new OpenR66RunnerErrorException( - "Close before ending"), this, true, - ErrorCode.Disconnection, runner);// True since called from closed - result.runner = runner; - try { - setFinalizeTransfer(false, result); - } catch (OpenR66RunnerErrorException e) { - } catch (OpenR66ProtocolSystemException e) { - } - } - } - } - if (dir != null) { - dir.clear(); - } - if (auth != null) { - auth.clear(); - } - if (runner != null) { - runner.clear(); - } - if (state != null) { - try { - state.setCurrent(R66FiniteDualStates.CLOSEDCHANNEL); - } catch (IllegalFiniteStateException e) { - } - // R66FiniteDualStates.endSessionMachineSate(state); - } - // No clean of file since it can be used after channel is closed - isReady = false; - if (businessObject != null) { - businessObject.releaseResources(); - businessObject = null; - } - } - - public R66Auth getAuth() { - return auth; - } - - public int getBlockSize() { - return blockSize; - } - - /** - * @param blocksize - * the blocksize to set - */ - public void setBlockSize(int blocksize) { - blockSize = blocksize; - } - - public R66Dir getDir() { - return dir; - } - - public FilesystemBasedFileParameterImpl getFileParameter() { - return Configuration.getFileParameter(); - } - - public R66Restart getRestart() { - return restart; - } - - /** - * - * @return True if the connection is currently authenticated - */ - public boolean isAuthenticated() { - if (auth == null) { - return false; - } - return auth.isIdentified(); - } - - /** - * @return True if the Channel is ready to accept transfer - */ - public boolean isReady() { - return isReady; - } - - /** - * @param isReady - * the isReady for transfer to set - */ - public void setReady(boolean isReady) { - this.isReady = isReady; - } - - /** - * @return the runner - */ - public DbTaskRunner getRunner() { - return runner; - } - - /** - * @param localChannelReference - * the localChannelReference to set - */ - public void setLocalChannelReference( - LocalChannelReference localChannelReference) { - this.localChannelReference = localChannelReference; - this.localChannelReference.setSession(this); - if (this.localChannelReference.getNetworkChannel() != null) { - this.raddress = this.localChannelReference.getNetworkChannel().getRemoteAddress(); - this.laddress = this.localChannelReference.getNetworkChannel().getLocalAddress(); - } else { - this.raddress = this.laddress = new InetSocketAddress(0); - } - } - - /** - * - * @return the remote SocketAddress - */ - public SocketAddress getRemoteAddress() { - return this.raddress; - } - - /** - * - * @return the local SocketAddress - */ - public SocketAddress getLocalAddress() { - return this.laddress; - } - - /** - * @return the localChannelReference - */ - public LocalChannelReference getLocalChannelReference() { - return localChannelReference; - } - - /** - * To be called in case of No Session not from a valid LocalChannelHandler - * - * @param runner - * @param localChannelReference - */ - public void setNoSessionRunner(DbTaskRunner runner, LocalChannelReference localChannelReference) { - this.runner = runner; - // Warning: the file is not correctly setup - try { - file = (R66File) dir.setFile(this.runner.getFilename(), - false); - } catch (CommandAbstractException e1) { - } - this.auth.specialNoSessionAuth(false, Configuration.configuration.HOST_ID); - this.localChannelReference = localChannelReference; - if (this.localChannelReference == null) { - if (this.runner.getLocalChannelReference() != null) { - this.localChannelReference = this.runner.getLocalChannelReference(); - } else { - this.localChannelReference = new LocalChannelReference(); - } - this.localChannelReference.setErrorMessage(this.runner.getErrorInfo().mesg, - this.runner.getErrorInfo()); - } - runner.setLocalChannelReference(this.localChannelReference); - this.localChannelReference.setSession(this); - } - - /** - * Set the File from the runner before PRE operation are done - * - * @throws OpenR66RunnerErrorException - */ - public void setFileBeforePreRunner() throws OpenR66RunnerErrorException { - // check first if the next step is the PRE task from beginning - String filename; - if (this.runner.isPreTaskStarting()) { - filename = R66Dir.normalizePath(this.runner.getOriginalFilename()); - if (filename.startsWith("file:/")) { - filename = filename.substring("file:/".length()); - try { - filename = URLDecoder.decode(filename, "UTF-8"); - } catch (UnsupportedEncodingException e) { - this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); - throw new OpenR66RunnerErrorException("File cannot be read: " + - filename); - } - } - this.runner.setOriginalFilename(filename); - } else { - filename = this.runner.getFilename(); - } - if (this.runner.isSender()) { - try { - if (file == null) { - try { - file = (R66File) dir.setFile(filename, false); - } catch (CommandAbstractException e) { - // file is not under normal base directory, so is external - // File should already exist but can be using special code ('*?') - file = dir.setFileNoCheck(filename); - } - } - if (runner.isSendThrough()) { - // no test on file since it does not really exist - logger.debug("File is in through mode: {}", file); - } else if (!file.canRead()) { - // file is not under normal base directory, so is external - // File should already exist but cannot use special code ('*?') - file = new R66File(this, dir, filename); - if (!file.canRead()) { - this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); - throw new OpenR66RunnerErrorException("File cannot be read: " + - file.getTrueFile().getAbsolutePath()); - } - } else { - // possibly resolved filename - runner.setOriginalFilename(file.getFile()); - runner.setFilename(file.getFile()); - } - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } else { - // not sender so file is just registered as is but no test of existence - file = new R66File(this, dir, filename); - } - } - - /** - * Set the File from the runner once PRE operation are done - * - * @param createFile - * When True, the file can be newly created if needed. If False, no new file will be - * created, thus having an Exception. - * @throws OpenR66RunnerErrorException - * @throws CommandAbstractException only when new received created file cannot be created - */ - public void setFileAfterPreRunner(boolean createFile) throws OpenR66RunnerErrorException, CommandAbstractException { - if (this.businessObject != null) { - this.businessObject.checkAtChangeFilename(this); - } - // Now create the associated file - if (this.runner.isSender()) { - try { - if (file == null) { - try { - file = (R66File) dir.setFile(this.runner.getFilename(), - false); - } catch (CommandAbstractException e) { - // file is not under normal base directory, so is external - // File must already exist but can be using special code ('*?') - file = dir.setFileNoCheck(this.runner.getFilename()); - // file = new R66File(this, dir, this.runner.getFilename()); - } - } - if (runner.isSendThrough()) { - // no test on file since it does not really exist - logger.debug("File is in through mode: {}", file); - } else if (!file.canRead()) { - // file is not under normal base directory, so is external - // File must already exist but cannot used special code ('*?') - file = new R66File(this, dir, this.runner.getFilename()); - if (!file.canRead()) { - this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); - throw new OpenR66RunnerErrorException("File cannot be read: " + - file.getTrueFile().getAbsolutePath()); - } - } - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } else { - // File should not exist except if restart - if (runner.getRank() > 0) { - // Filename should be get back from runner load from database - try { - file = (R66File) dir.setFile(this.runner - .getFilename(), true); - if (runner.isRecvThrough()) { - // no test on file since it does not really exist - logger.debug("File is in through mode: {}", file); - } else if (!file.canWrite()) { - throw new OpenR66RunnerErrorException( - "File cannot be write"); - } - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } else { - // New FILENAME if necessary and store it - if (createFile) { - file = null; - String newfilename = this.runner.getOriginalFilename(); - if (newfilename.charAt(1) == ':') { - // Windows path - newfilename = newfilename.substring(2); - } - this.runner.setFilename(R66File.getBasename(newfilename)); - try { - file = dir.setUniqueFile(this.runner.getSpecialId(), - this.runner.getFilename()); - } catch (CommandAbstractException e) { - this.runner.deleteTempFile(); - throw e; - } - try { - if (runner.isRecvThrough()) { - // no test on file since it does not really exist - logger.debug("File is in through mode: {}", file); - this.runner.deleteTempFile(); - } else if (!file.canWrite()) { - this.runner.deleteTempFile(); - throw new OpenR66RunnerErrorException( - "File cannot be write"); - } - } catch (CommandAbstractException e) { - this.runner.deleteTempFile(); - throw new OpenR66RunnerErrorException(e); - } - } else { - throw new OpenR66RunnerErrorException("No file created"); - } - } - } - // Store TRUEFILENAME - try { - if (this.runner.isFileMoved()) { - this.runner.setFileMoved(file.getFile(), true); - } else { - this.runner.setFilename(file.getFile()); - } - } catch (CommandAbstractException e) { - this.runner.deleteTempFile(); - throw new OpenR66RunnerErrorException(e); - } - // check fileSize - if (runner.isSender() && file != null) { - long originalSize = file.length(); - this.runner.setOriginalSize(originalSize); - } - } - - /** - * To be used when a request comes with a bad code so it cannot be set normally - * - * @param runner - * @param code - */ - public void setBadRunner(DbTaskRunner runner, ErrorCode code) { - this.runner = runner; - if (code == ErrorCode.QueryAlreadyFinished) { - if (this.runner.isSender()) { - // Change dir - try { - dir.changeDirectory(this.runner.getRule().sendPath); - } catch (CommandAbstractException e) { - } - } else { - // Change dir - try { - dir.changeDirectory(this.runner.getRule().workPath); - } catch (CommandAbstractException e) { - } - } - if (this.businessObject != null) { - try { - this.businessObject.checkAtError(this); - } catch (OpenR66RunnerErrorException e) { - } - } - this.runner.setPostTask(); - try { - setFileAfterPreRunner(false); - } catch (OpenR66RunnerErrorException e) { - } catch (CommandAbstractException e) { - } - } - } - - /** - * Set the runner, START from the PreTask if necessary, and prepare the file - * - * @param runner - * the runner to set - * @throws OpenR66RunnerErrorException - */ - public void setRunner(DbTaskRunner runner) - throws OpenR66RunnerErrorException { - this.runner = runner; - setBusinessObject(Configuration.configuration.r66BusinessFactory.getBusinessInterface(this)); - this.runner.checkThroughMode(); - if (this.businessObject != null) { - this.businessObject.checkAtStartup(this); - } - if (this.runner.isSender()) { - if (runner.isSendThrough()) { - // May not change dir as needed - // Change dir - try { - dir.changeDirectory(this.runner.getRule().sendPath); - } catch (CommandAbstractException e) { - // ignore - } - } else { - // Change dir - try { - dir.changeDirectory(this.runner.getRule().sendPath); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } - } else { - if (runner.isRecvThrough()) { - // May not change dir as needed - // Change dir - try { - dir.changeDirectory(this.runner.getRule().workPath); - } catch (CommandAbstractException e) { - } - } else { - // Change dir - try { - dir.changeDirectory(this.runner.getRule().workPath); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } - } - if (runner.getRank() > 0) { - logger.debug("restart at " + runner.getRank() + " {}", runner); - runner.setTransferTask(runner.getRank()); - restart.restartMarker(runner.getBlocksize() * runner.getRank()); - } else { - restart.restartMarker(0); - } - if (runner.getGloballaststep() == TASKSTEP.NOTASK.ordinal() || - runner.getGloballaststep() == TASKSTEP.PRETASK.ordinal()) { - setFileBeforePreRunner(); - this.runner.setPreTask(); - runner.saveStatus(); - this.runner.run(); - runner.saveStatus(); - runner.setTransferTask(runner.getRank()); - } else { - runner.reset(); - runner.changeUpdatedInfo(UpdatedInfo.RUNNING); - runner.saveStatus(); - } - // Now create the associated file - try { - setFileAfterPreRunner(true); - } catch (CommandAbstractException e2) { - // generated due to a possible wildcard not ready - file = null; - } - if (runner.getGloballaststep() == TASKSTEP.TRANSFERTASK.ordinal()) { - if (this.businessObject != null) { - this.businessObject.checkAfterPreCommand(this); - } - if (!this.runner.isSender()) { - // Check file length according to rank - if (runner.isRecvThrough()) { - // no size can be checked - } else { - if (file == null) { - this.runner.saveStatus(); - logger.info("Final PARTIAL init: {}", this.runner); - return; - } - try { - long length = file.length(); - long oldPosition = restart.getPosition(); - restart.setSet(true); - if (oldPosition > length) { - int newRank = ((int) (length / this.runner.getBlocksize())) - - Configuration.RANKRESTART; - if (newRank <= 0) { - newRank = 1; - } - logger.warn("Decreased Rank Restart for {} at " + newRank, runner); - runner.setTransferTask(newRank); - restart.restartMarker(this.runner.getBlocksize() - * this.runner.getRank()); - } - try { - file.restartMarker(restart); - } catch (CommandAbstractException e) { - this.runner.deleteTempFile(); - throw new OpenR66RunnerErrorException(e); - } - } catch (CommandAbstractException e1) { - // length wrong - throw new OpenR66RunnerErrorException("File length is wrong", e1); - } catch (NoRestartException e) { - // length is not to be changed - } - } - } else { - try { - this.localChannelReference.getFutureRequest().filesize = file.length(); - } catch (CommandAbstractException e1) { - } - try { - file.restartMarker(restart); - } catch (CommandAbstractException e) { - this.runner.deleteTempFile(); - throw new OpenR66RunnerErrorException(e); - } - } - } - this.runner.saveStatus(); - logger.debug("Final init: {} {}", this.runner, this.file != null); - } - - /** - * Rename the current receive file from the very beginning since the sender has a post action - * that changes its name - * - * @param newFilename - * @throws OpenR66RunnerErrorException - */ - public void renameReceiverFile(String newFilename) throws OpenR66RunnerErrorException { - if (runner == null) { - return; - } - // First delete the temporary file if needed - if (runner.getRank() > 0) { - logger.error("Renaming file is not correct since transfer does not start from first block"); - // Not correct - throw new OpenR66RunnerErrorException( - "Renaming file not correct since transfer already started"); - } - if (!runner.isRecvThrough()) { - this.runner.deleteTempFile(); - } - // Now rename it - this.runner.setOriginalFilename(newFilename); - try { - this.setFileAfterPreRunner(true); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - this.runner.saveStatus(); - } - - /** - * Finalize the transfer step by running the error or post operation according to the status. - * - * @param status - * @param finalValue - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - */ - public void setFinalizeTransfer(boolean status, R66Result finalValue) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { - logger.debug(status + ":" + finalValue + ":" + runner); - if (runner == null) { - if (localChannelReference != null) { - if (status) { - localChannelReference.validateRequest(finalValue); - } else { - localChannelReference.invalidateRequest(finalValue); - } - } - if (this.businessObject != null) { - if (status) { - this.businessObject.checkAfterTransfer(this); - } else { - this.businessObject.checkAtError(this); - } - } - return; - } - if (this.businessObject != null) { - if (this.businessObject != null) { - if (status) { - this.businessObject.checkAfterTransfer(this); - } else { - this.businessObject.checkAtError(this); - } - } - } - if (runner.isAllDone()) { - logger.debug( - "Transfer already done but " + status + " on " + file + runner.toShortString(), - new OpenR66RunnerErrorException(finalValue.toString())); - // FIXME ?? - /* - * if (! status) runner.finalizeTransfer(localChannelReference, file, finalValue, - * status); - */ - return; - } - if (localChannelReference.getFutureRequest().isDone()) { - logger.debug( - "Request already done but " + status + " on " + file + runner.toShortString(), - new OpenR66RunnerErrorException(finalValue.toString())); - // Already finished once so do nothing more - return; - } - if (!status) { - this.runner.deleteTempFile(); - runner.setErrorExecutionStatus(finalValue.code); - } - if (status) { - runner.finishTransferTask(ErrorCode.TransferOk); - } else { - runner.finishTransferTask(finalValue.code); - } - runner.saveStatus(); - logger.debug("Transfer " + status + " on {} and {}", file, runner); - if (!runner.ready()) { - // Pre task in error (or even before) - OpenR66RunnerErrorException runnerErrorException; - if (!status && finalValue.exception != null) { - runnerErrorException = new OpenR66RunnerErrorException( - "Pre task in error (or even before)", - finalValue.exception); - } else { - runnerErrorException = new OpenR66RunnerErrorException( - "Pre task in error (or even before)"); - } - finalValue.exception = runnerErrorException; - logger.debug("Pre task in error (or even before) : " + - runnerErrorException.getMessage()); - if (Configuration.configuration.isExecuteErrorBeforeTransferAllowed) { - runner.finalizeTransfer(localChannelReference, file, finalValue, status); - } - localChannelReference.invalidateRequest(finalValue); - throw runnerErrorException; - } - try { - if (file != null) { - file.closeFile(); - } - } catch (CommandAbstractException e1) { - R66Result result = finalValue; - if (status) { - result = new R66Result(new OpenR66RunnerErrorException(e1), - this, false, ErrorCode.Internal, runner); - } - localChannelReference.invalidateRequest(result); - throw (OpenR66RunnerErrorException) result.exception; - } - runner.finalizeTransfer(localChannelReference, file, finalValue, status); - if (this.businessObject != null) { - this.businessObject.checkAfterPost(this); - } - } - - /** - * Try to finalize the request if possible - * - * @param errorValue - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - */ - public void tryFinalizeRequest(R66Result errorValue) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { - if (this.getLocalChannelReference() == null) { - return; - } - if (this.getLocalChannelReference().getFutureRequest().isDone()) { - return; - } - // setRunnerFromLocalChannelReference(localChannelReference); - if (runner == null) { - localChannelReference.invalidateRequest(errorValue); - return; - } - // do the real end - if (runner.getStatus() == ErrorCode.CompleteOk) { - // status = true; - runner.setAllDone(); - runner.forceSaveStatus(); - localChannelReference.validateRequest( - new R66Result(this, true, ErrorCode.CompleteOk, runner)); - } else if (runner.getStatus() == ErrorCode.TransferOk && - ((!runner.isSender()) || errorValue.code == ErrorCode.QueryAlreadyFinished)) { - // Try to finalize it - // status = true; - try { - this.setFinalizeTransfer(true, - new R66Result(this, true, ErrorCode.CompleteOk, runner)); - localChannelReference.validateRequest( - localChannelReference.getFutureEndTransfer().getResult()); - } catch (OpenR66ProtocolSystemException e) { - logger.error("Cannot validate runner:\n {}", runner.toShortString()); - runner.changeUpdatedInfo(UpdatedInfo.INERROR); - runner.setErrorExecutionStatus(errorValue.code); - runner.forceSaveStatus(); - this.setFinalizeTransfer(false, errorValue); - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot validate runner:\n {}", runner.toShortString()); - runner.changeUpdatedInfo(UpdatedInfo.INERROR); - runner.setErrorExecutionStatus(errorValue.code); - runner.forceSaveStatus(); - this.setFinalizeTransfer(false, errorValue); - } - } else { - // invalidate Request - this.setFinalizeTransfer(false, errorValue); - } - } - - /** - * @return the file - */ - public R66File getFile() { - return file; - } - - @Override - public String toString() { - return "Session: FS[" + state.getCurrent() + "] " + status + "\n " + - (auth != null ? auth.toString() : "no Auth") + "\n " + - (dir != null ? dir.toString() : "no Dir") + "\n " + - (file != null ? file.toString() : "no File") + "\n " + - (runner != null ? runner.toShortString() : "no Runner"); - } - - public String getUniqueExtension() { - return Configuration.EXT_R66; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context; + +import java.io.UnsupportedEncodingException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.URLDecoder; +import java.util.HashMap; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.exception.IllegalFiniteStateException; +import org.waarp.common.exception.NoRestartException; +import org.waarp.common.file.SessionInterface; +import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.state.MachineState; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.filesystem.R66Restart; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; + +/** + * The global object session in OpenR66, a session by local channel + * + * @author frederic bregier + * + */ +public class R66Session implements SessionInterface { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66Session.class); + + /** + * Block size used during file transfer + */ + private int blockSize = Configuration.configuration.BLOCKSIZE; + /** + * The local channel reference + */ + private LocalChannelReference localChannelReference; + /** + * Authentication + */ + private final R66Auth auth; + /** + * Remote Address + */ + private SocketAddress raddress; + /** + * Local Address + */ + private SocketAddress laddress; + + /** + * Current directory + */ + private final R66Dir dir; + /** + * Current file + */ + private R66File file; + /** + * Does this session is Ready to server a request + */ + private volatile boolean isReady = false; + + /** + * Current Restart information + */ + private final R66Restart restart; + + /** + * DbTaskRunner + */ + private DbTaskRunner runner = null; + + private String status = "NoStatus"; + + /** + * The Finite Machine State + */ + private final MachineState state; + /** + * Business Object if used + */ + private R66BusinessInterface businessObject = null; + /** + * Extended protocol or not + */ + private boolean extendedProtocol = Configuration.configuration.extendedProtocol; + + public HashMap dirsFromSession = new HashMap(); + /** + * Create the session + */ + public R66Session() { + isReady = false; + auth = new R66Auth(this); + dir = new R66Dir(this); + restart = new R66Restart(this); + state = R66FiniteDualStates.newSessionMachineState(); + } + + /** + * @return extendedProtocol + */ + public boolean getExtendedProtocol() { + return extendedProtocol; + } + + /** + * @return the businessObject + */ + public R66BusinessInterface getBusinessObject() { + return businessObject; + } + + /** + * @param businessObject + * the businessObject to set + */ + public void setBusinessObject(R66BusinessInterface businessObject) { + this.businessObject = businessObject; + } + + /** + * Propose a new State + * + * @param desiredstate + * @throws IllegalFiniteStateException + * if the new status if not ok + */ + public void newState(R66FiniteDualStates desiredstate) { + try { + state.setCurrent(desiredstate); + } catch (IllegalFiniteStateException e) { + logger.warn("Should not changed of State: {} {}", this, e.getMessage()); + state.setDryCurrent(desiredstate); + } + } + + /** + * Debugging purpose + * + * @param stat + */ + public void setStatus(int stat) { + StackTraceElement elt = Thread.currentThread().getStackTrace()[2]; + this.status = "(" + elt.getFileName() + ":" + elt.getLineNumber() + "):" + stat; + } + + public void clear() { + // First check if a transfer was on going + if (runner != null && (!runner.isFinished()) && (!runner.continueTransfer())) { + if (localChannelReference != null) { + if (!localChannelReference.getFutureRequest().isDone()) { + R66Result result = new R66Result(new OpenR66RunnerErrorException( + "Close before ending"), this, true, + ErrorCode.Disconnection, runner);// True since called from closed + result.runner = runner; + try { + setFinalizeTransfer(false, result); + } catch (OpenR66RunnerErrorException e) { + } catch (OpenR66ProtocolSystemException e) { + } + } + } + } + if (dir != null) { + dir.clear(); + } + if (auth != null) { + auth.clear(); + } + if (runner != null) { + runner.clear(); + } + if (state != null) { + try { + state.setCurrent(R66FiniteDualStates.CLOSEDCHANNEL); + } catch (IllegalFiniteStateException e) { + } + // R66FiniteDualStates.endSessionMachineSate(state); + } + // No clean of file since it can be used after channel is closed + isReady = false; + if (businessObject != null) { + businessObject.releaseResources(); + businessObject = null; + } + } + + public R66Auth getAuth() { + return auth; + } + + public int getBlockSize() { + return blockSize; + } + + /** + * @param blocksize + * the blocksize to set + */ + public void setBlockSize(int blocksize) { + blockSize = blocksize; + } + + public R66Dir getDir() { + return dir; + } + + public FilesystemBasedFileParameterImpl getFileParameter() { + return Configuration.getFileParameter(); + } + + public R66Restart getRestart() { + return restart; + } + + /** + * + * @return True if the connection is currently authenticated + */ + public boolean isAuthenticated() { + if (auth == null) { + return false; + } + return auth.isIdentified(); + } + + /** + * @return True if the Channel is ready to accept transfer + */ + public boolean isReady() { + return isReady; + } + + /** + * @param isReady + * the isReady for transfer to set + */ + public void setReady(boolean isReady) { + this.isReady = isReady; + } + + /** + * @return the runner + */ + public DbTaskRunner getRunner() { + return runner; + } + + /** + * @param localChannelReference + * the localChannelReference to set + */ + public void setLocalChannelReference( + LocalChannelReference localChannelReference) { + this.localChannelReference = localChannelReference; + this.localChannelReference.setSession(this); + if (this.localChannelReference.getNetworkChannel() != null) { + this.raddress = this.localChannelReference.getNetworkChannel().getRemoteAddress(); + this.laddress = this.localChannelReference.getNetworkChannel().getLocalAddress(); + } else { + this.raddress = this.laddress = new InetSocketAddress(0); + } + } + + /** + * + * @return the remote SocketAddress + */ + public SocketAddress getRemoteAddress() { + return this.raddress; + } + + /** + * + * @return the local SocketAddress + */ + public SocketAddress getLocalAddress() { + return this.laddress; + } + + /** + * @return the localChannelReference + */ + public LocalChannelReference getLocalChannelReference() { + return localChannelReference; + } + + /** + * To be called in case of No Session not from a valid LocalChannelHandler + * + * @param runner + * @param localChannelReference + */ + public void setNoSessionRunner(DbTaskRunner runner, LocalChannelReference localChannelReference) { + this.runner = runner; + // Warning: the file is not correctly setup + try { + file = (R66File) dir.setFile(this.runner.getFilename(), + false); + } catch (CommandAbstractException e1) { + } + this.auth.specialNoSessionAuth(false, Configuration.configuration.HOST_ID); + this.localChannelReference = localChannelReference; + if (this.localChannelReference == null) { + if (this.runner.getLocalChannelReference() != null) { + this.localChannelReference = this.runner.getLocalChannelReference(); + } else { + this.localChannelReference = new LocalChannelReference(); + } + this.localChannelReference.setErrorMessage(this.runner.getErrorInfo().mesg, + this.runner.getErrorInfo()); + } + runner.setLocalChannelReference(this.localChannelReference); + this.localChannelReference.setSession(this); + } + + /** + * Set the File from the runner before PRE operation are done + * + * @throws OpenR66RunnerErrorException + */ + public void setFileBeforePreRunner() throws OpenR66RunnerErrorException { + // check first if the next step is the PRE task from beginning + String filename; + if (this.runner.isPreTaskStarting()) { + filename = R66Dir.normalizePath(this.runner.getOriginalFilename()); + if (filename.startsWith("file:/")) { + filename = filename.substring("file:/".length()); + try { + filename = URLDecoder.decode(filename, "UTF-8"); + } catch (UnsupportedEncodingException e) { + this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); + throw new OpenR66RunnerErrorException("File cannot be read: " + + filename); + } + } + this.runner.setOriginalFilename(filename); + } else { + filename = this.runner.getFilename(); + } + if (this.runner.isSender()) { + try { + if (file == null) { + try { + file = (R66File) dir.setFile(filename, false); + } catch (CommandAbstractException e) { + // file is not under normal base directory, so is external + // File should already exist but can be using special code ('*?') + file = dir.setFileNoCheck(filename); + } + } + if (runner.isSendThrough()) { + // no test on file since it does not really exist + logger.debug("File is in through mode: {}", file); + } else if (!file.canRead()) { + // file is not under normal base directory, so is external + // File should already exist but cannot use special code ('*?') + file = new R66File(this, dir, filename); + if (!file.canRead()) { + this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); + throw new OpenR66RunnerErrorException("File cannot be read: " + + file.getTrueFile().getAbsolutePath()); + } + } else { + // possibly resolved filename + runner.setOriginalFilename(file.getFile()); + runner.setFilename(file.getFile()); + } + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } else { + // not sender so file is just registered as is but no test of existence + file = new R66File(this, dir, filename); + } + } + + /** + * Set the File from the runner once PRE operation are done + * + * @param createFile + * When True, the file can be newly created if needed. If False, no new file will be + * created, thus having an Exception. + * @throws OpenR66RunnerErrorException + * @throws CommandAbstractException only when new received created file cannot be created + */ + public void setFileAfterPreRunner(boolean createFile) throws OpenR66RunnerErrorException, CommandAbstractException { + if (this.businessObject != null) { + this.businessObject.checkAtChangeFilename(this); + } + // Now create the associated file + if (this.runner.isSender()) { + try { + if (file == null) { + try { + file = (R66File) dir.setFile(this.runner.getFilename(), + false); + } catch (CommandAbstractException e) { + // file is not under normal base directory, so is external + // File must already exist but can be using special code ('*?') + file = dir.setFileNoCheck(this.runner.getFilename()); + // file = new R66File(this, dir, this.runner.getFilename()); + } + } + if (runner.isSendThrough()) { + // no test on file since it does not really exist + logger.debug("File is in through mode: {}", file); + } else if (!file.canRead()) { + // file is not under normal base directory, so is external + // File must already exist but cannot used special code ('*?') + file = new R66File(this, dir, this.runner.getFilename()); + if (!file.canRead()) { + this.runner.setErrorExecutionStatus(ErrorCode.FileNotFound); + throw new OpenR66RunnerErrorException("File cannot be read: " + + file.getTrueFile().getAbsolutePath()); + } + } + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } else { + // File should not exist except if restart + if (runner.getRank() > 0) { + // Filename should be get back from runner load from database + try { + file = (R66File) dir.setFile(this.runner + .getFilename(), true); + if (runner.isRecvThrough()) { + // no test on file since it does not really exist + logger.debug("File is in through mode: {}", file); + } else if (!file.canWrite()) { + throw new OpenR66RunnerErrorException( + "File cannot be write"); + } + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } else { + // New FILENAME if necessary and store it + if (createFile) { + file = null; + String newfilename = this.runner.getOriginalFilename(); + if (newfilename.charAt(1) == ':') { + // Windows path + newfilename = newfilename.substring(2); + } + this.runner.setFilename(R66File.getBasename(newfilename)); + try { + file = dir.setUniqueFile(this.runner.getSpecialId(), + this.runner.getFilename()); + } catch (CommandAbstractException e) { + this.runner.deleteTempFile(); + throw e; + } + try { + if (runner.isRecvThrough()) { + // no test on file since it does not really exist + logger.debug("File is in through mode: {}", file); + this.runner.deleteTempFile(); + } else if (!file.canWrite()) { + this.runner.deleteTempFile(); + throw new OpenR66RunnerErrorException( + "File cannot be write"); + } + } catch (CommandAbstractException e) { + this.runner.deleteTempFile(); + throw new OpenR66RunnerErrorException(e); + } + } else { + throw new OpenR66RunnerErrorException("No file created"); + } + } + } + // Store TRUEFILENAME + try { + if (this.runner.isFileMoved()) { + this.runner.setFileMoved(file.getFile(), true); + } else { + this.runner.setFilename(file.getFile()); + } + } catch (CommandAbstractException e) { + this.runner.deleteTempFile(); + throw new OpenR66RunnerErrorException(e); + } + // check fileSize + if (runner.isSender() && file != null) { + long originalSize = file.length(); + this.runner.setOriginalSize(originalSize); + } + } + + /** + * To be used when a request comes with a bad code so it cannot be set normally + * + * @param runner + * @param code + */ + public void setBadRunner(DbTaskRunner runner, ErrorCode code) { + this.runner = runner; + if (code == ErrorCode.QueryAlreadyFinished) { + if (this.runner.isSender()) { + // Change dir + try { + dir.changeDirectory(this.runner.getRule().sendPath); + } catch (CommandAbstractException e) { + } + } else { + // Change dir + try { + dir.changeDirectory(this.runner.getRule().workPath); + } catch (CommandAbstractException e) { + } + } + if (this.businessObject != null) { + try { + this.businessObject.checkAtError(this); + } catch (OpenR66RunnerErrorException e) { + } + } + this.runner.setPostTask(); + try { + setFileAfterPreRunner(false); + } catch (OpenR66RunnerErrorException e) { + } catch (CommandAbstractException e) { + } + } + } + + /** + * Set the runner, START from the PreTask if necessary, and prepare the file + * + * @param runner + * the runner to set + * @throws OpenR66RunnerErrorException + */ + public void setRunner(DbTaskRunner runner) + throws OpenR66RunnerErrorException { + this.runner = runner; + setBusinessObject(Configuration.configuration.r66BusinessFactory.getBusinessInterface(this)); + this.runner.checkThroughMode(); + if (this.businessObject != null) { + this.businessObject.checkAtStartup(this); + } + if (this.runner.isSender()) { + if (runner.isSendThrough()) { + // May not change dir as needed + // Change dir + try { + dir.changeDirectory(this.runner.getRule().sendPath); + } catch (CommandAbstractException e) { + // ignore + } + } else { + // Change dir + try { + dir.changeDirectory(this.runner.getRule().sendPath); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } + } else { + if (runner.isRecvThrough()) { + // May not change dir as needed + // Change dir + try { + dir.changeDirectory(this.runner.getRule().workPath); + } catch (CommandAbstractException e) { + } + } else { + // Change dir + try { + dir.changeDirectory(this.runner.getRule().workPath); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } + } + if (runner.getRank() > 0) { + logger.debug("restart at " + runner.getRank() + " {}", runner); + runner.setTransferTask(runner.getRank()); + restart.restartMarker(runner.getBlocksize() * runner.getRank()); + } else { + restart.restartMarker(0); + } + if (runner.getGloballaststep() == TASKSTEP.NOTASK.ordinal() || + runner.getGloballaststep() == TASKSTEP.PRETASK.ordinal()) { + setFileBeforePreRunner(); + this.runner.setPreTask(); + runner.saveStatus(); + this.runner.run(); + runner.saveStatus(); + runner.setTransferTask(runner.getRank()); + } else { + runner.reset(); + runner.changeUpdatedInfo(UpdatedInfo.RUNNING); + runner.saveStatus(); + } + // Now create the associated file + try { + setFileAfterPreRunner(true); + } catch (CommandAbstractException e2) { + // generated due to a possible wildcard not ready + file = null; + } + if (runner.getGloballaststep() == TASKSTEP.TRANSFERTASK.ordinal()) { + if (this.businessObject != null) { + this.businessObject.checkAfterPreCommand(this); + } + if (!this.runner.isSender()) { + // Check file length according to rank + if (runner.isRecvThrough()) { + // no size can be checked + } else { + if (file == null) { + this.runner.saveStatus(); + logger.info("Final PARTIAL init: {}", this.runner); + return; + } + try { + long length = file.length(); + long oldPosition = restart.getPosition(); + restart.setSet(true); + if (oldPosition > length) { + int newRank = ((int) (length / this.runner.getBlocksize())) + - Configuration.RANKRESTART; + if (newRank <= 0) { + newRank = 1; + } + logger.warn("Decreased Rank Restart for {} at " + newRank, runner); + runner.setTransferTask(newRank); + restart.restartMarker(this.runner.getBlocksize() + * this.runner.getRank()); + } + try { + file.restartMarker(restart); + } catch (CommandAbstractException e) { + this.runner.deleteTempFile(); + throw new OpenR66RunnerErrorException(e); + } + } catch (CommandAbstractException e1) { + // length wrong + throw new OpenR66RunnerErrorException("File length is wrong", e1); + } catch (NoRestartException e) { + // length is not to be changed + } + } + } else { + try { + this.localChannelReference.getFutureRequest().filesize = file.length(); + } catch (CommandAbstractException e1) { + } + try { + file.restartMarker(restart); + } catch (CommandAbstractException e) { + this.runner.deleteTempFile(); + throw new OpenR66RunnerErrorException(e); + } + } + } + this.runner.saveStatus(); + logger.debug("Final init: {} {}", this.runner, this.file != null); + } + + /** + * Rename the current receive file from the very beginning since the sender has a post action + * that changes its name + * + * @param newFilename + * @throws OpenR66RunnerErrorException + */ + public void renameReceiverFile(String newFilename) throws OpenR66RunnerErrorException { + if (runner == null) { + return; + } + // First delete the temporary file if needed + if (runner.getRank() > 0) { + logger.error("Renaming file is not correct since transfer does not start from first block"); + // Not correct + throw new OpenR66RunnerErrorException( + "Renaming file not correct since transfer already started"); + } + if (!runner.isRecvThrough()) { + this.runner.deleteTempFile(); + } + // Now rename it + this.runner.setOriginalFilename(newFilename); + try { + this.setFileAfterPreRunner(true); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + this.runner.saveStatus(); + } + + /** + * Finalize the transfer step by running the error or post operation according to the status. + * + * @param status + * @param finalValue + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + */ + public void setFinalizeTransfer(boolean status, R66Result finalValue) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { + logger.debug(status + ":" + finalValue + ":" + runner); + if (runner == null) { + if (localChannelReference != null) { + if (status) { + localChannelReference.validateRequest(finalValue); + } else { + localChannelReference.invalidateRequest(finalValue); + } + } + if (this.businessObject != null) { + if (status) { + this.businessObject.checkAfterTransfer(this); + } else { + this.businessObject.checkAtError(this); + } + } + return; + } + if (this.businessObject != null) { + if (this.businessObject != null) { + if (status) { + this.businessObject.checkAfterTransfer(this); + } else { + this.businessObject.checkAtError(this); + } + } + } + if (runner.isAllDone()) { + logger.debug( + "Transfer already done but " + status + " on " + file + runner.toShortString(), + new OpenR66RunnerErrorException(finalValue.toString())); + // FIXME ?? + /* + * if (! status) runner.finalizeTransfer(localChannelReference, file, finalValue, + * status); + */ + return; + } + if (localChannelReference.getFutureRequest().isDone()) { + logger.debug( + "Request already done but " + status + " on " + file + runner.toShortString(), + new OpenR66RunnerErrorException(finalValue.toString())); + // Already finished once so do nothing more + return; + } + if (!status) { + this.runner.deleteTempFile(); + runner.setErrorExecutionStatus(finalValue.code); + } + if (status) { + runner.finishTransferTask(ErrorCode.TransferOk); + } else { + runner.finishTransferTask(finalValue.code); + } + runner.saveStatus(); + logger.debug("Transfer " + status + " on {} and {}", file, runner); + if (!runner.ready()) { + // Pre task in error (or even before) + OpenR66RunnerErrorException runnerErrorException; + if (!status && finalValue.exception != null) { + runnerErrorException = new OpenR66RunnerErrorException( + "Pre task in error (or even before)", + finalValue.exception); + } else { + runnerErrorException = new OpenR66RunnerErrorException( + "Pre task in error (or even before)"); + } + finalValue.exception = runnerErrorException; + logger.debug("Pre task in error (or even before) : " + + runnerErrorException.getMessage()); + if (Configuration.configuration.isExecuteErrorBeforeTransferAllowed) { + runner.finalizeTransfer(localChannelReference, file, finalValue, status); + } + localChannelReference.invalidateRequest(finalValue); + throw runnerErrorException; + } + try { + if (file != null) { + file.closeFile(); + } + } catch (CommandAbstractException e1) { + R66Result result = finalValue; + if (status) { + result = new R66Result(new OpenR66RunnerErrorException(e1), + this, false, ErrorCode.Internal, runner); + } + localChannelReference.invalidateRequest(result); + throw (OpenR66RunnerErrorException) result.exception; + } + runner.finalizeTransfer(localChannelReference, file, finalValue, status); + if (this.businessObject != null) { + this.businessObject.checkAfterPost(this); + } + } + + /** + * Try to finalize the request if possible + * + * @param errorValue + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + */ + public void tryFinalizeRequest(R66Result errorValue) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { + if (this.getLocalChannelReference() == null) { + return; + } + if (this.getLocalChannelReference().getFutureRequest().isDone()) { + return; + } + // setRunnerFromLocalChannelReference(localChannelReference); + if (runner == null) { + localChannelReference.invalidateRequest(errorValue); + return; + } + // do the real end + if (runner.getStatus() == ErrorCode.CompleteOk) { + // status = true; + runner.setAllDone(); + runner.forceSaveStatus(); + localChannelReference.validateRequest( + new R66Result(this, true, ErrorCode.CompleteOk, runner)); + } else if (runner.getStatus() == ErrorCode.TransferOk && + ((!runner.isSender()) || errorValue.code == ErrorCode.QueryAlreadyFinished)) { + // Try to finalize it + // status = true; + try { + this.setFinalizeTransfer(true, + new R66Result(this, true, ErrorCode.CompleteOk, runner)); + localChannelReference.validateRequest( + localChannelReference.getFutureEndTransfer().getResult()); + } catch (OpenR66ProtocolSystemException e) { + logger.error("Cannot validate runner:\n {}", runner.toShortString()); + runner.changeUpdatedInfo(UpdatedInfo.INERROR); + runner.setErrorExecutionStatus(errorValue.code); + runner.forceSaveStatus(); + this.setFinalizeTransfer(false, errorValue); + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot validate runner:\n {}", runner.toShortString()); + runner.changeUpdatedInfo(UpdatedInfo.INERROR); + runner.setErrorExecutionStatus(errorValue.code); + runner.forceSaveStatus(); + this.setFinalizeTransfer(false, errorValue); + } + } else { + // invalidate Request + this.setFinalizeTransfer(false, errorValue); + } + } + + /** + * @return the file + */ + public R66File getFile() { + return file; + } + + @Override + public String toString() { + return "Session: FS[" + state.getCurrent() + "] " + status + "\n " + + (auth != null ? auth.toString() : "no Auth") + "\n " + + (dir != null ? dir.toString() : "no Dir") + "\n " + + (file != null ? file.toString() : "no File") + "\n " + + (runner != null ? runner.toShortString() : "no Runner"); + } + + public String getUniqueExtension() { + return Configuration.EXT_R66; + } + +} diff --git a/src/main/java/org/waarp/openr66/context/authentication/R66Auth.java b/src/main/java/org/waarp/openr66/context/authentication/R66Auth.java index af8d91650..8185fd158 100644 --- a/src/main/java/org/waarp/openr66/context/authentication/R66Auth.java +++ b/src/main/java/org/waarp/openr66/context/authentication/R66Auth.java @@ -1,276 +1,276 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.authentication; - -import java.io.File; - -import org.waarp.common.command.NextCommandReply; -import org.waarp.common.command.exception.Reply421Exception; -import org.waarp.common.command.exception.Reply530Exception; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.file.DirInterface; -import org.waarp.common.file.filesystembased.FilesystemBasedAuthImpl; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.role.RoleDefault; -import org.waarp.common.role.RoleDefault.ROLE; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * @author frederic bregier - * - */ -public class R66Auth extends FilesystemBasedAuthImpl { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66Auth.class); - - /** - * Current authentication - */ - private DbHostAuth currentAuth = null; - /** - * is Admin role - */ - private boolean isAdmin = false; - /** - * Role set from configuration file only - */ - private RoleDefault role = new RoleDefault(); - - /** - * @param session - */ - public R66Auth(R66Session session) { - super(session); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedAuthImpl#businessClean () - */ - @Override - protected void businessClean() { - currentAuth = null; - isAdmin = false; - role.clear(); - } - - public String getBaseDirectory() { - return Configuration.configuration.baseDirectory; - } - - /* - * (non-Javadoc) - * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# - * setBusinessPassword(java.lang.String) - */ - @Override - protected NextCommandReply setBusinessPassword(String arg0) - throws Reply421Exception, Reply530Exception { - throw new Reply421Exception("Command not valid"); - } - - /** - * @param dbSession - * @param hostId - * @param arg0 - * @return True if the connection is OK (authentication is OK) - * @throws Reply530Exception - * if the authentication is wrong - * @throws Reply421Exception - * If the service is not available - */ - public boolean connection(DbSession dbSession, String hostId, byte[] arg0) - throws Reply530Exception, Reply421Exception { - DbHostAuth auth = R66Auth - .getServerAuth(dbSession, hostId); - if (auth == null) { - logger.error("Cannot find authentication for " + hostId); - setIsIdentified(false); - currentAuth = null; - throw new Reply530Exception("HostId not allowed"); - } - currentAuth = auth; - if (currentAuth.isKeyValid(arg0)) { - setIsIdentified(true); - user = hostId; - setRootFromAuth(); - getSession().getDir().initAfterIdentification(); - isAdmin = currentAuth.isAdminrole(); - if (Configuration.configuration.roles.isEmpty()) { - if (isAdmin) { - role.setRole(ROLE.FULLADMIN); - } else { - role.setRole(ROLE.PARTNER); - } - } else { - RoleDefault configRole = Configuration.configuration.roles.get(hostId); - if (configRole == null) { - // set to default PARTNER - role.setRole(ROLE.PARTNER); - } else { - role.setRole(configRole); - if (this.role.isContaining(ROLE.FULLADMIN)) { - isAdmin = true; - } - } - } - return true; - } - throw new Reply530Exception("Key is not valid for this HostId"); - } - - /** - * - * @param key - * @return True if the key is valid for the current user - */ - public boolean isKeyValid(byte[] key) { - return currentAuth.isKeyValid(key); - } - - /** - * Set the root relative Path from current status of Authentication (should be the highest level - * for the current authentication). If setBusinessRootFromAuth returns null, by default set - * /user. - * - * @exception Reply421Exception - * if the business root is not available - */ - private void setRootFromAuth() throws Reply421Exception { - rootFromAuth = setBusinessRootFromAuth(); - if (rootFromAuth == null) { - rootFromAuth = DirInterface.SEPARATOR; - } - } - - /* - * (non-Javadoc) - * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# setBusinessRootFromAuth() - */ - @Override - protected String setBusinessRootFromAuth() throws Reply421Exception { - String path = null; - String fullpath = getAbsolutePath(path); - File file = new File(fullpath); - if (!file.isDirectory()) { - throw new Reply421Exception("Filesystem not ready"); - } - return path; - } - - /* - * (non-Javadoc) - * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# - * setBusinessUser(java.lang.String) - */ - @Override - protected NextCommandReply setBusinessUser(String arg0) - throws Reply421Exception, Reply530Exception { - throw new Reply421Exception("Command not valid"); - } - - public boolean isAdmin() { - return isAdmin; - } - - /** - * - * @param roleCheck - * @return True if the current role contains the specified role to check - */ - public boolean isValidRole(ROLE roleCheck) { - return this.role.isContaining(roleCheck); - } - - /** - * - * @return True if the associated host is using SSL - */ - public boolean isSsl() { - return currentAuth.isSsl(); - } - - public boolean isBusinessPathValid(String newPath) { - if (newPath == null) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Auth:" + isIdentified + " " + - (currentAuth != null ? currentAuth.toString() - : "no Internal Auth"); - } - - /** - * @param dbSession - * @param server - * @return the SimpleAuth if any for this user - */ - public static DbHostAuth getServerAuth(DbSession dbSession, String server) { - DbHostAuth auth = null; - try { - auth = new DbHostAuth(dbSession, server); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot find the authentication", e); - return null; - } - return auth; - } - - /** - * Special Authentication for local execution - * - * @param isSSL - * @param hostid - */ - public void specialNoSessionAuth(boolean isSSL, String hostid) { - this.isIdentified = true; - DbHostAuth auth = null; - try { - auth = new DbHostAuth(DbConstant.admin.session, - hostid); - } catch (WaarpDatabaseException e1) { - } - if (auth == null) { - auth = new DbHostAuth(DbConstant.admin.session, hostid, "127.0.0.1", 6666, isSSL, null, true, false); - } - currentAuth = auth; - setIsIdentified(true); - user = auth.getHostid(); - try { - setRootFromAuth(); - } catch (Reply421Exception e) { - } - getSession().getDir().initAfterIdentification(); - isAdmin = isSSL; - if (isSSL) { - this.user = Configuration.configuration.ADMINNAME; - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.authentication; + +import java.io.File; + +import org.waarp.common.command.NextCommandReply; +import org.waarp.common.command.exception.Reply421Exception; +import org.waarp.common.command.exception.Reply530Exception; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.file.DirInterface; +import org.waarp.common.file.filesystembased.FilesystemBasedAuthImpl; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.role.RoleDefault; +import org.waarp.common.role.RoleDefault.ROLE; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * @author frederic bregier + * + */ +public class R66Auth extends FilesystemBasedAuthImpl { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66Auth.class); + + /** + * Current authentication + */ + private DbHostAuth currentAuth = null; + /** + * is Admin role + */ + private boolean isAdmin = false; + /** + * Role set from configuration file only + */ + private RoleDefault role = new RoleDefault(); + + /** + * @param session + */ + public R66Auth(R66Session session) { + super(session); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedAuthImpl#businessClean () + */ + @Override + protected void businessClean() { + currentAuth = null; + isAdmin = false; + role.clear(); + } + + public String getBaseDirectory() { + return Configuration.configuration.baseDirectory; + } + + /* + * (non-Javadoc) + * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# + * setBusinessPassword(java.lang.String) + */ + @Override + protected NextCommandReply setBusinessPassword(String arg0) + throws Reply421Exception, Reply530Exception { + throw new Reply421Exception("Command not valid"); + } + + /** + * @param dbSession + * @param hostId + * @param arg0 + * @return True if the connection is OK (authentication is OK) + * @throws Reply530Exception + * if the authentication is wrong + * @throws Reply421Exception + * If the service is not available + */ + public boolean connection(DbSession dbSession, String hostId, byte[] arg0) + throws Reply530Exception, Reply421Exception { + DbHostAuth auth = R66Auth + .getServerAuth(dbSession, hostId); + if (auth == null) { + logger.error("Cannot find authentication for " + hostId); + setIsIdentified(false); + currentAuth = null; + throw new Reply530Exception("HostId not allowed"); + } + currentAuth = auth; + if (currentAuth.isKeyValid(arg0)) { + setIsIdentified(true); + user = hostId; + setRootFromAuth(); + getSession().getDir().initAfterIdentification(); + isAdmin = currentAuth.isAdminrole(); + if (Configuration.configuration.roles.isEmpty()) { + if (isAdmin) { + role.setRole(ROLE.FULLADMIN); + } else { + role.setRole(ROLE.PARTNER); + } + } else { + RoleDefault configRole = Configuration.configuration.roles.get(hostId); + if (configRole == null) { + // set to default PARTNER + role.setRole(ROLE.PARTNER); + } else { + role.setRole(configRole); + if (this.role.isContaining(ROLE.FULLADMIN)) { + isAdmin = true; + } + } + } + return true; + } + throw new Reply530Exception("Key is not valid for this HostId"); + } + + /** + * + * @param key + * @return True if the key is valid for the current user + */ + public boolean isKeyValid(byte[] key) { + return currentAuth.isKeyValid(key); + } + + /** + * Set the root relative Path from current status of Authentication (should be the highest level + * for the current authentication). If setBusinessRootFromAuth returns null, by default set + * /user. + * + * @exception Reply421Exception + * if the business root is not available + */ + private void setRootFromAuth() throws Reply421Exception { + rootFromAuth = setBusinessRootFromAuth(); + if (rootFromAuth == null) { + rootFromAuth = DirInterface.SEPARATOR; + } + } + + /* + * (non-Javadoc) + * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# setBusinessRootFromAuth() + */ + @Override + protected String setBusinessRootFromAuth() throws Reply421Exception { + String path = null; + String fullpath = getAbsolutePath(path); + File file = new File(fullpath); + if (!file.isDirectory()) { + throw new Reply421Exception("Filesystem not ready"); + } + return path; + } + + /* + * (non-Javadoc) + * @seeorg.waarp.common.file.filesystembased.FilesystemBasedAuthImpl# + * setBusinessUser(java.lang.String) + */ + @Override + protected NextCommandReply setBusinessUser(String arg0) + throws Reply421Exception, Reply530Exception { + throw new Reply421Exception("Command not valid"); + } + + public boolean isAdmin() { + return isAdmin; + } + + /** + * + * @param roleCheck + * @return True if the current role contains the specified role to check + */ + public boolean isValidRole(ROLE roleCheck) { + return this.role.isContaining(roleCheck); + } + + /** + * + * @return True if the associated host is using SSL + */ + public boolean isSsl() { + return currentAuth.isSsl(); + } + + public boolean isBusinessPathValid(String newPath) { + if (newPath == null) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Auth:" + isIdentified + " " + + (currentAuth != null ? currentAuth.toString() + : "no Internal Auth"); + } + + /** + * @param dbSession + * @param server + * @return the SimpleAuth if any for this user + */ + public static DbHostAuth getServerAuth(DbSession dbSession, String server) { + DbHostAuth auth = null; + try { + auth = new DbHostAuth(dbSession, server); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot find the authentication", e); + return null; + } + return auth; + } + + /** + * Special Authentication for local execution + * + * @param isSSL + * @param hostid + */ + public void specialNoSessionAuth(boolean isSSL, String hostid) { + this.isIdentified = true; + DbHostAuth auth = null; + try { + auth = new DbHostAuth(DbConstant.admin.session, + hostid); + } catch (WaarpDatabaseException e1) { + } + if (auth == null) { + auth = new DbHostAuth(DbConstant.admin.session, hostid, "127.0.0.1", 6666, isSSL, null, true, false); + } + currentAuth = auth; + setIsIdentified(true); + user = auth.getHostid(); + try { + setRootFromAuth(); + } catch (Reply421Exception e) { + } + getSession().getDir().initAfterIdentification(); + isAdmin = isSSL; + if (isSSL) { + this.user = Configuration.configuration.ADMINNAME; + } + } +} diff --git a/src/main/java/org/waarp/openr66/context/authentication/package-info.java b/src/main/java/org/waarp/openr66/context/authentication/package-info.java index 3cfe325cf..92302f4ba 100644 --- a/src/main/java/org/waarp/openr66/context/authentication/package-info.java +++ b/src/main/java/org/waarp/openr66/context/authentication/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Authentication - * - * @apiviz.landmark - */ -package org.waarp.openr66.context.authentication; - +/** + * Classes implementing Authentication + * + * @apiviz.landmark + */ +package org.waarp.openr66.context.authentication; + diff --git a/src/main/java/org/waarp/openr66/context/filesystem/R66Dir.java b/src/main/java/org/waarp/openr66/context/filesystem/R66Dir.java index 22f035afd..f77209313 100644 --- a/src/main/java/org/waarp/openr66/context/filesystem/R66Dir.java +++ b/src/main/java/org/waarp/openr66/context/filesystem/R66Dir.java @@ -1,213 +1,213 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.filesystem; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.command.exception.Reply550Exception; -import org.waarp.common.command.exception.Reply553Exception; -import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; -import org.waarp.common.file.filesystembased.FilesystemBasedOptsMLSxImpl; -import org.waarp.common.file.filesystembased.specific.FilesystemBasedCommonsIo; -import org.waarp.common.file.filesystembased.specific.FilesystemBasedDirJdkAbstract; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Directory representation - * - * @author frederic bregier - * - */ -public class R66Dir extends FilesystemBasedDirImpl { - - /** - * @param session - */ - public R66Dir(R66Session session) { - super(session, new FilesystemBasedOptsMLSxImpl()); - } - - public R66File newFile(String path, boolean append) - throws CommandAbstractException { - return new R66File((R66Session) getSession(), this, path, append); - } - - /** - * Same as setUnique() except that File will be prefixed by id and postfixed by filename - * - * @param prefix - * @param filename - * @return the R66File with a unique filename and a temporary extension - * @throws CommandAbstractException - */ - public synchronized R66File setUniqueFile(long prefix, String filename) - throws CommandAbstractException { - checkIdentify(); - File file = null; - String prename = prefix + "_"; - if (prename.length() < 3) { - prename = "xx_" + prename; - } - String basename = R66File.getBasename(filename); - try { - file = File.createTempFile(prename, "_" + basename + - Configuration.EXT_R66, getFileFromPath(currentDir)); - } catch (IOException e) { - throw new Reply550Exception("Cannot create unique file from " + - basename); - } - String currentFile = getRelativePath(file); - return newFile(normalizePath(currentFile), false); - } - - /** - * - * @param file - * @return the final unique basename without the temporary extension - */ - public static String getFinalUniqueFilename(R66File file) { - String finalpath = file.getBasename(); - int pos = finalpath.lastIndexOf(Configuration.EXT_R66); - if (pos > 0) { - finalpath = finalpath.substring(0, pos); - } - return finalpath; - } - - /** - * Finds all files matching a wildcard expression (based on '?', '~' or '*') but without - * checking BusinessPath, thus returning absolute path. - * - * @param pathWithWildcard - * The wildcard expression with a business path. - * @return List of String as relative paths matching the wildcard expression. Those files are - * tested as valid from business point of view. If Wildcard support is not active, if - * the path contains any wildcards, it will throw an error. - * @throws CommandAbstractException - */ - protected List wildcardFilesNoCheck(String pathWithWildcard) - throws CommandAbstractException { - List resultPaths = new ArrayList(); - // First check if pathWithWildcard contains wildcards - if (!(pathWithWildcard.contains("*") || pathWithWildcard.contains("?") || pathWithWildcard - .contains("~"))) { - // No so simply return the list containing this path - resultPaths.add(pathWithWildcard); - return resultPaths; - } - // Do we support Wildcard path - if (!FilesystemBasedDirJdkAbstract.ueApacheCommonsIo) { - throw new Reply553Exception("Wildcards in pathname is not allowed"); - } - File wildcardFile = new File(pathWithWildcard); - File rootFile; - initWindowsSupport(); - if (ISUNIX) { - rootFile = new File("/"); - } else { - rootFile = getCorrespondingRoot(wildcardFile); - } - // Split wildcard path into subdirectories. - List subdirs = new ArrayList(); - while (wildcardFile != null) { - File parent = wildcardFile.getParentFile(); - if (parent == null) { - subdirs.add(0, wildcardFile.getPath()); - break; - } - subdirs.add(0, wildcardFile.getName()); - if (parent.equals(rootFile)) { - // End of wildcard path - subdirs.add(0, parent.getPath()); - break; - } - wildcardFile = parent; - } - List basedPaths = new ArrayList(); - // First set root - basedPaths.add(new File(subdirs.get(0))); - int i = 1; - // For each wilcard subdirectory - while (i < subdirs.size()) { - // Set current filter - FileFilter fileFilter = FilesystemBasedCommonsIo - .getWildcardFileFilter(subdirs.get(i)); - List newBasedPaths = new ArrayList(); - // Look for matches in all the current search paths - for (File dir : basedPaths) { - if (dir.isDirectory()) { - for (File match : dir.listFiles(fileFilter)) { - newBasedPaths.add(match); - } - } - } - // base Search Path changes now - basedPaths = newBasedPaths; - i++; - } - // Valid each file first - for (File file : basedPaths) { - resultPaths.add(file.getAbsolutePath()); - } - return resultPaths; - } - - /** - * Create a new file according to the path without checking BusinessPath, so as external File. - * - * @param path - * @return the File created - * @throws CommandAbstractException - */ - public R66File setFileNoCheck(String path) - throws CommandAbstractException { - checkIdentify(); - String newpath = consolidatePath(path); - List paths = wildcardFilesNoCheck(newpath); - if (paths.size() != 1) { - throw new Reply550Exception("FileInterface not found: " + - paths.size() + " founds"); - } - String extDir = paths.get(0); - return new R66File((R66Session) getSession(), this, extDir); - } - - /** - * This method returns the Full path for the current directory - * - * @return the full path associated with the current Dir - */ - public String getFullPath() { - if (session.getAuth() == null) { - return currentDir; - } - return ((R66Auth) session.getAuth()).getAbsolutePath(currentDir); - } - - @Override - public String toString() { - return "Dir: " + currentDir; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.filesystem; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.command.exception.Reply550Exception; +import org.waarp.common.command.exception.Reply553Exception; +import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; +import org.waarp.common.file.filesystembased.FilesystemBasedOptsMLSxImpl; +import org.waarp.common.file.filesystembased.specific.FilesystemBasedCommonsIo; +import org.waarp.common.file.filesystembased.specific.FilesystemBasedDirJdkAbstract; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Directory representation + * + * @author frederic bregier + * + */ +public class R66Dir extends FilesystemBasedDirImpl { + + /** + * @param session + */ + public R66Dir(R66Session session) { + super(session, new FilesystemBasedOptsMLSxImpl()); + } + + public R66File newFile(String path, boolean append) + throws CommandAbstractException { + return new R66File((R66Session) getSession(), this, path, append); + } + + /** + * Same as setUnique() except that File will be prefixed by id and postfixed by filename + * + * @param prefix + * @param filename + * @return the R66File with a unique filename and a temporary extension + * @throws CommandAbstractException + */ + public synchronized R66File setUniqueFile(long prefix, String filename) + throws CommandAbstractException { + checkIdentify(); + File file = null; + String prename = prefix + "_"; + if (prename.length() < 3) { + prename = "xx_" + prename; + } + String basename = R66File.getBasename(filename); + try { + file = File.createTempFile(prename, "_" + basename + + Configuration.EXT_R66, getFileFromPath(currentDir)); + } catch (IOException e) { + throw new Reply550Exception("Cannot create unique file from " + + basename); + } + String currentFile = getRelativePath(file); + return newFile(normalizePath(currentFile), false); + } + + /** + * + * @param file + * @return the final unique basename without the temporary extension + */ + public static String getFinalUniqueFilename(R66File file) { + String finalpath = file.getBasename(); + int pos = finalpath.lastIndexOf(Configuration.EXT_R66); + if (pos > 0) { + finalpath = finalpath.substring(0, pos); + } + return finalpath; + } + + /** + * Finds all files matching a wildcard expression (based on '?', '~' or '*') but without + * checking BusinessPath, thus returning absolute path. + * + * @param pathWithWildcard + * The wildcard expression with a business path. + * @return List of String as relative paths matching the wildcard expression. Those files are + * tested as valid from business point of view. If Wildcard support is not active, if + * the path contains any wildcards, it will throw an error. + * @throws CommandAbstractException + */ + protected List wildcardFilesNoCheck(String pathWithWildcard) + throws CommandAbstractException { + List resultPaths = new ArrayList(); + // First check if pathWithWildcard contains wildcards + if (!(pathWithWildcard.contains("*") || pathWithWildcard.contains("?") || pathWithWildcard + .contains("~"))) { + // No so simply return the list containing this path + resultPaths.add(pathWithWildcard); + return resultPaths; + } + // Do we support Wildcard path + if (!FilesystemBasedDirJdkAbstract.ueApacheCommonsIo) { + throw new Reply553Exception("Wildcards in pathname is not allowed"); + } + File wildcardFile = new File(pathWithWildcard); + File rootFile; + initWindowsSupport(); + if (ISUNIX) { + rootFile = new File("/"); + } else { + rootFile = getCorrespondingRoot(wildcardFile); + } + // Split wildcard path into subdirectories. + List subdirs = new ArrayList(); + while (wildcardFile != null) { + File parent = wildcardFile.getParentFile(); + if (parent == null) { + subdirs.add(0, wildcardFile.getPath()); + break; + } + subdirs.add(0, wildcardFile.getName()); + if (parent.equals(rootFile)) { + // End of wildcard path + subdirs.add(0, parent.getPath()); + break; + } + wildcardFile = parent; + } + List basedPaths = new ArrayList(); + // First set root + basedPaths.add(new File(subdirs.get(0))); + int i = 1; + // For each wilcard subdirectory + while (i < subdirs.size()) { + // Set current filter + FileFilter fileFilter = FilesystemBasedCommonsIo + .getWildcardFileFilter(subdirs.get(i)); + List newBasedPaths = new ArrayList(); + // Look for matches in all the current search paths + for (File dir : basedPaths) { + if (dir.isDirectory()) { + for (File match : dir.listFiles(fileFilter)) { + newBasedPaths.add(match); + } + } + } + // base Search Path changes now + basedPaths = newBasedPaths; + i++; + } + // Valid each file first + for (File file : basedPaths) { + resultPaths.add(file.getAbsolutePath()); + } + return resultPaths; + } + + /** + * Create a new file according to the path without checking BusinessPath, so as external File. + * + * @param path + * @return the File created + * @throws CommandAbstractException + */ + public R66File setFileNoCheck(String path) + throws CommandAbstractException { + checkIdentify(); + String newpath = consolidatePath(path); + List paths = wildcardFilesNoCheck(newpath); + if (paths.size() != 1) { + throw new Reply550Exception("FileInterface not found: " + + paths.size() + " founds"); + } + String extDir = paths.get(0); + return new R66File((R66Session) getSession(), this, extDir); + } + + /** + * This method returns the Full path for the current directory + * + * @return the full path associated with the current Dir + */ + public String getFullPath() { + if (session.getAuth() == null) { + return currentDir; + } + return ((R66Auth) session.getAuth()).getAbsolutePath(currentDir); + } + + @Override + public String toString() { + return "Dir: " + currentDir; + } +} diff --git a/src/main/java/org/waarp/openr66/context/filesystem/R66File.java b/src/main/java/org/waarp/openr66/context/filesystem/R66File.java index eed399b07..bca50a03d 100644 --- a/src/main/java/org/waarp/openr66/context/filesystem/R66File.java +++ b/src/main/java/org/waarp/openr66/context/filesystem/R66File.java @@ -1,611 +1,611 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.filesystem; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.jboss.netty.channel.ChannelFuture; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.exception.FileEndOfTransferException; -import org.waarp.common.exception.FileTransferException; -import org.waarp.common.file.DataBlock; -import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; -import org.waarp.common.file.filesystembased.FilesystemBasedFileImpl; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.RetrieveRunner; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * File representation - * - * @author frederic bregier - * - */ -public class R66File extends FilesystemBasedFileImpl { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66File.class); - - /** - * Does the current file is external (i.e. out of R66 base directory) - */ - private boolean isExternal = false; - - /** - * @param session - * @param dir - * @param path - * @param append - * @throws CommandAbstractException - */ - public R66File(R66Session session, R66Dir dir, String path, boolean append) - throws CommandAbstractException { - super(session, dir, path, append); - } - - /** - * This constructor is for External file - * - * @param session - * @param dir - * @param path - */ - public R66File(R66Session session, R66Dir dir, String path) { - super(session, dir, path); - isExternal = true; - } - - /** - * Start the retrieve (send to the remote host the local file) - * - * @param running - * When false, should stop the runner - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - */ - public void retrieveBlocking(AtomicBoolean running) throws OpenR66RunnerErrorException, - OpenR66ProtocolSystemException { - boolean retrieveDone = false; - LocalChannelReference localChannelReference = getSession() - .getLocalChannelReference(); - FilesystemBasedDigest digest = null; - logger.debug("File to retrieve: " + this.toString()); - try { - if (!isReady) { - return; - } - DataBlock block = null; - try { - block = readDataBlock(); - } catch (FileEndOfTransferException e) { - // Last block (in fact, no data to read) - retrieveDone = true; - return; - } - if (block == null) { - // Last block (in fact, no data to read) - retrieveDone = true; - return; - } - if (Configuration.configuration.globalDigest) { - try { - digest = new FilesystemBasedDigest(Configuration.configuration.digest); - } catch (NoSuchAlgorithmException e2) { - // ignore - } - } - ChannelFuture future1 = null, future2 = null; - if ((block != null && (running.get()))) { - future1 = RetrieveRunner.writeWhenPossible( - block, localChannelReference); - if (Configuration.configuration.globalDigest) { - FileUtils.computeGlobalHash(digest, block.getBlock()); - } - } - // While not last block - while (block != null && (!block.isEOF()) && (running.get())) { - try { - block = readDataBlock(); - } catch (FileEndOfTransferException e) { - // Wait for last write - try { - future1.await(); - } catch (InterruptedException e1) { - } - if (future1.isSuccess()) { - retrieveDone = true; - } - return; - } - future2 = RetrieveRunner.writeWhenPossible( - block, localChannelReference); - if (Configuration.configuration.globalDigest) { - FileUtils.computeGlobalHash(digest, block.getBlock()); - } - try { - future1.await(); - } catch (InterruptedException e) { - } - if (!future1.isSuccess()) { - return; - } - future1 = future2; - } - if (!running.get()) { - // stopped - return; - } - // Wait for last write - if (future1 != null) { - try { - future1.await(); - } catch (InterruptedException e) { - } - if (!future1.isSuccess()) { - return; - } - } - retrieveDone = true; - return; - } catch (FileTransferException e) { - // An error occurs! - getSession() - .setFinalizeTransfer( - false, - new R66Result(new OpenR66ProtocolSystemException(e), - getSession(), false, ErrorCode.TransferError, getSession() - .getRunner())); - } catch (OpenR66ProtocolPacketException e) { - // An error occurs! - getSession() - .setFinalizeTransfer( - false, - new R66Result(e, getSession(), false, - ErrorCode.Internal, getSession().getRunner())); - } finally { - if (retrieveDone) { - String hash = null; - if (digest != null) { - hash = FilesystemBasedDigest.getHex(digest.Final()); - } - try { - if (hash == null) { - ChannelUtils.writeEndTransfer(localChannelReference); - } else { - ChannelUtils.writeEndTransfer(localChannelReference, hash); - } - } catch (OpenR66ProtocolPacketException e) { - // An error occurs! - getSession().setFinalizeTransfer( - false, - new R66Result(e, getSession(), false, - ErrorCode.Internal, getSession().getRunner())); - } - } else { - // An error occurs! - getSession().setFinalizeTransfer( - false, - new R66Result(new OpenR66ProtocolSystemException("Transfer in error"), - getSession(), false, ErrorCode.TransferError, getSession() - .getRunner())); - } - } - } - - /** - * This method is a good to have in a true FileInterface implementation. - * - * @return the File associated with the current FileInterface operation - */ - public File getTrueFile() { - if (isExternal) { - return new File(currentFile); - } - try { - return getFileFromPath(getFile()); - } catch (CommandAbstractException e) { - logger.info("Exception while getting file", e); - return null; - } - } - - /** - * - * @return the basename of the current file - */ - public String getBasename() { - return getBasename(currentFile); - } - - /** - * - * @param path - * @return the basename from the given path - */ - public static String getBasename(String path) { - File file = new File(path); - return file.getName(); - } - - @Override - public R66Session getSession() { - return (R66Session) session; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#canRead() - */ - @Override - public boolean canRead() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - return file.canRead(); - } - return super.canRead(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#canWrite() - */ - @Override - public boolean canWrite() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - if (file.exists()) { - return file.canWrite(); - } - return file.getParentFile().canWrite(); - } - return super.canWrite(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#delete() - */ - @Override - public boolean delete() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - checkIdentify(); - if (!isReady) { - return false; - } - if (!file.exists()) { - return true; - } - closeFile(); - return file.delete(); - } - return super.delete(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#exists() - */ - @Override - public boolean exists() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - return file.exists(); - } - return super.exists(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#getFileChannel () - */ - @Override - protected FileChannel getFileChannel() { - if (!isExternal) { - return super.getFileChannel(); - } - if (!isReady) { - return null; - } - File trueFile = getTrueFile(); - FileChannel fileChannel; - try { - @SuppressWarnings("resource") - FileInputStream fileInputStream = new FileInputStream(trueFile); - fileChannel = fileInputStream.getChannel(); - if (getPosition() > 0) { - fileChannel = fileChannel.position(getPosition()); - } - } catch (FileNotFoundException e) { - logger.error("FileInterface not found in getFileChannel:", e); - return null; - } catch (IOException e) { - logger.error("Change position in getFileChannel:", e); - return null; - } - return fileChannel; - } - - @Override - protected RandomAccessFile getRandomFile() { - if (!isExternal) { - return super.getRandomFile(); - } - if (!isReady) { - return null; - } - File trueFile = getTrueFile(); - RandomAccessFile raf = null; - try { - raf = new RandomAccessFile(trueFile, "rw"); - raf.seek(getPosition()); - } catch (FileNotFoundException e) { - logger.error("File not found in getRandomFile:", e); - return null; - } catch (IOException e) { - logger.error("Change position in getRandomFile:", e); - return null; - } - return raf; - } - - /** - * Returns the FileOutputStream in Out mode associated with the current file. - * - * @param append - * True if the FileOutputStream should be in append mode - * @return the FileOutputStream (OUT) - */ - protected FileOutputStream getFileOutputStream(boolean append) { - if (!isExternal) { - return super.getFileOutputStream(append); - } - if (!isReady) { - return null; - } - File trueFile = getTrueFile(); - if (getPosition() > 0) { - if (trueFile.length() < getPosition()) { - logger.error("Cannot Change position in getFileOutputStream: file is smaller than required position"); - return null; - } - RandomAccessFile raf = getRandomFile(); - try { - raf.setLength(getPosition()); - raf.close(); - } catch (IOException e) { - logger.error("Change position in getFileOutputStream:", e); - return null; - } - } - FileOutputStream fos = null; - try { - fos = new FileOutputStream(trueFile, append); - } catch (FileNotFoundException e) { - logger.error("File not found in getRandomFile:", e); - return null; - } - return fos; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#isDirectory () - */ - @Override - public boolean isDirectory() throws CommandAbstractException { - if (isExternal) { - File dir = new File(currentFile); - return dir.isDirectory(); - } - return super.isDirectory(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#isFile() - */ - @Override - public boolean isFile() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - return file.isFile(); - } - return super.isFile(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#length() - */ - @Override - public long length() throws CommandAbstractException { - if (isExternal) { - File file = new File(currentFile); - return file.length(); - } - return super.length(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#renameTo - * (java.lang.String) - */ - @SuppressWarnings("resource") - @Override - public boolean renameTo(String path) throws CommandAbstractException { - if (!isExternal) { - return super.renameTo(path); - } - checkIdentify(); - if (!isReady) { - return false; - } - File file = getTrueFile(); - if (file.canRead()) { - File newFile = getFileFromPath(path); - if (newFile.getParentFile().canWrite()) { - if (!file.renameTo(newFile)) { - FileOutputStream fileOutputStream; - try { - fileOutputStream = new FileOutputStream(newFile); - } catch (FileNotFoundException e) { - logger - .warn("Cannot find file: " + newFile.getName(), - e); - return false; - } - FileChannel fileChannelOut = fileOutputStream.getChannel(); - if (get(fileChannelOut)) { - delete(); - } else { - try { - fileChannelOut.close(); - } catch (IOException e) { - } - logger.error("Cannot write file: {}", newFile); - return false; - } - } - currentFile = getRelativePath(newFile); - isExternal = false; - isReady = true; - return true; - } - } - return false; - } - - /** - * Move the current file to the path as destination - * - * @param path - * @param external - * if True, the path is outside authentication control - * @return True if the operation is done - * @throws CommandAbstractException - */ - @SuppressWarnings("resource") - public boolean renameTo(String path, boolean external) - throws CommandAbstractException { - if (!external) { - return renameTo(path); - } - checkIdentify(); - if (!isReady) { - return false; - } - File file = getTrueFile(); - if (file.canRead()) { - File newFile = new File(path); - if (newFile.getParentFile().canWrite()) { - if (!file.renameTo(newFile)) { - FileOutputStream fileOutputStream; - try { - fileOutputStream = new FileOutputStream(newFile); - } catch (FileNotFoundException e) { - logger - .warn("Cannot find file: " + newFile.getName(), - e); - return false; - } - FileChannel fileChannelOut = fileOutputStream.getChannel(); - if (get(fileChannelOut)) { - delete(); - } else { - try { - fileChannelOut.close(); - } catch (IOException e) { - } - logger.error("Cannot write file: {}", newFile); - return false; - } - } - currentFile = FilesystemBasedDirImpl.normalizePath(newFile - .getAbsolutePath()); - isExternal = true; - isReady = true; - return true; - } - } - return false; - } - - /** - * Replace the current file with the new filename after closing the previous one. - * - * @param filename - * @param isExternal - * @throws CommandAbstractException - */ - public void replaceFilename(String filename, boolean isExternal) - throws CommandAbstractException { - closeFile(); - currentFile = filename; - this.isExternal = isExternal; - isReady = true; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#closeFile () - */ - @Override - public boolean closeFile() throws CommandAbstractException { - boolean status = super.closeFile(); - // FORCE re-open file - isReady = true; - return status; - } - - /** - * - * @return True if this file is outside OpenR66 Base directory - */ - public boolean isExternal() { - return isExternal; - } - - @Override - public String toString() { - return "File: " + currentFile + " Ready " + isReady + " " + - getPosition(); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.filesystem; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.security.NoSuchAlgorithmException; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.jboss.netty.channel.ChannelFuture; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.exception.FileEndOfTransferException; +import org.waarp.common.exception.FileTransferException; +import org.waarp.common.file.DataBlock; +import org.waarp.common.file.filesystembased.FilesystemBasedDirImpl; +import org.waarp.common.file.filesystembased.FilesystemBasedFileImpl; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.RetrieveRunner; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * File representation + * + * @author frederic bregier + * + */ +public class R66File extends FilesystemBasedFileImpl { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66File.class); + + /** + * Does the current file is external (i.e. out of R66 base directory) + */ + private boolean isExternal = false; + + /** + * @param session + * @param dir + * @param path + * @param append + * @throws CommandAbstractException + */ + public R66File(R66Session session, R66Dir dir, String path, boolean append) + throws CommandAbstractException { + super(session, dir, path, append); + } + + /** + * This constructor is for External file + * + * @param session + * @param dir + * @param path + */ + public R66File(R66Session session, R66Dir dir, String path) { + super(session, dir, path); + isExternal = true; + } + + /** + * Start the retrieve (send to the remote host the local file) + * + * @param running + * When false, should stop the runner + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + */ + public void retrieveBlocking(AtomicBoolean running) throws OpenR66RunnerErrorException, + OpenR66ProtocolSystemException { + boolean retrieveDone = false; + LocalChannelReference localChannelReference = getSession() + .getLocalChannelReference(); + FilesystemBasedDigest digest = null; + logger.debug("File to retrieve: " + this.toString()); + try { + if (!isReady) { + return; + } + DataBlock block = null; + try { + block = readDataBlock(); + } catch (FileEndOfTransferException e) { + // Last block (in fact, no data to read) + retrieveDone = true; + return; + } + if (block == null) { + // Last block (in fact, no data to read) + retrieveDone = true; + return; + } + if (Configuration.configuration.globalDigest) { + try { + digest = new FilesystemBasedDigest(Configuration.configuration.digest); + } catch (NoSuchAlgorithmException e2) { + // ignore + } + } + ChannelFuture future1 = null, future2 = null; + if ((block != null && (running.get()))) { + future1 = RetrieveRunner.writeWhenPossible( + block, localChannelReference); + if (Configuration.configuration.globalDigest) { + FileUtils.computeGlobalHash(digest, block.getBlock()); + } + } + // While not last block + while (block != null && (!block.isEOF()) && (running.get())) { + try { + block = readDataBlock(); + } catch (FileEndOfTransferException e) { + // Wait for last write + try { + future1.await(); + } catch (InterruptedException e1) { + } + if (future1.isSuccess()) { + retrieveDone = true; + } + return; + } + future2 = RetrieveRunner.writeWhenPossible( + block, localChannelReference); + if (Configuration.configuration.globalDigest) { + FileUtils.computeGlobalHash(digest, block.getBlock()); + } + try { + future1.await(); + } catch (InterruptedException e) { + } + if (!future1.isSuccess()) { + return; + } + future1 = future2; + } + if (!running.get()) { + // stopped + return; + } + // Wait for last write + if (future1 != null) { + try { + future1.await(); + } catch (InterruptedException e) { + } + if (!future1.isSuccess()) { + return; + } + } + retrieveDone = true; + return; + } catch (FileTransferException e) { + // An error occurs! + getSession() + .setFinalizeTransfer( + false, + new R66Result(new OpenR66ProtocolSystemException(e), + getSession(), false, ErrorCode.TransferError, getSession() + .getRunner())); + } catch (OpenR66ProtocolPacketException e) { + // An error occurs! + getSession() + .setFinalizeTransfer( + false, + new R66Result(e, getSession(), false, + ErrorCode.Internal, getSession().getRunner())); + } finally { + if (retrieveDone) { + String hash = null; + if (digest != null) { + hash = FilesystemBasedDigest.getHex(digest.Final()); + } + try { + if (hash == null) { + ChannelUtils.writeEndTransfer(localChannelReference); + } else { + ChannelUtils.writeEndTransfer(localChannelReference, hash); + } + } catch (OpenR66ProtocolPacketException e) { + // An error occurs! + getSession().setFinalizeTransfer( + false, + new R66Result(e, getSession(), false, + ErrorCode.Internal, getSession().getRunner())); + } + } else { + // An error occurs! + getSession().setFinalizeTransfer( + false, + new R66Result(new OpenR66ProtocolSystemException("Transfer in error"), + getSession(), false, ErrorCode.TransferError, getSession() + .getRunner())); + } + } + } + + /** + * This method is a good to have in a true FileInterface implementation. + * + * @return the File associated with the current FileInterface operation + */ + public File getTrueFile() { + if (isExternal) { + return new File(currentFile); + } + try { + return getFileFromPath(getFile()); + } catch (CommandAbstractException e) { + logger.info("Exception while getting file", e); + return null; + } + } + + /** + * + * @return the basename of the current file + */ + public String getBasename() { + return getBasename(currentFile); + } + + /** + * + * @param path + * @return the basename from the given path + */ + public static String getBasename(String path) { + File file = new File(path); + return file.getName(); + } + + @Override + public R66Session getSession() { + return (R66Session) session; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#canRead() + */ + @Override + public boolean canRead() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + return file.canRead(); + } + return super.canRead(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#canWrite() + */ + @Override + public boolean canWrite() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + if (file.exists()) { + return file.canWrite(); + } + return file.getParentFile().canWrite(); + } + return super.canWrite(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#delete() + */ + @Override + public boolean delete() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + checkIdentify(); + if (!isReady) { + return false; + } + if (!file.exists()) { + return true; + } + closeFile(); + return file.delete(); + } + return super.delete(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#exists() + */ + @Override + public boolean exists() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + return file.exists(); + } + return super.exists(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#getFileChannel () + */ + @Override + protected FileChannel getFileChannel() { + if (!isExternal) { + return super.getFileChannel(); + } + if (!isReady) { + return null; + } + File trueFile = getTrueFile(); + FileChannel fileChannel; + try { + @SuppressWarnings("resource") + FileInputStream fileInputStream = new FileInputStream(trueFile); + fileChannel = fileInputStream.getChannel(); + if (getPosition() > 0) { + fileChannel = fileChannel.position(getPosition()); + } + } catch (FileNotFoundException e) { + logger.error("FileInterface not found in getFileChannel:", e); + return null; + } catch (IOException e) { + logger.error("Change position in getFileChannel:", e); + return null; + } + return fileChannel; + } + + @Override + protected RandomAccessFile getRandomFile() { + if (!isExternal) { + return super.getRandomFile(); + } + if (!isReady) { + return null; + } + File trueFile = getTrueFile(); + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(trueFile, "rw"); + raf.seek(getPosition()); + } catch (FileNotFoundException e) { + logger.error("File not found in getRandomFile:", e); + return null; + } catch (IOException e) { + logger.error("Change position in getRandomFile:", e); + return null; + } + return raf; + } + + /** + * Returns the FileOutputStream in Out mode associated with the current file. + * + * @param append + * True if the FileOutputStream should be in append mode + * @return the FileOutputStream (OUT) + */ + protected FileOutputStream getFileOutputStream(boolean append) { + if (!isExternal) { + return super.getFileOutputStream(append); + } + if (!isReady) { + return null; + } + File trueFile = getTrueFile(); + if (getPosition() > 0) { + if (trueFile.length() < getPosition()) { + logger.error("Cannot Change position in getFileOutputStream: file is smaller than required position"); + return null; + } + RandomAccessFile raf = getRandomFile(); + try { + raf.setLength(getPosition()); + raf.close(); + } catch (IOException e) { + logger.error("Change position in getFileOutputStream:", e); + return null; + } + } + FileOutputStream fos = null; + try { + fos = new FileOutputStream(trueFile, append); + } catch (FileNotFoundException e) { + logger.error("File not found in getRandomFile:", e); + return null; + } + return fos; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#isDirectory () + */ + @Override + public boolean isDirectory() throws CommandAbstractException { + if (isExternal) { + File dir = new File(currentFile); + return dir.isDirectory(); + } + return super.isDirectory(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#isFile() + */ + @Override + public boolean isFile() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + return file.isFile(); + } + return super.isFile(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#length() + */ + @Override + public long length() throws CommandAbstractException { + if (isExternal) { + File file = new File(currentFile); + return file.length(); + } + return super.length(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#renameTo + * (java.lang.String) + */ + @SuppressWarnings("resource") + @Override + public boolean renameTo(String path) throws CommandAbstractException { + if (!isExternal) { + return super.renameTo(path); + } + checkIdentify(); + if (!isReady) { + return false; + } + File file = getTrueFile(); + if (file.canRead()) { + File newFile = getFileFromPath(path); + if (newFile.getParentFile().canWrite()) { + if (!file.renameTo(newFile)) { + FileOutputStream fileOutputStream; + try { + fileOutputStream = new FileOutputStream(newFile); + } catch (FileNotFoundException e) { + logger + .warn("Cannot find file: " + newFile.getName(), + e); + return false; + } + FileChannel fileChannelOut = fileOutputStream.getChannel(); + if (get(fileChannelOut)) { + delete(); + } else { + try { + fileChannelOut.close(); + } catch (IOException e) { + } + logger.error("Cannot write file: {}", newFile); + return false; + } + } + currentFile = getRelativePath(newFile); + isExternal = false; + isReady = true; + return true; + } + } + return false; + } + + /** + * Move the current file to the path as destination + * + * @param path + * @param external + * if True, the path is outside authentication control + * @return True if the operation is done + * @throws CommandAbstractException + */ + @SuppressWarnings("resource") + public boolean renameTo(String path, boolean external) + throws CommandAbstractException { + if (!external) { + return renameTo(path); + } + checkIdentify(); + if (!isReady) { + return false; + } + File file = getTrueFile(); + if (file.canRead()) { + File newFile = new File(path); + if (newFile.getParentFile().canWrite()) { + if (!file.renameTo(newFile)) { + FileOutputStream fileOutputStream; + try { + fileOutputStream = new FileOutputStream(newFile); + } catch (FileNotFoundException e) { + logger + .warn("Cannot find file: " + newFile.getName(), + e); + return false; + } + FileChannel fileChannelOut = fileOutputStream.getChannel(); + if (get(fileChannelOut)) { + delete(); + } else { + try { + fileChannelOut.close(); + } catch (IOException e) { + } + logger.error("Cannot write file: {}", newFile); + return false; + } + } + currentFile = FilesystemBasedDirImpl.normalizePath(newFile + .getAbsolutePath()); + isExternal = true; + isReady = true; + return true; + } + } + return false; + } + + /** + * Replace the current file with the new filename after closing the previous one. + * + * @param filename + * @param isExternal + * @throws CommandAbstractException + */ + public void replaceFilename(String filename, boolean isExternal) + throws CommandAbstractException { + closeFile(); + currentFile = filename; + this.isExternal = isExternal; + isReady = true; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.filesystembased.FilesystemBasedFileImpl#closeFile () + */ + @Override + public boolean closeFile() throws CommandAbstractException { + boolean status = super.closeFile(); + // FORCE re-open file + isReady = true; + return status; + } + + /** + * + * @return True if this file is outside OpenR66 Base directory + */ + public boolean isExternal() { + return isExternal; + } + + @Override + public String toString() { + return "File: " + currentFile + " Ready " + isReady + " " + + getPosition(); + } +} diff --git a/src/main/java/org/waarp/openr66/context/filesystem/R66Restart.java b/src/main/java/org/waarp/openr66/context/filesystem/R66Restart.java index 6f8030a8c..949def499 100644 --- a/src/main/java/org/waarp/openr66/context/filesystem/R66Restart.java +++ b/src/main/java/org/waarp/openr66/context/filesystem/R66Restart.java @@ -1,67 +1,67 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.filesystem; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.command.exception.Reply502Exception; -import org.waarp.common.file.filesystembased.FilesystemBasedRestartImpl; -import org.waarp.openr66.context.R66Session; - -/** - * Restart implementation - * - * @author frederic bregier - * - */ -public class R66Restart extends FilesystemBasedRestartImpl { - - /** - * @param session - */ - public R66Restart(R66Session session) { - super(session); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.file.Restart#restartMarker(java.lang.String) - */ - @Override - public boolean restartMarker(String marker) throws CommandAbstractException { - long newposition = 0; - try { - newposition = Long.parseLong(marker); - } catch (NumberFormatException e) { - throw new Reply502Exception( - "Marker must be length in byte as a position"); - } - return restartMarker(newposition); - } - - /** - * Same as restartMarker with String - * - * @param newposition - * @return True if OK - */ - public boolean restartMarker(long newposition) { - position = newposition; - setSet(true); - return true; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.filesystem; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.command.exception.Reply502Exception; +import org.waarp.common.file.filesystembased.FilesystemBasedRestartImpl; +import org.waarp.openr66.context.R66Session; + +/** + * Restart implementation + * + * @author frederic bregier + * + */ +public class R66Restart extends FilesystemBasedRestartImpl { + + /** + * @param session + */ + public R66Restart(R66Session session) { + super(session); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.file.Restart#restartMarker(java.lang.String) + */ + @Override + public boolean restartMarker(String marker) throws CommandAbstractException { + long newposition = 0; + try { + newposition = Long.parseLong(marker); + } catch (NumberFormatException e) { + throw new Reply502Exception( + "Marker must be length in byte as a position"); + } + return restartMarker(newposition); + } + + /** + * Same as restartMarker with String + * + * @param newposition + * @return True if OK + */ + public boolean restartMarker(long newposition) { + position = newposition; + setSet(true); + return true; + } +} diff --git a/src/main/java/org/waarp/openr66/context/filesystem/package-info.java b/src/main/java/org/waarp/openr66/context/filesystem/package-info.java index e84a5a1ef..25c165530 100644 --- a/src/main/java/org/waarp/openr66/context/filesystem/package-info.java +++ b/src/main/java/org/waarp/openr66/context/filesystem/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Filesystem - * - * @apiviz.landmark - */ -package org.waarp.openr66.context.filesystem; - +/** + * Classes implementing Filesystem + * + * @apiviz.landmark + */ +package org.waarp.openr66.context.filesystem; + diff --git a/src/main/java/org/waarp/openr66/context/package-info.java b/src/main/java/org/waarp/openr66/context/package-info.java index d5b708d86..649415c63 100644 --- a/src/main/java/org/waarp/openr66/context/package-info.java +++ b/src/main/java/org/waarp/openr66/context/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Session, Result and ErrorCode - * - * @apiviz.landmark - */ -package org.waarp.openr66.context; - +/** + * Classes implementing Session, Result and ErrorCode + * + * @apiviz.landmark + */ +package org.waarp.openr66.context; + diff --git a/src/main/java/org/waarp/openr66/context/task/AbstractExecJavaTask.java b/src/main/java/org/waarp/openr66/context/task/AbstractExecJavaTask.java index 6eec0c3b9..e868bd0f5 100644 --- a/src/main/java/org/waarp/openr66/context/task/AbstractExecJavaTask.java +++ b/src/main/java/org/waarp/openr66/context/task/AbstractExecJavaTask.java @@ -1,183 +1,183 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.AbstractBusinessRequest; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Dummy Runnable Task that only logs - * - * @author Frederic Bregier - * - */ -public abstract class AbstractExecJavaTask implements R66Runnable { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(AbstractExecJavaTask.class); - - protected int delay; - protected String[] args = null; - protected int status = -1; - protected R66Session session; - protected boolean waitForValidation; - protected boolean useLocalExec; - - protected String classname; - protected String fullarg; - protected boolean isToValidate; - protected boolean callFromBusiness; - - /** - * Server side methode to validate the request - * - * @param packet - */ - public void validate(BusinessRequestPacket packet) { - this.status = 0; - packet.validate(); - if (callFromBusiness) { - R66Result result = new R66Result(session, true, - ErrorCode.CompleteOk, null); - session.getLocalChannelReference().validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(session.getLocalChannelReference(), - packet, true); - } catch (OpenR66ProtocolPacketException e) { - } - } - } - - /** - * To be called by the requester when finished - * - * @param object - * special object to get back - */ - public void finalValidate(Object object) { - this.status = 0; - if (callFromBusiness) { - R66Result result = new R66Result(session, true, - ErrorCode.CompleteOk, null); - result.other = object; - session.getLocalChannelReference().validateRequest(result); - ChannelUtils.close(session.getLocalChannelReference().getLocalChannel()); - } - } - - /** - * To be used if abnormal usage is made of one Java Method - */ - public void invalid() { - this.status = 2; - if (!callFromBusiness) { - return; - } - R66Result result = new R66Result(null, session, true, - ErrorCode.Unimplemented, session.getRunner()); - LocalChannelReference localChannelReference = session.getLocalChannelReference(); - if (localChannelReference != null) { - localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket("Command Incompatible", - ErrorCode.ExternalOp.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e1) { - } - localChannelReference.invalidateRequest(result); - ChannelUtils.close(localChannelReference.getLocalChannel()); - } - } - - public void run() { - if (callFromBusiness) { - // Business Request to validate? - if (isToValidate) { - BusinessRequestPacket packet = - new BusinessRequestPacket(this.classname + " " + this.fullarg, 0); - validate(packet); - } - } - StringBuilder builder = new StringBuilder(this.getClass().getSimpleName() + ":"); - for (int i = 0; i < args.length; i++) { - builder.append(' '); - builder.append(args[i]); - } - logger.warn(builder.toString()); - this.status = 0; - } - - public void setArgs(R66Session session, boolean waitForValidation, - boolean useLocalExec, int delay, String[] args) { - this.session = session; - this.waitForValidation = waitForValidation; - this.useLocalExec = useLocalExec; - this.delay = delay; - this.args = args; - this.classname = args[0]; - if (args.length > 2) { - callFromBusiness = this.args[this.args.length - 2]. - equals(AbstractBusinessRequest.BUSINESSREQUEST); - } - if (callFromBusiness) { - isToValidate = Boolean.parseBoolean(this.args[this.args.length - 1]); - StringBuilder builder = new StringBuilder(args[1]); - for (int i = 2; i < args.length - 2; i++) { - builder.append(' '); - builder.append(args[i]); - } - fullarg = builder.toString(); - } else { - StringBuilder builder = new StringBuilder(args[1]); - for (int i = 2; i < args.length; i++) { - builder.append(' '); - builder.append(args[i]); - } - fullarg = builder.toString(); - } - } - - public int getFinalStatus() { - return status; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(this.getClass().getSimpleName() + ": ["); - builder.append(args[0]); - builder.append(']'); - for (int i = 1; i < args.length; i++) { - builder.append(' '); - builder.append(args[i]); - } - return builder.toString(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.AbstractBusinessRequest; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Dummy Runnable Task that only logs + * + * @author Frederic Bregier + * + */ +public abstract class AbstractExecJavaTask implements R66Runnable { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(AbstractExecJavaTask.class); + + protected int delay; + protected String[] args = null; + protected int status = -1; + protected R66Session session; + protected boolean waitForValidation; + protected boolean useLocalExec; + + protected String classname; + protected String fullarg; + protected boolean isToValidate; + protected boolean callFromBusiness; + + /** + * Server side methode to validate the request + * + * @param packet + */ + public void validate(BusinessRequestPacket packet) { + this.status = 0; + packet.validate(); + if (callFromBusiness) { + R66Result result = new R66Result(session, true, + ErrorCode.CompleteOk, null); + session.getLocalChannelReference().validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(session.getLocalChannelReference(), + packet, true); + } catch (OpenR66ProtocolPacketException e) { + } + } + } + + /** + * To be called by the requester when finished + * + * @param object + * special object to get back + */ + public void finalValidate(Object object) { + this.status = 0; + if (callFromBusiness) { + R66Result result = new R66Result(session, true, + ErrorCode.CompleteOk, null); + result.other = object; + session.getLocalChannelReference().validateRequest(result); + ChannelUtils.close(session.getLocalChannelReference().getLocalChannel()); + } + } + + /** + * To be used if abnormal usage is made of one Java Method + */ + public void invalid() { + this.status = 2; + if (!callFromBusiness) { + return; + } + R66Result result = new R66Result(null, session, true, + ErrorCode.Unimplemented, session.getRunner()); + LocalChannelReference localChannelReference = session.getLocalChannelReference(); + if (localChannelReference != null) { + localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket("Command Incompatible", + ErrorCode.ExternalOp.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e1) { + } + localChannelReference.invalidateRequest(result); + ChannelUtils.close(localChannelReference.getLocalChannel()); + } + } + + public void run() { + if (callFromBusiness) { + // Business Request to validate? + if (isToValidate) { + BusinessRequestPacket packet = + new BusinessRequestPacket(this.classname + " " + this.fullarg, 0); + validate(packet); + } + } + StringBuilder builder = new StringBuilder(this.getClass().getSimpleName() + ":"); + for (int i = 0; i < args.length; i++) { + builder.append(' '); + builder.append(args[i]); + } + logger.warn(builder.toString()); + this.status = 0; + } + + public void setArgs(R66Session session, boolean waitForValidation, + boolean useLocalExec, int delay, String[] args) { + this.session = session; + this.waitForValidation = waitForValidation; + this.useLocalExec = useLocalExec; + this.delay = delay; + this.args = args; + this.classname = args[0]; + if (args.length > 2) { + callFromBusiness = this.args[this.args.length - 2]. + equals(AbstractBusinessRequest.BUSINESSREQUEST); + } + if (callFromBusiness) { + isToValidate = Boolean.parseBoolean(this.args[this.args.length - 1]); + StringBuilder builder = new StringBuilder(args[1]); + for (int i = 2; i < args.length - 2; i++) { + builder.append(' '); + builder.append(args[i]); + } + fullarg = builder.toString(); + } else { + StringBuilder builder = new StringBuilder(args[1]); + for (int i = 2; i < args.length; i++) { + builder.append(' '); + builder.append(args[i]); + } + fullarg = builder.toString(); + } + } + + public int getFinalStatus() { + return status; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(this.getClass().getSimpleName() + ": ["); + builder.append(args[0]); + builder.append(']'); + for (int i = 1; i < args.length; i++) { + builder.append(' '); + builder.append(args[i]); + } + return builder.toString(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/AbstractTask.java b/src/main/java/org/waarp/openr66/context/task/AbstractTask.java index 122e3e4a2..3b9f24a4a 100644 --- a/src/main/java/org/waarp/openr66/context/task/AbstractTask.java +++ b/src/main/java/org/waarp/openr66/context/task/AbstractTask.java @@ -1,419 +1,419 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Abstract implementation of task - * - * @author Frederic Bregier - * - */ -public abstract class AbstractTask implements Runnable { - /** - * Current full path of current FILENAME - */ - public static final String TRUEFULLPATH = "#TRUEFULLPATH#"; - - /** - * Current FILENAME (basename) (change in retrieval part) - */ - public static final String TRUEFILENAME = "#TRUEFILENAME#"; - /** - * Current full path of Original FILENAME (as transmitted) (before changing in retrieval part) - */ - public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#"; - - /** - * Original FILENAME (basename) (before changing in retrieval part) - */ - public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#"; - - /** - * Size of the current FILE - */ - public static final String FILESIZE = "#FILESIZE#"; - - /** - * Current full path of current RULE - */ - public static final String RULE = "#RULE#"; - - /** - * Date in yyyyMMdd format - */ - public static final String DATE = "#DATE#"; - - /** - * Hour in HHmmss format - */ - public static final String HOUR = "#HOUR#"; - - /** - * Remote host id (if not the initiator of the call) - */ - public static final String REMOTEHOST = "#REMOTEHOST#"; - - /** - * Remote host address - */ - public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#"; - - /** - * Local host id - */ - public static final String LOCALHOST = "#LOCALHOST#"; - - /** - * Local host address - */ - public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#"; - - /** - * Transfer id - */ - public static final String TRANSFERID = "#TRANSFERID#"; - - /** - * Requester Host - */ - public static final String REQUESTERHOST = "#REQUESTERHOST#"; - - /** - * Requested Host - */ - public static final String REQUESTEDHOST = "#REQUESTEDHOST#"; - - /** - * Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST) - */ - public static final String FULLTRANSFERID = "#FULLTRANSFERID#"; - - /** - * Current or final RANK of block - */ - public static final String RANKTRANSFER = "#RANKTRANSFER#"; - - /** - * Block size used - */ - public static final String BLOCKSIZE = "#BLOCKSIZE#"; - - /** - * IN Path used - */ - public static final String INPATH = "#INPATH#"; - - /** - * OUT Path used - */ - public static final String OUTPATH = "#OUTPATH#"; - - /** - * WORK Path used - */ - public static final String WORKPATH = "#WORKPATH#"; - - /** - * ARCH Path used - */ - public static final String ARCHPATH = "#ARCHPATH#"; - - /** - * HOME Path used - */ - public static final String HOMEPATH = "#HOMEPATH#"; - /** - * Last Current Error Message - */ - public static final String ERRORMSG = "#ERRORMSG#"; - /** - * Last Current Error Code - */ - public static final String ERRORCODE = "#ERRORCODE#"; - /** - * Last Current Error Code in Full String - */ - public static final String ERRORSTRCODE = "#ERRORSTRCODE#"; - /** - * If specified, no Wait for Task Validation (default is wait) - */ - public static final String NOWAIT = "#NOWAIT#"; - /** - * If specified, use the LocalExec Daemon specified in the global configuration (default no - * usage of LocalExec) - */ - public static final String LOCALEXEC = "#LOCALEXEC#"; - /** - * Delimiter for -count option in Reschedule to be placed in the info of transfer as - * #CPTLIMIT#limit#CPTLIMIT# where limit is an integer. - */ - public static final String CPTLIMIT = "#CPTLIMIT#"; - - /** - * Type of operation - */ - final TaskType type; - - /** - * Argument from Rule - */ - final String argRule; - - /** - * Delay from Rule (if applicable) - */ - final int delay; - - /** - * Argument from Transfer - */ - final String argTransfer; - - /** - * Current session - */ - final R66Session session; - - /** - * R66Future of completion - */ - final R66Future futureCompletion; - /** - * Do we wait for a validation of the task ? Default = True - */ - boolean waitForValidation = true; - /** - * Do we need to use LocalExec for an Exec Task ? Default = False - */ - boolean useLocalExec = false; - - /** - * Constructor - * - * @param type - * @param delay - * @param arg - * @param session - */ - AbstractTask(TaskType type, int delay, String argRule, String argTransfer, - R66Session session) { - this.type = type; - this.delay = delay; - this.argRule = argRule; - this.argTransfer = argTransfer; - this.session = session; - futureCompletion = new R66Future(true); - } - - /** - * This is the only interface to execute an operator. - */ - abstract public void run(); - - /** - * - * @return True if the operation is in success status - */ - public boolean isSuccess() { - futureCompletion.awaitUninterruptibly(); - return futureCompletion.isSuccess(); - } - - /** - * - * @return the R66Future of completion - */ - public R66Future getFutureCompletion() { - return futureCompletion; - } - - /** - * - * @param arg - * as the Format string where FIXED items will be replaced by context values and next - * using argFormat as format second argument; this arg comes from the rule itself - * @param argFormat - * as format second argument; this argFormat comes from the transfer Information - * itself - * @return The string with replaced values from context and second argument - */ - protected String getReplacedValue(String arg, Object[] argFormat) { - StringBuilder builder = new StringBuilder(arg); - // check NOWAIT and LOCALEXEC - if (arg.contains(NOWAIT)) { - waitForValidation = false; - WaarpStringUtils.replaceAll(builder, NOWAIT, ""); - } - if (arg.contains(LOCALEXEC)) { - useLocalExec = true; - WaarpStringUtils.replaceAll(builder, LOCALEXEC, ""); - } - File trueFile = null; - if (session.getFile() != null) { - trueFile = session.getFile().getTrueFile(); - } - if (trueFile != null) { - WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath()); - WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir - .getFinalUniqueFilename(session.getFile())); - WaarpStringUtils.replaceAll(builder, FILESIZE, Long.toString(trueFile.length())); - } else { - WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile"); - WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile"); - WaarpStringUtils.replaceAll(builder, FILESIZE, "0"); - } - WaarpStringUtils.replaceAll(builder, ORIGINALFULLPATH, session.getRunner() - .getOriginalFilename()); - WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, - R66File.getBasename(session.getRunner() - .getOriginalFilename())); - WaarpStringUtils.replaceAll(builder, RULE, session.getRunner() - .getRuleId()); - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); - Date date = new Date(); - WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date)); - dateFormat = new SimpleDateFormat("HHmmss"); - WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date)); - if (session.getAuth() != null) { - WaarpStringUtils.replaceAll(builder, REMOTEHOST, session.getAuth().getUser()); - try { - WaarpStringUtils.replaceAll(builder, LOCALHOST, - Configuration.configuration.getHostId(session.getAuth().isSsl())); - } catch (OpenR66ProtocolNoSslException e) { - // replace by standard name - WaarpStringUtils.replaceAll(builder, LOCALHOST, - Configuration.configuration.HOST_ID); - } - } - if (session.getRemoteAddress() != null) { - WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, session.getRemoteAddress() - .toString()); - WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, session.getLocalAddress() - .toString()); - } else { - WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown"); - WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown"); - } - WaarpStringUtils.replaceAll(builder, TRANSFERID, Long.toString(session - .getRunner().getSpecialId())); - String requester = session.getRunner().getRequester(); - WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester); - String requested = session.getRunner().getRequested(); - WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested); - WaarpStringUtils.replaceAll(builder, FULLTRANSFERID, session - .getRunner().getSpecialId() + "_" + requester + "_" + requested); - WaarpStringUtils.replaceAll(builder, RANKTRANSFER, Integer.toString(session - .getRunner().getRank())); - WaarpStringUtils.replaceAll(builder, BLOCKSIZE, Integer.toString(session - .getBlockSize())); - R66Dir dir = new R66Dir(session); - if (session.getRunner().isRecvThrough() || session.getRunner().isSendThrough()) { - try { - dir.changeDirectoryNotChecked(session.getRunner().getRule().recvPath); - WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectoryNotChecked(session.getRunner().getRule().sendPath); - WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectoryNotChecked(session.getRunner().getRule().workPath); - WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectoryNotChecked(session.getRunner().getRule().archivePath); - WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - } else { - try { - dir.changeDirectoryNotChecked(session.getRunner().getRule().recvPath); - WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectory(session.getRunner().getRule().sendPath); - WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectory(session.getRunner().getRule().workPath); - WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - dir = new R66Dir(session); - try { - dir.changeDirectory(session.getRunner().getRule().archivePath); - WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath()); - } catch (CommandAbstractException e) { - } - } - WaarpStringUtils.replaceAll(builder, HOMEPATH, Configuration.configuration.baseDirectory); - if (session.getLocalChannelReference() == null) { - WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError"); - WaarpStringUtils.replaceAll(builder, ERRORCODE, "-"); - WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name()); - } else { - try { - WaarpStringUtils.replaceAll(builder, ERRORMSG, session.getLocalChannelReference() - .getErrorMessage()); - } catch (NullPointerException e) { - WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError"); - } - try { - WaarpStringUtils.replaceAll(builder, ERRORCODE, session.getLocalChannelReference() - .getCurrentCode().getCode()); - } catch (NullPointerException e) { - WaarpStringUtils.replaceAll(builder, ERRORCODE, "-"); - } - try { - WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, session - .getLocalChannelReference().getCurrentCode().name()); - } catch (NullPointerException e) { - WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name()); - } - } - // finalname - if (argFormat != null && argFormat.length > 0) - return String.format(builder.toString(), argFormat); - return builder.toString(); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Abstract implementation of task + * + * @author Frederic Bregier + * + */ +public abstract class AbstractTask implements Runnable { + /** + * Current full path of current FILENAME + */ + public static final String TRUEFULLPATH = "#TRUEFULLPATH#"; + + /** + * Current FILENAME (basename) (change in retrieval part) + */ + public static final String TRUEFILENAME = "#TRUEFILENAME#"; + /** + * Current full path of Original FILENAME (as transmitted) (before changing in retrieval part) + */ + public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#"; + + /** + * Original FILENAME (basename) (before changing in retrieval part) + */ + public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#"; + + /** + * Size of the current FILE + */ + public static final String FILESIZE = "#FILESIZE#"; + + /** + * Current full path of current RULE + */ + public static final String RULE = "#RULE#"; + + /** + * Date in yyyyMMdd format + */ + public static final String DATE = "#DATE#"; + + /** + * Hour in HHmmss format + */ + public static final String HOUR = "#HOUR#"; + + /** + * Remote host id (if not the initiator of the call) + */ + public static final String REMOTEHOST = "#REMOTEHOST#"; + + /** + * Remote host address + */ + public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#"; + + /** + * Local host id + */ + public static final String LOCALHOST = "#LOCALHOST#"; + + /** + * Local host address + */ + public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#"; + + /** + * Transfer id + */ + public static final String TRANSFERID = "#TRANSFERID#"; + + /** + * Requester Host + */ + public static final String REQUESTERHOST = "#REQUESTERHOST#"; + + /** + * Requested Host + */ + public static final String REQUESTEDHOST = "#REQUESTEDHOST#"; + + /** + * Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST) + */ + public static final String FULLTRANSFERID = "#FULLTRANSFERID#"; + + /** + * Current or final RANK of block + */ + public static final String RANKTRANSFER = "#RANKTRANSFER#"; + + /** + * Block size used + */ + public static final String BLOCKSIZE = "#BLOCKSIZE#"; + + /** + * IN Path used + */ + public static final String INPATH = "#INPATH#"; + + /** + * OUT Path used + */ + public static final String OUTPATH = "#OUTPATH#"; + + /** + * WORK Path used + */ + public static final String WORKPATH = "#WORKPATH#"; + + /** + * ARCH Path used + */ + public static final String ARCHPATH = "#ARCHPATH#"; + + /** + * HOME Path used + */ + public static final String HOMEPATH = "#HOMEPATH#"; + /** + * Last Current Error Message + */ + public static final String ERRORMSG = "#ERRORMSG#"; + /** + * Last Current Error Code + */ + public static final String ERRORCODE = "#ERRORCODE#"; + /** + * Last Current Error Code in Full String + */ + public static final String ERRORSTRCODE = "#ERRORSTRCODE#"; + /** + * If specified, no Wait for Task Validation (default is wait) + */ + public static final String NOWAIT = "#NOWAIT#"; + /** + * If specified, use the LocalExec Daemon specified in the global configuration (default no + * usage of LocalExec) + */ + public static final String LOCALEXEC = "#LOCALEXEC#"; + /** + * Delimiter for -count option in Reschedule to be placed in the info of transfer as + * #CPTLIMIT#limit#CPTLIMIT# where limit is an integer. + */ + public static final String CPTLIMIT = "#CPTLIMIT#"; + + /** + * Type of operation + */ + final TaskType type; + + /** + * Argument from Rule + */ + final String argRule; + + /** + * Delay from Rule (if applicable) + */ + final int delay; + + /** + * Argument from Transfer + */ + final String argTransfer; + + /** + * Current session + */ + final R66Session session; + + /** + * R66Future of completion + */ + final R66Future futureCompletion; + /** + * Do we wait for a validation of the task ? Default = True + */ + boolean waitForValidation = true; + /** + * Do we need to use LocalExec for an Exec Task ? Default = False + */ + boolean useLocalExec = false; + + /** + * Constructor + * + * @param type + * @param delay + * @param arg + * @param session + */ + AbstractTask(TaskType type, int delay, String argRule, String argTransfer, + R66Session session) { + this.type = type; + this.delay = delay; + this.argRule = argRule; + this.argTransfer = argTransfer; + this.session = session; + futureCompletion = new R66Future(true); + } + + /** + * This is the only interface to execute an operator. + */ + abstract public void run(); + + /** + * + * @return True if the operation is in success status + */ + public boolean isSuccess() { + futureCompletion.awaitUninterruptibly(); + return futureCompletion.isSuccess(); + } + + /** + * + * @return the R66Future of completion + */ + public R66Future getFutureCompletion() { + return futureCompletion; + } + + /** + * + * @param arg + * as the Format string where FIXED items will be replaced by context values and next + * using argFormat as format second argument; this arg comes from the rule itself + * @param argFormat + * as format second argument; this argFormat comes from the transfer Information + * itself + * @return The string with replaced values from context and second argument + */ + protected String getReplacedValue(String arg, Object[] argFormat) { + StringBuilder builder = new StringBuilder(arg); + // check NOWAIT and LOCALEXEC + if (arg.contains(NOWAIT)) { + waitForValidation = false; + WaarpStringUtils.replaceAll(builder, NOWAIT, ""); + } + if (arg.contains(LOCALEXEC)) { + useLocalExec = true; + WaarpStringUtils.replaceAll(builder, LOCALEXEC, ""); + } + File trueFile = null; + if (session.getFile() != null) { + trueFile = session.getFile().getTrueFile(); + } + if (trueFile != null) { + WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath()); + WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir + .getFinalUniqueFilename(session.getFile())); + WaarpStringUtils.replaceAll(builder, FILESIZE, Long.toString(trueFile.length())); + } else { + WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile"); + WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile"); + WaarpStringUtils.replaceAll(builder, FILESIZE, "0"); + } + WaarpStringUtils.replaceAll(builder, ORIGINALFULLPATH, session.getRunner() + .getOriginalFilename()); + WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, + R66File.getBasename(session.getRunner() + .getOriginalFilename())); + WaarpStringUtils.replaceAll(builder, RULE, session.getRunner() + .getRuleId()); + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date)); + dateFormat = new SimpleDateFormat("HHmmss"); + WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date)); + if (session.getAuth() != null) { + WaarpStringUtils.replaceAll(builder, REMOTEHOST, session.getAuth().getUser()); + try { + WaarpStringUtils.replaceAll(builder, LOCALHOST, + Configuration.configuration.getHostId(session.getAuth().isSsl())); + } catch (OpenR66ProtocolNoSslException e) { + // replace by standard name + WaarpStringUtils.replaceAll(builder, LOCALHOST, + Configuration.configuration.HOST_ID); + } + } + if (session.getRemoteAddress() != null) { + WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, session.getRemoteAddress() + .toString()); + WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, session.getLocalAddress() + .toString()); + } else { + WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown"); + WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown"); + } + WaarpStringUtils.replaceAll(builder, TRANSFERID, Long.toString(session + .getRunner().getSpecialId())); + String requester = session.getRunner().getRequester(); + WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester); + String requested = session.getRunner().getRequested(); + WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested); + WaarpStringUtils.replaceAll(builder, FULLTRANSFERID, session + .getRunner().getSpecialId() + "_" + requester + "_" + requested); + WaarpStringUtils.replaceAll(builder, RANKTRANSFER, Integer.toString(session + .getRunner().getRank())); + WaarpStringUtils.replaceAll(builder, BLOCKSIZE, Integer.toString(session + .getBlockSize())); + R66Dir dir = new R66Dir(session); + if (session.getRunner().isRecvThrough() || session.getRunner().isSendThrough()) { + try { + dir.changeDirectoryNotChecked(session.getRunner().getRule().recvPath); + WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectoryNotChecked(session.getRunner().getRule().sendPath); + WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectoryNotChecked(session.getRunner().getRule().workPath); + WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectoryNotChecked(session.getRunner().getRule().archivePath); + WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + } else { + try { + dir.changeDirectoryNotChecked(session.getRunner().getRule().recvPath); + WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectory(session.getRunner().getRule().sendPath); + WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectory(session.getRunner().getRule().workPath); + WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + dir = new R66Dir(session); + try { + dir.changeDirectory(session.getRunner().getRule().archivePath); + WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath()); + } catch (CommandAbstractException e) { + } + } + WaarpStringUtils.replaceAll(builder, HOMEPATH, Configuration.configuration.baseDirectory); + if (session.getLocalChannelReference() == null) { + WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError"); + WaarpStringUtils.replaceAll(builder, ERRORCODE, "-"); + WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name()); + } else { + try { + WaarpStringUtils.replaceAll(builder, ERRORMSG, session.getLocalChannelReference() + .getErrorMessage()); + } catch (NullPointerException e) { + WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError"); + } + try { + WaarpStringUtils.replaceAll(builder, ERRORCODE, session.getLocalChannelReference() + .getCurrentCode().getCode()); + } catch (NullPointerException e) { + WaarpStringUtils.replaceAll(builder, ERRORCODE, "-"); + } + try { + WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, session + .getLocalChannelReference().getCurrentCode().name()); + } catch (NullPointerException e) { + WaarpStringUtils.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name()); + } + } + // finalname + if (argFormat != null && argFormat.length > 0) + return String.format(builder.toString(), argFormat); + return builder.toString(); + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/AllLineReader.java b/src/main/java/org/waarp/openr66/context/task/AllLineReader.java index 83f02f5fc..5cb189124 100644 --- a/src/main/java/org/waarp/openr66/context/task/AllLineReader.java +++ b/src/main/java/org/waarp/openr66/context/task/AllLineReader.java @@ -1,63 +1,63 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; - -/** - * This class is used with external process in order to get the All echo from the stdout of the - * process. - * - * @author Frederic Bregier - * - */ -class AllLineReader implements Runnable { - private final BufferedReader reader; - /** - * This will be the result at the end - */ - public StringBuilder lastLine = new StringBuilder(); - - public AllLineReader(PipedInputStream inputStream) { - reader = new BufferedReader(new InputStreamReader(inputStream)); - } - - public void run() { - String line; - try { - while ((line = reader.readLine()) != null) { - line = line.trim(); - if (line.length() > 0) { - lastLine.append(line).append('\n'); - } - } - } catch (IOException e) { - // Could be a "Write end dead", which means the end of the thread - // writer is found - // before the thread closes the write pipe - } - try { - reader.close(); - } catch (IOException e) { - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; + +/** + * This class is used with external process in order to get the All echo from the stdout of the + * process. + * + * @author Frederic Bregier + * + */ +class AllLineReader implements Runnable { + private final BufferedReader reader; + /** + * This will be the result at the end + */ + public StringBuilder lastLine = new StringBuilder(); + + public AllLineReader(PipedInputStream inputStream) { + reader = new BufferedReader(new InputStreamReader(inputStream)); + } + + public void run() { + String line; + try { + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.length() > 0) { + lastLine.append(line).append('\n'); + } + } + } catch (IOException e) { + // Could be a "Write end dead", which means the end of the thread + // writer is found + // before the thread closes the write pipe + } + try { + reader.close(); + } catch (IOException e) { + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/CopyRenameTask.java b/src/main/java/org/waarp/openr66/context/task/CopyRenameTask.java index 1cef68ade..6f4cb1621 100644 --- a/src/main/java/org/waarp/openr66/context/task/CopyRenameTask.java +++ b/src/main/java/org/waarp/openr66/context/task/CopyRenameTask.java @@ -1,75 +1,75 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Copy and Rename task - * - * @author Frederic Bregier - * - */ -public class CopyRenameTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(CopyRenameTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public CopyRenameTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.COPYRENAME, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - logger.info("Copy and Rename to " + finalname + " with " + argRule + - ":" + argTransfer + " and {}", session); - File from = session.getFile().getTrueFile(); - File to = new File(finalname); - try { - FileUtils.copy(from, to, false, false); - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Copy and Rename to " + finalname + " with " + - argRule + ":" + argTransfer + " and " + session, e1); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); - return; - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Copy and Rename task + * + * @author Frederic Bregier + * + */ +public class CopyRenameTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(CopyRenameTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public CopyRenameTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.COPYRENAME, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + logger.info("Copy and Rename to " + finalname + " with " + argRule + + ":" + argTransfer + " and {}", session); + File from = session.getFile().getTrueFile(); + File to = new File(finalname); + try { + FileUtils.copy(from, to, false, false); + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Copy and Rename to " + finalname + " with " + + argRule + ":" + argTransfer + " and " + session, e1); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); + return; + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/CopyTask.java b/src/main/java/org/waarp/openr66/context/task/CopyTask.java index 685a22f96..a0981c422 100644 --- a/src/main/java/org/waarp/openr66/context/task/CopyTask.java +++ b/src/main/java/org/waarp/openr66/context/task/CopyTask.java @@ -1,73 +1,73 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Copy task - * - * @author Frederic Bregier - * - */ -public class CopyTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(CopyTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public CopyTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.COPY, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("Copy with " + argRule + ":" + argTransfer + " and {}", - session); - File from = session.getFile().getTrueFile(); - File to = new File(argRule + session.getFile().getBasename()); - try { - FileUtils.copy(from, to, false, false); - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Copy with " + argRule + ":" + argTransfer + " and " + - session, e1); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); - return; - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Copy task + * + * @author Frederic Bregier + * + */ +public class CopyTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(CopyTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public CopyTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.COPY, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("Copy with " + argRule + ":" + argTransfer + " and {}", + session); + File from = session.getFile().getTrueFile(); + File to = new File(argRule + session.getFile().getBasename()); + try { + FileUtils.copy(from, to, false, false); + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Copy with " + argRule + ":" + argTransfer + " and " + + session, e1); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); + return; + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/DeleteTask.java b/src/main/java/org/waarp/openr66/context/task/DeleteTask.java index 7c96ba952..47281d157 100644 --- a/src/main/java/org/waarp/openr66/context/task/DeleteTask.java +++ b/src/main/java/org/waarp/openr66/context/task/DeleteTask.java @@ -1,75 +1,75 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * Delete the file. The current file is no more valid.
- * No arguments are taken into account. - * - * @author Frederic Bregier - * - */ -public class DeleteTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(DeleteTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public DeleteTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.DELETE, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("Delete file from session {}", - session); - try { - session.getFile().delete(); - } catch (CommandAbstractException e1) { - logger.debug("CANNOT Delete file from session {}", - session, e1); - R66Result result = new R66Result(session, false, - ErrorCode.FileNotFound, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); - return; - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * Delete the file. The current file is no more valid.
+ * No arguments are taken into account. + * + * @author Frederic Bregier + * + */ +public class DeleteTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(DeleteTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public DeleteTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.DELETE, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("Delete file from session {}", + session); + try { + session.getFile().delete(); + } catch (CommandAbstractException e1) { + logger.debug("CANNOT Delete file from session {}", + session, e1); + R66Result result = new R66Result(session, false, + ErrorCode.FileNotFound, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); + return; + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/ExecJavaTask.java b/src/main/java/org/waarp/openr66/context/task/ExecJavaTask.java index 3b0202367..1e277973e 100644 --- a/src/main/java/org/waarp/openr66/context/task/ExecJavaTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ExecJavaTask.java @@ -1,153 +1,153 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; - -/** - * Execute a Java command through Class.forName call - * - * - * @author Frederic Bregier - * - */ -public class ExecJavaTask extends AbstractTask { - - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ExecJavaTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ExecJavaTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.EXECJAVA, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - /* - * First apply all replacements and format to argRule from context and argTransfer. Will - * call exec (from first element of resulting string) with arguments as the following value - * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change - * should be done in the FILENAME - */ - logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - if (argTransfer != null) { - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - } - // First get the Class Name - String[] args = finalname.split(" "); - String className = args[0]; - R66Runnable runnable = null; - try { - runnable = (R66Runnable) Class.forName(className).newInstance(); - } catch (Exception e) { - logger.error("ExecJava command is not available: " + className, e); - R66Result result = new R66Result(session, false, - ErrorCode.CommandNotFound, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.cancel(); - return; - } - runnable.setArgs(this.session, this.waitForValidation, this.useLocalExec, - this.delay, args); - logger.debug(className + " " + runnable.getClass().getName()); - if (!waitForValidation) { - // Do not wait for validation - futureCompletion.setSuccess(); - logger.info("Exec will start but no WAIT with {}", runnable); - } - int status = -1; - if (waitForValidation && delay <= 0) { - runnable.run(); - status = runnable.getFinalStatus(); - } else { - ExecutorService executorService = Executors.newFixedThreadPool(1); - executorService.execute(runnable); - try { - Thread.yield(); - executorService.shutdown(); - if (waitForValidation) { - if (delay > 0) { - if (!executorService.awaitTermination(delay, TimeUnit.MILLISECONDS)) { - executorService.shutdownNow(); - logger.error("Exec is in Time Out"); - status = -1; - } else { - status = runnable.getFinalStatus(); - } - } else { - while (!executorService.awaitTermination(30, TimeUnit.SECONDS)) - ; - status = runnable.getFinalStatus(); - } - } else { - while (!executorService.awaitTermination(30, TimeUnit.SECONDS)) - ; - status = runnable.getFinalStatus(); - } - } catch (InterruptedException e) { - logger.error("Status: " + e.getMessage() + "\n\t Exec in error with " + - runnable); - if (waitForValidation) { - futureCompletion.cancel(); - } - return; - } - } - if (status == 0) { - if (waitForValidation) { - futureCompletion.setSuccess(); - } - logger.info("Exec OK with {}", runnable); - } else if (status == 1) { - logger.warn("Exec in warning with " + runnable); - if (waitForValidation) { - futureCompletion.setSuccess(); - } - } else { - logger.error("Status: " + status + " Exec in error with " + - runnable); - if (waitForValidation) { - futureCompletion.cancel(); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; + +/** + * Execute a Java command through Class.forName call + * + * + * @author Frederic Bregier + * + */ +public class ExecJavaTask extends AbstractTask { + + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ExecJavaTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ExecJavaTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.EXECJAVA, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + /* + * First apply all replacements and format to argRule from context and argTransfer. Will + * call exec (from first element of resulting string) with arguments as the following value + * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change + * should be done in the FILENAME + */ + logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + if (argTransfer != null) { + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + } + // First get the Class Name + String[] args = finalname.split(" "); + String className = args[0]; + R66Runnable runnable = null; + try { + runnable = (R66Runnable) Class.forName(className).newInstance(); + } catch (Exception e) { + logger.error("ExecJava command is not available: " + className, e); + R66Result result = new R66Result(session, false, + ErrorCode.CommandNotFound, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.cancel(); + return; + } + runnable.setArgs(this.session, this.waitForValidation, this.useLocalExec, + this.delay, args); + logger.debug(className + " " + runnable.getClass().getName()); + if (!waitForValidation) { + // Do not wait for validation + futureCompletion.setSuccess(); + logger.info("Exec will start but no WAIT with {}", runnable); + } + int status = -1; + if (waitForValidation && delay <= 0) { + runnable.run(); + status = runnable.getFinalStatus(); + } else { + ExecutorService executorService = Executors.newFixedThreadPool(1); + executorService.execute(runnable); + try { + Thread.yield(); + executorService.shutdown(); + if (waitForValidation) { + if (delay > 0) { + if (!executorService.awaitTermination(delay, TimeUnit.MILLISECONDS)) { + executorService.shutdownNow(); + logger.error("Exec is in Time Out"); + status = -1; + } else { + status = runnable.getFinalStatus(); + } + } else { + while (!executorService.awaitTermination(30, TimeUnit.SECONDS)) + ; + status = runnable.getFinalStatus(); + } + } else { + while (!executorService.awaitTermination(30, TimeUnit.SECONDS)) + ; + status = runnable.getFinalStatus(); + } + } catch (InterruptedException e) { + logger.error("Status: " + e.getMessage() + "\n\t Exec in error with " + + runnable); + if (waitForValidation) { + futureCompletion.cancel(); + } + return; + } + } + if (status == 0) { + if (waitForValidation) { + futureCompletion.setSuccess(); + } + logger.info("Exec OK with {}", runnable); + } else if (status == 1) { + logger.warn("Exec in warning with " + runnable); + if (waitForValidation) { + futureCompletion.setSuccess(); + } + } else { + logger.error("Status: " + status + " Exec in error with " + + runnable); + if (waitForValidation) { + futureCompletion.cancel(); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/ExecMoveTask.java b/src/main/java/org/waarp/openr66/context/task/ExecMoveTask.java index 4da7a7c3a..ff5f7b96f 100644 --- a/src/main/java/org/waarp/openr66/context/task/ExecMoveTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ExecMoveTask.java @@ -1,298 +1,298 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.ExecuteException; -import org.apache.commons.exec.ExecuteWatchdog; -import org.apache.commons.exec.PumpStreamHandler; -import org.waarp.commandexec.utils.LocalExecResult; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Execute an external command and Rename the file (using the new name from the result).
- * - * The move of the file (if any) should be done by the external command itself.
- *
- * - * waitForValidation (#NOWAIT#) must not be set since it will prevent to have the MOVE TASK to occur - * normally. So even if set, the #NOWAIT# will be ignored. - * - * @author Frederic Bregier - * - */ -public class ExecMoveTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ExecMoveTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ExecMoveTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.EXECMOVE, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - /* - * First apply all replacements and format to argRule from context and argTransfer. Will - * call exec (from first element of resulting string) with arguments as the following value - * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last - * line of stdout will be the new name given to the R66File in case of status 0. The - * previous file should be deleted by the script or will be deleted in case of status 0. If - * the status is 1, no change is made to the file. - */ - logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - // Force the WaitForValidation - waitForValidation = true; - if (Configuration.configuration.useLocalExec && useLocalExec) { - LocalExecClient localExecClient = new LocalExecClient(); - if (localExecClient.connect()) { - localExecClient - .runOneCommand(finalname, delay, waitForValidation, futureCompletion); - LocalExecResult result = localExecClient.getLocalExecResult(); - move(result.status, result.result, finalname); - localExecClient.disconnect(); - return; - } // else continue - } - String[] args = finalname.split(" "); - File exec = new File(args[0]); - if (exec.isAbsolute()) { - if (!exec.canExecute()) { - logger.error("Exec command is not executable: " + finalname); - R66Result result = new R66Result(session, false, - ErrorCode.CommandNotFound, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.cancel(); - return; - } - } - CommandLine commandLine = new CommandLine(args[0]); - for (int i = 1; i < args.length; i++) { - commandLine.addArgument(args[i]); - } - DefaultExecutor defaultExecutor = new DefaultExecutor(); - PipedInputStream inputStream = new PipedInputStream(); - PipedOutputStream outputStream = null; - try { - outputStream = new PipedOutputStream(inputStream); - } catch (IOException e1) { - try { - inputStream.close(); - } catch (IOException e) { - } - logger.error("Exception: " + e1.getMessage() + - " Exec in error with " + commandLine.toString(), e1); - futureCompletion.setFailure(e1); - return; - } - PumpStreamHandler pumpStreamHandler = new PumpStreamHandler( - outputStream, null); - defaultExecutor.setStreamHandler(pumpStreamHandler); - int[] correctValues = { - 0, 1 }; - defaultExecutor.setExitValues(correctValues); - ExecuteWatchdog watchdog = null; - - if (delay > 0) { - watchdog = new ExecuteWatchdog(delay); - defaultExecutor.setWatchdog(watchdog); - } - LastLineReader lastLineReader = new LastLineReader(inputStream); - Thread thread = new Thread(lastLineReader, "ExecRename" - + session.getRunner().getSpecialId()); - thread.setDaemon(true); - Configuration.configuration.getExecutorService().execute(thread); - int status = -1; - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e) { - if (e.getExitValue() == -559038737) { - // Cannot run immediately so retry once - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e1) { - } - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e1) { - try { - outputStream.close(); - } catch (IOException e2) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e2) { - } - pumpStreamHandler.stop(); - logger.error("ExecuteException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } catch (IOException e1) { - try { - outputStream.close(); - } catch (IOException e2) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e2) { - } - pumpStreamHandler.stop(); - logger.error("IOException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } - } else { - try { - outputStream.close(); - } catch (IOException e1) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e1) { - } - pumpStreamHandler.stop(); - logger.error("ExecuteException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } - } catch (IOException e) { - try { - outputStream.close(); - } catch (IOException e1) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e1) { - } - pumpStreamHandler.stop(); - logger.error("IOException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } - try { - outputStream.flush(); - } catch (IOException e) { - } - try { - outputStream.close(); - } catch (IOException e) { - } - pumpStreamHandler.stop(); - try { - if (delay > 0) { - thread.join(delay); - } else { - thread.join(); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - try { - inputStream.close(); - } catch (IOException e1) { - } - String newname = null; - if (defaultExecutor.isFailure(status) && watchdog != null && - watchdog.killedProcess()) { - // kill by the watchdoc (time out) - status = -1; - newname = "TimeOut"; - } else { - newname = lastLineReader.lastLine; - if (status == 0 && (newname == null || newname.length() == 0)) { - status = 1; - } - } - move(status, newname, commandLine.toString()); - } - - private void move(int status, String newName, String commandLine) { - String newname = newName; - if (status == 0) { - if (newname.indexOf(' ') > 0) { - logger.warn("Exec returns a multiple string in final line: " + - newname); - String[] args = newname.split(" "); - newname = args[args.length - 1]; - } - // now test if the previous file was deleted (should be) - File file = new File(newname); - if (!file.exists()) { - logger.warn("New file does not exist at the end of the exec: " + newname); - } - // now replace the file with the new one - try { - session.getFile().replaceFilename(newname, true); - } catch (CommandAbstractException e) { - logger - .warn("Exec in warning with " + commandLine, - e); - } - session.getRunner().setFileMoved(newname, true); - futureCompletion.setSuccess(); - logger.info("Exec OK with {} returns {}", commandLine, - newname); - } else if (status == 1) { - logger.warn("Exec in warning with " + commandLine + - " returns " + newname); - session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); - futureCompletion.setSuccess(); - } else { - logger.error("Status: " + status + " Exec in error with " + - commandLine + " returns " + newname); - futureCompletion.cancel(); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteException; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.exec.PumpStreamHandler; +import org.waarp.commandexec.utils.LocalExecResult; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Execute an external command and Rename the file (using the new name from the result).
+ * + * The move of the file (if any) should be done by the external command itself.
+ *
+ * + * waitForValidation (#NOWAIT#) must not be set since it will prevent to have the MOVE TASK to occur + * normally. So even if set, the #NOWAIT# will be ignored. + * + * @author Frederic Bregier + * + */ +public class ExecMoveTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ExecMoveTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ExecMoveTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.EXECMOVE, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + /* + * First apply all replacements and format to argRule from context and argTransfer. Will + * call exec (from first element of resulting string) with arguments as the following value + * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last + * line of stdout will be the new name given to the R66File in case of status 0. The + * previous file should be deleted by the script or will be deleted in case of status 0. If + * the status is 1, no change is made to the file. + */ + logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + // Force the WaitForValidation + waitForValidation = true; + if (Configuration.configuration.useLocalExec && useLocalExec) { + LocalExecClient localExecClient = new LocalExecClient(); + if (localExecClient.connect()) { + localExecClient + .runOneCommand(finalname, delay, waitForValidation, futureCompletion); + LocalExecResult result = localExecClient.getLocalExecResult(); + move(result.status, result.result, finalname); + localExecClient.disconnect(); + return; + } // else continue + } + String[] args = finalname.split(" "); + File exec = new File(args[0]); + if (exec.isAbsolute()) { + if (!exec.canExecute()) { + logger.error("Exec command is not executable: " + finalname); + R66Result result = new R66Result(session, false, + ErrorCode.CommandNotFound, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.cancel(); + return; + } + } + CommandLine commandLine = new CommandLine(args[0]); + for (int i = 1; i < args.length; i++) { + commandLine.addArgument(args[i]); + } + DefaultExecutor defaultExecutor = new DefaultExecutor(); + PipedInputStream inputStream = new PipedInputStream(); + PipedOutputStream outputStream = null; + try { + outputStream = new PipedOutputStream(inputStream); + } catch (IOException e1) { + try { + inputStream.close(); + } catch (IOException e) { + } + logger.error("Exception: " + e1.getMessage() + + " Exec in error with " + commandLine.toString(), e1); + futureCompletion.setFailure(e1); + return; + } + PumpStreamHandler pumpStreamHandler = new PumpStreamHandler( + outputStream, null); + defaultExecutor.setStreamHandler(pumpStreamHandler); + int[] correctValues = { + 0, 1 }; + defaultExecutor.setExitValues(correctValues); + ExecuteWatchdog watchdog = null; + + if (delay > 0) { + watchdog = new ExecuteWatchdog(delay); + defaultExecutor.setWatchdog(watchdog); + } + LastLineReader lastLineReader = new LastLineReader(inputStream); + Thread thread = new Thread(lastLineReader, "ExecRename" + + session.getRunner().getSpecialId()); + thread.setDaemon(true); + Configuration.configuration.getExecutorService().execute(thread); + int status = -1; + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e) { + if (e.getExitValue() == -559038737) { + // Cannot run immediately so retry once + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e1) { + } + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e1) { + try { + outputStream.close(); + } catch (IOException e2) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e2) { + } + pumpStreamHandler.stop(); + logger.error("ExecuteException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } catch (IOException e1) { + try { + outputStream.close(); + } catch (IOException e2) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e2) { + } + pumpStreamHandler.stop(); + logger.error("IOException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } + } else { + try { + outputStream.close(); + } catch (IOException e1) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e1) { + } + pumpStreamHandler.stop(); + logger.error("ExecuteException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } + } catch (IOException e) { + try { + outputStream.close(); + } catch (IOException e1) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e1) { + } + pumpStreamHandler.stop(); + logger.error("IOException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } + try { + outputStream.flush(); + } catch (IOException e) { + } + try { + outputStream.close(); + } catch (IOException e) { + } + pumpStreamHandler.stop(); + try { + if (delay > 0) { + thread.join(delay); + } else { + thread.join(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + try { + inputStream.close(); + } catch (IOException e1) { + } + String newname = null; + if (defaultExecutor.isFailure(status) && watchdog != null && + watchdog.killedProcess()) { + // kill by the watchdoc (time out) + status = -1; + newname = "TimeOut"; + } else { + newname = lastLineReader.lastLine; + if (status == 0 && (newname == null || newname.length() == 0)) { + status = 1; + } + } + move(status, newname, commandLine.toString()); + } + + private void move(int status, String newName, String commandLine) { + String newname = newName; + if (status == 0) { + if (newname.indexOf(' ') > 0) { + logger.warn("Exec returns a multiple string in final line: " + + newname); + String[] args = newname.split(" "); + newname = args[args.length - 1]; + } + // now test if the previous file was deleted (should be) + File file = new File(newname); + if (!file.exists()) { + logger.warn("New file does not exist at the end of the exec: " + newname); + } + // now replace the file with the new one + try { + session.getFile().replaceFilename(newname, true); + } catch (CommandAbstractException e) { + logger + .warn("Exec in warning with " + commandLine, + e); + } + session.getRunner().setFileMoved(newname, true); + futureCompletion.setSuccess(); + logger.info("Exec OK with {} returns {}", commandLine, + newname); + } else if (status == 1) { + logger.warn("Exec in warning with " + commandLine + + " returns " + newname); + session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); + futureCompletion.setSuccess(); + } else { + logger.error("Status: " + status + " Exec in error with " + + commandLine + " returns " + newname); + futureCompletion.cancel(); + } + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/ExecOutputTask.java b/src/main/java/org/waarp/openr66/context/task/ExecOutputTask.java index 02ea543ed..22b33a2ba 100644 --- a/src/main/java/org/waarp/openr66/context/task/ExecOutputTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ExecOutputTask.java @@ -1,340 +1,340 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.ExecuteException; -import org.apache.commons.exec.ExecuteWatchdog; -import org.apache.commons.exec.PumpStreamHandler; -import org.waarp.commandexec.utils.LocalExecResult; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Execute an external command and Use the output if an error occurs.
- * - * The output is ignored if the command has a correct status.
- * If the output finishes with NEWFINALNAME:xxx then this part is removed from the output - * and the xxx is used as the last valid name for the file (meaning the file was moved or renamed)
- *
- * - * waitForValidation (#NOWAIT#) must not be set since it will prevent to have the feedback in case - * of error. So it is ignored. - * - * @author Frederic Bregier - * - */ -public class ExecOutputTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ExecOutputTask.class); - - public static final String DELIMITER = "NEWFINALNAME:"; - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ExecOutputTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.EXECOUTPUT, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - /* - * First apply all replacements and format to argRule from context and argTransfer. Will - * call exec (from first element of resulting string) with arguments as the following value - * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of - * an error (> 0), all the line from output will be send back to the partner with the Error - * code. No change is made to the file. - */ - logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - // Force the WaitForValidation - waitForValidation = true; - if (Configuration.configuration.useLocalExec && useLocalExec) { - LocalExecClient localExecClient = new LocalExecClient(); - if (localExecClient.connect()) { - localExecClient - .runOneCommand(finalname, delay, waitForValidation, futureCompletion); - LocalExecResult result = localExecClient.getLocalExecResult(); - finalize(result.status, result.result, finalname); - localExecClient.disconnect(); - return; - } // else continue - } - String[] args = finalname.split(" "); - File exec = new File(args[0]); - if (exec.isAbsolute()) { - if (!exec.canExecute()) { - logger.error("Exec command is not executable: " + finalname); - R66Result result = new R66Result(session, false, - ErrorCode.CommandNotFound, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.cancel(); - return; - } - } - CommandLine commandLine = new CommandLine(args[0]); - for (int i = 1; i < args.length; i++) { - commandLine.addArgument(args[i]); - } - DefaultExecutor defaultExecutor = new DefaultExecutor(); - PipedInputStream inputStream = new PipedInputStream(); - PipedOutputStream outputStream = null; - try { - outputStream = new PipedOutputStream(inputStream); - } catch (IOException e1) { - try { - inputStream.close(); - } catch (IOException e) { - } - logger.error("Exception: " + e1.getMessage() + - " Exec in error with " + commandLine.toString(), e1); - futureCompletion.setFailure(e1); - return; - } - PumpStreamHandler pumpStreamHandler = new PumpStreamHandler( - outputStream, null); - defaultExecutor.setStreamHandler(pumpStreamHandler); - int[] correctValues = { - 0, 1 }; - defaultExecutor.setExitValues(correctValues); - ExecuteWatchdog watchdog = null; - if (delay > 0) { - watchdog = new ExecuteWatchdog(delay); - defaultExecutor.setWatchdog(watchdog); - } - AllLineReader allLineReader = new AllLineReader(inputStream); - Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId()); - thread.setDaemon(true); - Configuration.configuration.getExecutorService().execute(thread); - int status = -1; - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e) { - if (e.getExitValue() == -559038737) { - // Cannot run immediately so retry once - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e1) { - } - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e1) { - finalizeFromError(outputStream, - pumpStreamHandler, - inputStream, - allLineReader, - thread, - status, - commandLine); - return; - } catch (IOException e1) { - try { - outputStream.flush(); - } catch (IOException e2) { - } - try { - outputStream.close(); - } catch (IOException e2) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e2) { - } - pumpStreamHandler.stop(); - logger.error("IOException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } - } else { - finalizeFromError(outputStream, - pumpStreamHandler, - inputStream, - allLineReader, - thread, - status, - commandLine); - return; - } - } catch (IOException e) { - try { - outputStream.close(); - } catch (IOException e1) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e1) { - } - pumpStreamHandler.stop(); - logger.error("IOException: " + e.getMessage() + - " . Exec in error with " + commandLine.toString()); - futureCompletion.setFailure(e); - return; - } - try { - outputStream.flush(); - } catch (IOException e) { - } - try { - outputStream.close(); - } catch (IOException e) { - } - pumpStreamHandler.stop(); - try { - if (delay > 0) { - thread.join(delay); - } else { - thread.join(); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - try { - inputStream.close(); - } catch (IOException e1) { - } - String newname = null; - if (defaultExecutor.isFailure(status) && watchdog != null && - watchdog.killedProcess()) { - // kill by the watchdoc (time out) - status = -1; - newname = "TimeOut"; - } else { - newname = allLineReader.lastLine.toString(); - } - finalize(status, newname, commandLine.toString()); - } - - private void finalize(int status, String newName, String commandLine) { - String newname = newName; - if (status == 0) { - futureCompletion.setSuccess(); - logger.info("Exec OK with {} returns {}", commandLine, - newname); - } else if (status == 1) { - logger.warn("Exec in warning with " + commandLine + - " returns " + newname); - session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); - futureCompletion.setSuccess(); - } else { - int pos = newname.lastIndexOf(DELIMITER); - if (pos >= 0) { - String newfilename = newname.substring(pos + DELIMITER.length()); - newname = newname.substring(0, pos); - if (newfilename.indexOf(' ') > 0) { - logger.warn("Exec returns a multiple string in final line: " + - newfilename); - String[] args = newfilename.split(" "); - newfilename = args[args.length - 1]; - } - // now test if the previous file was deleted (should be) - File file = new File(newfilename); - if (!file.exists()) { - logger.warn("New file does not exist at the end of the exec: " + newfilename); - } - // now replace the file with the new one - try { - session.getFile().replaceFilename(newfilename, true); - } catch (CommandAbstractException e) { - logger - .warn("Exec in warning with " + commandLine, - e); - } - session.getRunner().setFileMoved(newfilename, true); - } - logger.error("Status: " + status + " Exec in error with " + - commandLine + " returns " + newname); - OpenR66RunnerErrorException exc = - new OpenR66RunnerErrorException("" + status + "" - + newname + ""); - futureCompletion.setFailure(exc); - } - } - - private void finalizeFromError(PipedOutputStream outputStream, - PumpStreamHandler pumpStreamHandler, - PipedInputStream inputStream, AllLineReader allLineReader, Thread thread, - int status, CommandLine commandLine) { - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - try { - outputStream.flush(); - } catch (IOException e2) { - } - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - try { - outputStream.close(); - } catch (IOException e1) { - } - thread.interrupt(); - try { - inputStream.close(); - } catch (IOException e1) { - } - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - pumpStreamHandler.stop(); - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - String result = allLineReader.lastLine.toString(); - logger.error("Status: " + status + " Exec in error with " + - commandLine + " returns\n" + result); - OpenR66RunnerErrorException exc = - new OpenR66RunnerErrorException("" + status + "" + result - + ""); - futureCompletion.setFailure(exc); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteException; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.exec.PumpStreamHandler; +import org.waarp.commandexec.utils.LocalExecResult; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Execute an external command and Use the output if an error occurs.
+ * + * The output is ignored if the command has a correct status.
+ * If the output finishes with NEWFINALNAME:xxx then this part is removed from the output + * and the xxx is used as the last valid name for the file (meaning the file was moved or renamed)
+ *
+ * + * waitForValidation (#NOWAIT#) must not be set since it will prevent to have the feedback in case + * of error. So it is ignored. + * + * @author Frederic Bregier + * + */ +public class ExecOutputTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ExecOutputTask.class); + + public static final String DELIMITER = "NEWFINALNAME:"; + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ExecOutputTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.EXECOUTPUT, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + /* + * First apply all replacements and format to argRule from context and argTransfer. Will + * call exec (from first element of resulting string) with arguments as the following value + * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of + * an error (> 0), all the line from output will be send back to the partner with the Error + * code. No change is made to the file. + */ + logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + // Force the WaitForValidation + waitForValidation = true; + if (Configuration.configuration.useLocalExec && useLocalExec) { + LocalExecClient localExecClient = new LocalExecClient(); + if (localExecClient.connect()) { + localExecClient + .runOneCommand(finalname, delay, waitForValidation, futureCompletion); + LocalExecResult result = localExecClient.getLocalExecResult(); + finalize(result.status, result.result, finalname); + localExecClient.disconnect(); + return; + } // else continue + } + String[] args = finalname.split(" "); + File exec = new File(args[0]); + if (exec.isAbsolute()) { + if (!exec.canExecute()) { + logger.error("Exec command is not executable: " + finalname); + R66Result result = new R66Result(session, false, + ErrorCode.CommandNotFound, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.cancel(); + return; + } + } + CommandLine commandLine = new CommandLine(args[0]); + for (int i = 1; i < args.length; i++) { + commandLine.addArgument(args[i]); + } + DefaultExecutor defaultExecutor = new DefaultExecutor(); + PipedInputStream inputStream = new PipedInputStream(); + PipedOutputStream outputStream = null; + try { + outputStream = new PipedOutputStream(inputStream); + } catch (IOException e1) { + try { + inputStream.close(); + } catch (IOException e) { + } + logger.error("Exception: " + e1.getMessage() + + " Exec in error with " + commandLine.toString(), e1); + futureCompletion.setFailure(e1); + return; + } + PumpStreamHandler pumpStreamHandler = new PumpStreamHandler( + outputStream, null); + defaultExecutor.setStreamHandler(pumpStreamHandler); + int[] correctValues = { + 0, 1 }; + defaultExecutor.setExitValues(correctValues); + ExecuteWatchdog watchdog = null; + if (delay > 0) { + watchdog = new ExecuteWatchdog(delay); + defaultExecutor.setWatchdog(watchdog); + } + AllLineReader allLineReader = new AllLineReader(inputStream); + Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId()); + thread.setDaemon(true); + Configuration.configuration.getExecutorService().execute(thread); + int status = -1; + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e) { + if (e.getExitValue() == -559038737) { + // Cannot run immediately so retry once + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e1) { + } + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e1) { + finalizeFromError(outputStream, + pumpStreamHandler, + inputStream, + allLineReader, + thread, + status, + commandLine); + return; + } catch (IOException e1) { + try { + outputStream.flush(); + } catch (IOException e2) { + } + try { + outputStream.close(); + } catch (IOException e2) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e2) { + } + pumpStreamHandler.stop(); + logger.error("IOException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } + } else { + finalizeFromError(outputStream, + pumpStreamHandler, + inputStream, + allLineReader, + thread, + status, + commandLine); + return; + } + } catch (IOException e) { + try { + outputStream.close(); + } catch (IOException e1) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e1) { + } + pumpStreamHandler.stop(); + logger.error("IOException: " + e.getMessage() + + " . Exec in error with " + commandLine.toString()); + futureCompletion.setFailure(e); + return; + } + try { + outputStream.flush(); + } catch (IOException e) { + } + try { + outputStream.close(); + } catch (IOException e) { + } + pumpStreamHandler.stop(); + try { + if (delay > 0) { + thread.join(delay); + } else { + thread.join(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + try { + inputStream.close(); + } catch (IOException e1) { + } + String newname = null; + if (defaultExecutor.isFailure(status) && watchdog != null && + watchdog.killedProcess()) { + // kill by the watchdoc (time out) + status = -1; + newname = "TimeOut"; + } else { + newname = allLineReader.lastLine.toString(); + } + finalize(status, newname, commandLine.toString()); + } + + private void finalize(int status, String newName, String commandLine) { + String newname = newName; + if (status == 0) { + futureCompletion.setSuccess(); + logger.info("Exec OK with {} returns {}", commandLine, + newname); + } else if (status == 1) { + logger.warn("Exec in warning with " + commandLine + + " returns " + newname); + session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); + futureCompletion.setSuccess(); + } else { + int pos = newname.lastIndexOf(DELIMITER); + if (pos >= 0) { + String newfilename = newname.substring(pos + DELIMITER.length()); + newname = newname.substring(0, pos); + if (newfilename.indexOf(' ') > 0) { + logger.warn("Exec returns a multiple string in final line: " + + newfilename); + String[] args = newfilename.split(" "); + newfilename = args[args.length - 1]; + } + // now test if the previous file was deleted (should be) + File file = new File(newfilename); + if (!file.exists()) { + logger.warn("New file does not exist at the end of the exec: " + newfilename); + } + // now replace the file with the new one + try { + session.getFile().replaceFilename(newfilename, true); + } catch (CommandAbstractException e) { + logger + .warn("Exec in warning with " + commandLine, + e); + } + session.getRunner().setFileMoved(newfilename, true); + } + logger.error("Status: " + status + " Exec in error with " + + commandLine + " returns " + newname); + OpenR66RunnerErrorException exc = + new OpenR66RunnerErrorException("" + status + "" + + newname + ""); + futureCompletion.setFailure(exc); + } + } + + private void finalizeFromError(PipedOutputStream outputStream, + PumpStreamHandler pumpStreamHandler, + PipedInputStream inputStream, AllLineReader allLineReader, Thread thread, + int status, CommandLine commandLine) { + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + try { + outputStream.flush(); + } catch (IOException e2) { + } + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + try { + outputStream.close(); + } catch (IOException e1) { + } + thread.interrupt(); + try { + inputStream.close(); + } catch (IOException e1) { + } + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + pumpStreamHandler.stop(); + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + String result = allLineReader.lastLine.toString(); + logger.error("Status: " + status + " Exec in error with " + + commandLine + " returns\n" + result); + OpenR66RunnerErrorException exc = + new OpenR66RunnerErrorException("" + status + "" + result + + ""); + futureCompletion.setFailure(exc); + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/ExecTask.java b/src/main/java/org/waarp/openr66/context/task/ExecTask.java index eea369436..e84f8c543 100644 --- a/src/main/java/org/waarp/openr66/context/task/ExecTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ExecTask.java @@ -1,194 +1,194 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.ExecuteException; -import org.apache.commons.exec.ExecuteWatchdog; -import org.apache.commons.exec.PumpStreamHandler; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Execute an external command - * - * - * @author Frederic Bregier - * - */ -public class ExecTask extends AbstractTask { - - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ExecTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ExecTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.EXEC, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - /* - * First apply all replacements and format to argRule from context and argTransfer. Will - * call exec (from first element of resulting string) with arguments as the following value - * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change - * should be done in the FILENAME - */ - logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - // Check if the execution will be done through LocalExec daemon - if (Configuration.configuration.useLocalExec && useLocalExec) { - LocalExecClient localExecClient = new LocalExecClient(); - if (localExecClient.connect()) { - localExecClient - .runOneCommand(finalname, delay, waitForValidation, futureCompletion); - localExecClient.disconnect(); - return; - }// else continue - } - // Execution is done internally - String[] args = finalname.split(" "); - File exec = new File(args[0]); - if (exec.isAbsolute()) { - if (!exec.canExecute()) { - logger.error("Exec command is not executable: " + finalname); - R66Result result = new R66Result(session, false, - ErrorCode.CommandNotFound, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.cancel(); - return; - } - } - CommandLine commandLine = new CommandLine(args[0]); - for (int i = 1; i < args.length; i++) { - commandLine.addArgument(args[i]); - } - DefaultExecutor defaultExecutor = new DefaultExecutor(); - PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); - defaultExecutor.setStreamHandler(pumpStreamHandler); - int[] correctValues = { - 0, 1 }; - defaultExecutor.setExitValues(correctValues); - ExecuteWatchdog watchdog = null; - if (delay > 0 && waitForValidation) { - watchdog = new ExecuteWatchdog(delay); - defaultExecutor.setWatchdog(watchdog); - } - if (!waitForValidation) { - // Do not wait for validation - futureCompletion.setSuccess(); - logger.info("Exec will start but no WAIT with {}", commandLine); - } - int status = -1; - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e) { - if (e.getExitValue() == -559038737) { - // Cannot run immediately so retry once - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e1) { - } - try { - status = defaultExecutor.execute(commandLine); - } catch (ExecuteException e1) { - pumpStreamHandler.stop(); - logger.error("Exception: " + e.getMessage() + - " Exec in error with " + commandLine.toString()); - if (waitForValidation) { - futureCompletion.setFailure(e); - } - return; - } catch (IOException e1) { - pumpStreamHandler.stop(); - logger.error("Exception: " + e.getMessage() + - " Exec in error with " + commandLine.toString()); - if (waitForValidation) { - futureCompletion.setFailure(e); - } - return; - } - } else { - pumpStreamHandler.stop(); - logger.error("Exception: " + e.getMessage() + - " Exec in error with " + commandLine.toString()); - if (waitForValidation) { - futureCompletion.setFailure(e); - } - return; - } - } catch (IOException e) { - pumpStreamHandler.stop(); - logger.error("Exception: " + e.getMessage() + - " Exec in error with " + commandLine.toString()); - if (waitForValidation) { - futureCompletion.setFailure(e); - } - return; - } - pumpStreamHandler.stop(); - if (defaultExecutor.isFailure(status) && watchdog != null && - watchdog.killedProcess()) { - // kill by the watchdoc (time out) - logger.error("Exec is in Time Out"); - status = -1; - } - if (status == 0) { - if (waitForValidation) { - futureCompletion.setSuccess(); - } - logger.info("Exec OK with {}", commandLine); - } else if (status == 1) { - logger.warn("Exec in warning with " + commandLine.toString()); - if (waitForValidation) { - futureCompletion.setSuccess(); - } - } else { - logger.error("Status: " + status + " Exec in error with " + - commandLine.toString()); - if (waitForValidation) { - futureCompletion.cancel(); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteException; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.exec.PumpStreamHandler; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Execute an external command + * + * + * @author Frederic Bregier + * + */ +public class ExecTask extends AbstractTask { + + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ExecTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ExecTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.EXEC, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + /* + * First apply all replacements and format to argRule from context and argTransfer. Will + * call exec (from first element of resulting string) with arguments as the following value + * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change + * should be done in the FILENAME + */ + logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + // Check if the execution will be done through LocalExec daemon + if (Configuration.configuration.useLocalExec && useLocalExec) { + LocalExecClient localExecClient = new LocalExecClient(); + if (localExecClient.connect()) { + localExecClient + .runOneCommand(finalname, delay, waitForValidation, futureCompletion); + localExecClient.disconnect(); + return; + }// else continue + } + // Execution is done internally + String[] args = finalname.split(" "); + File exec = new File(args[0]); + if (exec.isAbsolute()) { + if (!exec.canExecute()) { + logger.error("Exec command is not executable: " + finalname); + R66Result result = new R66Result(session, false, + ErrorCode.CommandNotFound, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.cancel(); + return; + } + } + CommandLine commandLine = new CommandLine(args[0]); + for (int i = 1; i < args.length; i++) { + commandLine.addArgument(args[i]); + } + DefaultExecutor defaultExecutor = new DefaultExecutor(); + PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); + defaultExecutor.setStreamHandler(pumpStreamHandler); + int[] correctValues = { + 0, 1 }; + defaultExecutor.setExitValues(correctValues); + ExecuteWatchdog watchdog = null; + if (delay > 0 && waitForValidation) { + watchdog = new ExecuteWatchdog(delay); + defaultExecutor.setWatchdog(watchdog); + } + if (!waitForValidation) { + // Do not wait for validation + futureCompletion.setSuccess(); + logger.info("Exec will start but no WAIT with {}", commandLine); + } + int status = -1; + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e) { + if (e.getExitValue() == -559038737) { + // Cannot run immediately so retry once + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e1) { + } + try { + status = defaultExecutor.execute(commandLine); + } catch (ExecuteException e1) { + pumpStreamHandler.stop(); + logger.error("Exception: " + e.getMessage() + + " Exec in error with " + commandLine.toString()); + if (waitForValidation) { + futureCompletion.setFailure(e); + } + return; + } catch (IOException e1) { + pumpStreamHandler.stop(); + logger.error("Exception: " + e.getMessage() + + " Exec in error with " + commandLine.toString()); + if (waitForValidation) { + futureCompletion.setFailure(e); + } + return; + } + } else { + pumpStreamHandler.stop(); + logger.error("Exception: " + e.getMessage() + + " Exec in error with " + commandLine.toString()); + if (waitForValidation) { + futureCompletion.setFailure(e); + } + return; + } + } catch (IOException e) { + pumpStreamHandler.stop(); + logger.error("Exception: " + e.getMessage() + + " Exec in error with " + commandLine.toString()); + if (waitForValidation) { + futureCompletion.setFailure(e); + } + return; + } + pumpStreamHandler.stop(); + if (defaultExecutor.isFailure(status) && watchdog != null && + watchdog.killedProcess()) { + // kill by the watchdoc (time out) + logger.error("Exec is in Time Out"); + status = -1; + } + if (status == 0) { + if (waitForValidation) { + futureCompletion.setSuccess(); + } + logger.info("Exec OK with {}", commandLine); + } else if (status == 1) { + logger.warn("Exec in warning with " + commandLine.toString()); + if (waitForValidation) { + futureCompletion.setSuccess(); + } + } else { + logger.error("Status: " + status + " Exec in error with " + + commandLine.toString()); + if (waitForValidation) { + futureCompletion.cancel(); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/FtpTransferTask.java b/src/main/java/org/waarp/openr66/context/task/FtpTransferTask.java index df278433b..e2dcf5766 100644 --- a/src/main/java/org/waarp/openr66/context/task/FtpTransferTask.java +++ b/src/main/java/org/waarp/openr66/context/task/FtpTransferTask.java @@ -1,326 +1,326 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; - -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.ftp.client.WaarpFtp4jClient; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Ftp Transfer task: synchronous
- * - * Result of arguments will be as FTP command.
- * Format is the following:
- * "-file filepath
- * -to requestedHost
- * -port port
- * -user user
- * -pwd pwd
- * [-account account]
- * [-mode active/passive]
- * [-ssl no/implicit/explicit]
- * [-cwd remotepath]
- * [-digest (crc,md5,sha1)]
- * [-pre extraCommand1 with ',' as separator of arguments]
- * -command command from (get,put,append)
- * [-post extraCommand2 with ',' as separator of arguments]"
- *
- *
- * The order of commands will be:
- * 1) connection to requestHost on port (if ssl native => using native ssl link)
- * 2) User user
- * 3) PASS pwd
- * 4) if account => ACCT account
- * 5) if -ssl & auth => AUTH, PBSZ 0, PROT P
- * 6) if passive => PASV
- * 7) CWD remotepath; if error => MKD remotepath then CWD remotepath (and ignoring any error)
- * 8) if pre => extraCommand1 with ',' replaced by ' ' (note: do not use standard commands from FTP like - * ACCT,PASS,REIN,USER,APPE,STOR,STOU,RETR,RMD,RNFR,RNTO,ABOR,CWD,CDUP,MODE,PASV,PORT,STRU,TYPE,MDTM,MLSD,MLST,SIZE,AUTH)
- * 9) BINARY (binary format)
- * 10) if get => RETR filepath.basename ; if put => STOR filepath ; if append => APPE filepath.basename
- * 11) if digest & get/put/append & remote site compatible with XCRC,XMD5,XSHA1 - * => FEAT (parsing if found corresponding XCRC,XMD5,XSHA1) ; then XCRC/XMD5/XSHA1 filepath.basename ; - * then locally comparing this XCRC/XMD5/XSHA1 with the local file
- * 12) if post => extraCommand2 with ',' replaced by ' ' (note: do not use standard commands from FTP like - * ACCT,PASS,REIN,USER,APPE,STOR,STOU,RETR,RMD,RNFR,RNTO,ABOR,CWD,CDUP,MODE,PASV,PORT,STRU,TYPE,MDTM,MLSD,MLST,SIZE,AUTH)
- * 13) QUIT
- * - * @author Frederic Bregier - * - */ -public class FtpTransferTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(FtpTransferTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public FtpTransferTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.FTP, delay, argRule, argTransfer, session); - } - - @Override - public void run() { - logger.info("FtpTransfer with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - String[] args = finalname.split(" "); - if (args.length < 10) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Not enough argument in Transfer"); - R66Result result = new R66Result(exception, session, false, ErrorCode.CommandNotFound, session.getRunner()); - logger.error("Not enough arguments"); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - return; - } - String filepath = null; - String filename = null; - String requested = null; - int port = 21; - String user = null; - String pwd = null; - String acct = null; - boolean isPassive = true; - int ssl = 0; // -1 native, 1 auth - String cwd = null; - int digest = 0; // 1 CRC, 2 MD5, 3 SHA1 - String command = null; - int codeCommand = 0; // -1 get, 1 put, 2 append - String preArgs = null; - String postArgs = null; - /* - * "-file filepath
- * -to requestedHost
- * -port port
- * -user user
- * -pwd pwd
- * [-account account]
- * [-mode active/passive]
- * [-ssl no/implicit/explicit]
- * [-cwd remotepath]
- * [-digest (crc,md5,sha1)]
- * [-pre extraCommand1 with ',' as separator of arguments]
- * -command command from (get,put,append)
- * [-post extraCommand2 with ',' as separator of arguments]"
- */ - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-file")) { - i++; - filepath = args[i]; - filename = new File(filepath).getName(); - } else if (args[i].equalsIgnoreCase("-to")) { - i++; - requested = args[i]; - } else if (args[i].equalsIgnoreCase("-port")) { - i++; - port = Integer.parseInt(args[i]); - } else if (args[i].equalsIgnoreCase("-user")) { - i++; - user = args[i]; - } else if (args[i].equalsIgnoreCase("-pwd")) { - i++; - pwd = args[i]; - } else if (args[i].equalsIgnoreCase("-account")) { - i++; - acct = args[i]; - } else if (args[i].equalsIgnoreCase("-mode")) { - i++; - isPassive = (args[i].equalsIgnoreCase("passive")); - } else if (args[i].equalsIgnoreCase("-ssl")) { - i++; - if (args[i].equalsIgnoreCase("implicit")) { - ssl = -1; - } else if (args[i].equalsIgnoreCase("explicit")) { - ssl = 1; - } else { - ssl = 0; - } - } else if (args[i].equalsIgnoreCase("-cwd")) { - i++; - cwd = args[i]; - } else if (args[i].equalsIgnoreCase("-digest")) { - i++; - if (args[i].equalsIgnoreCase("crc")) { - digest = 1; - } else if (args[i].equalsIgnoreCase("md5")) { - digest = 2; - } else if (args[i].equalsIgnoreCase("sha1")) { - digest = 3; - } else { - digest = 0; - } - } else if (args[i].equalsIgnoreCase("-pre")) { - i++; - preArgs = args[i].replace(',', ' '); - } else if (args[i].equalsIgnoreCase("-post")) { - i++; - postArgs = args[i].replace(',', ' '); - } else if (args[i].equalsIgnoreCase("-command")) { - i++; - command = args[i]; - // get,put,append,list - // -1 get, 1 put, 2 append - if (command.equalsIgnoreCase("get")) { - codeCommand = -1; - } else if (command.equalsIgnoreCase("put")) { - codeCommand = 1; - } else if (command.equalsIgnoreCase("append")) { - codeCommand = 2; - } else { - // error - codeCommand = 0; - } - } - } - if (filepath == null || requested == null || port <= 0 || user == null || pwd == null || - codeCommand == 0) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Not enough argument in Transfer"); - R66Result result = new R66Result(exception, session, false, ErrorCode.CommandNotFound, session.getRunner()); - int code = 0 + - (filepath == null ? 1 : 0) + (requested == null ? 10 : 0) + - (port <= 0 ? 100 : 0) + (user == null ? 1000 : 0) + (pwd == null ? 10000 : 0) + - (codeCommand == 0 ? 100000 : 0); - logger.error("Not enough arguments: "+code); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - return; - } - WaarpFtp4jClient ftpClient = - new WaarpFtp4jClient(requested, port, user, pwd, acct, isPassive, ssl, - 5000, (int) Configuration.configuration.TIMEOUTCON); - boolean status = false; - for (int i = 0; i < Configuration.RETRYNB; i++) { - if (ftpClient.connect()) { - status = true; - break; - } - } - if (! status) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Cannot connect to remote FTP host"); - R66Result result = new R66Result(exception, session, false, ErrorCode.ConnectionImpossible, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - logger.error(ftpClient.getResult()); - return; - } - try { - if (cwd != null && !ftpClient.changeDir(cwd)) { - ftpClient.makeDir(cwd); - if (!ftpClient.changeDir(cwd)) { - logger.warn("Cannot change od directory: "+cwd); - } - } - if (preArgs != null) { - String [] result = ftpClient.executeCommand(preArgs); - for (String string : result) { - logger.debug("PRE: "+string); - } - } - if (! ftpClient.transferFile(filepath, filename, codeCommand)) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Cannot transfert file from/to remote FTP host"); - R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - logger.error(ftpClient.getResult()); - return; - } - if (digest > 0) { - // digest check - String params = null; - DigestAlgo algo = null; - switch (digest) { - case 1: // CRC - params = "XCRC "; - algo = DigestAlgo.CRC32; - break; - case 2: // MD5 - params = "XMD5 "; - algo = DigestAlgo.MD5; - break; - case 3: // SHA1 - params = "XSHA1 "; - algo = DigestAlgo.SHA1; - break; - } - params += filename; - String [] values = ftpClient.executeCommand(params); - String hashresult = null; - if (values != null) { - values = values[0].split(" "); - hashresult = (values.length > 3 ? values[1] : values[0]); - } - if (hashresult == null) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Hash cannot be computed while FTP transfer is done"); - R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - logger.error("Hash cannot be computed: "+ftpClient.getResult()); - return; - } - // now check locally - String hash; - try { - hash = FilesystemBasedDigest.getHex( - FilesystemBasedDigest.getHash(new File(filepath), false, algo)); - } catch (IOException e) { - hash = null; - } - if (hash == null || (!hash.equalsIgnoreCase(hashresult))) { - OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Hash not equal while FTP transfer is done"); - R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); - futureCompletion.setResult(result); - futureCompletion.setFailure(exception); - logger.error("Hash not equal: "+ftpClient.getResult()); - return; - } - } - if (postArgs != null) { - String [] result = ftpClient.executeCommand(postArgs); - for (String string : result) { - logger.debug("POST: "+string); - } - } - } finally { - ftpClient.logout(); - } - R66Result result = new R66Result(session, false, ErrorCode.TransferOk, session.getRunner()); - futureCompletion.setResult(result); - logger.info("FTP transfer in\n SUCCESS\n " + session.getRunner().toShortString() + - "\n " + requested + ""); - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; + +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.ftp.client.WaarpFtp4jClient; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Ftp Transfer task: synchronous
+ * + * Result of arguments will be as FTP command.
+ * Format is the following:
+ * "-file filepath
+ * -to requestedHost
+ * -port port
+ * -user user
+ * -pwd pwd
+ * [-account account]
+ * [-mode active/passive]
+ * [-ssl no/implicit/explicit]
+ * [-cwd remotepath]
+ * [-digest (crc,md5,sha1)]
+ * [-pre extraCommand1 with ',' as separator of arguments]
+ * -command command from (get,put,append)
+ * [-post extraCommand2 with ',' as separator of arguments]"
+ *
+ *
+ * The order of commands will be:
+ * 1) connection to requestHost on port (if ssl native => using native ssl link)
+ * 2) User user
+ * 3) PASS pwd
+ * 4) if account => ACCT account
+ * 5) if -ssl & auth => AUTH, PBSZ 0, PROT P
+ * 6) if passive => PASV
+ * 7) CWD remotepath; if error => MKD remotepath then CWD remotepath (and ignoring any error)
+ * 8) if pre => extraCommand1 with ',' replaced by ' ' (note: do not use standard commands from FTP like + * ACCT,PASS,REIN,USER,APPE,STOR,STOU,RETR,RMD,RNFR,RNTO,ABOR,CWD,CDUP,MODE,PASV,PORT,STRU,TYPE,MDTM,MLSD,MLST,SIZE,AUTH)
+ * 9) BINARY (binary format)
+ * 10) if get => RETR filepath.basename ; if put => STOR filepath ; if append => APPE filepath.basename
+ * 11) if digest & get/put/append & remote site compatible with XCRC,XMD5,XSHA1 + * => FEAT (parsing if found corresponding XCRC,XMD5,XSHA1) ; then XCRC/XMD5/XSHA1 filepath.basename ; + * then locally comparing this XCRC/XMD5/XSHA1 with the local file
+ * 12) if post => extraCommand2 with ',' replaced by ' ' (note: do not use standard commands from FTP like + * ACCT,PASS,REIN,USER,APPE,STOR,STOU,RETR,RMD,RNFR,RNTO,ABOR,CWD,CDUP,MODE,PASV,PORT,STRU,TYPE,MDTM,MLSD,MLST,SIZE,AUTH)
+ * 13) QUIT
+ * + * @author Frederic Bregier + * + */ +public class FtpTransferTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(FtpTransferTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public FtpTransferTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.FTP, delay, argRule, argTransfer, session); + } + + @Override + public void run() { + logger.info("FtpTransfer with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + String[] args = finalname.split(" "); + if (args.length < 10) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Not enough argument in Transfer"); + R66Result result = new R66Result(exception, session, false, ErrorCode.CommandNotFound, session.getRunner()); + logger.error("Not enough arguments"); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + return; + } + String filepath = null; + String filename = null; + String requested = null; + int port = 21; + String user = null; + String pwd = null; + String acct = null; + boolean isPassive = true; + int ssl = 0; // -1 native, 1 auth + String cwd = null; + int digest = 0; // 1 CRC, 2 MD5, 3 SHA1 + String command = null; + int codeCommand = 0; // -1 get, 1 put, 2 append + String preArgs = null; + String postArgs = null; + /* + * "-file filepath
+ * -to requestedHost
+ * -port port
+ * -user user
+ * -pwd pwd
+ * [-account account]
+ * [-mode active/passive]
+ * [-ssl no/implicit/explicit]
+ * [-cwd remotepath]
+ * [-digest (crc,md5,sha1)]
+ * [-pre extraCommand1 with ',' as separator of arguments]
+ * -command command from (get,put,append)
+ * [-post extraCommand2 with ',' as separator of arguments]"
+ */ + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-file")) { + i++; + filepath = args[i]; + filename = new File(filepath).getName(); + } else if (args[i].equalsIgnoreCase("-to")) { + i++; + requested = args[i]; + } else if (args[i].equalsIgnoreCase("-port")) { + i++; + port = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-user")) { + i++; + user = args[i]; + } else if (args[i].equalsIgnoreCase("-pwd")) { + i++; + pwd = args[i]; + } else if (args[i].equalsIgnoreCase("-account")) { + i++; + acct = args[i]; + } else if (args[i].equalsIgnoreCase("-mode")) { + i++; + isPassive = (args[i].equalsIgnoreCase("passive")); + } else if (args[i].equalsIgnoreCase("-ssl")) { + i++; + if (args[i].equalsIgnoreCase("implicit")) { + ssl = -1; + } else if (args[i].equalsIgnoreCase("explicit")) { + ssl = 1; + } else { + ssl = 0; + } + } else if (args[i].equalsIgnoreCase("-cwd")) { + i++; + cwd = args[i]; + } else if (args[i].equalsIgnoreCase("-digest")) { + i++; + if (args[i].equalsIgnoreCase("crc")) { + digest = 1; + } else if (args[i].equalsIgnoreCase("md5")) { + digest = 2; + } else if (args[i].equalsIgnoreCase("sha1")) { + digest = 3; + } else { + digest = 0; + } + } else if (args[i].equalsIgnoreCase("-pre")) { + i++; + preArgs = args[i].replace(',', ' '); + } else if (args[i].equalsIgnoreCase("-post")) { + i++; + postArgs = args[i].replace(',', ' '); + } else if (args[i].equalsIgnoreCase("-command")) { + i++; + command = args[i]; + // get,put,append,list + // -1 get, 1 put, 2 append + if (command.equalsIgnoreCase("get")) { + codeCommand = -1; + } else if (command.equalsIgnoreCase("put")) { + codeCommand = 1; + } else if (command.equalsIgnoreCase("append")) { + codeCommand = 2; + } else { + // error + codeCommand = 0; + } + } + } + if (filepath == null || requested == null || port <= 0 || user == null || pwd == null || + codeCommand == 0) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Not enough argument in Transfer"); + R66Result result = new R66Result(exception, session, false, ErrorCode.CommandNotFound, session.getRunner()); + int code = 0 + + (filepath == null ? 1 : 0) + (requested == null ? 10 : 0) + + (port <= 0 ? 100 : 0) + (user == null ? 1000 : 0) + (pwd == null ? 10000 : 0) + + (codeCommand == 0 ? 100000 : 0); + logger.error("Not enough arguments: "+code); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + return; + } + WaarpFtp4jClient ftpClient = + new WaarpFtp4jClient(requested, port, user, pwd, acct, isPassive, ssl, + 5000, (int) Configuration.configuration.TIMEOUTCON); + boolean status = false; + for (int i = 0; i < Configuration.RETRYNB; i++) { + if (ftpClient.connect()) { + status = true; + break; + } + } + if (! status) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Cannot connect to remote FTP host"); + R66Result result = new R66Result(exception, session, false, ErrorCode.ConnectionImpossible, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + logger.error(ftpClient.getResult()); + return; + } + try { + if (cwd != null && !ftpClient.changeDir(cwd)) { + ftpClient.makeDir(cwd); + if (!ftpClient.changeDir(cwd)) { + logger.warn("Cannot change od directory: "+cwd); + } + } + if (preArgs != null) { + String [] result = ftpClient.executeCommand(preArgs); + for (String string : result) { + logger.debug("PRE: "+string); + } + } + if (! ftpClient.transferFile(filepath, filename, codeCommand)) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Cannot transfert file from/to remote FTP host"); + R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + logger.error(ftpClient.getResult()); + return; + } + if (digest > 0) { + // digest check + String params = null; + DigestAlgo algo = null; + switch (digest) { + case 1: // CRC + params = "XCRC "; + algo = DigestAlgo.CRC32; + break; + case 2: // MD5 + params = "XMD5 "; + algo = DigestAlgo.MD5; + break; + case 3: // SHA1 + params = "XSHA1 "; + algo = DigestAlgo.SHA1; + break; + } + params += filename; + String [] values = ftpClient.executeCommand(params); + String hashresult = null; + if (values != null) { + values = values[0].split(" "); + hashresult = (values.length > 3 ? values[1] : values[0]); + } + if (hashresult == null) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Hash cannot be computed while FTP transfer is done"); + R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + logger.error("Hash cannot be computed: "+ftpClient.getResult()); + return; + } + // now check locally + String hash; + try { + hash = FilesystemBasedDigest.getHex( + FilesystemBasedDigest.getHash(new File(filepath), false, algo)); + } catch (IOException e) { + hash = null; + } + if (hash == null || (!hash.equalsIgnoreCase(hashresult))) { + OpenR66RunnerErrorException exception = new OpenR66RunnerErrorException("Hash not equal while FTP transfer is done"); + R66Result result = new R66Result(exception, session, false, ErrorCode.TransferError, session.getRunner()); + futureCompletion.setResult(result); + futureCompletion.setFailure(exception); + logger.error("Hash not equal: "+ftpClient.getResult()); + return; + } + } + if (postArgs != null) { + String [] result = ftpClient.executeCommand(postArgs); + for (String string : result) { + logger.debug("POST: "+string); + } + } + } finally { + ftpClient.logout(); + } + R66Result result = new R66Result(session, false, ErrorCode.TransferOk, session.getRunner()); + futureCompletion.setResult(result); + logger.info("FTP transfer in\n SUCCESS\n " + session.getRunner().toShortString() + + "\n " + requested + ""); + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/LastLineReader.java b/src/main/java/org/waarp/openr66/context/task/LastLineReader.java index b9ea0dd2b..55809a8db 100644 --- a/src/main/java/org/waarp/openr66/context/task/LastLineReader.java +++ b/src/main/java/org/waarp/openr66/context/task/LastLineReader.java @@ -1,63 +1,63 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; - -/** - * This class is used with external process in order to get the last echo from the stdout of the - * process. - * - * @author Frederic Bregier - * - */ -class LastLineReader implements Runnable { - private final BufferedReader reader; - /** - * This will be the result at the end - */ - public String lastLine = null; - - public LastLineReader(PipedInputStream inputStream) { - reader = new BufferedReader(new InputStreamReader(inputStream)); - } - - public void run() { - String line; - try { - while ((line = reader.readLine()) != null) { - line = line.trim(); - if (line.length() > 0) { - lastLine = line; - } - } - } catch (IOException e) { - // Could be a "Write end dead", which means the end of the thread - // writer is found - // before the thread closes the write pipe - } - try { - reader.close(); - } catch (IOException e) { - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; + +/** + * This class is used with external process in order to get the last echo from the stdout of the + * process. + * + * @author Frederic Bregier + * + */ +class LastLineReader implements Runnable { + private final BufferedReader reader; + /** + * This will be the result at the end + */ + public String lastLine = null; + + public LastLineReader(PipedInputStream inputStream) { + reader = new BufferedReader(new InputStreamReader(inputStream)); + } + + public void run() { + String line; + try { + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.length() > 0) { + lastLine = line; + } + } + } catch (IOException e) { + // Could be a "Write end dead", which means the end of the thread + // writer is found + // before the thread closes the write pipe + } + try { + reader.close(); + } catch (IOException e) { + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/LinkRenameTask.java b/src/main/java/org/waarp/openr66/context/task/LinkRenameTask.java index cf001b4fa..c90eebbaf 100644 --- a/src/main/java/org/waarp/openr66/context/task/LinkRenameTask.java +++ b/src/main/java/org/waarp/openr66/context/task/LinkRenameTask.java @@ -1,81 +1,81 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Create a link of the current file and make the file pointing to it. - * - * The link first tries to be a hard link, then a soft link, and if really not possible (not - * supported by the filesystem), it does a copy and rename task. - * - * @author Frederic Bregier - * - */ -public class LinkRenameTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LinkRenameTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public LinkRenameTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.LINKRENAME, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - logger.info("Move and Rename to " + finalname + " with " + argRule + - ":" + argTransfer + " and {}", session); - // First try hard link - // FIXME wait for NIO.2 in JDK7 to have such functions, in the meantime only move... - File from = session.getFile().getTrueFile(); - File to = new File(finalname); - try { - FileUtils.copy(from, to, false, false); - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Copy and Rename to " + finalname + " with " + - argRule + ":" + argTransfer + " and " + session, e1); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); - return; - } - session.getRunner().setFileMoved(finalname, true); - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Create a link of the current file and make the file pointing to it. + * + * The link first tries to be a hard link, then a soft link, and if really not possible (not + * supported by the filesystem), it does a copy and rename task. + * + * @author Frederic Bregier + * + */ +public class LinkRenameTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LinkRenameTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public LinkRenameTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.LINKRENAME, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + logger.info("Move and Rename to " + finalname + " with " + argRule + + ":" + argTransfer + " and {}", session); + // First try hard link + // FIXME wait for NIO.2 in JDK7 to have such functions, in the meantime only move... + File from = session.getFile().getTrueFile(); + File to = new File(finalname); + try { + FileUtils.copy(from, to, false, false); + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Copy and Rename to " + finalname + " with " + + argRule + ":" + argTransfer + " and " + session, e1); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e1)); + return; + } + session.getRunner().setFileMoved(finalname, true); + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/LogTask.java b/src/main/java/org/waarp/openr66/context/task/LogTask.java index e0f0ebf1b..aee1c7afb 100644 --- a/src/main/java/org/waarp/openr66/context/task/LogTask.java +++ b/src/main/java/org/waarp/openr66/context/task/LogTask.java @@ -1,146 +1,146 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.jboss.netty.logging.InternalLogLevel; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Session; - -/** - * This class is for logging or write to an external file some info:
- * - if delay is 0, no echo at all will be done
- * - if delay is 1, will echo some information in the normal log
- * - if delay is 2, will echo some information in the file (last deduced argument will be the full - * path for the file output)
- * - if delay is 3, will echo both in the normal log and in the file (last deduced argument will be - * the full path for the file output)
- *
- * If first word for logging is one of debug, info, warn, error, then the corresponding - * level of log will be used. - * - * @author Frederic Bregier - * - */ -public class LogTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LogTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public LogTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.LOG, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - String finalValue = argRule; - finalValue = getReplacedValue(finalValue, argTransfer.split(" ")); - String tempValue = finalValue.toUpperCase(); - InternalLogLevel finalLevel = InternalLogLevel.WARN; - for (InternalLogLevel level : InternalLogLevel.values()) { - if (tempValue.startsWith(level.name())) { - finalLevel = level; - break; - } - } - switch (delay) { - case 0: - break; - case 1: - logger.log(finalLevel, finalValue + "\n " + session.toString()); - break; - case 3: - logger.log(finalLevel, finalValue + "\n " + session.toString()); - case 2: - String[] args = finalValue.split(" "); - String filename = args[args.length - 1]; - File file = new File(filename); - if (file.getParentFile() == null || - (file.exists() && !file.canWrite())) { - // File cannot be written so revert to log - session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); - if (delay == 2) { - logger.log(finalLevel, finalValue + "\n " + session.toString()); - } - futureCompletion.setSuccess(); - return; - } - FileOutputStream outputStream = null; - try { - outputStream = new FileOutputStream(file, true); - } catch (FileNotFoundException e) { - // File cannot be written so revert to log - session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); - if (delay == 2) { - logger.log(finalLevel, finalValue + "\n " + session.toString()); - } - futureCompletion.setSuccess(); - return; - } - try { - int len = args.length -1; - for (int i = 0; i < len; i++) { - outputStream.write(args[i].getBytes()); - outputStream.write(' '); - } - outputStream.write('\n'); - } catch (IOException e) { - // File cannot be written so revert to log - try { - outputStream.close(); - } catch (IOException e1) { - } - file.delete(); - session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); - if (delay == 2) { - logger.log(finalLevel, finalValue + "\n " + session.toString()); - } - futureCompletion.setSuccess(); - return; - } - try { - outputStream.close(); - } catch (IOException e) { - } - break; - default: - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.jboss.netty.logging.InternalLogLevel; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Session; + +/** + * This class is for logging or write to an external file some info:
+ * - if delay is 0, no echo at all will be done
+ * - if delay is 1, will echo some information in the normal log
+ * - if delay is 2, will echo some information in the file (last deduced argument will be the full + * path for the file output)
+ * - if delay is 3, will echo both in the normal log and in the file (last deduced argument will be + * the full path for the file output)
+ *
+ * If first word for logging is one of debug, info, warn, error, then the corresponding + * level of log will be used. + * + * @author Frederic Bregier + * + */ +public class LogTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LogTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public LogTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.LOG, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + String finalValue = argRule; + finalValue = getReplacedValue(finalValue, argTransfer.split(" ")); + String tempValue = finalValue.toUpperCase(); + InternalLogLevel finalLevel = InternalLogLevel.WARN; + for (InternalLogLevel level : InternalLogLevel.values()) { + if (tempValue.startsWith(level.name())) { + finalLevel = level; + break; + } + } + switch (delay) { + case 0: + break; + case 1: + logger.log(finalLevel, finalValue + "\n " + session.toString()); + break; + case 3: + logger.log(finalLevel, finalValue + "\n " + session.toString()); + case 2: + String[] args = finalValue.split(" "); + String filename = args[args.length - 1]; + File file = new File(filename); + if (file.getParentFile() == null || + (file.exists() && !file.canWrite())) { + // File cannot be written so revert to log + session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); + if (delay == 2) { + logger.log(finalLevel, finalValue + "\n " + session.toString()); + } + futureCompletion.setSuccess(); + return; + } + FileOutputStream outputStream = null; + try { + outputStream = new FileOutputStream(file, true); + } catch (FileNotFoundException e) { + // File cannot be written so revert to log + session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); + if (delay == 2) { + logger.log(finalLevel, finalValue + "\n " + session.toString()); + } + futureCompletion.setSuccess(); + return; + } + try { + int len = args.length -1; + for (int i = 0; i < len; i++) { + outputStream.write(args[i].getBytes()); + outputStream.write(' '); + } + outputStream.write('\n'); + } catch (IOException e) { + // File cannot be written so revert to log + try { + outputStream.close(); + } catch (IOException e1) { + } + file.delete(); + session.getRunner().setErrorExecutionStatus(ErrorCode.Warning); + if (delay == 2) { + logger.log(finalLevel, finalValue + "\n " + session.toString()); + } + futureCompletion.setSuccess(); + return; + } + try { + outputStream.close(); + } catch (IOException e) { + } + break; + default: + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/MoveRenameTask.java b/src/main/java/org/waarp/openr66/context/task/MoveRenameTask.java index 4971975b6..42b81bad9 100644 --- a/src/main/java/org/waarp/openr66/context/task/MoveRenameTask.java +++ b/src/main/java/org/waarp/openr66/context/task/MoveRenameTask.java @@ -1,80 +1,80 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * Move and Rename the current file - * - * @author Frederic Bregier - * - */ -public class MoveRenameTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(MoveRenameTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public MoveRenameTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.MOVERENAME, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - boolean success = false; - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")).split(" ")[0]; - logger.debug("Move and Rename to " + finalname + " with " + argRule + - ":" + argTransfer + " and {}", session); - try { - success = session.getFile().renameTo(finalname, true); - } catch (CommandAbstractException e) { - logger.error("Move and Rename to " + finalname + " with " + - argRule + ":" + argTransfer + " and " + session, e); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e)); - return; - } - if (success) { - session.getRunner().setFileMoved(finalname, success); - futureCompletion.setSuccess(); - } else { - logger.error("Cannot Move and Rename to " + finalname + " with " + - argRule + ":" + argTransfer + " and " + session); - futureCompletion.setFailure(new OpenR66ProtocolSystemException( - "Cannot move file")); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * Move and Rename the current file + * + * @author Frederic Bregier + * + */ +public class MoveRenameTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(MoveRenameTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public MoveRenameTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.MOVERENAME, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + boolean success = false; + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")).split(" ")[0]; + logger.debug("Move and Rename to " + finalname + " with " + argRule + + ":" + argTransfer + " and {}", session); + try { + success = session.getFile().renameTo(finalname, true); + } catch (CommandAbstractException e) { + logger.error("Move and Rename to " + finalname + " with " + + argRule + ":" + argTransfer + " and " + session, e); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e)); + return; + } + if (success) { + session.getRunner().setFileMoved(finalname, success); + futureCompletion.setSuccess(); + } else { + logger.error("Cannot Move and Rename to " + finalname + " with " + + argRule + ":" + argTransfer + " and " + session); + futureCompletion.setFailure(new OpenR66ProtocolSystemException( + "Cannot move file")); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/MoveTask.java b/src/main/java/org/waarp/openr66/context/task/MoveTask.java index b280a3839..522c573cd 100644 --- a/src/main/java/org/waarp/openr66/context/task/MoveTask.java +++ b/src/main/java/org/waarp/openr66/context/task/MoveTask.java @@ -1,83 +1,83 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * Move the file (without renaming it) - * - * @author Frederic Bregier - * - */ -public class MoveTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(MoveTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public MoveTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.MOVE, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("Move with " + argRule + ":" + argTransfer + " and {}", - session); - boolean success = false; - String directory = argRule; - directory = getReplacedValue(directory, argTransfer.split(" ")); - String finalname = directory.split(" ")[0] + R66Dir.SEPARATOR + - session.getFile().getBasename(); - try { - success = session.getFile().renameTo(finalname, true); - } catch (CommandAbstractException e) { - logger.error("Move with " + argRule + ":" + argTransfer + " to " + finalname + " and " + - session, e); - futureCompletion.setFailure(new OpenR66ProtocolSystemException(e)); - return; - } - if (success) { - session.getRunner().setFileMoved(finalname, success); - futureCompletion.setSuccess(); - } else { - logger.error("Cannot Move with " + argRule + ":" + argTransfer + " to " + finalname + - " and " + session); - futureCompletion.setFailure(new OpenR66ProtocolSystemException( - "Cannot move file")); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * Move the file (without renaming it) + * + * @author Frederic Bregier + * + */ +public class MoveTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(MoveTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public MoveTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.MOVE, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("Move with " + argRule + ":" + argTransfer + " and {}", + session); + boolean success = false; + String directory = argRule; + directory = getReplacedValue(directory, argTransfer.split(" ")); + String finalname = directory.split(" ")[0] + R66Dir.SEPARATOR + + session.getFile().getBasename(); + try { + success = session.getFile().renameTo(finalname, true); + } catch (CommandAbstractException e) { + logger.error("Move with " + argRule + ":" + argTransfer + " to " + finalname + " and " + + session, e); + futureCompletion.setFailure(new OpenR66ProtocolSystemException(e)); + return; + } + if (success) { + session.getRunner().setFileMoved(finalname, success); + futureCompletion.setSuccess(); + } else { + logger.error("Cannot Move with " + argRule + ":" + argTransfer + " to " + finalname + + " and " + session); + futureCompletion.setFailure(new OpenR66ProtocolSystemException( + "Cannot move file")); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/R66Runnable.java b/src/main/java/org/waarp/openr66/context/task/R66Runnable.java index 350fa6d63..6f924d1c8 100644 --- a/src/main/java/org/waarp/openr66/context/task/R66Runnable.java +++ b/src/main/java/org/waarp/openr66/context/task/R66Runnable.java @@ -1,59 +1,59 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.openr66.context.R66Session; - -/** - * Runnable interface for internal R66 tasks (through Rule EXECJAVA, or through message - * BusinessRequestPacket) - * - * @author Frederic Bregier - * - */ -public interface R66Runnable extends Runnable { - - /** - * The way the parameter will be set - * - * @param session - * The current R66Session - * @param waitForValidation - * True if the caller will wait up to delay time in ms - * @param useLocalExec - * True if currently R66 is configured to use LocalExec (may be ignored) - * @param delay - * Delay in ms used only if waitForValidation is True - * @param args - * First arg is the Class name used - */ - public void setArgs(R66Session session, boolean waitForValidation, - boolean useLocalExec, int delay, String[] args); - - /** - * - * @return the final status where 0 is OK, 1 is Warning, 2 is Error - */ - public int getFinalStatus(); - - /** - * - * @return Information on task - */ - public String toString(); -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.openr66.context.R66Session; + +/** + * Runnable interface for internal R66 tasks (through Rule EXECJAVA, or through message + * BusinessRequestPacket) + * + * @author Frederic Bregier + * + */ +public interface R66Runnable extends Runnable { + + /** + * The way the parameter will be set + * + * @param session + * The current R66Session + * @param waitForValidation + * True if the caller will wait up to delay time in ms + * @param useLocalExec + * True if currently R66 is configured to use LocalExec (may be ignored) + * @param delay + * Delay in ms used only if waitForValidation is True + * @param args + * First arg is the Class name used + */ + public void setArgs(R66Session session, boolean waitForValidation, + boolean useLocalExec, int delay, String[] args); + + /** + * + * @return the final status where 0 is OK, 1 is Warning, 2 is Error + */ + public int getFinalStatus(); + + /** + * + * @return Information on task + */ + public String toString(); +} diff --git a/src/main/java/org/waarp/openr66/context/task/RescheduleTransferTask.java b/src/main/java/org/waarp/openr66/context/task/RescheduleTransferTask.java index 5647c9f33..11ecd6e59 100644 --- a/src/main/java/org/waarp/openr66/context/task/RescheduleTransferTask.java +++ b/src/main/java/org/waarp/openr66/context/task/RescheduleTransferTask.java @@ -1,501 +1,501 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp. If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Date; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; - -/** - * Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error - * code is one of the specified codes and the optional intervals of date are compatible with the new - * time schedule
- *
- * - * Result of arguments will be as following options (the two first are mandatory):
- *
- * - * "-delay ms" where ms is the added number of ms on current time before retry on schedule
- *
- * "-case errorCode,errorCode,..." where errorCode is one of the following error of the current - * transfer (either literal or code in 1 character:
- * ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), - * MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), - * RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), - * QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), - * FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
- *
- * "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can - * be not set) and where start and stop are in the following format:
- * Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is - * optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
- * Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, - * while X=n or Xn means setting exact value
- * If one time specification is not set, it is based on the current date.
- *
- * "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule - * as "#CPTLIMIT#newlimit#CPTLIMIT#". Each time this function is called, the - * limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".
- * To ensure correctness, the value must be in the "info of transfer" since this value will be - * changed statically in the "info of transfer". If taken from the rule, it will be wrong since - * the value will never decrease. However, a value must be setup in the rule in order to reset the value - * when the count reach 0. - *
So in the rule, "-count resetlimit" must be present, where resetlimit will be - * the new value set when the limit reach 0, and in the "info on transfer", - * "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied. - *
- *
- * If "-notbetween" is specified, the planned date must not be in the area.
- * If "-between" is specified, the planned date must be found in any such specified areas (could be - * in any of the occurrence). If not specified, it only depends on "-notbetween".
- * If none is specified, the planned date is always valid.
- *
- * - * Note that if a previous called to a reschedule was done for this attempt and was successful, the - * following calls will be ignored.
- *
- * Important note: any subsequent task will be ignored and not executed once the reschedule is accepted.
- *
- * In case start > end, end will be +1 day
- * In case start and end < current planned date, both will have +1 day.
- *
- * - * Example: -delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween - * H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0
- * means retry in case of error during initialization of connection in 1 hour if not between 7AM to - * 7PM and not between 1AM to 3AM.
- * - * @author Frederic Bregier - * - */ -public class RescheduleTransferTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(RescheduleTransferTask.class); - - protected long newdate = 0; - - protected Calendar newDate = null; - - protected boolean countUsed = false; - - protected int limitCount = -1; - - protected int resetCount = -1; - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public RescheduleTransferTask(String argRule, int delay, - String argTransfer, R66Session session) { - super(TaskType.RESCHEDULE, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("Reschedule with " + argRule + ":" + argTransfer + - " and {}", session); - DbTaskRunner runner = session.getRunner(); - if (runner == null) { - futureCompletion.setFailure(new OpenR66RunnerErrorException( - "No valid runner in Reschedule")); - return; - } - if (runner.isRescheduledTransfer()) { - // Already rescheduled so ignore - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Transfer already Rescheduled: " + runner.toShortString()); - futureCompletion.setSuccess(); - return; - } - if (runner.isSelfRequested()) { - // Self Requested Request so reschedule is ignored - R66Result result = new R66Result(session, false, ErrorCode.LoopSelfRequestedHost, - runner); - futureCompletion.setResult(result); - futureCompletion.setFailure(new OpenR66RunnerErrorException( - "No valid runner in Reschedule since Self Requested")); - return; - } - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - String[] args = finalname.split(" "); - if (args.length < 4) { - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Not enough argument in Reschedule: " + runner.toShortString()); - futureCompletion.setSuccess(); - return; - } - if (!validateArgs(args)) { - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Reschedule unallowed due to argument: " + runner.toShortString()); - futureCompletion.setSuccess(); - return; - } - String newFileInformation = null; - if (countUsed) { - limitCount --; - if (limitCount >= 0) { - // restart is allowed so resetting to new limitCount - resetCount = limitCount; - } - newFileInformation = resetInformation(runner, resetCount); - if (limitCount < 0) { - // Must not reschedule since limit is reached - runner.setFileInformation(newFileInformation); - try { - runner.saveStatus(); - } catch (OpenR66RunnerErrorException e) { - } - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Reschedule unallowed due to limit reached: " + runner.toShortString()); - futureCompletion.setSuccess(); - return; - } - } - Timestamp start = new Timestamp(newdate); - try { - runner.setStart(start); - if (runner.restart(true)) { - runner.setFileInformation(newFileInformation); - runner.saveStatus(); - } - } catch (OpenR66RunnerErrorException e) { - logger.error( - "Prepare transfer in\n FAILURE\n " + - runner.toShortString() + "\n " + - (new Date(newdate)).toString() + "", e); - futureCompletion.setFailure(new OpenR66RunnerErrorException( - "Reschedule failed: " + e.getMessage(), e)); - return; - } - runner.setRescheduledTransfer(); - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Reschedule transfer in\n SUCCESS\n " + - runner.toShortString() + "\n " + - (new Date(newdate)).toString() + ""); - futureCompletion.setSuccess(); - } - - protected String resetInformation(DbTaskRunner runner, int value) { - String info = runner.getFileInformation(); - int pos = info.indexOf(CPTLIMIT); - if (pos >= 0) { - pos += CPTLIMIT.length(); - int endpos = info.indexOf(CPTLIMIT, pos); - if (endpos >= 0) { - // now string replace - String limit = info.substring(pos, endpos); - return info.replaceFirst(CPTLIMIT+limit+CPTLIMIT, CPTLIMIT+value+CPTLIMIT); - } - } - return info; - } - - protected boolean validateArgs(String[] args) { - boolean validCode = false; - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-delay")) { - i++; - try { - newdate = Long.parseLong(args[i]); - } catch (NumberFormatException e) { - logger.warn("Bad Long format: args[i]"); - return false; - } - } else if (args[i].equalsIgnoreCase("-case")) { - i++; - if (!validCode) { - String[] codes = args[i].split(","); - for (int j = 0; j < codes.length; j++) { - ErrorCode code = ErrorCode.getFromCode(codes[j]); - if (session.getLocalChannelReference().getCurrentCode() == code) { - logger.debug("Code valid: " + code); - validCode = true; - } - } - } - } else if (args[i].equalsIgnoreCase("-count")) { - i++; - try { - resetCount = Integer.parseInt(args[i]); - } catch (NumberFormatException e) { - logger.warn("ResetLimit is not an integer: "+args[i]); - countUsed = false; - return false; - } - String []find = argTransfer.split(CPTLIMIT); - if (find.length > 1) { - // should be 2nd value - try { - limitCount = Integer.parseInt(find[1]); - } catch (NumberFormatException e) { - logger.warn("Limit is not an integer: "+find[1]); - countUsed = false; - return false; - } - } - countUsed = true; - } - } - // now we have new delay plus code - if (!validCode) { - logger.warn("No valid Code found"); - return false; - } - if (newdate <= 0) { - logger.warn("Delay is negative: " + newdate); - return false; - } - newdate += System.currentTimeMillis(); - newDate = Calendar.getInstance(); - newDate.setTimeInMillis(newdate); - boolean betweenTest = false; - boolean betweenResult = false; - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-notbetween")) { - i++; - String[] elmts = args[i].split(";"); - boolean startModified = false; - String[] values = elmts[0].split(":"); - Calendar start = getCalendar(values); - if (start != null) { - startModified = true; - } else { - start = Calendar.getInstance(); - } - boolean stopModified = false; - values = elmts[1].split(":"); - Calendar stop = getCalendar(values); - if (stop != null) { - stopModified = true; - } else { - stop = Calendar.getInstance(); - } - logger.debug("Dates before check: Not between " + start.getTime() + " and " - + stop.getTime()); - // Check that start < stop - if (start.compareTo(stop) > 0) { - // no so add 24H to stop - stop.add(Calendar.DAY_OF_MONTH, 1); - } - // Check that start and stop > newDate (only start is checked since start <= stop) - if (start.compareTo(newDate) < 0) { - start.add(Calendar.DAY_OF_MONTH, 1); - stop.add(Calendar.DAY_OF_MONTH, 1); - } - logger.debug("Dates after check: Not between " + start.getTime() + " and " - + stop.getTime()); - if (!startModified) { - if (newDate.compareTo(stop) < 0) { - logger.debug("newDate: " + newDate.getTime() + " Should not be between " - + start.getTime() + " and " + stop.getTime()); - return false; - } - } else if (start.compareTo(newDate) < 0) { - if ((!stopModified) || (newDate.compareTo(stop) < 0)) { - logger.debug("newDate: " + newDate.getTime() + " Should not be between " - + start.getTime() + " and " + stop.getTime()); - return false; - } - } - } else if (args[i].equalsIgnoreCase("-between")) { - i++; - betweenTest = true; - String[] elmts = args[i].split(";"); - boolean startModified = false; - String[] values = elmts[0].split(":"); - Calendar start = getCalendar(values); - if (start != null) { - startModified = true; - } else { - start = Calendar.getInstance(); - } - boolean stopModified = false; - values = elmts[1].split(":"); - Calendar stop = getCalendar(values); - if (stop != null) { - stopModified = true; - } else { - stop = Calendar.getInstance(); - } - logger.debug("Dates before check: Between " + start.getTime() + " and " - + stop.getTime()); - // Check that start < stop - if (start.compareTo(stop) > 0) { - // no so add 24H to stop - stop.add(Calendar.DAY_OF_MONTH, 1); - } - // Check that start and stop > newDate (only start is checked since start <= stop) - if (start.compareTo(newDate) < 0) { - start.add(Calendar.DAY_OF_MONTH, 1); - stop.add(Calendar.DAY_OF_MONTH, 1); - } - logger.debug("Dates before check: Between " + start.getTime() + " and " - + stop.getTime()); - if (!startModified) { - if (newDate.compareTo(stop) < 0) { - logger.debug("newDate: " + newDate.getTime() + " is between " - + start.getTime() + " and " + stop.getTime()); - betweenResult = true; - } - } else if (start.compareTo(newDate) < 0) { - if ((!stopModified) || (newDate.compareTo(stop) < 0)) { - logger.debug("newDate: " + newDate.getTime() + " is between " - + start.getTime() + " and " + stop.getTime()); - betweenResult = true; - } - } - } - } - if (betweenTest) { - logger.debug("Since between is specified, do we found newDate: " + newDate.getTime() - + " Result: " + betweenResult); - return betweenResult; - } - logger.debug("newDate: " + newDate.getTime() + " rescheduled"); - return true; - } - - /** - * - * @param values - * as X+n or X-n or X=n or Xn where X=Y/M/D/H/m/s, n=number and +/- meaning - * adding/subtracting from current date and = meaning specific set value - * @return the Calendar if any specification, or null if no calendar specified - */ - private Calendar getCalendar(String[] values) { - Calendar newcal = Calendar.getInstance(); - boolean isModified = false; - for (int j = 0; j < values.length; j++) { - if (values[j].length() > 1) { - int addvalue = 0; // will be different of 0 - int value = -1; // will be >= 0 - switch (values[j].charAt(0)) { - case '+': - try { - addvalue = Integer.parseInt(values[j].substring(2)); - } catch (NumberFormatException e) { - continue; - } - break; - case '-': - try { - addvalue = Integer.parseInt(values[j].substring(1)); - } catch (NumberFormatException e) { - continue; - } - break; - case '=': - try { - value = Integer.parseInt(values[j].substring(2)); - } catch (NumberFormatException e) { - continue; - } - break; - default: // no sign - try { - value = Integer.parseInt(values[j].substring(1)); - } catch (NumberFormatException e) { - continue; - } - } - switch (values[j].charAt(0)) { - case 'Y': - if (value >= 0) { - newcal.set(Calendar.YEAR, value); - } else { - newcal.add(Calendar.YEAR, addvalue); - } - isModified = true; - break; - case 'M': - if (value >= 0) { - newcal.set(Calendar.MONTH, value); - } else { - newcal.add(Calendar.MONTH, addvalue); - } - isModified = true; - break; - case 'D': - if (value >= 0) { - newcal.set(Calendar.DAY_OF_MONTH, value); - } else { - newcal.add(Calendar.DAY_OF_MONTH, addvalue); - } - isModified = true; - break; - case 'H': - if (value >= 0) { - newcal.set(Calendar.HOUR_OF_DAY, value); - } else { - newcal.add(Calendar.HOUR_OF_DAY, addvalue); - } - isModified = true; - break; - case 'm': - if (value >= 0) { - newcal.set(Calendar.MINUTE, value); - } else { - newcal.add(Calendar.MINUTE, addvalue); - } - isModified = true; - break; - case 'S': - if (value >= 0) { - newcal.set(Calendar.SECOND, value); - } else { - newcal.add(Calendar.SECOND, addvalue); - } - isModified = true; - break; - } - } - } - if (isModified) - return newcal; - return null; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp. If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Date; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; + +/** + * Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error + * code is one of the specified codes and the optional intervals of date are compatible with the new + * time schedule
+ *
+ * + * Result of arguments will be as following options (the two first are mandatory):
+ *
+ * + * "-delay ms" where ms is the added number of ms on current time before retry on schedule
+ *
+ * "-case errorCode,errorCode,..." where errorCode is one of the following error of the current + * transfer (either literal or code in 1 character:
+ * ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), + * MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), + * RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), + * QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), + * FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
+ *
+ * "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can + * be not set) and where start and stop are in the following format:
+ * Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is + * optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
+ * Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, + * while X=n or Xn means setting exact value
+ * If one time specification is not set, it is based on the current date.
+ *
+ * "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule + * as "#CPTLIMIT#newlimit#CPTLIMIT#". Each time this function is called, the + * limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".
+ * To ensure correctness, the value must be in the "info of transfer" since this value will be + * changed statically in the "info of transfer". If taken from the rule, it will be wrong since + * the value will never decrease. However, a value must be setup in the rule in order to reset the value + * when the count reach 0. + *
So in the rule, "-count resetlimit" must be present, where resetlimit will be + * the new value set when the limit reach 0, and in the "info on transfer", + * "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied. + *
+ *
+ * If "-notbetween" is specified, the planned date must not be in the area.
+ * If "-between" is specified, the planned date must be found in any such specified areas (could be + * in any of the occurrence). If not specified, it only depends on "-notbetween".
+ * If none is specified, the planned date is always valid.
+ *
+ * + * Note that if a previous called to a reschedule was done for this attempt and was successful, the + * following calls will be ignored.
+ *
+ * Important note: any subsequent task will be ignored and not executed once the reschedule is accepted.
+ *
+ * In case start > end, end will be +1 day
+ * In case start and end < current planned date, both will have +1 day.
+ *
+ * + * Example: -delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween + * H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0
+ * means retry in case of error during initialization of connection in 1 hour if not between 7AM to + * 7PM and not between 1AM to 3AM.
+ * + * @author Frederic Bregier + * + */ +public class RescheduleTransferTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(RescheduleTransferTask.class); + + protected long newdate = 0; + + protected Calendar newDate = null; + + protected boolean countUsed = false; + + protected int limitCount = -1; + + protected int resetCount = -1; + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public RescheduleTransferTask(String argRule, int delay, + String argTransfer, R66Session session) { + super(TaskType.RESCHEDULE, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("Reschedule with " + argRule + ":" + argTransfer + + " and {}", session); + DbTaskRunner runner = session.getRunner(); + if (runner == null) { + futureCompletion.setFailure(new OpenR66RunnerErrorException( + "No valid runner in Reschedule")); + return; + } + if (runner.isRescheduledTransfer()) { + // Already rescheduled so ignore + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Transfer already Rescheduled: " + runner.toShortString()); + futureCompletion.setSuccess(); + return; + } + if (runner.isSelfRequested()) { + // Self Requested Request so reschedule is ignored + R66Result result = new R66Result(session, false, ErrorCode.LoopSelfRequestedHost, + runner); + futureCompletion.setResult(result); + futureCompletion.setFailure(new OpenR66RunnerErrorException( + "No valid runner in Reschedule since Self Requested")); + return; + } + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + String[] args = finalname.split(" "); + if (args.length < 4) { + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Not enough argument in Reschedule: " + runner.toShortString()); + futureCompletion.setSuccess(); + return; + } + if (!validateArgs(args)) { + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Reschedule unallowed due to argument: " + runner.toShortString()); + futureCompletion.setSuccess(); + return; + } + String newFileInformation = null; + if (countUsed) { + limitCount --; + if (limitCount >= 0) { + // restart is allowed so resetting to new limitCount + resetCount = limitCount; + } + newFileInformation = resetInformation(runner, resetCount); + if (limitCount < 0) { + // Must not reschedule since limit is reached + runner.setFileInformation(newFileInformation); + try { + runner.saveStatus(); + } catch (OpenR66RunnerErrorException e) { + } + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Reschedule unallowed due to limit reached: " + runner.toShortString()); + futureCompletion.setSuccess(); + return; + } + } + Timestamp start = new Timestamp(newdate); + try { + runner.setStart(start); + if (runner.restart(true)) { + runner.setFileInformation(newFileInformation); + runner.saveStatus(); + } + } catch (OpenR66RunnerErrorException e) { + logger.error( + "Prepare transfer in\n FAILURE\n " + + runner.toShortString() + "\n " + + (new Date(newdate)).toString() + "", e); + futureCompletion.setFailure(new OpenR66RunnerErrorException( + "Reschedule failed: " + e.getMessage(), e)); + return; + } + runner.setRescheduledTransfer(); + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Reschedule transfer in\n SUCCESS\n " + + runner.toShortString() + "\n " + + (new Date(newdate)).toString() + ""); + futureCompletion.setSuccess(); + } + + protected String resetInformation(DbTaskRunner runner, int value) { + String info = runner.getFileInformation(); + int pos = info.indexOf(CPTLIMIT); + if (pos >= 0) { + pos += CPTLIMIT.length(); + int endpos = info.indexOf(CPTLIMIT, pos); + if (endpos >= 0) { + // now string replace + String limit = info.substring(pos, endpos); + return info.replaceFirst(CPTLIMIT+limit+CPTLIMIT, CPTLIMIT+value+CPTLIMIT); + } + } + return info; + } + + protected boolean validateArgs(String[] args) { + boolean validCode = false; + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-delay")) { + i++; + try { + newdate = Long.parseLong(args[i]); + } catch (NumberFormatException e) { + logger.warn("Bad Long format: args[i]"); + return false; + } + } else if (args[i].equalsIgnoreCase("-case")) { + i++; + if (!validCode) { + String[] codes = args[i].split(","); + for (int j = 0; j < codes.length; j++) { + ErrorCode code = ErrorCode.getFromCode(codes[j]); + if (session.getLocalChannelReference().getCurrentCode() == code) { + logger.debug("Code valid: " + code); + validCode = true; + } + } + } + } else if (args[i].equalsIgnoreCase("-count")) { + i++; + try { + resetCount = Integer.parseInt(args[i]); + } catch (NumberFormatException e) { + logger.warn("ResetLimit is not an integer: "+args[i]); + countUsed = false; + return false; + } + String []find = argTransfer.split(CPTLIMIT); + if (find.length > 1) { + // should be 2nd value + try { + limitCount = Integer.parseInt(find[1]); + } catch (NumberFormatException e) { + logger.warn("Limit is not an integer: "+find[1]); + countUsed = false; + return false; + } + } + countUsed = true; + } + } + // now we have new delay plus code + if (!validCode) { + logger.warn("No valid Code found"); + return false; + } + if (newdate <= 0) { + logger.warn("Delay is negative: " + newdate); + return false; + } + newdate += System.currentTimeMillis(); + newDate = Calendar.getInstance(); + newDate.setTimeInMillis(newdate); + boolean betweenTest = false; + boolean betweenResult = false; + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-notbetween")) { + i++; + String[] elmts = args[i].split(";"); + boolean startModified = false; + String[] values = elmts[0].split(":"); + Calendar start = getCalendar(values); + if (start != null) { + startModified = true; + } else { + start = Calendar.getInstance(); + } + boolean stopModified = false; + values = elmts[1].split(":"); + Calendar stop = getCalendar(values); + if (stop != null) { + stopModified = true; + } else { + stop = Calendar.getInstance(); + } + logger.debug("Dates before check: Not between " + start.getTime() + " and " + + stop.getTime()); + // Check that start < stop + if (start.compareTo(stop) > 0) { + // no so add 24H to stop + stop.add(Calendar.DAY_OF_MONTH, 1); + } + // Check that start and stop > newDate (only start is checked since start <= stop) + if (start.compareTo(newDate) < 0) { + start.add(Calendar.DAY_OF_MONTH, 1); + stop.add(Calendar.DAY_OF_MONTH, 1); + } + logger.debug("Dates after check: Not between " + start.getTime() + " and " + + stop.getTime()); + if (!startModified) { + if (newDate.compareTo(stop) < 0) { + logger.debug("newDate: " + newDate.getTime() + " Should not be between " + + start.getTime() + " and " + stop.getTime()); + return false; + } + } else if (start.compareTo(newDate) < 0) { + if ((!stopModified) || (newDate.compareTo(stop) < 0)) { + logger.debug("newDate: " + newDate.getTime() + " Should not be between " + + start.getTime() + " and " + stop.getTime()); + return false; + } + } + } else if (args[i].equalsIgnoreCase("-between")) { + i++; + betweenTest = true; + String[] elmts = args[i].split(";"); + boolean startModified = false; + String[] values = elmts[0].split(":"); + Calendar start = getCalendar(values); + if (start != null) { + startModified = true; + } else { + start = Calendar.getInstance(); + } + boolean stopModified = false; + values = elmts[1].split(":"); + Calendar stop = getCalendar(values); + if (stop != null) { + stopModified = true; + } else { + stop = Calendar.getInstance(); + } + logger.debug("Dates before check: Between " + start.getTime() + " and " + + stop.getTime()); + // Check that start < stop + if (start.compareTo(stop) > 0) { + // no so add 24H to stop + stop.add(Calendar.DAY_OF_MONTH, 1); + } + // Check that start and stop > newDate (only start is checked since start <= stop) + if (start.compareTo(newDate) < 0) { + start.add(Calendar.DAY_OF_MONTH, 1); + stop.add(Calendar.DAY_OF_MONTH, 1); + } + logger.debug("Dates before check: Between " + start.getTime() + " and " + + stop.getTime()); + if (!startModified) { + if (newDate.compareTo(stop) < 0) { + logger.debug("newDate: " + newDate.getTime() + " is between " + + start.getTime() + " and " + stop.getTime()); + betweenResult = true; + } + } else if (start.compareTo(newDate) < 0) { + if ((!stopModified) || (newDate.compareTo(stop) < 0)) { + logger.debug("newDate: " + newDate.getTime() + " is between " + + start.getTime() + " and " + stop.getTime()); + betweenResult = true; + } + } + } + } + if (betweenTest) { + logger.debug("Since between is specified, do we found newDate: " + newDate.getTime() + + " Result: " + betweenResult); + return betweenResult; + } + logger.debug("newDate: " + newDate.getTime() + " rescheduled"); + return true; + } + + /** + * + * @param values + * as X+n or X-n or X=n or Xn where X=Y/M/D/H/m/s, n=number and +/- meaning + * adding/subtracting from current date and = meaning specific set value + * @return the Calendar if any specification, or null if no calendar specified + */ + private Calendar getCalendar(String[] values) { + Calendar newcal = Calendar.getInstance(); + boolean isModified = false; + for (int j = 0; j < values.length; j++) { + if (values[j].length() > 1) { + int addvalue = 0; // will be different of 0 + int value = -1; // will be >= 0 + switch (values[j].charAt(0)) { + case '+': + try { + addvalue = Integer.parseInt(values[j].substring(2)); + } catch (NumberFormatException e) { + continue; + } + break; + case '-': + try { + addvalue = Integer.parseInt(values[j].substring(1)); + } catch (NumberFormatException e) { + continue; + } + break; + case '=': + try { + value = Integer.parseInt(values[j].substring(2)); + } catch (NumberFormatException e) { + continue; + } + break; + default: // no sign + try { + value = Integer.parseInt(values[j].substring(1)); + } catch (NumberFormatException e) { + continue; + } + } + switch (values[j].charAt(0)) { + case 'Y': + if (value >= 0) { + newcal.set(Calendar.YEAR, value); + } else { + newcal.add(Calendar.YEAR, addvalue); + } + isModified = true; + break; + case 'M': + if (value >= 0) { + newcal.set(Calendar.MONTH, value); + } else { + newcal.add(Calendar.MONTH, addvalue); + } + isModified = true; + break; + case 'D': + if (value >= 0) { + newcal.set(Calendar.DAY_OF_MONTH, value); + } else { + newcal.add(Calendar.DAY_OF_MONTH, addvalue); + } + isModified = true; + break; + case 'H': + if (value >= 0) { + newcal.set(Calendar.HOUR_OF_DAY, value); + } else { + newcal.add(Calendar.HOUR_OF_DAY, addvalue); + } + isModified = true; + break; + case 'm': + if (value >= 0) { + newcal.set(Calendar.MINUTE, value); + } else { + newcal.add(Calendar.MINUTE, addvalue); + } + isModified = true; + break; + case 'S': + if (value >= 0) { + newcal.set(Calendar.SECOND, value); + } else { + newcal.add(Calendar.SECOND, addvalue); + } + isModified = true; + break; + } + } + } + if (isModified) + return newcal; + return null; + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/SnmpTask.java b/src/main/java/org/waarp/openr66/context/task/SnmpTask.java index 71d9c0008..631d0179c 100644 --- a/src/main/java/org/waarp/openr66/context/task/SnmpTask.java +++ b/src/main/java/org/waarp/openr66/context/task/SnmpTask.java @@ -1,74 +1,74 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * This class is for sending a SNMP trap/info (according to snmp configuration):
- * - if delay is 0, only a warning will be send with the message accordingly
- * - if delay is 1, a notification with the current task and the current message will be send
- *
- * - * @author Frederic Bregier - * - */ -public class SnmpTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(SnmpTask.class); - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public SnmpTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.SNMP, delay, argRule, argTransfer, session); - } - - @Override - public void run() { - if (Configuration.configuration.r66Mib == null) { - logger.warn("SNMP support is not active"); - futureCompletion.setSuccess(); - return; - } - String finalValue = argRule; - finalValue = getReplacedValue(finalValue, argTransfer.split(" ")); - switch (delay) { - case 0: - Configuration.configuration.r66Mib.notifyWarning( - finalValue, "TransferId:" + this.session.getRunner().getSpecialId()); - break; - case 1: - Configuration.configuration.r66Mib.notifyInternalTask( - finalValue, this.session.getRunner()); - break; - default: - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * This class is for sending a SNMP trap/info (according to snmp configuration):
+ * - if delay is 0, only a warning will be send with the message accordingly
+ * - if delay is 1, a notification with the current task and the current message will be send
+ *
+ * + * @author Frederic Bregier + * + */ +public class SnmpTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(SnmpTask.class); + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public SnmpTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.SNMP, delay, argRule, argTransfer, session); + } + + @Override + public void run() { + if (Configuration.configuration.r66Mib == null) { + logger.warn("SNMP support is not active"); + futureCompletion.setSuccess(); + return; + } + String finalValue = argRule; + finalValue = getReplacedValue(finalValue, argTransfer.split(" ")); + switch (delay) { + case 0: + Configuration.configuration.r66Mib.notifyWarning( + finalValue, "TransferId:" + this.session.getRunner().getSpecialId()); + break; + case 1: + Configuration.configuration.r66Mib.notifyInternalTask( + finalValue, this.session.getRunner()); + break; + default: + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/TarTask.java b/src/main/java/org/waarp/openr66/context/task/TarTask.java index 01493e7a7..705e0a704 100644 --- a/src/main/java/org/waarp/openr66/context/task/TarTask.java +++ b/src/main/java/org/waarp/openr66/context/task/TarTask.java @@ -1,106 +1,106 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.tar.TarUtility; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * TAR task - * - * @author Frederic Bregier - * - */ -public class TarTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TarTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public TarTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.TAR, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("TAR with " + argRule + ":" + argTransfer + ":" + delay + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - boolean tar = false; - switch (delay) { - case 2: { - // directory: tar finalname where finalname="target directory" - String[] args = finalname.split(" "); - tar = TarUtility.createTarFromDirectory(args[1], args[0], false); - break; - } - case 3: { - // list of files: tar finalname where finalname="target file1 file2..." - String[] args = finalname.split(" "); - List files = new ArrayList(args.length - 1); - for (int i = 1; i < args.length; i++) { - files.add(new File(args[i])); - } - tar = TarUtility.createTarFromFiles(files, args[0]); - break; - } - default: - // untar - // directory: untar finalname where finalname="source directory" - String[] args = finalname.split(" "); - File tarFile = new File(args[0]); - File directory = new File(args[1]); - try { - TarUtility.unTar(tarFile, directory); - } catch (IOException e) { - logger.warn("Error while untar", e); - tar = false; - } - break; - } - if (!tar) { - logger.error("Tar error with " + argRule + ":" + argTransfer + ":" + delay + " and " + - session); - futureCompletion.setFailure(new OpenR66ProtocolSystemException("Tar error")); - return; - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.tar.TarUtility; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * TAR task + * + * @author Frederic Bregier + * + */ +public class TarTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TarTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public TarTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.TAR, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("TAR with " + argRule + ":" + argTransfer + ":" + delay + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + boolean tar = false; + switch (delay) { + case 2: { + // directory: tar finalname where finalname="target directory" + String[] args = finalname.split(" "); + tar = TarUtility.createTarFromDirectory(args[1], args[0], false); + break; + } + case 3: { + // list of files: tar finalname where finalname="target file1 file2..." + String[] args = finalname.split(" "); + List files = new ArrayList(args.length - 1); + for (int i = 1; i < args.length; i++) { + files.add(new File(args[i])); + } + tar = TarUtility.createTarFromFiles(files, args[0]); + break; + } + default: + // untar + // directory: untar finalname where finalname="source directory" + String[] args = finalname.split(" "); + File tarFile = new File(args[0]); + File directory = new File(args[1]); + try { + TarUtility.unTar(tarFile, directory); + } catch (IOException e) { + logger.warn("Error while untar", e); + tar = false; + } + break; + } + if (!tar) { + logger.error("Tar error with " + argRule + ":" + argTransfer + ":" + delay + " and " + + session); + futureCompletion.setFailure(new OpenR66ProtocolSystemException("Tar error")); + return; + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/TaskType.java b/src/main/java/org/waarp/openr66/context/task/TaskType.java index ed601ab45..23651d5cf 100644 --- a/src/main/java/org/waarp/openr66/context/task/TaskType.java +++ b/src/main/java/org/waarp/openr66/context/task/TaskType.java @@ -1,151 +1,151 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; - -/** - * This enum class references all available tasks. - * - * If a new task type is to be created, this is the place where it should be referenced. - * - * @author Frederic Bregier - * - */ -public enum TaskType { - LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, LINKRENAME, TRANSFER, - VALIDFILEPATH, DELETE, TAR, ZIP, EXECOUTPUT, RESCHEDULE, EXECJAVA, TRANSCODE, SNMP, FTP; - - public int type; - - public String name; - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TaskType.class); - - private TaskType() { - type = ordinal(); - name = name(); - } - - /** - * - * @param type - * @param argRule - * @param delay - * @param session - * @return the corresponding AbstractTask - * @throws OpenR66RunnerErrorException - */ - public static AbstractTask getTaskFromId(TaskType type, String argRule, - int delay, R66Session session) - throws OpenR66RunnerErrorException { - switch (type) { - case LOG: - return new LogTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case MOVE: - return new MoveTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case MOVERENAME: - return new MoveRenameTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case COPY: - return new CopyTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case COPYRENAME: - return new CopyRenameTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case EXEC: - return new ExecTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case EXECMOVE: - return new ExecMoveTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case LINKRENAME: - return new LinkRenameTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case TRANSFER: - return new TransferTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case VALIDFILEPATH: - return new ValidFilePathTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case DELETE: - return new DeleteTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case TAR: - return new TarTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case ZIP: - return new ZipTask(argRule, delay, session.getRunner() - .getFileInformation(), session); - case EXECOUTPUT: - return new ExecOutputTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - case RESCHEDULE: - return new RescheduleTransferTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - case EXECJAVA: - return new ExecJavaTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - case TRANSCODE: - return new TranscodeTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - case SNMP: - return new SnmpTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - case FTP: - return new FtpTransferTask(argRule, delay, session.getRunner(). - getFileInformation(), session); - default: - logger.error("name unknown: " + type.name); - throw new OpenR66RunnerErrorException("Unvalid Task: " + - type.name); - } - } - - /** - * - * @param name - * @param argRule - * @param delay - * @param session - * @return the corresponding AbstractTask - * @throws OpenR66RunnerErrorException - */ - public static AbstractTask getTaskFromId(String name, String argRule, - int delay, R66Session session) throws OpenR66RunnerErrorException { - TaskType type; - try { - type = valueOf(name); - } catch (NullPointerException e) { - logger.error("name empty " + name); - throw new OpenR66RunnerErrorException("Unvalid Task: " + name); - } catch (IllegalArgumentException e) { - logger.error("name unknown: " + name); - throw new OpenR66RunnerErrorException("Unvalid Task: " + name); - } - return getTaskFromId(type, argRule, delay, session); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; + +/** + * This enum class references all available tasks. + * + * If a new task type is to be created, this is the place where it should be referenced. + * + * @author Frederic Bregier + * + */ +public enum TaskType { + LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, LINKRENAME, TRANSFER, + VALIDFILEPATH, DELETE, TAR, ZIP, EXECOUTPUT, RESCHEDULE, EXECJAVA, TRANSCODE, SNMP, FTP; + + public int type; + + public String name; + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TaskType.class); + + private TaskType() { + type = ordinal(); + name = name(); + } + + /** + * + * @param type + * @param argRule + * @param delay + * @param session + * @return the corresponding AbstractTask + * @throws OpenR66RunnerErrorException + */ + public static AbstractTask getTaskFromId(TaskType type, String argRule, + int delay, R66Session session) + throws OpenR66RunnerErrorException { + switch (type) { + case LOG: + return new LogTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case MOVE: + return new MoveTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case MOVERENAME: + return new MoveRenameTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case COPY: + return new CopyTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case COPYRENAME: + return new CopyRenameTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case EXEC: + return new ExecTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case EXECMOVE: + return new ExecMoveTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case LINKRENAME: + return new LinkRenameTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case TRANSFER: + return new TransferTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case VALIDFILEPATH: + return new ValidFilePathTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case DELETE: + return new DeleteTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case TAR: + return new TarTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case ZIP: + return new ZipTask(argRule, delay, session.getRunner() + .getFileInformation(), session); + case EXECOUTPUT: + return new ExecOutputTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + case RESCHEDULE: + return new RescheduleTransferTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + case EXECJAVA: + return new ExecJavaTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + case TRANSCODE: + return new TranscodeTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + case SNMP: + return new SnmpTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + case FTP: + return new FtpTransferTask(argRule, delay, session.getRunner(). + getFileInformation(), session); + default: + logger.error("name unknown: " + type.name); + throw new OpenR66RunnerErrorException("Unvalid Task: " + + type.name); + } + } + + /** + * + * @param name + * @param argRule + * @param delay + * @param session + * @return the corresponding AbstractTask + * @throws OpenR66RunnerErrorException + */ + public static AbstractTask getTaskFromId(String name, String argRule, + int delay, R66Session session) throws OpenR66RunnerErrorException { + TaskType type; + try { + type = valueOf(name); + } catch (NullPointerException e) { + logger.error("name empty " + name); + throw new OpenR66RunnerErrorException("Unvalid Task: " + name); + } catch (IllegalArgumentException e) { + logger.error("name unknown: " + name); + throw new OpenR66RunnerErrorException("Unvalid Task: " + name); + } + return getTaskFromId(type, argRule, delay, session); + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/TranscodeTask.java b/src/main/java/org/waarp/openr66/context/task/TranscodeTask.java index 8e6f5209b..6d93f8b21 100644 --- a/src/main/java/org/waarp/openr66/context/task/TranscodeTask.java +++ b/src/main/java/org/waarp/openr66/context/task/TranscodeTask.java @@ -1,152 +1,152 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.transcode.CharsetsUtil; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * Transcode the current file from one Charset to another Charset as specified
- *
- * Arguments are:
- * -from charset
- * -to charset
- * -newfile newfilename ; optional argument ; if not used, will be current filename.extension ; - * if used, extension is ignored
- * -extension extension ; optional argument ; if not used, will be filename.transcode
- *
- * A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) - * all the supported Charsets from your JVM. To use it, run the following command:
- * java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]
- *
- * It could also be used as a test of transcode outside R66:
- * java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset
- * - * The current file is not touched and is not marked as moved. - * - * @author Frederic Bregier - * - */ -public class TranscodeTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TranscodeTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public TranscodeTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.TRANSCODE, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - boolean success = false; - DbTaskRunner runner = session.getRunner(); - String arg = argRule; - arg = getReplacedValue(arg, argTransfer.split(" ")); - String [] args = arg.split(" "); - if (args.length < 4) { - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Not enough argument in Transcode: " + runner.toShortString()); - futureCompletion.setFailure(new OpenR66ProtocolSystemException( - "Not enough argument in Transcode")); - return; - } - String fromCharset = null; - String toCharset = null; - String newfilename = null; - String extension = null; - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-from")) { - i++; - if (i < args.length) { - fromCharset = args[i]; - } - } else if (args[i].equalsIgnoreCase("-to")) { - i++; - if (i < args.length) { - toCharset = args[i]; - } - } else if (args[i].equalsIgnoreCase("-newfile")) { - i++; - if (i < args.length) { - newfilename = args[i]; - } - } else if (args[i].equalsIgnoreCase("-extension")) { - i++; - if (i < args.length) { - extension = args[i]; - } - } - } - if (fromCharset == null || toCharset == null) { - R66Result result = new R66Result(session, false, ErrorCode.Warning, - runner); - futureCompletion.setResult(result); - logger.warn("Not enough argument in Transcode: " + runner.toShortString()); - futureCompletion.setFailure(new OpenR66ProtocolSystemException( - "Not enough argument in Transcode")); - return; - } - File from = session.getFile().getTrueFile(); - if (newfilename != null) { - success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, - newfilename, toCharset, - Configuration.BUFFERSIZEDEFAULT); - } else if (extension != null) { - success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, - from.getAbsolutePath()+"."+extension, toCharset, - Configuration.BUFFERSIZEDEFAULT); - } else { - success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, - from.getAbsolutePath()+".transcode", toCharset, - Configuration.BUFFERSIZEDEFAULT); - } - if (success) { - futureCompletion.setSuccess(); - } else { - logger.error("Cannot Transcode from " + fromCharset + " to " + toCharset+" with " + - argRule + ":" + argTransfer + " and " + session); - futureCompletion.setFailure(new OpenR66ProtocolSystemException( - "Cannot Transcode file")); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.transcode.CharsetsUtil; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * Transcode the current file from one Charset to another Charset as specified
+ *
+ * Arguments are:
+ * -from charset
+ * -to charset
+ * -newfile newfilename ; optional argument ; if not used, will be current filename.extension ; + * if used, extension is ignored
+ * -extension extension ; optional argument ; if not used, will be filename.transcode
+ *
+ * A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) + * all the supported Charsets from your JVM. To use it, run the following command:
+ * java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]
+ *
+ * It could also be used as a test of transcode outside R66:
+ * java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset
+ * + * The current file is not touched and is not marked as moved. + * + * @author Frederic Bregier + * + */ +public class TranscodeTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TranscodeTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public TranscodeTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.TRANSCODE, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + boolean success = false; + DbTaskRunner runner = session.getRunner(); + String arg = argRule; + arg = getReplacedValue(arg, argTransfer.split(" ")); + String [] args = arg.split(" "); + if (args.length < 4) { + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Not enough argument in Transcode: " + runner.toShortString()); + futureCompletion.setFailure(new OpenR66ProtocolSystemException( + "Not enough argument in Transcode")); + return; + } + String fromCharset = null; + String toCharset = null; + String newfilename = null; + String extension = null; + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-from")) { + i++; + if (i < args.length) { + fromCharset = args[i]; + } + } else if (args[i].equalsIgnoreCase("-to")) { + i++; + if (i < args.length) { + toCharset = args[i]; + } + } else if (args[i].equalsIgnoreCase("-newfile")) { + i++; + if (i < args.length) { + newfilename = args[i]; + } + } else if (args[i].equalsIgnoreCase("-extension")) { + i++; + if (i < args.length) { + extension = args[i]; + } + } + } + if (fromCharset == null || toCharset == null) { + R66Result result = new R66Result(session, false, ErrorCode.Warning, + runner); + futureCompletion.setResult(result); + logger.warn("Not enough argument in Transcode: " + runner.toShortString()); + futureCompletion.setFailure(new OpenR66ProtocolSystemException( + "Not enough argument in Transcode")); + return; + } + File from = session.getFile().getTrueFile(); + if (newfilename != null) { + success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, + newfilename, toCharset, + Configuration.BUFFERSIZEDEFAULT); + } else if (extension != null) { + success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, + from.getAbsolutePath()+"."+extension, toCharset, + Configuration.BUFFERSIZEDEFAULT); + } else { + success = CharsetsUtil.transcode(from.getAbsolutePath(), fromCharset, + from.getAbsolutePath()+".transcode", toCharset, + Configuration.BUFFERSIZEDEFAULT); + } + if (success) { + futureCompletion.setSuccess(); + } else { + logger.error("Cannot Transcode from " + fromCharset + " to " + toCharset+" with " + + argRule + ":" + argTransfer + " and " + session); + futureCompletion.setFailure(new OpenR66ProtocolSystemException( + "Cannot Transcode file")); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/TransferTask.java b/src/main/java/org/waarp/openr66/context/task/TransferTask.java index acf9dde90..3a2161138 100644 --- a/src/main/java/org/waarp/openr66/context/task/TransferTask.java +++ b/src/main/java/org/waarp/openr66/context/task/TransferTask.java @@ -1,174 +1,174 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.SubmitTransfer; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Transfer task:
- * - * Result of arguments will be as r66send command.
- * Format is like r66send command in any order except "-info" which should be the last item:
- * "-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] [-info information]" - *
- *
- * INFO is the only one field that can contains blank character.
- * - * @author Frederic Bregier - * - */ -public class TransferTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TransferTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public TransferTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.TRANSFER, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("Transfer with " + argRule + ":" + argTransfer + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - String[] args = finalname.split(" "); - if (args.length < 6) { - futureCompletion.setFailure( - new OpenR66RunnerErrorException("Not enough argument in Transfer")); - return; - } - String filepath = null; - String requested = null; - String rule = null; - String information = null; - boolean isMD5 = false; - int blocksize = Configuration.configuration.BLOCKSIZE; - Timestamp timestart = null; - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-to")) { - i++; - requested = args[i]; - } else if (args[i].equalsIgnoreCase("-file")) { - i++; - filepath = args[i]; - } else if (args[i].equalsIgnoreCase("-rule")) { - i++; - rule = args[i]; - } else if (args[i].equalsIgnoreCase("-info")) { - i++; - information = args[i]; - i++; - while (i < args.length) { - information += " " + args[i]; - i++; - } - } else if (args[i].equalsIgnoreCase("-md5")) { - isMD5 = true; - } else if (args[i].equalsIgnoreCase("-block")) { - i++; - blocksize = Integer.parseInt(args[i]); - if (blocksize < 100) { - logger.warn("Block size is too small: " + blocksize); - blocksize = Configuration.configuration.BLOCKSIZE; - } - } else if (args[i].equalsIgnoreCase("-start")) { - i++; - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - Date date; - try { - date = dateFormat.parse(args[i]); - timestart = new Timestamp(date.getTime()); - } catch (ParseException e) { - } - } else if (args[i].equalsIgnoreCase("-delay")) { - i++; - try { - if (args[i].charAt(0) == '+') { - timestart = new Timestamp(System.currentTimeMillis() + - Long.parseLong(args[i].substring(1))); - } else { - timestart = new Timestamp(Long.parseLong(args[i])); - } - } catch (NumberFormatException e) { - } - } - } - if (information == null) { - information = "noinfo"; - } - R66Future future = new R66Future(true); - SubmitTransfer transaction = new SubmitTransfer(future, - requested, filepath, rule, information, isMD5, blocksize, DbConstant.ILLEGALVALUE, - timestart); - transaction.run(); - future.awaitUninterruptibly(); - futureCompletion.setResult(future.getResult()); - DbTaskRunner runner = future.getResult().runner; - if (future.isSuccess()) { - logger.info("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + - "\n " + requested + ""); - futureCompletion.setSuccess(); - } else { - if (runner != null) { - if (future.getCause() == null) { - futureCompletion.cancel(); - } else { - futureCompletion.setFailure(future.getCause()); - } - logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + - "\n " + requested + "", future.getCause()); - } else { - if (future.getCause() == null) { - futureCompletion.cancel(); - } else { - futureCompletion.setFailure(future.getCause()); - } - logger.error("Prepare transfer in\n FAILURE without any runner back", - future.getCause()); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.SubmitTransfer; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Transfer task:
+ * + * Result of arguments will be as r66send command.
+ * Format is like r66send command in any order except "-info" which should be the last item:
+ * "-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] [-info information]" + *
+ *
+ * INFO is the only one field that can contains blank character.
+ * + * @author Frederic Bregier + * + */ +public class TransferTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TransferTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public TransferTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.TRANSFER, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("Transfer with " + argRule + ":" + argTransfer + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + String[] args = finalname.split(" "); + if (args.length < 6) { + futureCompletion.setFailure( + new OpenR66RunnerErrorException("Not enough argument in Transfer")); + return; + } + String filepath = null; + String requested = null; + String rule = null; + String information = null; + boolean isMD5 = false; + int blocksize = Configuration.configuration.BLOCKSIZE; + Timestamp timestart = null; + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-to")) { + i++; + requested = args[i]; + } else if (args[i].equalsIgnoreCase("-file")) { + i++; + filepath = args[i]; + } else if (args[i].equalsIgnoreCase("-rule")) { + i++; + rule = args[i]; + } else if (args[i].equalsIgnoreCase("-info")) { + i++; + information = args[i]; + i++; + while (i < args.length) { + information += " " + args[i]; + i++; + } + } else if (args[i].equalsIgnoreCase("-md5")) { + isMD5 = true; + } else if (args[i].equalsIgnoreCase("-block")) { + i++; + blocksize = Integer.parseInt(args[i]); + if (blocksize < 100) { + logger.warn("Block size is too small: " + blocksize); + blocksize = Configuration.configuration.BLOCKSIZE; + } + } else if (args[i].equalsIgnoreCase("-start")) { + i++; + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + Date date; + try { + date = dateFormat.parse(args[i]); + timestart = new Timestamp(date.getTime()); + } catch (ParseException e) { + } + } else if (args[i].equalsIgnoreCase("-delay")) { + i++; + try { + if (args[i].charAt(0) == '+') { + timestart = new Timestamp(System.currentTimeMillis() + + Long.parseLong(args[i].substring(1))); + } else { + timestart = new Timestamp(Long.parseLong(args[i])); + } + } catch (NumberFormatException e) { + } + } + } + if (information == null) { + information = "noinfo"; + } + R66Future future = new R66Future(true); + SubmitTransfer transaction = new SubmitTransfer(future, + requested, filepath, rule, information, isMD5, blocksize, DbConstant.ILLEGALVALUE, + timestart); + transaction.run(); + future.awaitUninterruptibly(); + futureCompletion.setResult(future.getResult()); + DbTaskRunner runner = future.getResult().runner; + if (future.isSuccess()) { + logger.info("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + + "\n " + requested + ""); + futureCompletion.setSuccess(); + } else { + if (runner != null) { + if (future.getCause() == null) { + futureCompletion.cancel(); + } else { + futureCompletion.setFailure(future.getCause()); + } + logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + + "\n " + requested + "", future.getCause()); + } else { + if (future.getCause() == null) { + futureCompletion.cancel(); + } else { + futureCompletion.setFailure(future.getCause()); + } + logger.error("Prepare transfer in\n FAILURE without any runner back", + future.getCause()); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/ValidFilePathTask.java b/src/main/java/org/waarp/openr66/context/task/ValidFilePathTask.java index 7c0bf87db..2790d512f 100644 --- a/src/main/java/org/waarp/openr66/context/task/ValidFilePathTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ValidFilePathTask.java @@ -1,89 +1,89 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.context.task.exception.OpenR66RunnerException; - -/** - * This task validate the File Path according to the follwing argument:
- * - the full path is get from the current file
- * - the arg path is transformed as usual (static and dynamic from information transfer) and should - * be the beginning of the correct valid path
- * - the full path should begin with one of the result of the transformation (blank separated)
- *
- * For instance "#OUTPATH# #INPATH# #WORKPATH# #ARHCPATH#" will test that the current file is in one - * of the standard path. - * - * @author Frederic Bregier - * - */ -public class ValidFilePathTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ValidFilePathTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ValidFilePathTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.VALIDFILEPATH, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - String finalname = argRule; - finalname = R66Dir.normalizePath( - getReplacedValue(finalname, argTransfer.split(" "))); - logger.info("Test Valid Path with " + finalname + " from {}", session); - File from = session.getFile().getTrueFile(); - String curpath = R66Dir.normalizePath(from.getAbsolutePath()); - String[] paths = finalname.split(" "); - for (String base : paths) { - if (curpath.startsWith(base)) { - if (delay > 0) { - logger.info("Validate File " + curpath + " from " + base + " and\n " + - session.toString()); - } - futureCompletion.setSuccess(); - return; - } - } - if (delay > 0) { - logger.error("Unvalidate File: " + curpath + "\n " + - session.toString()); - } - futureCompletion.setFailure(new OpenR66RunnerException("File not Validated")); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.context.task.exception.OpenR66RunnerException; + +/** + * This task validate the File Path according to the follwing argument:
+ * - the full path is get from the current file
+ * - the arg path is transformed as usual (static and dynamic from information transfer) and should + * be the beginning of the correct valid path
+ * - the full path should begin with one of the result of the transformation (blank separated)
+ *
+ * For instance "#OUTPATH# #INPATH# #WORKPATH# #ARHCPATH#" will test that the current file is in one + * of the standard path. + * + * @author Frederic Bregier + * + */ +public class ValidFilePathTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ValidFilePathTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ValidFilePathTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.VALIDFILEPATH, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + String finalname = argRule; + finalname = R66Dir.normalizePath( + getReplacedValue(finalname, argTransfer.split(" "))); + logger.info("Test Valid Path with " + finalname + " from {}", session); + File from = session.getFile().getTrueFile(); + String curpath = R66Dir.normalizePath(from.getAbsolutePath()); + String[] paths = finalname.split(" "); + for (String base : paths) { + if (curpath.startsWith(base)) { + if (delay > 0) { + logger.info("Validate File " + curpath + " from " + base + " and\n " + + session.toString()); + } + futureCompletion.setSuccess(); + return; + } + } + if (delay > 0) { + logger.error("Unvalidate File: " + curpath + "\n " + + session.toString()); + } + futureCompletion.setFailure(new OpenR66RunnerException("File not Validated")); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/ZipTask.java b/src/main/java/org/waarp/openr66/context/task/ZipTask.java index 08c9fe2cf..0482ba54d 100644 --- a/src/main/java/org/waarp/openr66/context/task/ZipTask.java +++ b/src/main/java/org/waarp/openr66/context/task/ZipTask.java @@ -1,107 +1,107 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.tar.ZipUtility; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * TAR task - * - * @author Frederic Bregier - * - */ -public class ZipTask extends AbstractTask { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ZipTask.class); - - /** - * @param argRule - * @param delay - * @param argTransfer - * @param session - */ - public ZipTask(String argRule, int delay, String argTransfer, - R66Session session) { - super(TaskType.ZIP, delay, argRule, argTransfer, session); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.context.task.AbstractTask#run() - */ - @Override - public void run() { - logger.info("ZIP with " + argRule + ":" + argTransfer + ":" + delay + " and {}", - session); - String finalname = argRule; - finalname = getReplacedValue(finalname, argTransfer.split(" ")); - boolean zip = false; - switch (delay) { - case 2: { - // directory: zip finalname where finalname="target directory" - String[] args = finalname.split(" "); - zip = ZipUtility.createZipFromDirectory(args[1], args[0], false); - break; - } - case 3: { - // list of files: zip finalname where finalname="target file1 file2..." - String[] args = finalname.split(" "); - List files = new ArrayList(args.length - 1); - for (int i = 1; i < args.length; i++) { - files.add(new File(args[i])); - } - zip = ZipUtility.createZipFromFiles(files, args[0]); - break; - } - default: { - // unzip - // directory: unzip finalname where finalname="source directory" - String[] args = finalname.split(" "); - File zipFile = new File(args[0]); - File directory = new File(args[1]); - try { - ZipUtility.unZip(zipFile, directory); - } catch (IOException e) { - logger.warn("Error while unzip", e); - zip = false; - } - break; - } - } - if (!zip) { - logger.error("Zip error with " + argRule + ":" + argTransfer + ":" + delay + " and " + - session); - futureCompletion.setFailure(new OpenR66ProtocolSystemException("Zip error")); - return; - } - futureCompletion.setSuccess(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.tar.ZipUtility; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * TAR task + * + * @author Frederic Bregier + * + */ +public class ZipTask extends AbstractTask { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ZipTask.class); + + /** + * @param argRule + * @param delay + * @param argTransfer + * @param session + */ + public ZipTask(String argRule, int delay, String argTransfer, + R66Session session) { + super(TaskType.ZIP, delay, argRule, argTransfer, session); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.context.task.AbstractTask#run() + */ + @Override + public void run() { + logger.info("ZIP with " + argRule + ":" + argTransfer + ":" + delay + " and {}", + session); + String finalname = argRule; + finalname = getReplacedValue(finalname, argTransfer.split(" ")); + boolean zip = false; + switch (delay) { + case 2: { + // directory: zip finalname where finalname="target directory" + String[] args = finalname.split(" "); + zip = ZipUtility.createZipFromDirectory(args[1], args[0], false); + break; + } + case 3: { + // list of files: zip finalname where finalname="target file1 file2..." + String[] args = finalname.split(" "); + List files = new ArrayList(args.length - 1); + for (int i = 1; i < args.length; i++) { + files.add(new File(args[i])); + } + zip = ZipUtility.createZipFromFiles(files, args[0]); + break; + } + default: { + // unzip + // directory: unzip finalname where finalname="source directory" + String[] args = finalname.split(" "); + File zipFile = new File(args[0]); + File directory = new File(args[1]); + try { + ZipUtility.unZip(zipFile, directory); + } catch (IOException e) { + logger.warn("Error while unzip", e); + zip = false; + } + break; + } + } + if (!zip) { + logger.error("Zip error with " + argRule + ":" + argTransfer + ":" + delay + " and " + + session); + futureCompletion.setFailure(new OpenR66ProtocolSystemException("Zip error")); + return; + } + futureCompletion.setSuccess(); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerEndTasksException.java b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerEndTasksException.java index 17739189b..00052b12f 100644 --- a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerEndTasksException.java +++ b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerEndTasksException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task.exception; - -/** - * Runner exception in end of tasks status - * - * @author frederic bregier - */ -public class OpenR66RunnerEndTasksException extends OpenR66RunnerException { - - /** - * - */ - private static final long serialVersionUID = -5410909604328960778L; - - /** - * - */ - public OpenR66RunnerEndTasksException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66RunnerEndTasksException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66RunnerEndTasksException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66RunnerEndTasksException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task.exception; + +/** + * Runner exception in end of tasks status + * + * @author frederic bregier + */ +public class OpenR66RunnerEndTasksException extends OpenR66RunnerException { + + /** + * + */ + private static final long serialVersionUID = -5410909604328960778L; + + /** + * + */ + public OpenR66RunnerEndTasksException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66RunnerEndTasksException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66RunnerEndTasksException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66RunnerEndTasksException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerErrorException.java b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerErrorException.java index f47c89edd..3770f23f6 100644 --- a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerErrorException.java +++ b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerErrorException.java @@ -1,60 +1,60 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task.exception; - -/** - * Runner exception in error status - * - * @author frederic bregier - */ -public class OpenR66RunnerErrorException extends OpenR66RunnerException { - /** - * - */ - private static final long serialVersionUID = 3794468302790427511L; - - /** - * - */ - public OpenR66RunnerErrorException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66RunnerErrorException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66RunnerErrorException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66RunnerErrorException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task.exception; + +/** + * Runner exception in error status + * + * @author frederic bregier + */ +public class OpenR66RunnerErrorException extends OpenR66RunnerException { + /** + * + */ + private static final long serialVersionUID = 3794468302790427511L; + + /** + * + */ + public OpenR66RunnerErrorException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66RunnerErrorException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66RunnerErrorException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66RunnerErrorException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerException.java b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerException.java index 37a149b2f..6208875ee 100644 --- a/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerException.java +++ b/src/main/java/org/waarp/openr66/context/task/exception/OpenR66RunnerException.java @@ -1,63 +1,63 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task.exception; - -import org.waarp.openr66.protocol.exception.OpenR66Exception; - -/** - * Runner exception - * - * @author frederic bregier - */ -public class OpenR66RunnerException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 5701631625487838804L; - - /** - * - */ - public OpenR66RunnerException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66RunnerException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66RunnerException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66RunnerException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task.exception; + +import org.waarp.openr66.protocol.exception.OpenR66Exception; + +/** + * Runner exception + * + * @author frederic bregier + */ +public class OpenR66RunnerException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 5701631625487838804L; + + /** + * + */ + public OpenR66RunnerException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66RunnerException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66RunnerException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66RunnerException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/context/task/exception/package-info.java b/src/main/java/org/waarp/openr66/context/task/exception/package-info.java index 15d0d3750..6a41e1c9a 100644 --- a/src/main/java/org/waarp/openr66/context/task/exception/package-info.java +++ b/src/main/java/org/waarp/openr66/context/task/exception/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Exceptions for Runner - * - * @apiviz.exclude - */ -package org.waarp.openr66.context.task.exception; - +/** + * Classes implementing Exceptions for Runner + * + * @apiviz.exclude + */ +package org.waarp.openr66.context.task.exception; + diff --git a/src/main/java/org/waarp/openr66/context/task/localexec/LocalExecClient.java b/src/main/java/org/waarp/openr66/context/task/localexec/LocalExecClient.java index a6f73c39e..1e2509bdb 100644 --- a/src/main/java/org/waarp/openr66/context/task/localexec/LocalExecClient.java +++ b/src/main/java/org/waarp/openr66/context/task/localexec/LocalExecClient.java @@ -1,166 +1,166 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task.localexec; - -import java.net.InetSocketAddress; - -import org.jboss.netty.bootstrap.ClientBootstrap; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; -import org.waarp.commandexec.client.LocalExecClientHandler; -import org.waarp.commandexec.client.LocalExecClientPipelineFactory; -import org.waarp.commandexec.utils.LocalExecResult; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.future.WaarpFuture; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Client to execute external command through Waarp Local Exec - * - * @author Frederic Bregier - * - */ -public class LocalExecClient { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LocalExecClient.class); - - static public InetSocketAddress address; - // Configure the client. - static private ClientBootstrap bootstrapLocalExec; - // Configure the pipeline factory. - static private LocalExecClientPipelineFactory localExecClientPipelineFactory; - - /** - * Initialize the LocalExec Client context - */ - public static void initialize() { - // Configure the client. - bootstrapLocalExec = new ClientBootstrap( - new NioClientSocketChannelFactory( - Configuration.configuration.getLocalPipelineExecutor(), - Configuration.configuration.getLocalPipelineExecutor())); - // Configure the pipeline factory. - localExecClientPipelineFactory = - new LocalExecClientPipelineFactory(); - bootstrapLocalExec.setPipelineFactory(localExecClientPipelineFactory); - } - - /** - * To be called when the server is shutting down to release the resources - */ - public static void releaseResources() { - if (bootstrapLocalExec == null) { - return; - } - // Shut down all thread pools to exit. - bootstrapLocalExec.releaseExternalResources(); - localExecClientPipelineFactory.releaseResources(); - } - - private Channel channel; - private LocalExecResult result; - - public LocalExecClient() { - - } - - public LocalExecResult getLocalExecResult() { - return result; - } - - /** - * Run one command with a specific allowed delay for execution. The connection must be ready - * (done with connect()). - * - * @param command - * @param delay - * @param futureCompletion - */ - public void runOneCommand(String command, long delay, boolean waitFor, - WaarpFuture futureCompletion) { - // Initialize the command context - LocalExecClientHandler clientHandler = - (LocalExecClientHandler) channel.getPipeline().getLast(); - // Command to execute - clientHandler.initExecClient(delay, command); - if (!waitFor) { - futureCompletion.setSuccess(); - logger.info("Exec OK with {}", command); - } - // Wait for the end of the exec command - LocalExecResult localExecResult = clientHandler.waitFor(delay * 2); - result = localExecResult; - if (futureCompletion == null) { - return; - } - if (result.status == 0) { - if (waitFor) { - futureCompletion.setSuccess(); - } - logger.info("Exec OK with {}", command); - } else if (result.status == 1) { - logger.warn("Exec in warning with {}", command); - if (waitFor) { - futureCompletion.setSuccess(); - } - } else { - logger.error("Status: " + result.status + " Exec in error with " + - command + "\n" + result.result); - if (waitFor) { - futureCompletion.cancel(); - } - } - } - - /** - * Connect to the Server - */ - public boolean connect() { - // Start the connection attempt. - ChannelFuture future = bootstrapLocalExec.connect(address); - - // Wait until the connection attempt succeeds or fails. - try { - channel = future.await().getChannel(); - } catch (InterruptedException e) { - } - if (!future.isSuccess()) { - logger.error("Client Not Connected", future.getCause()); - return false; - } - return true; - } - - /** - * Disconnect from the server - */ - public void disconnect() { - // Close the connection. Make sure the close operation ends because - // all I/O operations are asynchronous in Netty. - try { - WaarpSslUtility.closingSslChannel(channel).await(); - } catch (InterruptedException e) { - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task.localexec; + +import java.net.InetSocketAddress; + +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.waarp.commandexec.client.LocalExecClientHandler; +import org.waarp.commandexec.client.LocalExecClientPipelineFactory; +import org.waarp.commandexec.utils.LocalExecResult; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.future.WaarpFuture; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Client to execute external command through Waarp Local Exec + * + * @author Frederic Bregier + * + */ +public class LocalExecClient { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LocalExecClient.class); + + static public InetSocketAddress address; + // Configure the client. + static private ClientBootstrap bootstrapLocalExec; + // Configure the pipeline factory. + static private LocalExecClientPipelineFactory localExecClientPipelineFactory; + + /** + * Initialize the LocalExec Client context + */ + public static void initialize() { + // Configure the client. + bootstrapLocalExec = new ClientBootstrap( + new NioClientSocketChannelFactory( + Configuration.configuration.getLocalPipelineExecutor(), + Configuration.configuration.getLocalPipelineExecutor())); + // Configure the pipeline factory. + localExecClientPipelineFactory = + new LocalExecClientPipelineFactory(); + bootstrapLocalExec.setPipelineFactory(localExecClientPipelineFactory); + } + + /** + * To be called when the server is shutting down to release the resources + */ + public static void releaseResources() { + if (bootstrapLocalExec == null) { + return; + } + // Shut down all thread pools to exit. + bootstrapLocalExec.releaseExternalResources(); + localExecClientPipelineFactory.releaseResources(); + } + + private Channel channel; + private LocalExecResult result; + + public LocalExecClient() { + + } + + public LocalExecResult getLocalExecResult() { + return result; + } + + /** + * Run one command with a specific allowed delay for execution. The connection must be ready + * (done with connect()). + * + * @param command + * @param delay + * @param futureCompletion + */ + public void runOneCommand(String command, long delay, boolean waitFor, + WaarpFuture futureCompletion) { + // Initialize the command context + LocalExecClientHandler clientHandler = + (LocalExecClientHandler) channel.getPipeline().getLast(); + // Command to execute + clientHandler.initExecClient(delay, command); + if (!waitFor) { + futureCompletion.setSuccess(); + logger.info("Exec OK with {}", command); + } + // Wait for the end of the exec command + LocalExecResult localExecResult = clientHandler.waitFor(delay * 2); + result = localExecResult; + if (futureCompletion == null) { + return; + } + if (result.status == 0) { + if (waitFor) { + futureCompletion.setSuccess(); + } + logger.info("Exec OK with {}", command); + } else if (result.status == 1) { + logger.warn("Exec in warning with {}", command); + if (waitFor) { + futureCompletion.setSuccess(); + } + } else { + logger.error("Status: " + result.status + " Exec in error with " + + command + "\n" + result.result); + if (waitFor) { + futureCompletion.cancel(); + } + } + } + + /** + * Connect to the Server + */ + public boolean connect() { + // Start the connection attempt. + ChannelFuture future = bootstrapLocalExec.connect(address); + + // Wait until the connection attempt succeeds or fails. + try { + channel = future.await().getChannel(); + } catch (InterruptedException e) { + } + if (!future.isSuccess()) { + logger.error("Client Not Connected", future.getCause()); + return false; + } + return true; + } + + /** + * Disconnect from the server + */ + public void disconnect() { + // Close the connection. Make sure the close operation ends because + // all I/O operations are asynchronous in Netty. + try { + WaarpSslUtility.closingSslChannel(channel).await(); + } catch (InterruptedException e) { + } + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/localexec/package-info.java b/src/main/java/org/waarp/openr66/context/task/localexec/package-info.java index 0cd2f77af..39888f872 100644 --- a/src/main/java/org/waarp/openr66/context/task/localexec/package-info.java +++ b/src/main/java/org/waarp/openr66/context/task/localexec/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Execution of Commands through LocalExec Daemon - * - * @apiviz.landmark - */ -package org.waarp.openr66.context.task.localexec; - +/** + * Classes implementing Execution of Commands through LocalExec Daemon + * + * @apiviz.landmark + */ +package org.waarp.openr66.context.task.localexec; + diff --git a/src/main/java/org/waarp/openr66/context/task/package-info.java b/src/main/java/org/waarp/openr66/context/task/package-info.java index 62078ca61..0cdb14474 100644 --- a/src/main/java/org/waarp/openr66/context/task/package-info.java +++ b/src/main/java/org/waarp/openr66/context/task/package-info.java @@ -1,128 +1,128 @@ -/** - * Classes implementing Tasks for pre, post or error operations - * - * - * Several kind of tasks exist in OpenR66:
- * LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, LINKRENAME, TRANSFER, VALIDFILEPATH, - * DELETE
- *
- *
- *
- * - * Several tasks are possible to run before a transfer starts (pre action), after a transfer is - * finished correctly (post action) or after an error occurs (either in pre or post action or during - * transfer: error action). - * - * Those actions are defined in one rule. Each rule contains 2 parts: - *
    - *
  • Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the - * requested on a RECV rule.
  • - *
  • Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the - * requested on a SEND rule.
  • - *
- * - * Each action could be on pre, post or error step, each step can have several actions. - * - * It is defined with a unified form of XML:
- * <tasks> <task> <type>NAME</type> <path>path</path> <delay>x</delay> </task> <task> - * <type>NAME</type> <path>path</path> <delay>x</delay> </task> </tasks>
- * Where - *
    - *
  • Type is the type of task to execute (see below the supported types)
  • - *
  • Path is a fixed argument for the task to execute. On this argument, string replacements are - * done when the following patterns are found: - *
      - *
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • - *
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • - *
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • - *
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • - *
    • #FILESIZE# : File size if it exists
    • - *
    • #INPATH# : In (Receive) path
    • - *
    • #OUTPATH# : Out (Send) path
    • - *
    • #WORKPATH# : Working (while receiving) path
    • - *
    • #ARCHPATH# : Archive path (for export Log)
    • - *
    • #HOMEPATH# : Home path (to enable for instance relative path commands)
    • - *
    • #RULE# : Rule used during transfer
    • - *
    • #DATE# : Current Date in yyyyMMdd format
    • - *
    • #HOUR# : Current Hour in HHmmss format
    • - *
    • #REMOTEHOST# : Remote host Id (if not the initiator of the call)
    • - *
    • #LOCALHOST# : Local host Id
    • - *
    • #TRANSFERID# : Transfer Id
    • - *
    • #REQUESTERHOST# : Requester host Id
    • - *
    • #REQUESTEDHOST# : Requested host Id
    • - *
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST
    • - *
    • #RANKTRANSFER# : Current or final RANK of block
    • - *
    • #BLOCKSIZE# : Block size used
    • - *
    - *
  • - *
  • Delay is generally the delay (if any) for execution before the execution becomes out of time. - *
  • - *
  • Additionnaly, a task will use also the argument from the transfer itself (Transfer - * Information).
  • - *
- *
- * - * The different kinds of TASK are:
- *
    - *
  • LOG
  • This task logs or writes to an external file some info:
    - * - if delay is 0, no echo at all will be done
    - * - if delay is 1, will echo some information in the normal log
    - * - if delay is 2, will echo some information in the file (last deduced argument will be the full - * path for the file output)
    - * - if delay is 3, will echo both in the normal log and in the file (last deduced argument will be - * the full path for the file output) - *
  • MOVE
  • Move the file to the path designed by Path and Transfer Information arguments - * without renaming the filename (same basename). Delay is ignored. The file is marked as moved. - *
  • MOVERENAME
  • Move the file to the path designed by Path and Transfer Information - * arguments. Delay is ignored. After Path is transformed according to above dynamic replacements, - * it is then used as a String Format where Transfer Information is used as input - * (String.format(Path,Info)). The file is marked as moved. - *
  • COPY
  • Copy the file to the path designed by Path argument without renaming the filename - * (same basename). Delay and Transfer Information are ignored. The file is not marked as moved. - *
  • COPYRENAME
  • Copy the file to the path designed by Path and Transfer Information - * arguments. Delay is ignored. After Path is transformed according to above dynamic replacements, - * it is then used as a String Format where Transfer Information is used as input - * (String.format(Path,Info)). The file is not marked as moved. - *
  • EXEC
  • Execute an external command given by Path and Transfer Information arguments. The - * Delay is the maximum amount of time in milliseconds before the task should be considered as over - * time and so in error.
    - * The command path is obtained from Path transformed according to above dynamic replacements, and - * after a String Format where Transfer Information is used as input (String.format(Path,Info)). - *
  • EXECMOVE
  • Execute an external command given by Path and Transfer Information arguments. - * The Delay is the maximum amount of time in milliseconds before the task should be considered as - * over time and so in error.
    - * The command path is obtained from Path transformed according to above dynamic replacements, and - * after a String Format where Transfer Information is used as input (String.format(Path,Info)).
    - * The last line returned by the external command is interpreted as the new full file path. The - * external command is responsible to really move the previous file to the new one. The file is - * marked as moved. - *
  • TRANSFER
  • Submit a new transfer based on the Path and Transfer Information arguments. The - * transfer arguments are obtained from Path transformed according to above dynamic replacements, - * and after a String Format where Transfer Information is used as input (String.format(Path,Info)). - * The result should be as r66send except that "-info" must be the last entry:
    - * "-file filepath -to requestedHost -rule rule [-md5] -info transferInformation" where each field - * is separated by blank character. Last field (transferInformation) may contain however blank - * character. Delay is ignored. The file is not marked as moved. - *
  • VALIDFILEPATH
  • Test if the current file is under one of the paths based on the Path and - * Transfer Information arguments. The paths arguments are obtained from Path transformed according - * to above dynamic replacements, and after a String Format where Transfer Information is used as - * input (String.format(Path,Info)). The result should be as: "path1 path2 ..." where each path is - * separated by blank character. If Delay is not 0, a log is printed out. The file is not marked as - * moved. - *
  • DELETE
  • This task deletes the current file.The current file is no more valid. No - * arguments are taken into account. - *
  • LINKRENAME
  • Create a link of the current file and make the file pointing to it. The link - * first tries to be a hard link, then a soft link, and if it is really not possible (not supported - * by the filesystem), it does a copy and rename task.
    - * Delay is ignored. After Path is transformed according to above dynamic replacements, it is then - * used as a String Format where Transfer Information is used as input (String.format(Path,Info)). - * The file is not marked as moved. - *
- *
- *
- * - * - * @apiviz.landmark - */ -package org.waarp.openr66.context.task; - +/** + * Classes implementing Tasks for pre, post or error operations + * + * + * Several kind of tasks exist in OpenR66:
+ * LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, LINKRENAME, TRANSFER, VALIDFILEPATH, + * DELETE
+ *
+ *
+ *
+ * + * Several tasks are possible to run before a transfer starts (pre action), after a transfer is + * finished correctly (post action) or after an error occurs (either in pre or post action or during + * transfer: error action). + * + * Those actions are defined in one rule. Each rule contains 2 parts: + *
    + *
  • Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the + * requested on a RECV rule.
  • + *
  • Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the + * requested on a SEND rule.
  • + *
+ * + * Each action could be on pre, post or error step, each step can have several actions. + * + * It is defined with a unified form of XML:
+ * <tasks> <task> <type>NAME</type> <path>path</path> <delay>x</delay> </task> <task> + * <type>NAME</type> <path>path</path> <delay>x</delay> </task> </tasks>
+ * Where + *
    + *
  • Type is the type of task to execute (see below the supported types)
  • + *
  • Path is a fixed argument for the task to execute. On this argument, string replacements are + * done when the following patterns are found: + *
      + *
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • + *
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • + *
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • + *
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • + *
    • #FILESIZE# : File size if it exists
    • + *
    • #INPATH# : In (Receive) path
    • + *
    • #OUTPATH# : Out (Send) path
    • + *
    • #WORKPATH# : Working (while receiving) path
    • + *
    • #ARCHPATH# : Archive path (for export Log)
    • + *
    • #HOMEPATH# : Home path (to enable for instance relative path commands)
    • + *
    • #RULE# : Rule used during transfer
    • + *
    • #DATE# : Current Date in yyyyMMdd format
    • + *
    • #HOUR# : Current Hour in HHmmss format
    • + *
    • #REMOTEHOST# : Remote host Id (if not the initiator of the call)
    • + *
    • #LOCALHOST# : Local host Id
    • + *
    • #TRANSFERID# : Transfer Id
    • + *
    • #REQUESTERHOST# : Requester host Id
    • + *
    • #REQUESTEDHOST# : Requested host Id
    • + *
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST
    • + *
    • #RANKTRANSFER# : Current or final RANK of block
    • + *
    • #BLOCKSIZE# : Block size used
    • + *
    + *
  • + *
  • Delay is generally the delay (if any) for execution before the execution becomes out of time. + *
  • + *
  • Additionnaly, a task will use also the argument from the transfer itself (Transfer + * Information).
  • + *
+ *
+ * + * The different kinds of TASK are:
+ *
    + *
  • LOG
  • This task logs or writes to an external file some info:
    + * - if delay is 0, no echo at all will be done
    + * - if delay is 1, will echo some information in the normal log
    + * - if delay is 2, will echo some information in the file (last deduced argument will be the full + * path for the file output)
    + * - if delay is 3, will echo both in the normal log and in the file (last deduced argument will be + * the full path for the file output) + *
  • MOVE
  • Move the file to the path designed by Path and Transfer Information arguments + * without renaming the filename (same basename). Delay is ignored. The file is marked as moved. + *
  • MOVERENAME
  • Move the file to the path designed by Path and Transfer Information + * arguments. Delay is ignored. After Path is transformed according to above dynamic replacements, + * it is then used as a String Format where Transfer Information is used as input + * (String.format(Path,Info)). The file is marked as moved. + *
  • COPY
  • Copy the file to the path designed by Path argument without renaming the filename + * (same basename). Delay and Transfer Information are ignored. The file is not marked as moved. + *
  • COPYRENAME
  • Copy the file to the path designed by Path and Transfer Information + * arguments. Delay is ignored. After Path is transformed according to above dynamic replacements, + * it is then used as a String Format where Transfer Information is used as input + * (String.format(Path,Info)). The file is not marked as moved. + *
  • EXEC
  • Execute an external command given by Path and Transfer Information arguments. The + * Delay is the maximum amount of time in milliseconds before the task should be considered as over + * time and so in error.
    + * The command path is obtained from Path transformed according to above dynamic replacements, and + * after a String Format where Transfer Information is used as input (String.format(Path,Info)). + *
  • EXECMOVE
  • Execute an external command given by Path and Transfer Information arguments. + * The Delay is the maximum amount of time in milliseconds before the task should be considered as + * over time and so in error.
    + * The command path is obtained from Path transformed according to above dynamic replacements, and + * after a String Format where Transfer Information is used as input (String.format(Path,Info)).
    + * The last line returned by the external command is interpreted as the new full file path. The + * external command is responsible to really move the previous file to the new one. The file is + * marked as moved. + *
  • TRANSFER
  • Submit a new transfer based on the Path and Transfer Information arguments. The + * transfer arguments are obtained from Path transformed according to above dynamic replacements, + * and after a String Format where Transfer Information is used as input (String.format(Path,Info)). + * The result should be as r66send except that "-info" must be the last entry:
    + * "-file filepath -to requestedHost -rule rule [-md5] -info transferInformation" where each field + * is separated by blank character. Last field (transferInformation) may contain however blank + * character. Delay is ignored. The file is not marked as moved. + *
  • VALIDFILEPATH
  • Test if the current file is under one of the paths based on the Path and + * Transfer Information arguments. The paths arguments are obtained from Path transformed according + * to above dynamic replacements, and after a String Format where Transfer Information is used as + * input (String.format(Path,Info)). The result should be as: "path1 path2 ..." where each path is + * separated by blank character. If Delay is not 0, a log is printed out. The file is not marked as + * moved. + *
  • DELETE
  • This task deletes the current file.The current file is no more valid. No + * arguments are taken into account. + *
  • LINKRENAME
  • Create a link of the current file and make the file pointing to it. The link + * first tries to be a hard link, then a soft link, and if it is really not possible (not supported + * by the filesystem), it does a copy and rename task.
    + * Delay is ignored. After Path is transformed according to above dynamic replacements, it is then + * used as a String Format where Transfer Information is used as input (String.format(Path,Info)). + * The file is not marked as moved. + *
+ *
+ *
+ * + * + * @apiviz.landmark + */ +package org.waarp.openr66.context.task; + diff --git a/src/main/java/org/waarp/openr66/context/task/test/TestExecJavaTask.java b/src/main/java/org/waarp/openr66/context/task/test/TestExecJavaTask.java index a7e62a507..3ac326ea3 100644 --- a/src/main/java/org/waarp/openr66/context/task/test/TestExecJavaTask.java +++ b/src/main/java/org/waarp/openr66/context/task/test/TestExecJavaTask.java @@ -1,90 +1,90 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.context.task.test; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.task.AbstractExecJavaTask; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Example of Java Task for ExecJava - * - * @author Frederic Bregier - * - */ -public class TestExecJavaTask extends AbstractExecJavaTask { - - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TestExecJavaTask.class); - - @Override - public void run() { - if (callFromBusiness) { - // Business Request to validate? - if (isToValidate) { - int rank = Integer.parseInt(args[2]); - rank++; - BusinessRequestPacket packet = - new BusinessRequestPacket(this.getClass().getName() + " business " + rank - + " final return", 0); - if (rank > 100) { - validate(packet); - logger.info("Will NOT close the channel: " + rank); - } else { - logger.info("Continue: " + rank); - } - try { - ChannelUtils.writeAbstractLocalPacket(session.getLocalChannelReference(), - packet, true); - } catch (OpenR66ProtocolPacketException e) { - } - this.status = 0; - return; - } - finalValidate("Validated"); - return; - } else { - // Rule EXECJAVA based - R66File file = session.getFile(); - DbTaskRunner runner = session.getRunner(); - if (file == null) { - logger.info("TestExecJavaTask No File"); - } else { - try { - logger.info("TestExecJavaTask File: " + file.getFile()); - } catch (CommandAbstractException e) { - } - } - if (runner == null) { - logger.info("TestExecJavaTask No Runner"); - } else { - logger.info("TestExecJavaTask Runner: " + runner.toShortString()); - } - this.status = 0; - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.context.task.test; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.task.AbstractExecJavaTask; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Example of Java Task for ExecJava + * + * @author Frederic Bregier + * + */ +public class TestExecJavaTask extends AbstractExecJavaTask { + + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TestExecJavaTask.class); + + @Override + public void run() { + if (callFromBusiness) { + // Business Request to validate? + if (isToValidate) { + int rank = Integer.parseInt(args[2]); + rank++; + BusinessRequestPacket packet = + new BusinessRequestPacket(this.getClass().getName() + " business " + rank + + " final return", 0); + if (rank > 100) { + validate(packet); + logger.info("Will NOT close the channel: " + rank); + } else { + logger.info("Continue: " + rank); + } + try { + ChannelUtils.writeAbstractLocalPacket(session.getLocalChannelReference(), + packet, true); + } catch (OpenR66ProtocolPacketException e) { + } + this.status = 0; + return; + } + finalValidate("Validated"); + return; + } else { + // Rule EXECJAVA based + R66File file = session.getFile(); + DbTaskRunner runner = session.getRunner(); + if (file == null) { + logger.info("TestExecJavaTask No File"); + } else { + try { + logger.info("TestExecJavaTask File: " + file.getFile()); + } catch (CommandAbstractException e) { + } + } + if (runner == null) { + logger.info("TestExecJavaTask No Runner"); + } else { + logger.info("TestExecJavaTask Runner: " + runner.toShortString()); + } + this.status = 0; + } + } +} diff --git a/src/main/java/org/waarp/openr66/context/task/test/package-info.java b/src/main/java/org/waarp/openr66/context/task/test/package-info.java index 253e02ed7..cbf7777d2 100644 --- a/src/main/java/org/waarp/openr66/context/task/test/package-info.java +++ b/src/main/java/org/waarp/openr66/context/task/test/package-info.java @@ -1,24 +1,24 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -/** - * Package for an example of Java Task for ExecJava - * - * @author "Frederic Bregier" - * - */ +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +/** + * Package for an example of Java Task for ExecJava + * + * @author "Frederic Bregier" + * + */ package org.waarp.openr66.context.task.test; \ No newline at end of file diff --git a/src/main/java/org/waarp/openr66/database/DbConstant.java b/src/main/java/org/waarp/openr66/database/DbConstant.java index 568cc406d..f2e913579 100644 --- a/src/main/java/org/waarp/openr66/database/DbConstant.java +++ b/src/main/java/org/waarp/openr66/database/DbConstant.java @@ -1,27 +1,27 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database; - -/** - * Constants value for database - * - * @author Frederic Bregier - * - */ -public class DbConstant extends org.waarp.common.database.DbConstant { -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database; + +/** + * Constants value for database + * + * @author Frederic Bregier + * + */ +public class DbConstant extends org.waarp.common.database.DbConstant { +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java b/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java index 399516dac..cfed20a3c 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java +++ b/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java @@ -1,445 +1,445 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.sql.Types; -import java.util.concurrent.ConcurrentHashMap; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.commander.CommanderNoDb; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Configuration Table object - * - * @author Frederic Bregier - * - */ -public class DbConfiguration extends AbstractDbData { - public static enum Columns { - READGLOBALLIMIT, - WRITEGLOBALLIMIT, - READSESSIONLIMIT, - WRITESESSIONLIMIT, - DELAYLIMIT, - UPDATEDINFO, - HOSTID - } - - public static final int[] dbTypes = { - Types.BIGINT, Types.BIGINT, Types.BIGINT, Types.BIGINT, - Types.BIGINT, Types.INTEGER, Types.VARCHAR }; - - public static final String table = " CONFIGURATION "; - - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66ConfigurationHashMap = - new ConcurrentHashMap(); - - private String hostid; - - private long readgloballimit; - - private long writegloballimit; - - private long readsessionlimit; - - private long writesessionlimit; - - private long delayllimit; - - private int updatedInfo = UpdatedInfo.UNKNOWN - .ordinal(); - - // ALL TABLE SHOULD IMPLEMENT THIS - public static final int NBPRKEY = 1; - - protected static final String selectAllFields = Columns.READGLOBALLIMIT - .name() - + - "," - + - Columns.WRITEGLOBALLIMIT - .name() - + - "," - + - Columns.READSESSIONLIMIT - .name() - + - "," - + - Columns.WRITESESSIONLIMIT - .name() - + - "," - + - Columns.DELAYLIMIT - .name() - + - "," - + Columns.UPDATEDINFO - .name() - + "," - + Columns.HOSTID - .name(); - - protected static final String updateAllFields = Columns.READGLOBALLIMIT - .name() - + - "=?," - + - Columns.WRITEGLOBALLIMIT - .name() - + - "=?," - + - Columns.READSESSIONLIMIT - .name() - + - "=?," - + - Columns.WRITESESSIONLIMIT - .name() - + - "=?," - + - Columns.DELAYLIMIT - .name() - + - "=?," - + - Columns.UPDATEDINFO - .name() - + - "=?"; - - protected static final String insertAllValues = " (?,?,?,?,?,?,?) "; - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID - .name()) }; - otherFields = new DbValue[] { - new DbValue(readgloballimit, Columns.READGLOBALLIMIT.name()), - new DbValue(writegloballimit, Columns.WRITEGLOBALLIMIT.name()), - new DbValue(readsessionlimit, Columns.READSESSIONLIMIT.name()), - new DbValue(writesessionlimit, Columns.WRITESESSIONLIMIT.name()), - new DbValue(delayllimit, Columns.DELAYLIMIT.name()), - new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], otherFields[3], - otherFields[4], otherFields[5], primaryKey[0] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.HOSTID.ordinal()].setValue(hostid); - allFields[Columns.READGLOBALLIMIT.ordinal()].setValue((readgloballimit / 10) * 10); - allFields[Columns.WRITEGLOBALLIMIT.ordinal()] - .setValue((writegloballimit / 10) * 10); - allFields[Columns.READSESSIONLIMIT.ordinal()] - .setValue((readsessionlimit / 10) * 10); - allFields[Columns.WRITESESSIONLIMIT.ordinal()] - .setValue((writesessionlimit / 10) * 10); - allFields[Columns.DELAYLIMIT.ordinal()].setValue(delayllimit); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); - readgloballimit = (((Long) allFields[Columns.READGLOBALLIMIT.ordinal()] - .getValue()) / 10) * 10; - writegloballimit = (((Long) allFields[Columns.WRITEGLOBALLIMIT.ordinal()] - .getValue()) / 10) * 10; - readsessionlimit = (((Long) allFields[Columns.READSESSIONLIMIT.ordinal()] - .getValue()) / 10) * 10; - writesessionlimit = (((Long) allFields[Columns.WRITESESSIONLIMIT - .ordinal()].getValue()) / 10) * 10; - delayllimit = (Long) allFields[Columns.DELAYLIMIT.ordinal()].getValue(); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() - */ - @Override - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? "; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() - */ - @Override - protected void setPrimaryKey() { - primaryKey[0].setValue(hostid); - } - - /** - * @param dbSession - * @param hostid - * @param rg - * Read Global Limit - * @param wg - * Write Global Limit - * @param rs - * Read Session Limit - * @param ws - * Write Session Limit - * @param del - * Delay Limit - */ - public DbConfiguration(DbSession dbSession, String hostid, long rg, long wg, long rs, - long ws, long del) { - super(dbSession); - this.hostid = hostid; - readgloballimit = (rg / 10) * 10; - writegloballimit = (wg / 10) * 10; - readsessionlimit = (rs / 10) * 10; - writesessionlimit = (ws / 10) * 10; - delayllimit = del; - setToArray(); - isSaved = false; - } - - /** - * @param dbSession - * @param hostid - * @throws WaarpDatabaseException - */ - public DbConfiguration(DbSession dbSession, String hostid) throws WaarpDatabaseException { - super(dbSession); - this.hostid = hostid; - // load from DB - select(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - if (dbSession == null) { - dbR66ConfigurationHashMap.remove(this.hostid); - isSaved = false; - return; - } - super.delete(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66ConfigurationHashMap.put(this.hostid, this); - isSaved = true; - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - CommanderNoDb.todoList.add(this); - } - return; - } - super.insert(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - if (dbSession == null) { - return dbR66ConfigurationHashMap.containsKey(hostid); - } - return super.exist(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - if (dbSession == null) { - DbConfiguration conf = dbR66ConfigurationHashMap.get(this.hostid); - if (conf == null) { - throw new WaarpDatabaseNoDataException("No row found"); - } else { - // copy info - for (int i = 0; i < allFields.length; i++) { - allFields[i].value = conf.allFields[i].value; - } - setFromArray(); - isSaved = true; - return; - } - } - super.select(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66ConfigurationHashMap.put(this.hostid, this); - isSaved = true; - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - CommanderNoDb.todoList.add(this); - } - return; - } - super.update(); - } - - /** - * Private constructor for Commander only - */ - private DbConfiguration(DbSession session) { - super(session); - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated Configuration - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbConfiguration getFromStatement(DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbConfiguration dbConfiguration = new DbConfiguration(preparedStatement.getDbSession()); - dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); - dbConfiguration.setFromArray(); - dbConfiguration.isSaved = true; - return dbConfiguration; - } - - /** - * - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields; - request += " FROM " + table + - " WHERE " + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + - " AND " + Columns.HOSTID.name() + " = '" + Configuration.configuration.HOST_ID - + "'"; - DbPreparedStatement prep = new DbPreparedStatement(session, request); - return prep; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - if (updatedInfo != info.ordinal()) { - updatedInfo = info.ordinal(); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - isSaved = false; - } - } - - /** - * Update configuration according to new value of limits - */ - public void updateConfiguration() { - Configuration.configuration.changeNetworkLimit(writegloballimit, - readgloballimit, writesessionlimit, readsessionlimit, delayllimit); - } - - /** - * - * @return True if this Configuration refers to the current host - */ - public boolean isOwnConfiguration() { - return this.hostid.equals(Configuration.configuration.HOST_ID); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.sql.Types; +import java.util.concurrent.ConcurrentHashMap; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.commander.CommanderNoDb; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Configuration Table object + * + * @author Frederic Bregier + * + */ +public class DbConfiguration extends AbstractDbData { + public static enum Columns { + READGLOBALLIMIT, + WRITEGLOBALLIMIT, + READSESSIONLIMIT, + WRITESESSIONLIMIT, + DELAYLIMIT, + UPDATEDINFO, + HOSTID + } + + public static final int[] dbTypes = { + Types.BIGINT, Types.BIGINT, Types.BIGINT, Types.BIGINT, + Types.BIGINT, Types.INTEGER, Types.VARCHAR }; + + public static final String table = " CONFIGURATION "; + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66ConfigurationHashMap = + new ConcurrentHashMap(); + + private String hostid; + + private long readgloballimit; + + private long writegloballimit; + + private long readsessionlimit; + + private long writesessionlimit; + + private long delayllimit; + + private int updatedInfo = UpdatedInfo.UNKNOWN + .ordinal(); + + // ALL TABLE SHOULD IMPLEMENT THIS + public static final int NBPRKEY = 1; + + protected static final String selectAllFields = Columns.READGLOBALLIMIT + .name() + + + "," + + + Columns.WRITEGLOBALLIMIT + .name() + + + "," + + + Columns.READSESSIONLIMIT + .name() + + + "," + + + Columns.WRITESESSIONLIMIT + .name() + + + "," + + + Columns.DELAYLIMIT + .name() + + + "," + + Columns.UPDATEDINFO + .name() + + "," + + Columns.HOSTID + .name(); + + protected static final String updateAllFields = Columns.READGLOBALLIMIT + .name() + + + "=?," + + + Columns.WRITEGLOBALLIMIT + .name() + + + "=?," + + + Columns.READSESSIONLIMIT + .name() + + + "=?," + + + Columns.WRITESESSIONLIMIT + .name() + + + "=?," + + + Columns.DELAYLIMIT + .name() + + + "=?," + + + Columns.UPDATEDINFO + .name() + + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?,?,?,?) "; + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID + .name()) }; + otherFields = new DbValue[] { + new DbValue(readgloballimit, Columns.READGLOBALLIMIT.name()), + new DbValue(writegloballimit, Columns.WRITEGLOBALLIMIT.name()), + new DbValue(readsessionlimit, Columns.READSESSIONLIMIT.name()), + new DbValue(writesessionlimit, Columns.WRITESESSIONLIMIT.name()), + new DbValue(delayllimit, Columns.DELAYLIMIT.name()), + new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], otherFields[3], + otherFields[4], otherFields[5], primaryKey[0] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.HOSTID.ordinal()].setValue(hostid); + allFields[Columns.READGLOBALLIMIT.ordinal()].setValue((readgloballimit / 10) * 10); + allFields[Columns.WRITEGLOBALLIMIT.ordinal()] + .setValue((writegloballimit / 10) * 10); + allFields[Columns.READSESSIONLIMIT.ordinal()] + .setValue((readsessionlimit / 10) * 10); + allFields[Columns.WRITESESSIONLIMIT.ordinal()] + .setValue((writesessionlimit / 10) * 10); + allFields[Columns.DELAYLIMIT.ordinal()].setValue(delayllimit); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); + readgloballimit = (((Long) allFields[Columns.READGLOBALLIMIT.ordinal()] + .getValue()) / 10) * 10; + writegloballimit = (((Long) allFields[Columns.WRITEGLOBALLIMIT.ordinal()] + .getValue()) / 10) * 10; + readsessionlimit = (((Long) allFields[Columns.READSESSIONLIMIT.ordinal()] + .getValue()) / 10) * 10; + writesessionlimit = (((Long) allFields[Columns.WRITESESSIONLIMIT + .ordinal()].getValue()) / 10) * 10; + delayllimit = (Long) allFields[Columns.DELAYLIMIT.ordinal()].getValue(); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() + */ + @Override + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? "; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() + */ + @Override + protected void setPrimaryKey() { + primaryKey[0].setValue(hostid); + } + + /** + * @param dbSession + * @param hostid + * @param rg + * Read Global Limit + * @param wg + * Write Global Limit + * @param rs + * Read Session Limit + * @param ws + * Write Session Limit + * @param del + * Delay Limit + */ + public DbConfiguration(DbSession dbSession, String hostid, long rg, long wg, long rs, + long ws, long del) { + super(dbSession); + this.hostid = hostid; + readgloballimit = (rg / 10) * 10; + writegloballimit = (wg / 10) * 10; + readsessionlimit = (rs / 10) * 10; + writesessionlimit = (ws / 10) * 10; + delayllimit = del; + setToArray(); + isSaved = false; + } + + /** + * @param dbSession + * @param hostid + * @throws WaarpDatabaseException + */ + public DbConfiguration(DbSession dbSession, String hostid) throws WaarpDatabaseException { + super(dbSession); + this.hostid = hostid; + // load from DB + select(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + if (dbSession == null) { + dbR66ConfigurationHashMap.remove(this.hostid); + isSaved = false; + return; + } + super.delete(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66ConfigurationHashMap.put(this.hostid, this); + isSaved = true; + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + CommanderNoDb.todoList.add(this); + } + return; + } + super.insert(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + if (dbSession == null) { + return dbR66ConfigurationHashMap.containsKey(hostid); + } + return super.exist(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + if (dbSession == null) { + DbConfiguration conf = dbR66ConfigurationHashMap.get(this.hostid); + if (conf == null) { + throw new WaarpDatabaseNoDataException("No row found"); + } else { + // copy info + for (int i = 0; i < allFields.length; i++) { + allFields[i].value = conf.allFields[i].value; + } + setFromArray(); + isSaved = true; + return; + } + } + super.select(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66ConfigurationHashMap.put(this.hostid, this); + isSaved = true; + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + CommanderNoDb.todoList.add(this); + } + return; + } + super.update(); + } + + /** + * Private constructor for Commander only + */ + private DbConfiguration(DbSession session) { + super(session); + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated Configuration + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbConfiguration getFromStatement(DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbConfiguration dbConfiguration = new DbConfiguration(preparedStatement.getDbSession()); + dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); + dbConfiguration.setFromArray(); + dbConfiguration.isSaved = true; + return dbConfiguration; + } + + /** + * + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields; + request += " FROM " + table + + " WHERE " + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + + " AND " + Columns.HOSTID.name() + " = '" + Configuration.configuration.HOST_ID + + "'"; + DbPreparedStatement prep = new DbPreparedStatement(session, request); + return prep; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + if (updatedInfo != info.ordinal()) { + updatedInfo = info.ordinal(); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + isSaved = false; + } + } + + /** + * Update configuration according to new value of limits + */ + public void updateConfiguration() { + Configuration.configuration.changeNetworkLimit(writegloballimit, + readgloballimit, writesessionlimit, readsessionlimit, delayllimit); + } + + /** + * + * @return True if this Configuration refers to the current host + */ + public boolean isOwnConfiguration() { + return this.hostid.equals(Configuration.configuration.HOST_ID); + } +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java index ca7024027..969791bdf 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java +++ b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java @@ -1,728 +1,728 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; - -/** - * Host Authentication Table object - * - * @author Frederic Bregier - * - */ -public class DbHostAuth extends AbstractDbData { - public static enum Columns { - ADDRESS, PORT, ISSSL, HOSTKEY, ADMINROLE, ISCLIENT, UPDATEDINFO, HOSTID - } - - public static final int[] dbTypes = { - Types.VARCHAR, Types.INTEGER, Types.BIT, - Types.VARBINARY, Types.BIT, Types.BIT, Types.INTEGER, Types.VARCHAR }; - - public static final String table = " HOSTS "; - - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66HostAuthHashMap = - new ConcurrentHashMap(); - - private String hostid; - - private String address; - - private int port; - - private boolean isSsl; - - private byte[] hostkey; - - private boolean adminrole; - - private boolean isClient; - - private int updatedInfo = UpdatedInfo.UNKNOWN - .ordinal(); - - // ALL TABLE SHOULD IMPLEMENT THIS - public static final int NBPRKEY = 1; - - protected static final String selectAllFields = Columns.ADDRESS - .name() - + "," - + - Columns.PORT - .name() - + "," - + Columns.ISSSL - .name() - + "," - + - Columns.HOSTKEY - .name() - + "," - + - Columns.ADMINROLE - .name() - + "," - + Columns.ISCLIENT - .name() - + "," - + - Columns.UPDATEDINFO - .name() - + "," - + - Columns.HOSTID - .name(); - - protected static final String updateAllFields = - Columns.ADDRESS - .name() - + "=?," - + Columns.PORT - .name() - + - "=?," - + Columns.ISSSL - .name() - + "=?," - + Columns.HOSTKEY - .name() - + - "=?," - + Columns.ADMINROLE - .name() - + "=?," - + - Columns.ISCLIENT - .name() - + "=?," - + - Columns.UPDATEDINFO - .name() - + "=?"; - - protected static final String insertAllValues = " (?,?,?,?,?,?,?,?) "; - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID - .name()) }; - otherFields = new DbValue[] { - new DbValue(address, Columns.ADDRESS.name()), - new DbValue(port, Columns.PORT.name()), - new DbValue(isSsl, Columns.ISSSL.name()), - new DbValue(hostkey, Columns.HOSTKEY.name()), - new DbValue(adminrole, Columns.ADMINROLE.name()), - new DbValue(isClient, Columns.ISCLIENT.name()), - new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], - otherFields[3], otherFields[4], otherFields[5], otherFields[6], primaryKey[0] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.ADDRESS.ordinal()].setValue(address); - allFields[Columns.PORT.ordinal()].setValue(port); - allFields[Columns.ISSSL.ordinal()].setValue(isSsl); - allFields[Columns.HOSTKEY.ordinal()].setValue(hostkey); - allFields[Columns.ADMINROLE.ordinal()].setValue(adminrole); - allFields[Columns.ISCLIENT.ordinal()].setValue(isClient); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - allFields[Columns.HOSTID.ordinal()].setValue(hostid); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - address = (String) allFields[Columns.ADDRESS.ordinal()].getValue(); - port = (Integer) allFields[Columns.PORT.ordinal()].getValue(); - isSsl = (Boolean) allFields[Columns.ISSSL.ordinal()].getValue(); - hostkey = (byte[]) allFields[Columns.HOSTKEY.ordinal()].getValue(); - adminrole = (Boolean) allFields[Columns.ADMINROLE.ordinal()].getValue(); - isClient = (Boolean) allFields[Columns.ISCLIENT.ordinal()].getValue(); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() - */ - @Override - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? "; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() - */ - @Override - protected void setPrimaryKey() { - primaryKey[0].setValue(hostid); - } - - /** - * @param dbSession - * @param hostid - * @param address - * @param port - * @param isSSL - * @param hostkey - * @param adminrole - * @param isClient - */ - public DbHostAuth(DbSession dbSession, String hostid, String address, int port, - boolean isSSL, byte[] hostkey, boolean adminrole, boolean isClient) { - super(dbSession); - this.hostid = hostid; - this.address = address; - this.port = port; - this.isSsl = isSSL; - if (hostkey == null) { - this.hostkey = null; - } else { - try { - // Save as crypted with the local Key and Base64 - this.hostkey = Configuration.configuration.cryptoKey.cryptToHex(hostkey).getBytes(); - } catch (Exception e) { - this.hostkey = new byte[0]; - } - } - this.adminrole = adminrole; - this.isClient = isClient; - setToArray(); - isSaved = false; - } - - /** - * @param dbSession - * @param hostid - * @throws WaarpDatabaseException - */ - public DbHostAuth(DbSession dbSession, String hostid) throws WaarpDatabaseException { - super(dbSession); - this.hostid = hostid; - // load from DB - select(); - } - - /** - * Delete all entries (used when purge and reload) - * - * @param dbSession - * @return the previous existing array of DbRule - * @throws WaarpDatabaseException - */ - public static DbHostAuth[] deleteAll(DbSession dbSession) throws WaarpDatabaseException { - DbHostAuth[] result = getAllHosts(dbSession); - if (dbSession == null) { - dbR66HostAuthHashMap.clear(); - return result; - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("DELETE FROM " + table); - preparedStatement.executeUpdate(); - return result; - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - if (dbSession == null) { - dbR66HostAuthHashMap.remove(this.hostid); - isSaved = false; - return; - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("DELETE FROM " + table + - " WHERE " + getWherePrimaryKey()); - setPrimaryKey(); - setValues(preparedStatement, primaryKey); - int count = preparedStatement.executeUpdate(); - if (count <= 0) { - throw new WaarpDatabaseNoDataException("No row found"); - } - isSaved = false; - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66HostAuthHashMap.put(this.hostid, this); - isSaved = true; - return; - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("INSERT INTO " + table + - " (" + selectAllFields + ") VALUES " + insertAllValues); - setValues(preparedStatement, allFields); - int count = preparedStatement.executeUpdate(); - if (count <= 0) { - throw new WaarpDatabaseNoDataException("No row found"); - } - isSaved = true; - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - if (dbSession == null) { - return dbR66HostAuthHashMap.containsKey(hostid); - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("SELECT " + - primaryKey[0].column + " FROM " + table + " WHERE " + - getWherePrimaryKey()); - setPrimaryKey(); - setValues(preparedStatement, primaryKey); - preparedStatement.executeQuery(); - return preparedStatement.getNext(); - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - if (dbSession == null) { - DbHostAuth host = dbR66HostAuthHashMap.get(this.hostid); - if (host == null) { - throw new WaarpDatabaseNoDataException("No row found"); - } else { - // copy info - for (int i = 0; i < allFields.length; i++) { - allFields[i].value = host.allFields[i].value; - } - setFromArray(); - isSaved = true; - return; - } - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("SELECT " + - selectAllFields + " FROM " + table + " WHERE " + - getWherePrimaryKey()); - setPrimaryKey(); - setValues(preparedStatement, primaryKey); - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - getValues(preparedStatement, allFields); - setFromArray(); - isSaved = true; - } else { - throw new WaarpDatabaseNoDataException("No row found"); - } - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66HostAuthHashMap.put(this.hostid, this); - isSaved = true; - return; - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("UPDATE " + table + - " SET " + updateAllFields + " WHERE " + - getWherePrimaryKey()); - setValues(preparedStatement, allFields); - int count = preparedStatement.executeUpdate(); - if (count <= 0) { - throw new WaarpDatabaseNoDataException("No row found"); - } - isSaved = true; - } finally { - preparedStatement.realClose(); - } - } - - /** - * Private constructor for Commander only - */ - private DbHostAuth(DbSession session) { - super(session); - } - - /** - * Get All DbHostAuth from database or from internal hashMap in case of no database support - * - * @param dbSession - * may be null - * @return the array of DbHostAuth - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbHostAuth[] getAllHosts(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - if (dbSession == null) { - DbHostAuth[] result = new DbHostAuth[0]; - return dbR66HostAuthHashMap.values().toArray(result); - } - String request = "SELECT " + selectAllFields; - request += " FROM " + table; - DbPreparedStatement preparedStatement = new DbPreparedStatement(dbSession, request); - ArrayList dbArrayList = new ArrayList(); - preparedStatement.executeQuery(); - while (preparedStatement.getNext()) { - DbHostAuth hostAuth = getFromStatement(preparedStatement); - dbArrayList.add(hostAuth); - } - preparedStatement.realClose(); - DbHostAuth[] result = new DbHostAuth[0]; - return dbArrayList.toArray(result); - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated DbHostAuth - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbHostAuth getFromStatement(DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbHostAuth dbHostAuth = new DbHostAuth(preparedStatement.getDbSession()); - dbHostAuth.getValues(preparedStatement, dbHostAuth.allFields); - dbHostAuth.setFromArray(); - dbHostAuth.isSaved = true; - return dbHostAuth; - } - - /** - * - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields; - request += " FROM " + table + - " WHERE " + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal(); - DbPreparedStatement prep = new DbPreparedStatement(session, request); - return prep; - } - - /** - * - * @param session - * @param host - * @param addr - * @param ssl - * @return the DbPreparedStatement according to the filter - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getFilterPrepareStament(DbSession session, - String host, String addr, boolean ssl) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "SELECT " + selectAllFields + " FROM " + table + " WHERE "; - String condition = null; - if (host != null) { - condition = Columns.HOSTID.name() + " LIKE '%" + host + "%' "; - } - if (addr != null) { - if (condition != null) { - condition += " AND "; - } else { - condition = ""; - } - condition += Columns.ADDRESS.name() + " LIKE '%" + addr + "%' "; - } - if (condition != null) { - condition += " AND "; - } else { - condition = ""; - } - condition += Columns.ISSSL.name() + " = ?"; - preparedStatement.createPrepareStatement(request + condition + - " ORDER BY " + Columns.HOSTID.name()); - try { - preparedStatement.getPreparedStatement().setBoolean(1, ssl); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - return preparedStatement; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - if (updatedInfo != info.ordinal()) { - updatedInfo = info.ordinal(); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - isSaved = false; - } - } - - /** - * Is the given key a valid one - * - * @param newkey - * @return True if the key is valid (or any key is valid) - */ - public boolean isKeyValid(byte[] newkey) { - // It is valid to not have a key - if (this.hostkey == null) { - return true; - } - if (newkey == null) { - return false; - } - try { - return FilesystemBasedDigest.equalPasswd( - Configuration.configuration.cryptoKey.decryptHexInBytes(this.hostkey), - newkey); - } catch (Exception e) { - return false; - } - } - - /** - * @return the hostkey - */ - public byte[] getHostkey() { - if (hostkey == null) { - return null; - } - try { - return Configuration.configuration.cryptoKey.decryptHexInBytes(hostkey); - } catch (Exception e) { - return new byte[0]; - } - } - - /** - * @return the adminrole - */ - public boolean isAdminrole() { - return adminrole; - } - - /** - * Test if the address is 0.0.0.0 for a client or isClient - * - * @return True if the address is a client address (0.0.0.0) or isClient - */ - public boolean isClient() { - return isClient || (this.address.equals("0.0.0.0")); - } - - /** - * True if the address is a client address (0.0.0.0) - * - * @return True if the address is a client address (0.0.0.0) - */ - public boolean isNoAddress() { - return (this.address.equals("0.0.0.0")); - } - - /** - * - * @return the SocketAddress from the address and port - */ - public SocketAddress getSocketAddress() { - return new InetSocketAddress(this.address, this.port); - } - - /** - * - * @return True if this Host ref is with SSL support - */ - public boolean isSsl() { - return this.isSsl; - } - - /** - * @return the hostid - */ - public String getHostid() { - return hostid; - } - - /** - * @return the address - */ - public String getAddress() { - return address; - } - - /** - * @return the port - */ - public int getPort() { - return port; - } - - @Override - public String toString() { - return "HostAuth: " + hostid + " address: " + address + ":" + port + " isSSL: " + isSsl + - " admin: " + adminrole + " isClient: " + isClient + " (" - + (hostkey != null ? hostkey.length : 0) + ")"; - } - - /** - * @param session - * @param body - * @param crypted - * True if the Key is kept crypted, False it will be in clear form - * @return the runner in Html format specified by body by replacing all instance of fields - */ - public String toSpecializedHtml(R66Session session, String body, boolean crypted) { - StringBuilder builder = new StringBuilder(body); - WaarpStringUtils.replace(builder, "XXXHOSTXXX", hostid); - WaarpStringUtils.replace(builder, "XXXADDRXXX", address); - WaarpStringUtils.replace(builder, "XXXPORTXXX", Integer.toString(port)); - if (crypted) { - WaarpStringUtils.replace(builder, "XXXKEYXXX", new String(hostkey)); - } else { - try { - WaarpStringUtils.replace(builder, "XXXKEYXXX", - Configuration.configuration.cryptoKey.decryptHexInString(new String( - this.hostkey))); - } catch (Exception e) { - WaarpStringUtils.replace(builder, "XXXKEYXXX", "BAD DECRYPT"); - } - } - WaarpStringUtils.replace(builder, "XXXSSLXXX", isSsl ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXADMXXX", adminrole ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXISCXXX", isClient ? "checked" : ""); - int nb = NetworkTransaction.existConnection(getSocketAddress(), getHostid()); - WaarpStringUtils.replace(builder, "XXXCONNXXX", (nb > 0) - ? "(" + nb + " Connected) " : ""); - return builder.toString(); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; + +/** + * Host Authentication Table object + * + * @author Frederic Bregier + * + */ +public class DbHostAuth extends AbstractDbData { + public static enum Columns { + ADDRESS, PORT, ISSSL, HOSTKEY, ADMINROLE, ISCLIENT, UPDATEDINFO, HOSTID + } + + public static final int[] dbTypes = { + Types.VARCHAR, Types.INTEGER, Types.BIT, + Types.VARBINARY, Types.BIT, Types.BIT, Types.INTEGER, Types.VARCHAR }; + + public static final String table = " HOSTS "; + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66HostAuthHashMap = + new ConcurrentHashMap(); + + private String hostid; + + private String address; + + private int port; + + private boolean isSsl; + + private byte[] hostkey; + + private boolean adminrole; + + private boolean isClient; + + private int updatedInfo = UpdatedInfo.UNKNOWN + .ordinal(); + + // ALL TABLE SHOULD IMPLEMENT THIS + public static final int NBPRKEY = 1; + + protected static final String selectAllFields = Columns.ADDRESS + .name() + + "," + + + Columns.PORT + .name() + + "," + + Columns.ISSSL + .name() + + "," + + + Columns.HOSTKEY + .name() + + "," + + + Columns.ADMINROLE + .name() + + "," + + Columns.ISCLIENT + .name() + + "," + + + Columns.UPDATEDINFO + .name() + + "," + + + Columns.HOSTID + .name(); + + protected static final String updateAllFields = + Columns.ADDRESS + .name() + + "=?," + + Columns.PORT + .name() + + + "=?," + + Columns.ISSSL + .name() + + "=?," + + Columns.HOSTKEY + .name() + + + "=?," + + Columns.ADMINROLE + .name() + + "=?," + + + Columns.ISCLIENT + .name() + + "=?," + + + Columns.UPDATEDINFO + .name() + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?,?,?,?,?) "; + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID + .name()) }; + otherFields = new DbValue[] { + new DbValue(address, Columns.ADDRESS.name()), + new DbValue(port, Columns.PORT.name()), + new DbValue(isSsl, Columns.ISSSL.name()), + new DbValue(hostkey, Columns.HOSTKEY.name()), + new DbValue(adminrole, Columns.ADMINROLE.name()), + new DbValue(isClient, Columns.ISCLIENT.name()), + new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], + otherFields[3], otherFields[4], otherFields[5], otherFields[6], primaryKey[0] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.ADDRESS.ordinal()].setValue(address); + allFields[Columns.PORT.ordinal()].setValue(port); + allFields[Columns.ISSSL.ordinal()].setValue(isSsl); + allFields[Columns.HOSTKEY.ordinal()].setValue(hostkey); + allFields[Columns.ADMINROLE.ordinal()].setValue(adminrole); + allFields[Columns.ISCLIENT.ordinal()].setValue(isClient); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + allFields[Columns.HOSTID.ordinal()].setValue(hostid); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + address = (String) allFields[Columns.ADDRESS.ordinal()].getValue(); + port = (Integer) allFields[Columns.PORT.ordinal()].getValue(); + isSsl = (Boolean) allFields[Columns.ISSSL.ordinal()].getValue(); + hostkey = (byte[]) allFields[Columns.HOSTKEY.ordinal()].getValue(); + adminrole = (Boolean) allFields[Columns.ADMINROLE.ordinal()].getValue(); + isClient = (Boolean) allFields[Columns.ISCLIENT.ordinal()].getValue(); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() + */ + @Override + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? "; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() + */ + @Override + protected void setPrimaryKey() { + primaryKey[0].setValue(hostid); + } + + /** + * @param dbSession + * @param hostid + * @param address + * @param port + * @param isSSL + * @param hostkey + * @param adminrole + * @param isClient + */ + public DbHostAuth(DbSession dbSession, String hostid, String address, int port, + boolean isSSL, byte[] hostkey, boolean adminrole, boolean isClient) { + super(dbSession); + this.hostid = hostid; + this.address = address; + this.port = port; + this.isSsl = isSSL; + if (hostkey == null) { + this.hostkey = null; + } else { + try { + // Save as crypted with the local Key and Base64 + this.hostkey = Configuration.configuration.cryptoKey.cryptToHex(hostkey).getBytes(); + } catch (Exception e) { + this.hostkey = new byte[0]; + } + } + this.adminrole = adminrole; + this.isClient = isClient; + setToArray(); + isSaved = false; + } + + /** + * @param dbSession + * @param hostid + * @throws WaarpDatabaseException + */ + public DbHostAuth(DbSession dbSession, String hostid) throws WaarpDatabaseException { + super(dbSession); + this.hostid = hostid; + // load from DB + select(); + } + + /** + * Delete all entries (used when purge and reload) + * + * @param dbSession + * @return the previous existing array of DbRule + * @throws WaarpDatabaseException + */ + public static DbHostAuth[] deleteAll(DbSession dbSession) throws WaarpDatabaseException { + DbHostAuth[] result = getAllHosts(dbSession); + if (dbSession == null) { + dbR66HostAuthHashMap.clear(); + return result; + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("DELETE FROM " + table); + preparedStatement.executeUpdate(); + return result; + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + if (dbSession == null) { + dbR66HostAuthHashMap.remove(this.hostid); + isSaved = false; + return; + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("DELETE FROM " + table + + " WHERE " + getWherePrimaryKey()); + setPrimaryKey(); + setValues(preparedStatement, primaryKey); + int count = preparedStatement.executeUpdate(); + if (count <= 0) { + throw new WaarpDatabaseNoDataException("No row found"); + } + isSaved = false; + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66HostAuthHashMap.put(this.hostid, this); + isSaved = true; + return; + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("INSERT INTO " + table + + " (" + selectAllFields + ") VALUES " + insertAllValues); + setValues(preparedStatement, allFields); + int count = preparedStatement.executeUpdate(); + if (count <= 0) { + throw new WaarpDatabaseNoDataException("No row found"); + } + isSaved = true; + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + if (dbSession == null) { + return dbR66HostAuthHashMap.containsKey(hostid); + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("SELECT " + + primaryKey[0].column + " FROM " + table + " WHERE " + + getWherePrimaryKey()); + setPrimaryKey(); + setValues(preparedStatement, primaryKey); + preparedStatement.executeQuery(); + return preparedStatement.getNext(); + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + if (dbSession == null) { + DbHostAuth host = dbR66HostAuthHashMap.get(this.hostid); + if (host == null) { + throw new WaarpDatabaseNoDataException("No row found"); + } else { + // copy info + for (int i = 0; i < allFields.length; i++) { + allFields[i].value = host.allFields[i].value; + } + setFromArray(); + isSaved = true; + return; + } + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("SELECT " + + selectAllFields + " FROM " + table + " WHERE " + + getWherePrimaryKey()); + setPrimaryKey(); + setValues(preparedStatement, primaryKey); + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + getValues(preparedStatement, allFields); + setFromArray(); + isSaved = true; + } else { + throw new WaarpDatabaseNoDataException("No row found"); + } + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66HostAuthHashMap.put(this.hostid, this); + isSaved = true; + return; + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("UPDATE " + table + + " SET " + updateAllFields + " WHERE " + + getWherePrimaryKey()); + setValues(preparedStatement, allFields); + int count = preparedStatement.executeUpdate(); + if (count <= 0) { + throw new WaarpDatabaseNoDataException("No row found"); + } + isSaved = true; + } finally { + preparedStatement.realClose(); + } + } + + /** + * Private constructor for Commander only + */ + private DbHostAuth(DbSession session) { + super(session); + } + + /** + * Get All DbHostAuth from database or from internal hashMap in case of no database support + * + * @param dbSession + * may be null + * @return the array of DbHostAuth + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbHostAuth[] getAllHosts(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + if (dbSession == null) { + DbHostAuth[] result = new DbHostAuth[0]; + return dbR66HostAuthHashMap.values().toArray(result); + } + String request = "SELECT " + selectAllFields; + request += " FROM " + table; + DbPreparedStatement preparedStatement = new DbPreparedStatement(dbSession, request); + ArrayList dbArrayList = new ArrayList(); + preparedStatement.executeQuery(); + while (preparedStatement.getNext()) { + DbHostAuth hostAuth = getFromStatement(preparedStatement); + dbArrayList.add(hostAuth); + } + preparedStatement.realClose(); + DbHostAuth[] result = new DbHostAuth[0]; + return dbArrayList.toArray(result); + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated DbHostAuth + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbHostAuth getFromStatement(DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbHostAuth dbHostAuth = new DbHostAuth(preparedStatement.getDbSession()); + dbHostAuth.getValues(preparedStatement, dbHostAuth.allFields); + dbHostAuth.setFromArray(); + dbHostAuth.isSaved = true; + return dbHostAuth; + } + + /** + * + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields; + request += " FROM " + table + + " WHERE " + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal(); + DbPreparedStatement prep = new DbPreparedStatement(session, request); + return prep; + } + + /** + * + * @param session + * @param host + * @param addr + * @param ssl + * @return the DbPreparedStatement according to the filter + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getFilterPrepareStament(DbSession session, + String host, String addr, boolean ssl) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "SELECT " + selectAllFields + " FROM " + table + " WHERE "; + String condition = null; + if (host != null) { + condition = Columns.HOSTID.name() + " LIKE '%" + host + "%' "; + } + if (addr != null) { + if (condition != null) { + condition += " AND "; + } else { + condition = ""; + } + condition += Columns.ADDRESS.name() + " LIKE '%" + addr + "%' "; + } + if (condition != null) { + condition += " AND "; + } else { + condition = ""; + } + condition += Columns.ISSSL.name() + " = ?"; + preparedStatement.createPrepareStatement(request + condition + + " ORDER BY " + Columns.HOSTID.name()); + try { + preparedStatement.getPreparedStatement().setBoolean(1, ssl); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + return preparedStatement; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + if (updatedInfo != info.ordinal()) { + updatedInfo = info.ordinal(); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + isSaved = false; + } + } + + /** + * Is the given key a valid one + * + * @param newkey + * @return True if the key is valid (or any key is valid) + */ + public boolean isKeyValid(byte[] newkey) { + // It is valid to not have a key + if (this.hostkey == null) { + return true; + } + if (newkey == null) { + return false; + } + try { + return FilesystemBasedDigest.equalPasswd( + Configuration.configuration.cryptoKey.decryptHexInBytes(this.hostkey), + newkey); + } catch (Exception e) { + return false; + } + } + + /** + * @return the hostkey + */ + public byte[] getHostkey() { + if (hostkey == null) { + return null; + } + try { + return Configuration.configuration.cryptoKey.decryptHexInBytes(hostkey); + } catch (Exception e) { + return new byte[0]; + } + } + + /** + * @return the adminrole + */ + public boolean isAdminrole() { + return adminrole; + } + + /** + * Test if the address is 0.0.0.0 for a client or isClient + * + * @return True if the address is a client address (0.0.0.0) or isClient + */ + public boolean isClient() { + return isClient || (this.address.equals("0.0.0.0")); + } + + /** + * True if the address is a client address (0.0.0.0) + * + * @return True if the address is a client address (0.0.0.0) + */ + public boolean isNoAddress() { + return (this.address.equals("0.0.0.0")); + } + + /** + * + * @return the SocketAddress from the address and port + */ + public SocketAddress getSocketAddress() { + return new InetSocketAddress(this.address, this.port); + } + + /** + * + * @return True if this Host ref is with SSL support + */ + public boolean isSsl() { + return this.isSsl; + } + + /** + * @return the hostid + */ + public String getHostid() { + return hostid; + } + + /** + * @return the address + */ + public String getAddress() { + return address; + } + + /** + * @return the port + */ + public int getPort() { + return port; + } + + @Override + public String toString() { + return "HostAuth: " + hostid + " address: " + address + ":" + port + " isSSL: " + isSsl + + " admin: " + adminrole + " isClient: " + isClient + " (" + + (hostkey != null ? hostkey.length : 0) + ")"; + } + + /** + * @param session + * @param body + * @param crypted + * True if the Key is kept crypted, False it will be in clear form + * @return the runner in Html format specified by body by replacing all instance of fields + */ + public String toSpecializedHtml(R66Session session, String body, boolean crypted) { + StringBuilder builder = new StringBuilder(body); + WaarpStringUtils.replace(builder, "XXXHOSTXXX", hostid); + WaarpStringUtils.replace(builder, "XXXADDRXXX", address); + WaarpStringUtils.replace(builder, "XXXPORTXXX", Integer.toString(port)); + if (crypted) { + WaarpStringUtils.replace(builder, "XXXKEYXXX", new String(hostkey)); + } else { + try { + WaarpStringUtils.replace(builder, "XXXKEYXXX", + Configuration.configuration.cryptoKey.decryptHexInString(new String( + this.hostkey))); + } catch (Exception e) { + WaarpStringUtils.replace(builder, "XXXKEYXXX", "BAD DECRYPT"); + } + } + WaarpStringUtils.replace(builder, "XXXSSLXXX", isSsl ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXADMXXX", adminrole ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXISCXXX", isClient ? "checked" : ""); + int nb = NetworkTransaction.existConnection(getSocketAddress(), getHostid()); + WaarpStringUtils.replace(builder, "XXXCONNXXX", (nb > 0) + ? "(" + nb + " Connected) " : ""); + return builder.toString(); + } +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java b/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java index 46b795749..c64e13bee 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java +++ b/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java @@ -1,504 +1,504 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.sql.Types; -import java.util.concurrent.ConcurrentHashMap; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.commander.CommanderNoDb; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Configuration Table object - * - * @author Frederic Bregier - * - */ -public class DbHostConfiguration extends AbstractDbData { - public static enum Columns { - BUSINESS, - ROLES, - ALIASES, - OTHERS, - UPDATEDINFO, - HOSTID - } - - public static final int[] dbTypes = { - Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, - Types.INTEGER, Types.VARCHAR }; - - public static final String table = " HOSTCONFIG "; - - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66HostConfigurationHashMap = - new ConcurrentHashMap(); - - private String hostid; - - private String business; - - private String roles; - - private String aliases; - - private String others; - - private int updatedInfo = UpdatedInfo.UNKNOWN - .ordinal(); - - // ALL TABLE SHOULD IMPLEMENT THIS - public static final int NBPRKEY = 1; - - protected static final String selectAllFields = Columns.BUSINESS - .name() - + - "," - + - Columns.ROLES - .name() - + - "," - + - Columns.ALIASES - .name() - + - "," - + - Columns.OTHERS - .name() - + - "," - + Columns.UPDATEDINFO - .name() - + "," - + Columns.HOSTID - .name(); - - protected static final String updateAllFields = Columns.BUSINESS - .name() - + - "=?," - + - Columns.ROLES - .name() - + - "=?," - + - Columns.ALIASES - .name() - + - "=?," - + - Columns.OTHERS - .name() - + - "=?," - + - Columns.UPDATEDINFO - .name() - + - "=?"; - - protected static final String insertAllValues = " (?,?,?,?,?,?) "; - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID - .name()) }; - otherFields = new DbValue[] { - new DbValue(business, Columns.BUSINESS.name(), true), - new DbValue(roles, Columns.ROLES.name(), true), - new DbValue(aliases, Columns.ALIASES.name(), true), - new DbValue(others, Columns.OTHERS.name(), true), - new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], otherFields[3], - otherFields[4], primaryKey[0] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.HOSTID.ordinal()].setValue(hostid); - if (business == null) { - business = ""; - } - allFields[Columns.BUSINESS.ordinal()].setValue(business); - if (roles == null) { - roles = ""; - } - allFields[Columns.ROLES.ordinal()] - .setValue(roles); - if (aliases == null) { - aliases = ""; - } - allFields[Columns.ALIASES.ordinal()] - .setValue(aliases); - if (others == null) { - others = ""; - } - allFields[Columns.OTHERS.ordinal()] - .setValue(others); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); - business = (String) allFields[Columns.BUSINESS.ordinal()].getValue(); - roles = (String) allFields[Columns.ROLES.ordinal()].getValue(); - aliases = (String) allFields[Columns.ALIASES.ordinal()].getValue(); - others = (String) allFields[Columns.OTHERS.ordinal()].getValue(); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() - */ - @Override - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? "; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() - */ - @Override - protected void setPrimaryKey() { - primaryKey[0].setValue(hostid); - } - - /** - * @param dbSession - * @param hostid - * @param business - * Business configuration - * @param roles - * Roles configuration - * @param aliases - * Aliases configuration - * @param others - * Other configuration - */ - public DbHostConfiguration(DbSession dbSession, String hostid, String business, String roles, String aliases, String others) { - super(dbSession); - this.hostid = hostid; - this.business = business; - this.roles = roles; - this.aliases = aliases; - this.others = others; - setToArray(); - isSaved = false; - } - - /** - * @param dbSession - * @param hostid - * @throws WaarpDatabaseException - */ - public DbHostConfiguration(DbSession dbSession, String hostid) throws WaarpDatabaseException { - super(dbSession); - this.hostid = hostid; - // load from DB - select(); - } - - /** - * @return the hostid - */ - public String getHostid() { - return hostid; - } - - /** - * @return the business - */ - public String getBusiness() { - return business; - } - - /** - * @param business the business to set - */ - public void setBusiness(String business) { - this.business = business == null ? "" : business; - allFields[Columns.BUSINESS.ordinal()].setValue(business); - isSaved = false; - } - - /** - * @return the roles - */ - public String getRoles() { - return roles; - } - - /** - * @param roles the roles to set - */ - public void setRoles(String roles) { - this.roles = roles == null ? "" : roles; - allFields[Columns.ROLES.ordinal()].setValue(roles); - isSaved = false; - } - - /** - * @return the aliases - */ - public String getAliases() { - return aliases; - } - - /** - * @param aliases the aliases to set - */ - public void setAliases(String aliases) { - this.aliases = aliases == null ? "" : aliases; - allFields[Columns.ALIASES.ordinal()].setValue(aliases); - isSaved = false; - } - - /** - * @return the others - */ - public String getOthers() { - return others; - } - - /** - * @param others the others to set - */ - public void setOthers(String others) { - this.others = others == null ? "" : others; - allFields[Columns.OTHERS.ordinal()].setValue(others); - isSaved = false; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - if (dbSession == null) { - dbR66HostConfigurationHashMap.remove(this.hostid); - isSaved = false; - return; - } - super.delete(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66HostConfigurationHashMap.put(this.hostid, this); - isSaved = true; - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - CommanderNoDb.todoList.add(this); - } - return; - } - super.insert(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - if (dbSession == null) { - return dbR66HostConfigurationHashMap.containsKey(hostid); - } - return super.exist(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - if (dbSession == null) { - DbHostConfiguration conf = dbR66HostConfigurationHashMap.get(this.hostid); - if (conf == null) { - throw new WaarpDatabaseNoDataException("No row found"); - } else { - // copy info - for (int i = 0; i < allFields.length; i++) { - allFields[i].value = conf.allFields[i].value; - } - setFromArray(); - isSaved = true; - return; - } - } - super.select(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66HostConfigurationHashMap.put(this.hostid, this); - isSaved = true; - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - CommanderNoDb.todoList.add(this); - } - return; - } - super.update(); - } - - /** - * Private constructor for Commander only - */ - private DbHostConfiguration(DbSession session) { - super(session); - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated Configuration - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbHostConfiguration getFromStatement(DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbHostConfiguration dbConfiguration = new DbHostConfiguration(preparedStatement.getDbSession()); - dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); - dbConfiguration.setFromArray(); - dbConfiguration.isSaved = true; - return dbConfiguration; - } - - /** - * - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields; - request += " FROM " + table + - " WHERE " + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + - " AND " + Columns.HOSTID.name() + " = '" + Configuration.configuration.HOST_ID - + "'"; - DbPreparedStatement prep = new DbPreparedStatement(session, request); - return prep; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - if (updatedInfo != info.ordinal()) { - updatedInfo = info.ordinal(); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - isSaved = false; - } - } - - /** - * Update configuration according to new values - */ - public void updateConfiguration() { - FileBasedConfiguration.updateHostConfiguration(Configuration.configuration, this); - } - - /** - * - * @return True if this Configuration refers to the current host - */ - public boolean isOwnConfiguration() { - return this.hostid.equals(Configuration.configuration.HOST_ID); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.sql.Types; +import java.util.concurrent.ConcurrentHashMap; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.commander.CommanderNoDb; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Configuration Table object + * + * @author Frederic Bregier + * + */ +public class DbHostConfiguration extends AbstractDbData { + public static enum Columns { + BUSINESS, + ROLES, + ALIASES, + OTHERS, + UPDATEDINFO, + HOSTID + } + + public static final int[] dbTypes = { + Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, + Types.INTEGER, Types.VARCHAR }; + + public static final String table = " HOSTCONFIG "; + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66HostConfigurationHashMap = + new ConcurrentHashMap(); + + private String hostid; + + private String business; + + private String roles; + + private String aliases; + + private String others; + + private int updatedInfo = UpdatedInfo.UNKNOWN + .ordinal(); + + // ALL TABLE SHOULD IMPLEMENT THIS + public static final int NBPRKEY = 1; + + protected static final String selectAllFields = Columns.BUSINESS + .name() + + + "," + + + Columns.ROLES + .name() + + + "," + + + Columns.ALIASES + .name() + + + "," + + + Columns.OTHERS + .name() + + + "," + + Columns.UPDATEDINFO + .name() + + "," + + Columns.HOSTID + .name(); + + protected static final String updateAllFields = Columns.BUSINESS + .name() + + + "=?," + + + Columns.ROLES + .name() + + + "=?," + + + Columns.ALIASES + .name() + + + "=?," + + + Columns.OTHERS + .name() + + + "=?," + + + Columns.UPDATEDINFO + .name() + + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?,?,?) "; + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID + .name()) }; + otherFields = new DbValue[] { + new DbValue(business, Columns.BUSINESS.name(), true), + new DbValue(roles, Columns.ROLES.name(), true), + new DbValue(aliases, Columns.ALIASES.name(), true), + new DbValue(others, Columns.OTHERS.name(), true), + new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], otherFields[3], + otherFields[4], primaryKey[0] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.HOSTID.ordinal()].setValue(hostid); + if (business == null) { + business = ""; + } + allFields[Columns.BUSINESS.ordinal()].setValue(business); + if (roles == null) { + roles = ""; + } + allFields[Columns.ROLES.ordinal()] + .setValue(roles); + if (aliases == null) { + aliases = ""; + } + allFields[Columns.ALIASES.ordinal()] + .setValue(aliases); + if (others == null) { + others = ""; + } + allFields[Columns.OTHERS.ordinal()] + .setValue(others); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); + business = (String) allFields[Columns.BUSINESS.ordinal()].getValue(); + roles = (String) allFields[Columns.ROLES.ordinal()].getValue(); + aliases = (String) allFields[Columns.ALIASES.ordinal()].getValue(); + others = (String) allFields[Columns.OTHERS.ordinal()].getValue(); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() + */ + @Override + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? "; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() + */ + @Override + protected void setPrimaryKey() { + primaryKey[0].setValue(hostid); + } + + /** + * @param dbSession + * @param hostid + * @param business + * Business configuration + * @param roles + * Roles configuration + * @param aliases + * Aliases configuration + * @param others + * Other configuration + */ + public DbHostConfiguration(DbSession dbSession, String hostid, String business, String roles, String aliases, String others) { + super(dbSession); + this.hostid = hostid; + this.business = business; + this.roles = roles; + this.aliases = aliases; + this.others = others; + setToArray(); + isSaved = false; + } + + /** + * @param dbSession + * @param hostid + * @throws WaarpDatabaseException + */ + public DbHostConfiguration(DbSession dbSession, String hostid) throws WaarpDatabaseException { + super(dbSession); + this.hostid = hostid; + // load from DB + select(); + } + + /** + * @return the hostid + */ + public String getHostid() { + return hostid; + } + + /** + * @return the business + */ + public String getBusiness() { + return business; + } + + /** + * @param business the business to set + */ + public void setBusiness(String business) { + this.business = business == null ? "" : business; + allFields[Columns.BUSINESS.ordinal()].setValue(business); + isSaved = false; + } + + /** + * @return the roles + */ + public String getRoles() { + return roles; + } + + /** + * @param roles the roles to set + */ + public void setRoles(String roles) { + this.roles = roles == null ? "" : roles; + allFields[Columns.ROLES.ordinal()].setValue(roles); + isSaved = false; + } + + /** + * @return the aliases + */ + public String getAliases() { + return aliases; + } + + /** + * @param aliases the aliases to set + */ + public void setAliases(String aliases) { + this.aliases = aliases == null ? "" : aliases; + allFields[Columns.ALIASES.ordinal()].setValue(aliases); + isSaved = false; + } + + /** + * @return the others + */ + public String getOthers() { + return others; + } + + /** + * @param others the others to set + */ + public void setOthers(String others) { + this.others = others == null ? "" : others; + allFields[Columns.OTHERS.ordinal()].setValue(others); + isSaved = false; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + if (dbSession == null) { + dbR66HostConfigurationHashMap.remove(this.hostid); + isSaved = false; + return; + } + super.delete(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66HostConfigurationHashMap.put(this.hostid, this); + isSaved = true; + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + CommanderNoDb.todoList.add(this); + } + return; + } + super.insert(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + if (dbSession == null) { + return dbR66HostConfigurationHashMap.containsKey(hostid); + } + return super.exist(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + if (dbSession == null) { + DbHostConfiguration conf = dbR66HostConfigurationHashMap.get(this.hostid); + if (conf == null) { + throw new WaarpDatabaseNoDataException("No row found"); + } else { + // copy info + for (int i = 0; i < allFields.length; i++) { + allFields[i].value = conf.allFields[i].value; + } + setFromArray(); + isSaved = true; + return; + } + } + super.select(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66HostConfigurationHashMap.put(this.hostid, this); + isSaved = true; + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + CommanderNoDb.todoList.add(this); + } + return; + } + super.update(); + } + + /** + * Private constructor for Commander only + */ + private DbHostConfiguration(DbSession session) { + super(session); + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated Configuration + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbHostConfiguration getFromStatement(DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbHostConfiguration dbConfiguration = new DbHostConfiguration(preparedStatement.getDbSession()); + dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); + dbConfiguration.setFromArray(); + dbConfiguration.isSaved = true; + return dbConfiguration; + } + + /** + * + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields; + request += " FROM " + table + + " WHERE " + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + + " AND " + Columns.HOSTID.name() + " = '" + Configuration.configuration.HOST_ID + + "'"; + DbPreparedStatement prep = new DbPreparedStatement(session, request); + return prep; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + if (updatedInfo != info.ordinal()) { + updatedInfo = info.ordinal(); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + isSaved = false; + } + } + + /** + * Update configuration according to new values + */ + public void updateConfiguration() { + FileBasedConfiguration.updateHostConfiguration(Configuration.configuration, this); + } + + /** + * + * @return True if this Configuration refers to the current host + */ + public boolean isOwnConfiguration() { + return this.hostid.equals(Configuration.configuration.HOST_ID); + } +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java b/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java index f1ee61c35..b0353099c 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java +++ b/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java @@ -1,415 +1,415 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.sql.Types; -import java.util.concurrent.ConcurrentHashMap; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Configuration Table object - * - * @author Frederic Bregier - * - */ -public class DbMultipleMonitor extends AbstractDbData { - public static enum Columns { - COUNTCONFIG, - COUNTHOST, - COUNTRULE, - HOSTID - } - - public static final int[] dbTypes = { - Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR }; - - public static final String table = " MULTIPLEMONITOR "; - - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66MMHashMap = - new ConcurrentHashMap(); - - private String hostid; - - public int countConfig; - - public int countHost; - - public int countRule; - - // ALL TABLE SHOULD IMPLEMENT THIS - public static final int NBPRKEY = 1; - - protected static final String selectAllFields = Columns.COUNTCONFIG - .name() - + - "," - + - Columns.COUNTHOST - .name() - + - "," - + - Columns.COUNTRULE - .name() - + - "," - + - Columns.HOSTID - .name(); - - protected static final String updateAllFields = Columns.COUNTCONFIG - .name() - + - "=?," - + - Columns.COUNTHOST - .name() - + - "=?," - + - Columns.COUNTRULE - .name() - + - "=?"; - - protected static final String insertAllValues = " (?,?,?,?) "; - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID - .name()) }; - otherFields = new DbValue[] { - new DbValue(countConfig, Columns.COUNTCONFIG.name()), - new DbValue(countHost, Columns.COUNTHOST.name()), - new DbValue(countRule, Columns.COUNTRULE.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], primaryKey[0] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.HOSTID.ordinal()].setValue(hostid); - allFields[Columns.COUNTCONFIG.ordinal()].setValue(countConfig); - allFields[Columns.COUNTHOST.ordinal()] - .setValue(countHost); - allFields[Columns.COUNTRULE.ordinal()] - .setValue(countRule); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); - countConfig = (Integer) allFields[Columns.COUNTCONFIG.ordinal()] - .getValue(); - countHost = (Integer) allFields[Columns.COUNTHOST.ordinal()] - .getValue(); - countRule = (Integer) allFields[Columns.COUNTRULE.ordinal()] - .getValue(); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() - */ - @Override - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? "; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() - */ - @Override - protected void setPrimaryKey() { - primaryKey[0].setValue(hostid); - } - - /** - * @param dbSession - * @param hostid - * @param cc - * count for Config - * @param ch - * count for Host - * @param cr - * count for Rule - */ - public DbMultipleMonitor(DbSession dbSession, String hostid, int cc, int ch, int cr) { - super(dbSession); - this.hostid = hostid; - countConfig = cc; - countHost = ch; - countRule = cr; - setToArray(); - isSaved = false; - } - - /** - * @param dbSession - * @param hostid - * @throws WaarpDatabaseException - */ - public DbMultipleMonitor(DbSession dbSession, String hostid) throws WaarpDatabaseException { - super(dbSession); - this.hostid = hostid; - // load from DB - select(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - if (dbSession == null) { - dbR66MMHashMap.remove(this.hostid); - isSaved = false; - return; - } - super.delete(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66MMHashMap.put(this.hostid, this); - isSaved = true; - return; - } - super.insert(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - if (dbSession == null) { - return dbR66MMHashMap.containsKey(hostid); - } - return super.exist(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - if (dbSession == null) { - DbMultipleMonitor conf = dbR66MMHashMap.get(this.hostid); - if (conf == null) { - throw new WaarpDatabaseNoDataException("No row found"); - } else { - // copy info - for (int i = 0; i < allFields.length; i++) { - allFields[i].value = conf.allFields[i].value; - } - setFromArray(); - isSaved = true; - return; - } - } - super.select(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - dbR66MMHashMap.put(this.hostid, this); - isSaved = true; - return; - } - super.update(); - } - - /** - * Private constructor for Commander only - */ - private DbMultipleMonitor(DbSession session) { - super(session); - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated Configuration - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbMultipleMonitor getFromStatement(DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbMultipleMonitor dbMm = new DbMultipleMonitor(preparedStatement.getDbSession()); - dbMm.getValues(preparedStatement, dbMm.allFields); - dbMm.setFromArray(); - dbMm.isSaved = true; - return dbMm; - } - - /** - * - * @return the DbPreparedStatement for getting Updated Object in "FOR UPDATE" mode - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields; - request += " FROM " + table + " WHERE " + Columns.HOSTID.name() + " = '" - + Configuration.configuration.HOST_ID + "'" + - " FOR UPDATE "; - DbPreparedStatement prep = new DbPreparedStatement(session, request); - return prep; - } - - /** - * On Commander side - * - * @return True if this is the last update - */ - public boolean checkUpdateConfig() { - if (countConfig <= 0) { - countConfig = Configuration.configuration.multipleMonitors; - countConfig--; - this.isSaved = false; - } else { - countConfig--; - this.isSaved = false; - } - return this.countConfig <= 0; - } - - /** - * On Commander side - * - * @return True if this is the last update - */ - public boolean checkUpdateHost() { - if (countHost <= 0) { - countHost = Configuration.configuration.multipleMonitors; - countHost--; - this.isSaved = false; - } else { - countHost--; - this.isSaved = false; - } - return this.countHost <= 0; - } - - /** - * On Commander side - * - * @return True if this is the last update - */ - public boolean checkUpdateRule() { - if (countRule <= 0) { - countRule = Configuration.configuration.multipleMonitors; - countRule--; - this.isSaved = false; - } else { - countRule--; - this.isSaved = false; - } - return this.countRule <= 0; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - } - - /** - * return the String representation - */ - public String toString() { - return "DbMM " + countConfig + ":" + countHost + ":" + countRule; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.sql.Types; +import java.util.concurrent.ConcurrentHashMap; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Configuration Table object + * + * @author Frederic Bregier + * + */ +public class DbMultipleMonitor extends AbstractDbData { + public static enum Columns { + COUNTCONFIG, + COUNTHOST, + COUNTRULE, + HOSTID + } + + public static final int[] dbTypes = { + Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR }; + + public static final String table = " MULTIPLEMONITOR "; + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66MMHashMap = + new ConcurrentHashMap(); + + private String hostid; + + public int countConfig; + + public int countHost; + + public int countRule; + + // ALL TABLE SHOULD IMPLEMENT THIS + public static final int NBPRKEY = 1; + + protected static final String selectAllFields = Columns.COUNTCONFIG + .name() + + + "," + + + Columns.COUNTHOST + .name() + + + "," + + + Columns.COUNTRULE + .name() + + + "," + + + Columns.HOSTID + .name(); + + protected static final String updateAllFields = Columns.COUNTCONFIG + .name() + + + "=?," + + + Columns.COUNTHOST + .name() + + + "=?," + + + Columns.COUNTRULE + .name() + + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?) "; + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { new DbValue(hostid, Columns.HOSTID + .name()) }; + otherFields = new DbValue[] { + new DbValue(countConfig, Columns.COUNTCONFIG.name()), + new DbValue(countHost, Columns.COUNTHOST.name()), + new DbValue(countRule, Columns.COUNTRULE.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], primaryKey[0] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.HOSTID.ordinal()].setValue(hostid); + allFields[Columns.COUNTCONFIG.ordinal()].setValue(countConfig); + allFields[Columns.COUNTHOST.ordinal()] + .setValue(countHost); + allFields[Columns.COUNTRULE.ordinal()] + .setValue(countRule); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + hostid = (String) allFields[Columns.HOSTID.ordinal()].getValue(); + countConfig = (Integer) allFields[Columns.COUNTCONFIG.ordinal()] + .getValue(); + countHost = (Integer) allFields[Columns.COUNTHOST.ordinal()] + .getValue(); + countRule = (Integer) allFields[Columns.COUNTRULE.ordinal()] + .getValue(); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() + */ + @Override + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? "; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() + */ + @Override + protected void setPrimaryKey() { + primaryKey[0].setValue(hostid); + } + + /** + * @param dbSession + * @param hostid + * @param cc + * count for Config + * @param ch + * count for Host + * @param cr + * count for Rule + */ + public DbMultipleMonitor(DbSession dbSession, String hostid, int cc, int ch, int cr) { + super(dbSession); + this.hostid = hostid; + countConfig = cc; + countHost = ch; + countRule = cr; + setToArray(); + isSaved = false; + } + + /** + * @param dbSession + * @param hostid + * @throws WaarpDatabaseException + */ + public DbMultipleMonitor(DbSession dbSession, String hostid) throws WaarpDatabaseException { + super(dbSession); + this.hostid = hostid; + // load from DB + select(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + if (dbSession == null) { + dbR66MMHashMap.remove(this.hostid); + isSaved = false; + return; + } + super.delete(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66MMHashMap.put(this.hostid, this); + isSaved = true; + return; + } + super.insert(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + if (dbSession == null) { + return dbR66MMHashMap.containsKey(hostid); + } + return super.exist(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + if (dbSession == null) { + DbMultipleMonitor conf = dbR66MMHashMap.get(this.hostid); + if (conf == null) { + throw new WaarpDatabaseNoDataException("No row found"); + } else { + // copy info + for (int i = 0; i < allFields.length; i++) { + allFields[i].value = conf.allFields[i].value; + } + setFromArray(); + isSaved = true; + return; + } + } + super.select(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + dbR66MMHashMap.put(this.hostid, this); + isSaved = true; + return; + } + super.update(); + } + + /** + * Private constructor for Commander only + */ + private DbMultipleMonitor(DbSession session) { + super(session); + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated Configuration + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbMultipleMonitor getFromStatement(DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbMultipleMonitor dbMm = new DbMultipleMonitor(preparedStatement.getDbSession()); + dbMm.getValues(preparedStatement, dbMm.allFields); + dbMm.setFromArray(); + dbMm.isSaved = true; + return dbMm; + } + + /** + * + * @return the DbPreparedStatement for getting Updated Object in "FOR UPDATE" mode + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields; + request += " FROM " + table + " WHERE " + Columns.HOSTID.name() + " = '" + + Configuration.configuration.HOST_ID + "'" + + " FOR UPDATE "; + DbPreparedStatement prep = new DbPreparedStatement(session, request); + return prep; + } + + /** + * On Commander side + * + * @return True if this is the last update + */ + public boolean checkUpdateConfig() { + if (countConfig <= 0) { + countConfig = Configuration.configuration.multipleMonitors; + countConfig--; + this.isSaved = false; + } else { + countConfig--; + this.isSaved = false; + } + return this.countConfig <= 0; + } + + /** + * On Commander side + * + * @return True if this is the last update + */ + public boolean checkUpdateHost() { + if (countHost <= 0) { + countHost = Configuration.configuration.multipleMonitors; + countHost--; + this.isSaved = false; + } else { + countHost--; + this.isSaved = false; + } + return this.countHost <= 0; + } + + /** + * On Commander side + * + * @return True if this is the last update + */ + public boolean checkUpdateRule() { + if (countRule <= 0) { + countRule = Configuration.configuration.multipleMonitors; + countRule--; + this.isSaved = false; + } else { + countRule--; + this.isSaved = false; + } + return this.countRule <= 0; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + } + + /** + * return the String representation + */ + public String toString() { + return "DbMM " + countConfig + ":" + countHost + ":" + countRule; + } +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbRule.java b/src/main/java/org/waarp/openr66/database/data/DbRule.java index 60fa41854..76b6efc57 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbRule.java +++ b/src/main/java/org/waarp/openr66/database/data/DbRule.java @@ -1,1234 +1,1234 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.io.File; -import java.io.StringReader; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.io.SAXReader; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.file.DirInterface; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.common.xml.XmlUtil; -import org.waarp.common.xml.XmlValue; -import org.waarp.openr66.configuration.RuleFileBasedConfiguration; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Rule Table object - * - * @author Frederic Bregier - * - */ -public class DbRule extends AbstractDbData { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(DbRule.class); - - public static enum Columns { - HOSTIDS, - MODETRANS, - RECVPATH, - SENDPATH, - ARCHIVEPATH, - WORKPATH, - RPRETASKS, - RPOSTTASKS, - RERRORTASKS, - SPRETASKS, - SPOSTTASKS, - SERRORTASKS, - UPDATEDINFO, - IDRULE - } - - public static final int[] dbTypes = { - Types.LONGVARCHAR, - Types.INTEGER, Types.VARCHAR, Types.VARCHAR, - Types.VARCHAR, Types.VARCHAR, - Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, - Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, - Types.INTEGER, Types.VARCHAR }; - - public static final String table = " RULES "; - - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66RuleHashMap = - new ConcurrentHashMap(); - - /** - * Internal context XML fields - */ - private static final String XMLHOSTIDS = "<" - + RuleFileBasedConfiguration.XHOSTIDS - + ">"; - - /** - * Internal context XML fields - */ - private static final String XMLENDHOSTIDS = ""; - - /** - * Internal context XML fields - */ - private static final String XMLHOSTID = "<" - + RuleFileBasedConfiguration.XHOSTID - + ">"; - - /** - * Internal context XML fields - */ - private static final String XMLENDHOSTID = ""; - - /** - * Internal context XML fields - */ - private static final String XMLTASKS = "<" - + RuleFileBasedConfiguration.XTASKS - + ">"; - - /** - * Internal context XML fields - */ - private static final String XMLENDTASKS = ""; - - /** - * Internal context XML fields - */ - private static final String XMLTASK = "<" - + RuleFileBasedConfiguration.XTASK - + ">"; - - /** - * Internal context XML fields - */ - private static final String XMLENDTASK = ""; - - /** - * Internal context XML fields - */ - public static final String TASK_TYPE = "type"; - - /** - * Internal context XML fields - */ - public static final String TASK_PATH = "path"; - - /** - * Internal context XML fields - */ - public static final String TASK_DELAY = "delay"; - - /** - * Global Id - */ - public String idRule = null; - - /** - * The Name addresses (serverIds) - */ - public String ids = null; - - /** - * Supported Mode for this rule (SENDMODE => SENDMD5MODE, RECVMODE => RECVMD5MODE) - */ - public int mode; - - /** - * The associated Recv Path - */ - public String recvPath = null; - - /** - * The associated Send Path - */ - public String sendPath = null; - - /** - * The associated Archive Path - */ - public String archivePath = null; - - /** - * The associated Work Path - */ - public String workPath = null; - - /** - * The associated Pre Tasks for Receiver - */ - public String rpreTasks = null; - - /** - * The associated Post Tasks for Receiver - */ - public String rpostTasks = null; - - /** - * The associated Error Tasks for Receiver - */ - public String rerrorTasks = null; - - /** - * The associated Pre Tasks for Sender - */ - public String spreTasks = null; - - /** - * The associated Post Tasks for Sender - */ - public String spostTasks = null; - - /** - * The associated Error Tasks for Sender - */ - public String serrorTasks = null; - - /** - * The Ids as an array - */ - public String[] idsArray = null; - - /** - * The associated Pre Tasks as an array for Receiver - */ - public String[][] rpreTasksArray = null; - - /** - * The associated Post Tasks as an array for Receiver - */ - public String[][] rpostTasksArray = null; - - /** - * The associated Error Tasks as an array for Receiver - */ - public String[][] rerrorTasksArray = null; - - /** - * The associated Pre Tasks as an array for Sender - */ - public String[][] spreTasksArray = null; - - /** - * The associated Post Tasks as an array for Sender - */ - public String[][] spostTasksArray = null; - - /** - * The associated Error Tasks as an array for Sender - */ - public String[][] serrorTasksArray = null; - - private int updatedInfo = UpdatedInfo.UNKNOWN - .ordinal(); - - // ALL TABLE SHOULD IMPLEMENT THIS - public static final int NBPRKEY = 1; - - protected static final String selectAllFields = Columns.HOSTIDS - .name() - + "," - + - Columns.MODETRANS - .name() - + "," - + Columns.RECVPATH - .name() - + "," - + - Columns.SENDPATH - .name() - + "," - + Columns.ARCHIVEPATH - .name() - + "," - + - Columns.WORKPATH - .name() - + "," - + - Columns.RPRETASKS - .name() - + "," - + - Columns.RPOSTTASKS - .name() - + "," - + Columns.RERRORTASKS - .name() - + "," - + - Columns.SPRETASKS - .name() - + "," - + - Columns.SPOSTTASKS - .name() - + "," - + Columns.SERRORTASKS - .name() - + "," - + - Columns.UPDATEDINFO - .name() - + "," - + Columns.IDRULE - .name(); - - protected static final String updateAllFields = Columns.HOSTIDS - .name() - + - "=?," - + Columns.MODETRANS - .name() - + "=?," - + Columns.RECVPATH - .name() - + - "=?," - + Columns.SENDPATH - .name() - + "=?," - + - Columns.ARCHIVEPATH - .name() - + "=?," - + Columns.WORKPATH - .name() - + - "=?," - + Columns.RPRETASKS - .name() - + "=?," - + Columns.RPOSTTASKS - .name() - + - "=?," - + Columns.RERRORTASKS - .name() - + "=?," - + - Columns.SPRETASKS - .name() - + "=?," - + Columns.SPOSTTASKS - .name() - + - "=?," - + Columns.SERRORTASKS - .name() - + "=?," - + - Columns.UPDATEDINFO - .name() - + "=?"; - - protected static final String insertAllValues = " (?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { new DbValue(idRule, Columns.IDRULE - .name()) }; - otherFields = new DbValue[] { - // HOSTIDS, MODETRANS, RECVPATH, SENDPATH, ARCHIVEPATH, WORKPATH, - // PRETASKS, POSTTASKS, ERRORTASKS - new DbValue(ids, Columns.HOSTIDS.name(), true), - new DbValue(mode, Columns.MODETRANS.name()), - new DbValue(recvPath, Columns.RECVPATH.name()), - new DbValue(sendPath, Columns.SENDPATH.name()), - new DbValue(archivePath, Columns.ARCHIVEPATH.name()), - new DbValue(workPath, Columns.WORKPATH.name()), - new DbValue(rpreTasks, Columns.RPRETASKS.name(), true), - new DbValue(rpostTasks, Columns.RPOSTTASKS.name(), true), - new DbValue(rerrorTasks, Columns.RERRORTASKS.name(), true), - new DbValue(spreTasks, Columns.SPRETASKS.name(), true), - new DbValue(spostTasks, Columns.SPOSTTASKS.name(), true), - new DbValue(serrorTasks, Columns.SERRORTASKS.name(), true), - new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], otherFields[3], - otherFields[4], otherFields[5], otherFields[6], otherFields[7], - otherFields[8], otherFields[9], otherFields[10], - otherFields[11], otherFields[12], primaryKey[0] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.HOSTIDS.ordinal()].setValue(ids); - allFields[Columns.MODETRANS.ordinal()].setValue(mode); - allFields[Columns.RECVPATH.ordinal()].setValue(recvPath); - allFields[Columns.SENDPATH.ordinal()].setValue(sendPath); - allFields[Columns.ARCHIVEPATH.ordinal()].setValue(archivePath); - allFields[Columns.WORKPATH.ordinal()].setValue(workPath); - allFields[Columns.RPRETASKS.ordinal()].setValue(rpreTasks); - allFields[Columns.RPOSTTASKS.ordinal()].setValue(rpostTasks); - allFields[Columns.RERRORTASKS.ordinal()].setValue(rerrorTasks); - allFields[Columns.SPRETASKS.ordinal()].setValue(spreTasks); - allFields[Columns.SPOSTTASKS.ordinal()].setValue(spostTasks); - allFields[Columns.SERRORTASKS.ordinal()].setValue(serrorTasks); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - allFields[Columns.IDRULE.ordinal()].setValue(idRule); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue(); - mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); - recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue(); - sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue(); - archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()] - .getValue(); - workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue(); - rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue(); - rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue(); - rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()] - .getValue(); - spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue(); - spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue(); - serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()] - .getValue(); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue(); - getIdsRule(ids); - rpreTasksArray = getTasksRule(rpreTasks); - rpostTasksArray = getTasksRule(rpostTasks); - rerrorTasksArray = getTasksRule(rerrorTasks); - spreTasksArray = getTasksRule(spreTasks); - spostTasksArray = getTasksRule(spostTasks); - serrorTasksArray = getTasksRule(serrorTasks); - } - - protected void setFromArrayClone(DbRule source) throws WaarpDatabaseSqlException { - ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue(); - mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); - recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue(); - sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue(); - archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()] - .getValue(); - workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue(); - rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue(); - rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue(); - rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()] - .getValue(); - spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue(); - spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue(); - serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()] - .getValue(); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue(); - if (source.ids == null) { - // No ids so setting to the default! - ids = null; - idsArray = null; - } else { - ids = source.ids; - idsArray = source.idsArray; - } - rpreTasksArray = source.rpreTasksArray; - rpostTasksArray = source.rpostTasksArray; - rerrorTasksArray = source.rerrorTasksArray; - spreTasksArray = source.spreTasksArray; - spostTasksArray = source.spostTasksArray; - serrorTasksArray = source.serrorTasksArray; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() - */ - @Override - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? "; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() - */ - @Override - protected void setPrimaryKey() { - primaryKey[0].setValue(idRule); - } - - /** - * @param dbSession - * @param idRule - * @param ids - * @param mode - * @param recvPath - * @param sendPath - * @param archivePath - * @param workPath - * @param rpreTasks - * @param rpostTasks - * @param rerrorTasks - * @param spreTasks - * @param spostTasks - * @param serrorTasks - */ - public DbRule(DbSession dbSession, String idRule, String ids, int mode, String recvPath, - String sendPath, String archivePath, String workPath, - String rpreTasks, String rpostTasks, String rerrorTasks, - String spreTasks, String spostTasks, String serrorTasks) { - super(dbSession); - this.idRule = idRule; - this.ids = ids; - this.mode = mode; - this.recvPath = recvPath; - this.sendPath = sendPath; - this.archivePath = archivePath; - this.workPath = workPath; - this.rpreTasks = rpreTasks; - this.rpostTasks = rpostTasks; - this.rerrorTasks = rerrorTasks; - this.spreTasks = spreTasks; - this.spostTasks = spostTasks; - this.serrorTasks = serrorTasks; - getIdsRule(this.ids); - rpreTasksArray = getTasksRule(this.rpreTasks); - rpostTasksArray = getTasksRule(this.rpostTasks); - rerrorTasksArray = getTasksRule(this.rerrorTasks); - spreTasksArray = getTasksRule(this.spreTasks); - spostTasksArray = getTasksRule(this.spostTasks); - serrorTasksArray = getTasksRule(this.serrorTasks); - // and reverse - this.rpreTasks = setTasksRule(rpreTasksArray); - this.rpostTasks = setTasksRule(rpostTasksArray); - this.rerrorTasks = setTasksRule(rerrorTasksArray); - this.spreTasks = setTasksRule(spreTasksArray); - this.spostTasks = setTasksRule(spostTasksArray); - this.serrorTasks = setTasksRule(serrorTasksArray); - setToArray(); - isSaved = false; - } - - /** - * @param dbSession - * @param idRule - * @throws WaarpDatabaseException - */ - public DbRule(DbSession dbSession, String idRule) throws WaarpDatabaseException { - super(dbSession); - this.idRule = idRule; - // load from DB - select(); - /* - * getIdsRule(ids); rpreTasksArray = getTasksRule(this.rpreTasks); rpostTasksArray = - * getTasksRule(this.rpostTasks); rerrorTasksArray = getTasksRule(this.rerrorTasks); - * spreTasksArray = getTasksRule(this.spreTasks); spostTasksArray = - * getTasksRule(this.spostTasks); serrorTasksArray = getTasksRule(this.serrorTasks); - */ - } - - /** - * Constructor used from XML file - * - * @param dbSession - * @param idrule - * @param idsArrayRef - * @param recvpath - * @param sendpath - * @param archivepath - * @param workpath - * @param rpretasksArray - * @param rposttasksArray - * @param rerrortasksArray - * @param spretasksArray - * @param sposttasksArray - * @param serrortasksArray - */ - public DbRule(DbSession dbSession, String idrule, String[] idsArrayRef, int mode, - String recvpath, String sendpath, String archivepath, - String workpath, - String[][] rpretasksArray, String[][] rposttasksArray, String[][] rerrortasksArray, - String[][] spretasksArray, String[][] sposttasksArray, String[][] serrortasksArray) { - super(dbSession); - idRule = idrule; - idsArray = idsArrayRef; - this.mode = mode; - recvPath = recvpath; - sendPath = sendpath; - archivePath = archivepath; - workPath = workpath; - rpreTasksArray = rpretasksArray; - rpostTasksArray = rposttasksArray; - rerrorTasksArray = rerrortasksArray; - spreTasksArray = spretasksArray; - spostTasksArray = sposttasksArray; - serrorTasksArray = serrortasksArray; - ids = setIdsRule(idsArrayRef); - rpreTasks = setTasksRule(rpretasksArray); - rpostTasks = setTasksRule(rposttasksArray); - rerrorTasks = setTasksRule(rerrortasksArray); - spreTasks = setTasksRule(spretasksArray); - spostTasks = setTasksRule(sposttasksArray); - serrorTasks = setTasksRule(serrortasksArray); - setToArray(); - isSaved = false; - } - - /** - * Delete all entries (used when purge and reload) - * - * @param dbSession - * @return the previous existing array of DbRule - * @throws WaarpDatabaseException - */ - public static DbRule[] deleteAll(DbSession dbSession) throws WaarpDatabaseException { - DbRule[] result = getAllRules(dbSession); - dbR66RuleHashMap.clear(); - if (dbSession == null) { - return result; - } - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("DELETE FROM " + table); - preparedStatement.executeUpdate(); - return result; - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - dbR66RuleHashMap.remove(this.idRule); - if (dbSession == null) { - isSaved = false; - return; - } - super.delete(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - dbR66RuleHashMap.put(this.idRule, this); - if (dbSession == null) { - isSaved = true; - return; - } - super.insert(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - boolean result = dbR66RuleHashMap.containsKey(idRule); - if (result) { - return result; - } - if (dbSession == null) { - if (!result) { - isSaved = false; - } - return result; - } - return super.exist(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - DbRule rule = dbR66RuleHashMap.get(this.idRule); - if (rule != null) { - // copy info - for (int i = 0; i < allFields.length; i++) { - allFields[i].value = rule.allFields[i].value; - } - setFromArrayClone(rule); - if (recvPath == null) { - recvPath = Configuration.configuration.inPath; - } - if (sendPath == null) { - sendPath = Configuration.configuration.outPath; - } - if (archivePath == null) { - archivePath = Configuration.configuration.archivePath; - } - if (workPath == null) { - workPath = Configuration.configuration.workingPath; - } - isSaved = true; - return; - } - if (dbSession == null) { - if (rule == null) { - throw new WaarpDatabaseNoDataException("No row found"); - } - } - super.select(); - if (recvPath == null) { - recvPath = Configuration.configuration.inPath; - } - if (sendPath == null) { - sendPath = Configuration.configuration.outPath; - } - if (archivePath == null) { - archivePath = Configuration.configuration.archivePath; - } - if (workPath == null) { - workPath = Configuration.configuration.workingPath; - } - setFromArray(); - dbR66RuleHashMap.put(this.idRule, this); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - dbR66RuleHashMap.put(this.idRule, this); - if (dbSession == null) { - isSaved = true; - return; - } - super.update(); - } - - /** - * Private constructor for Commander only - */ - private DbRule(DbSession session) { - super(session); - } - - /** - * Get All DbRule from database or from internal hashMap in case of no database support - * - * @param dbSession - * may be null - * @return the array of DbRule - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbRule[] getAllRules(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbRule[] result = new DbRule[0]; - if (!dbR66RuleHashMap.isEmpty()) { - return dbR66RuleHashMap.values().toArray(result); - } - if (dbSession == null) { - return result; - } - String request = "SELECT " + selectAllFields; - request += " FROM " + table; - DbPreparedStatement preparedStatement = new DbPreparedStatement(dbSession, request); - ArrayList dbArrayList = new ArrayList(); - preparedStatement.executeQuery(); - while (preparedStatement.getNext()) { - DbRule dbrule = getFromStatement(preparedStatement); - dbArrayList.add(dbrule); - } - preparedStatement.realClose(); - return dbArrayList.toArray(result); - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated DbRule - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbRule getFromStatement(DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbRule dbRule = new DbRule(preparedStatement.getDbSession()); - dbRule.getValues(preparedStatement, dbRule.allFields); - dbRule.setFromArray(); - dbRule.isSaved = true; - logger.debug("Get one Rule from Db: "+dbRule.idRule); - dbR66RuleHashMap.put(dbRule.idRule, dbRule); - return dbRule; - } - - /** - * - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields; - request += " FROM " + table + - " WHERE " + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal(); - DbPreparedStatement prep = new DbPreparedStatement(session, request); - return prep; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - if (updatedInfo != info.ordinal()) { - updatedInfo = info.ordinal(); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - isSaved = false; - } - } - - /** - * Get Ids from String. If it is not ok, then it sets the default values and return False, else - * returns True. - * - * @param idsref - * @return True if ok, else False (default values). - */ - private boolean getIdsRule(String idsref) { - if (idsref == null) { - // No ids so setting to the default! - ids = null; - idsArray = null; - return false; - } - ids = idsref; - StringReader reader = new StringReader(idsref); - Document document = null; - try { - document = new SAXReader().read(reader); - } catch (DocumentException e) { - logger.warn("Unable to read the ids for Rule: " + idsref, e); - // No ids so setting to the default! - ids = null; - idsArray = null; - reader.close(); - return false; - } - XmlValue[] values = XmlUtil.read(document, - RuleFileBasedConfiguration.hostsDecls); - idsArray = RuleFileBasedConfiguration.getHostIds(values[0]); - reader.close(); - return true; - } - - /** - * Get Tasks from String. If it is not ok, then it sets the default values and return new array - * of Tasks or null if in error. - * - * @param tasks - * @return Array of tasks or empty array if in error. - */ - private String[][] getTasksRule(String tasks) { - if (tasks == null) { - // No tasks so setting to the default! - return new String[0][0]; - } - StringReader reader = new StringReader(tasks); - Document document = null; - try { - document = new SAXReader().read(reader); - } catch (DocumentException e) { - logger.warn("Unable to read the tasks for Rule: " + tasks, e); - // No tasks so setting to the default! - reader.close(); - return new String[0][0]; - } - XmlValue[] values = XmlUtil.read(document, RuleFileBasedConfiguration.tasksDecl); - String[][] result = RuleFileBasedConfiguration.getTasksRule(values[0]); - reader.close(); - return result; - } - - /** - * Initialized a ids String from args - * - * @param idsArray - * @return the new ids string - */ - private static String setIdsRule(String[] idsArray) { - String ids = null; - if (idsArray != null) { - ids = XMLHOSTIDS; - for (String element : idsArray) { - ids += XMLHOSTID + element + XMLENDHOSTID + "\n"; - } - ids += XMLENDHOSTIDS; - } - return ids; - } - - /** - * Initialized a tasks String from args - * - * @param tasksArray - * @return the new tasks string - */ - private static String setTasksRule(String[][] tasksArray) { - StringBuilder builder = new StringBuilder(); - if (tasksArray != null) { - builder.append(XMLTASKS); - for (int i = 0; i < tasksArray.length; i++) { - builder.append(XMLTASK); - builder.append('<').append(TASK_TYPE).append('>'); - builder.append(tasksArray[i][0]); - builder.append("\n"); - builder.append('<').append(TASK_PATH).append('>'); - builder.append(tasksArray[i][1]); - builder.append("\n"); - builder.append('<').append(TASK_DELAY).append('>'); - builder.append(tasksArray[i][2]); - builder.append("'); - builder.append(XMLENDTASK).append('\n'); - } - builder.append(XMLENDTASKS); - } - return builder.toString(); - } - - /** - * Get the full path from RecvPath (used only in copy MODETRANS) - * - * @param filename - * @return the full String path - * @throws OpenR66ProtocolSystemException - */ - public String setRecvPath(String filename) - throws OpenR66ProtocolSystemException { - if (recvPath != null) { - return recvPath + DirInterface.SEPARATOR + filename; - } - return FileUtils.consolidatePath(Configuration.configuration.inPath, - filename); - } - - /** - * Get the full path from sendPath - * - * @param filename - * @return the full String path - * @throws OpenR66ProtocolSystemException - */ - public String setSendPath(String filename) - throws OpenR66ProtocolSystemException { - if (sendPath != null) { - File file = new File(filename); - String basename = file.getName(); - return sendPath + DirInterface.SEPARATOR + basename; - } - return FileUtils.consolidatePath(Configuration.configuration.outPath, - filename); - } - - /** - * Get the full path from archivePath - * - * @param filename - * @return the full String path - * @throws OpenR66ProtocolSystemException - */ - public String setArchivePath(String filename) - throws OpenR66ProtocolSystemException { - if (archivePath != null) { - return archivePath + DirInterface.SEPARATOR + filename; - } - return FileUtils.consolidatePath( - Configuration.configuration.archivePath, filename); - } - - /** - * Get the full path from workPath - * - * @param filename - * @return the full String path - * @throws OpenR66ProtocolSystemException - */ - public String setWorkingPath(String filename) - throws OpenR66ProtocolSystemException { - if (workPath != null) { - return workPath + DirInterface.SEPARATOR + filename + - Configuration.EXT_R66; - } - return FileUtils.consolidatePath( - Configuration.configuration.workingPath, filename); - } - - /** - * Check if the given hostTo is in the allowed list - * - * @param hostId - * @return True if allow, else False - */ - public boolean checkHostAllow(String hostId) { - if (idsArray == null || idsArray.length == 0) { - return true; // always true in this case - } - for (String element : idsArray) { - if (element.equalsIgnoreCase(hostId)) { - return true; - } - } - return false; - } - - /** - * - * @return True if this rule is adapted for SENDMODE - */ - public boolean isSendMode() { - return (!RequestPacket.isRecvMode(mode)); - } - - /** - * - * @return True if this rule is adapted for RECVMODE - */ - public boolean isRecvMode() { - return RequestPacket.isRecvMode(mode); - } - - /** - * Object to String - * - * @return the string that displays this object - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Rule Name:" + idRule + " IDS:" + ids + " MODETRANS: " + - RequestPacket.TRANSFERMODE.values()[mode].toString() + - " RECV:" + recvPath + " SEND:" + sendPath + " ARCHIVE:" + - archivePath + " WORK:" + workPath + - "\nRPRET:" + rpreTasks + "\nRPOST:" + rpostTasks + "\nRERROR:" + rerrorTasks + - "\nSPRET:" + spreTasks + "\nSPOST:" + spostTasks + "\nSERROR:" + serrorTasks; - } - - /** - * - * @param isSender - * @param step - * @return a string that prints (debug) the tasks to execute - */ - public String printTasks(boolean isSender, TASKSTEP step) { - if (isSender) { - switch (step) { - case PRETASK: - return "S:" + spreTasks; - case POSTTASK: - return "S:" + spostTasks; - case ERRORTASK: - return "S:" + serrorTasks; - default: - return "S:no task"; - } - } else { - switch (step) { - case PRETASK: - return "R:" + rpreTasks; - case POSTTASK: - return "R:" + rpostTasks; - case ERRORTASK: - return "R:" + rerrorTasks; - default: - return "R:no task"; - } - } - } - - /** - * Object to String - * - * @return the string that displays this object - * @see java.lang.Object#toString() - */ - public String toShortString() { - return "Rule Name:" + idRule + " MODETRANS: " + - RequestPacket.TRANSFERMODE.values()[mode].toString(); - } - - /** - * - * @param session - * @param rule - * @param mode - * @return the DbPreparedStatement according to the filter - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getFilterPrepareStament(DbSession session, - String rule, int mode) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "SELECT " + selectAllFields + " FROM " + table; - String condition = null; - if (rule != null) { - condition = " WHERE " + Columns.IDRULE.name() + " LIKE '%" + rule + "%' "; - } - if (mode >= 0) { - if (condition != null) { - condition += " AND "; - } else { - condition = " WHERE "; - } - condition += Columns.MODETRANS.name() + " = ?"; - } else { - condition = ""; - } - preparedStatement.createPrepareStatement(request + condition + - " ORDER BY " + Columns.IDRULE.name()); - if (mode >= 0) { - try { - preparedStatement.getPreparedStatement().setInt(1, mode); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } - return preparedStatement; - } - - /** - * @param session - * @param body - * @return the runner in Html format specified by body by replacing all instance of fields - */ - public String toSpecializedHtml(R66Session session, String body) { - StringBuilder builder = new StringBuilder(body); - WaarpStringUtils.replace(builder, "XXXRULEXXX", idRule); - WaarpStringUtils.replace(builder, "XXXIDSXXX", ids == null ? "" : ids); - if (mode == RequestPacket.TRANSFERMODE.RECVMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXRECVXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.SENDMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXSENDXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXRECVMXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXSENDMXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXRECVTXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXSENDTXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXRECVMTXXX", "checked"); - } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal()) { - WaarpStringUtils.replace(builder, "XXXSENDMTXXX", "checked"); - } - WaarpStringUtils.replace(builder, "XXXRPXXX", recvPath == null ? "" : recvPath); - WaarpStringUtils.replace(builder, "XXXSPXXX", sendPath == null ? "" : sendPath); - WaarpStringUtils.replace(builder, "XXXAPXXX", archivePath == null ? "" : archivePath); - WaarpStringUtils.replace(builder, "XXXWPXXX", workPath == null ? "" : workPath); - WaarpStringUtils.replace(builder, "XXXRPTXXX", rpreTasks == null ? "" : rpreTasks); - WaarpStringUtils.replace(builder, "XXXRSTXXX", rpostTasks == null ? "" : rpostTasks); - WaarpStringUtils.replace(builder, "XXXRETXXX", rerrorTasks == null ? "" : rerrorTasks); - WaarpStringUtils.replace(builder, "XXXSPTXXX", spreTasks == null ? "" : spreTasks); - WaarpStringUtils.replace(builder, "XXXSSTXXX", spostTasks == null ? "" : spostTasks); - WaarpStringUtils.replace(builder, "XXXSETXXX", serrorTasks == null ? "" : serrorTasks); - return builder.toString(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.io.File; +import java.io.StringReader; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.io.SAXReader; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.file.DirInterface; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.common.xml.XmlUtil; +import org.waarp.common.xml.XmlValue; +import org.waarp.openr66.configuration.RuleFileBasedConfiguration; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Rule Table object + * + * @author Frederic Bregier + * + */ +public class DbRule extends AbstractDbData { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(DbRule.class); + + public static enum Columns { + HOSTIDS, + MODETRANS, + RECVPATH, + SENDPATH, + ARCHIVEPATH, + WORKPATH, + RPRETASKS, + RPOSTTASKS, + RERRORTASKS, + SPRETASKS, + SPOSTTASKS, + SERRORTASKS, + UPDATEDINFO, + IDRULE + } + + public static final int[] dbTypes = { + Types.LONGVARCHAR, + Types.INTEGER, Types.VARCHAR, Types.VARCHAR, + Types.VARCHAR, Types.VARCHAR, + Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, + Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR, + Types.INTEGER, Types.VARCHAR }; + + public static final String table = " RULES "; + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66RuleHashMap = + new ConcurrentHashMap(); + + /** + * Internal context XML fields + */ + private static final String XMLHOSTIDS = "<" + + RuleFileBasedConfiguration.XHOSTIDS + + ">"; + + /** + * Internal context XML fields + */ + private static final String XMLENDHOSTIDS = ""; + + /** + * Internal context XML fields + */ + private static final String XMLHOSTID = "<" + + RuleFileBasedConfiguration.XHOSTID + + ">"; + + /** + * Internal context XML fields + */ + private static final String XMLENDHOSTID = ""; + + /** + * Internal context XML fields + */ + private static final String XMLTASKS = "<" + + RuleFileBasedConfiguration.XTASKS + + ">"; + + /** + * Internal context XML fields + */ + private static final String XMLENDTASKS = ""; + + /** + * Internal context XML fields + */ + private static final String XMLTASK = "<" + + RuleFileBasedConfiguration.XTASK + + ">"; + + /** + * Internal context XML fields + */ + private static final String XMLENDTASK = ""; + + /** + * Internal context XML fields + */ + public static final String TASK_TYPE = "type"; + + /** + * Internal context XML fields + */ + public static final String TASK_PATH = "path"; + + /** + * Internal context XML fields + */ + public static final String TASK_DELAY = "delay"; + + /** + * Global Id + */ + public String idRule = null; + + /** + * The Name addresses (serverIds) + */ + public String ids = null; + + /** + * Supported Mode for this rule (SENDMODE => SENDMD5MODE, RECVMODE => RECVMD5MODE) + */ + public int mode; + + /** + * The associated Recv Path + */ + public String recvPath = null; + + /** + * The associated Send Path + */ + public String sendPath = null; + + /** + * The associated Archive Path + */ + public String archivePath = null; + + /** + * The associated Work Path + */ + public String workPath = null; + + /** + * The associated Pre Tasks for Receiver + */ + public String rpreTasks = null; + + /** + * The associated Post Tasks for Receiver + */ + public String rpostTasks = null; + + /** + * The associated Error Tasks for Receiver + */ + public String rerrorTasks = null; + + /** + * The associated Pre Tasks for Sender + */ + public String spreTasks = null; + + /** + * The associated Post Tasks for Sender + */ + public String spostTasks = null; + + /** + * The associated Error Tasks for Sender + */ + public String serrorTasks = null; + + /** + * The Ids as an array + */ + public String[] idsArray = null; + + /** + * The associated Pre Tasks as an array for Receiver + */ + public String[][] rpreTasksArray = null; + + /** + * The associated Post Tasks as an array for Receiver + */ + public String[][] rpostTasksArray = null; + + /** + * The associated Error Tasks as an array for Receiver + */ + public String[][] rerrorTasksArray = null; + + /** + * The associated Pre Tasks as an array for Sender + */ + public String[][] spreTasksArray = null; + + /** + * The associated Post Tasks as an array for Sender + */ + public String[][] spostTasksArray = null; + + /** + * The associated Error Tasks as an array for Sender + */ + public String[][] serrorTasksArray = null; + + private int updatedInfo = UpdatedInfo.UNKNOWN + .ordinal(); + + // ALL TABLE SHOULD IMPLEMENT THIS + public static final int NBPRKEY = 1; + + protected static final String selectAllFields = Columns.HOSTIDS + .name() + + "," + + + Columns.MODETRANS + .name() + + "," + + Columns.RECVPATH + .name() + + "," + + + Columns.SENDPATH + .name() + + "," + + Columns.ARCHIVEPATH + .name() + + "," + + + Columns.WORKPATH + .name() + + "," + + + Columns.RPRETASKS + .name() + + "," + + + Columns.RPOSTTASKS + .name() + + "," + + Columns.RERRORTASKS + .name() + + "," + + + Columns.SPRETASKS + .name() + + "," + + + Columns.SPOSTTASKS + .name() + + "," + + Columns.SERRORTASKS + .name() + + "," + + + Columns.UPDATEDINFO + .name() + + "," + + Columns.IDRULE + .name(); + + protected static final String updateAllFields = Columns.HOSTIDS + .name() + + + "=?," + + Columns.MODETRANS + .name() + + "=?," + + Columns.RECVPATH + .name() + + + "=?," + + Columns.SENDPATH + .name() + + "=?," + + + Columns.ARCHIVEPATH + .name() + + "=?," + + Columns.WORKPATH + .name() + + + "=?," + + Columns.RPRETASKS + .name() + + "=?," + + Columns.RPOSTTASKS + .name() + + + "=?," + + Columns.RERRORTASKS + .name() + + "=?," + + + Columns.SPRETASKS + .name() + + "=?," + + Columns.SPOSTTASKS + .name() + + + "=?," + + Columns.SERRORTASKS + .name() + + "=?," + + + Columns.UPDATEDINFO + .name() + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { new DbValue(idRule, Columns.IDRULE + .name()) }; + otherFields = new DbValue[] { + // HOSTIDS, MODETRANS, RECVPATH, SENDPATH, ARCHIVEPATH, WORKPATH, + // PRETASKS, POSTTASKS, ERRORTASKS + new DbValue(ids, Columns.HOSTIDS.name(), true), + new DbValue(mode, Columns.MODETRANS.name()), + new DbValue(recvPath, Columns.RECVPATH.name()), + new DbValue(sendPath, Columns.SENDPATH.name()), + new DbValue(archivePath, Columns.ARCHIVEPATH.name()), + new DbValue(workPath, Columns.WORKPATH.name()), + new DbValue(rpreTasks, Columns.RPRETASKS.name(), true), + new DbValue(rpostTasks, Columns.RPOSTTASKS.name(), true), + new DbValue(rerrorTasks, Columns.RERRORTASKS.name(), true), + new DbValue(spreTasks, Columns.SPRETASKS.name(), true), + new DbValue(spostTasks, Columns.SPOSTTASKS.name(), true), + new DbValue(serrorTasks, Columns.SERRORTASKS.name(), true), + new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], otherFields[3], + otherFields[4], otherFields[5], otherFields[6], otherFields[7], + otherFields[8], otherFields[9], otherFields[10], + otherFields[11], otherFields[12], primaryKey[0] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.HOSTIDS.ordinal()].setValue(ids); + allFields[Columns.MODETRANS.ordinal()].setValue(mode); + allFields[Columns.RECVPATH.ordinal()].setValue(recvPath); + allFields[Columns.SENDPATH.ordinal()].setValue(sendPath); + allFields[Columns.ARCHIVEPATH.ordinal()].setValue(archivePath); + allFields[Columns.WORKPATH.ordinal()].setValue(workPath); + allFields[Columns.RPRETASKS.ordinal()].setValue(rpreTasks); + allFields[Columns.RPOSTTASKS.ordinal()].setValue(rpostTasks); + allFields[Columns.RERRORTASKS.ordinal()].setValue(rerrorTasks); + allFields[Columns.SPRETASKS.ordinal()].setValue(spreTasks); + allFields[Columns.SPOSTTASKS.ordinal()].setValue(spostTasks); + allFields[Columns.SERRORTASKS.ordinal()].setValue(serrorTasks); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + allFields[Columns.IDRULE.ordinal()].setValue(idRule); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue(); + mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); + recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue(); + sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue(); + archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()] + .getValue(); + workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue(); + rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue(); + rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue(); + rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()] + .getValue(); + spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue(); + spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue(); + serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()] + .getValue(); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue(); + getIdsRule(ids); + rpreTasksArray = getTasksRule(rpreTasks); + rpostTasksArray = getTasksRule(rpostTasks); + rerrorTasksArray = getTasksRule(rerrorTasks); + spreTasksArray = getTasksRule(spreTasks); + spostTasksArray = getTasksRule(spostTasks); + serrorTasksArray = getTasksRule(serrorTasks); + } + + protected void setFromArrayClone(DbRule source) throws WaarpDatabaseSqlException { + ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue(); + mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); + recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue(); + sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue(); + archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()] + .getValue(); + workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue(); + rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue(); + rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue(); + rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()] + .getValue(); + spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue(); + spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue(); + serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()] + .getValue(); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue(); + if (source.ids == null) { + // No ids so setting to the default! + ids = null; + idsArray = null; + } else { + ids = source.ids; + idsArray = source.idsArray; + } + rpreTasksArray = source.rpreTasksArray; + rpostTasksArray = source.rpostTasksArray; + rerrorTasksArray = source.rerrorTasksArray; + spreTasksArray = source.spreTasksArray; + spostTasksArray = source.spostTasksArray; + serrorTasksArray = source.serrorTasksArray; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getWherePrimaryKey() + */ + @Override + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? "; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#setPrimaryKey() + */ + @Override + protected void setPrimaryKey() { + primaryKey[0].setValue(idRule); + } + + /** + * @param dbSession + * @param idRule + * @param ids + * @param mode + * @param recvPath + * @param sendPath + * @param archivePath + * @param workPath + * @param rpreTasks + * @param rpostTasks + * @param rerrorTasks + * @param spreTasks + * @param spostTasks + * @param serrorTasks + */ + public DbRule(DbSession dbSession, String idRule, String ids, int mode, String recvPath, + String sendPath, String archivePath, String workPath, + String rpreTasks, String rpostTasks, String rerrorTasks, + String spreTasks, String spostTasks, String serrorTasks) { + super(dbSession); + this.idRule = idRule; + this.ids = ids; + this.mode = mode; + this.recvPath = recvPath; + this.sendPath = sendPath; + this.archivePath = archivePath; + this.workPath = workPath; + this.rpreTasks = rpreTasks; + this.rpostTasks = rpostTasks; + this.rerrorTasks = rerrorTasks; + this.spreTasks = spreTasks; + this.spostTasks = spostTasks; + this.serrorTasks = serrorTasks; + getIdsRule(this.ids); + rpreTasksArray = getTasksRule(this.rpreTasks); + rpostTasksArray = getTasksRule(this.rpostTasks); + rerrorTasksArray = getTasksRule(this.rerrorTasks); + spreTasksArray = getTasksRule(this.spreTasks); + spostTasksArray = getTasksRule(this.spostTasks); + serrorTasksArray = getTasksRule(this.serrorTasks); + // and reverse + this.rpreTasks = setTasksRule(rpreTasksArray); + this.rpostTasks = setTasksRule(rpostTasksArray); + this.rerrorTasks = setTasksRule(rerrorTasksArray); + this.spreTasks = setTasksRule(spreTasksArray); + this.spostTasks = setTasksRule(spostTasksArray); + this.serrorTasks = setTasksRule(serrorTasksArray); + setToArray(); + isSaved = false; + } + + /** + * @param dbSession + * @param idRule + * @throws WaarpDatabaseException + */ + public DbRule(DbSession dbSession, String idRule) throws WaarpDatabaseException { + super(dbSession); + this.idRule = idRule; + // load from DB + select(); + /* + * getIdsRule(ids); rpreTasksArray = getTasksRule(this.rpreTasks); rpostTasksArray = + * getTasksRule(this.rpostTasks); rerrorTasksArray = getTasksRule(this.rerrorTasks); + * spreTasksArray = getTasksRule(this.spreTasks); spostTasksArray = + * getTasksRule(this.spostTasks); serrorTasksArray = getTasksRule(this.serrorTasks); + */ + } + + /** + * Constructor used from XML file + * + * @param dbSession + * @param idrule + * @param idsArrayRef + * @param recvpath + * @param sendpath + * @param archivepath + * @param workpath + * @param rpretasksArray + * @param rposttasksArray + * @param rerrortasksArray + * @param spretasksArray + * @param sposttasksArray + * @param serrortasksArray + */ + public DbRule(DbSession dbSession, String idrule, String[] idsArrayRef, int mode, + String recvpath, String sendpath, String archivepath, + String workpath, + String[][] rpretasksArray, String[][] rposttasksArray, String[][] rerrortasksArray, + String[][] spretasksArray, String[][] sposttasksArray, String[][] serrortasksArray) { + super(dbSession); + idRule = idrule; + idsArray = idsArrayRef; + this.mode = mode; + recvPath = recvpath; + sendPath = sendpath; + archivePath = archivepath; + workPath = workpath; + rpreTasksArray = rpretasksArray; + rpostTasksArray = rposttasksArray; + rerrorTasksArray = rerrortasksArray; + spreTasksArray = spretasksArray; + spostTasksArray = sposttasksArray; + serrorTasksArray = serrortasksArray; + ids = setIdsRule(idsArrayRef); + rpreTasks = setTasksRule(rpretasksArray); + rpostTasks = setTasksRule(rposttasksArray); + rerrorTasks = setTasksRule(rerrortasksArray); + spreTasks = setTasksRule(spretasksArray); + spostTasks = setTasksRule(sposttasksArray); + serrorTasks = setTasksRule(serrortasksArray); + setToArray(); + isSaved = false; + } + + /** + * Delete all entries (used when purge and reload) + * + * @param dbSession + * @return the previous existing array of DbRule + * @throws WaarpDatabaseException + */ + public static DbRule[] deleteAll(DbSession dbSession) throws WaarpDatabaseException { + DbRule[] result = getAllRules(dbSession); + dbR66RuleHashMap.clear(); + if (dbSession == null) { + return result; + } + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("DELETE FROM " + table); + preparedStatement.executeUpdate(); + return result; + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + dbR66RuleHashMap.remove(this.idRule); + if (dbSession == null) { + isSaved = false; + return; + } + super.delete(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + dbR66RuleHashMap.put(this.idRule, this); + if (dbSession == null) { + isSaved = true; + return; + } + super.insert(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + boolean result = dbR66RuleHashMap.containsKey(idRule); + if (result) { + return result; + } + if (dbSession == null) { + if (!result) { + isSaved = false; + } + return result; + } + return super.exist(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + DbRule rule = dbR66RuleHashMap.get(this.idRule); + if (rule != null) { + // copy info + for (int i = 0; i < allFields.length; i++) { + allFields[i].value = rule.allFields[i].value; + } + setFromArrayClone(rule); + if (recvPath == null) { + recvPath = Configuration.configuration.inPath; + } + if (sendPath == null) { + sendPath = Configuration.configuration.outPath; + } + if (archivePath == null) { + archivePath = Configuration.configuration.archivePath; + } + if (workPath == null) { + workPath = Configuration.configuration.workingPath; + } + isSaved = true; + return; + } + if (dbSession == null) { + if (rule == null) { + throw new WaarpDatabaseNoDataException("No row found"); + } + } + super.select(); + if (recvPath == null) { + recvPath = Configuration.configuration.inPath; + } + if (sendPath == null) { + sendPath = Configuration.configuration.outPath; + } + if (archivePath == null) { + archivePath = Configuration.configuration.archivePath; + } + if (workPath == null) { + workPath = Configuration.configuration.workingPath; + } + setFromArray(); + dbR66RuleHashMap.put(this.idRule, this); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + dbR66RuleHashMap.put(this.idRule, this); + if (dbSession == null) { + isSaved = true; + return; + } + super.update(); + } + + /** + * Private constructor for Commander only + */ + private DbRule(DbSession session) { + super(session); + } + + /** + * Get All DbRule from database or from internal hashMap in case of no database support + * + * @param dbSession + * may be null + * @return the array of DbRule + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbRule[] getAllRules(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbRule[] result = new DbRule[0]; + if (!dbR66RuleHashMap.isEmpty()) { + return dbR66RuleHashMap.values().toArray(result); + } + if (dbSession == null) { + return result; + } + String request = "SELECT " + selectAllFields; + request += " FROM " + table; + DbPreparedStatement preparedStatement = new DbPreparedStatement(dbSession, request); + ArrayList dbArrayList = new ArrayList(); + preparedStatement.executeQuery(); + while (preparedStatement.getNext()) { + DbRule dbrule = getFromStatement(preparedStatement); + dbArrayList.add(dbrule); + } + preparedStatement.realClose(); + return dbArrayList.toArray(result); + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated DbRule + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbRule getFromStatement(DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbRule dbRule = new DbRule(preparedStatement.getDbSession()); + dbRule.getValues(preparedStatement, dbRule.allFields); + dbRule.setFromArray(); + dbRule.isSaved = true; + logger.debug("Get one Rule from Db: "+dbRule.idRule); + dbR66RuleHashMap.put(dbRule.idRule, dbRule); + return dbRule; + } + + /** + * + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields; + request += " FROM " + table + + " WHERE " + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal(); + DbPreparedStatement prep = new DbPreparedStatement(session, request); + return prep; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + if (updatedInfo != info.ordinal()) { + updatedInfo = info.ordinal(); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + isSaved = false; + } + } + + /** + * Get Ids from String. If it is not ok, then it sets the default values and return False, else + * returns True. + * + * @param idsref + * @return True if ok, else False (default values). + */ + private boolean getIdsRule(String idsref) { + if (idsref == null) { + // No ids so setting to the default! + ids = null; + idsArray = null; + return false; + } + ids = idsref; + StringReader reader = new StringReader(idsref); + Document document = null; + try { + document = new SAXReader().read(reader); + } catch (DocumentException e) { + logger.warn("Unable to read the ids for Rule: " + idsref, e); + // No ids so setting to the default! + ids = null; + idsArray = null; + reader.close(); + return false; + } + XmlValue[] values = XmlUtil.read(document, + RuleFileBasedConfiguration.hostsDecls); + idsArray = RuleFileBasedConfiguration.getHostIds(values[0]); + reader.close(); + return true; + } + + /** + * Get Tasks from String. If it is not ok, then it sets the default values and return new array + * of Tasks or null if in error. + * + * @param tasks + * @return Array of tasks or empty array if in error. + */ + private String[][] getTasksRule(String tasks) { + if (tasks == null) { + // No tasks so setting to the default! + return new String[0][0]; + } + StringReader reader = new StringReader(tasks); + Document document = null; + try { + document = new SAXReader().read(reader); + } catch (DocumentException e) { + logger.warn("Unable to read the tasks for Rule: " + tasks, e); + // No tasks so setting to the default! + reader.close(); + return new String[0][0]; + } + XmlValue[] values = XmlUtil.read(document, RuleFileBasedConfiguration.tasksDecl); + String[][] result = RuleFileBasedConfiguration.getTasksRule(values[0]); + reader.close(); + return result; + } + + /** + * Initialized a ids String from args + * + * @param idsArray + * @return the new ids string + */ + private static String setIdsRule(String[] idsArray) { + String ids = null; + if (idsArray != null) { + ids = XMLHOSTIDS; + for (String element : idsArray) { + ids += XMLHOSTID + element + XMLENDHOSTID + "\n"; + } + ids += XMLENDHOSTIDS; + } + return ids; + } + + /** + * Initialized a tasks String from args + * + * @param tasksArray + * @return the new tasks string + */ + private static String setTasksRule(String[][] tasksArray) { + StringBuilder builder = new StringBuilder(); + if (tasksArray != null) { + builder.append(XMLTASKS); + for (int i = 0; i < tasksArray.length; i++) { + builder.append(XMLTASK); + builder.append('<').append(TASK_TYPE).append('>'); + builder.append(tasksArray[i][0]); + builder.append("\n"); + builder.append('<').append(TASK_PATH).append('>'); + builder.append(tasksArray[i][1]); + builder.append("\n"); + builder.append('<').append(TASK_DELAY).append('>'); + builder.append(tasksArray[i][2]); + builder.append("'); + builder.append(XMLENDTASK).append('\n'); + } + builder.append(XMLENDTASKS); + } + return builder.toString(); + } + + /** + * Get the full path from RecvPath (used only in copy MODETRANS) + * + * @param filename + * @return the full String path + * @throws OpenR66ProtocolSystemException + */ + public String setRecvPath(String filename) + throws OpenR66ProtocolSystemException { + if (recvPath != null) { + return recvPath + DirInterface.SEPARATOR + filename; + } + return FileUtils.consolidatePath(Configuration.configuration.inPath, + filename); + } + + /** + * Get the full path from sendPath + * + * @param filename + * @return the full String path + * @throws OpenR66ProtocolSystemException + */ + public String setSendPath(String filename) + throws OpenR66ProtocolSystemException { + if (sendPath != null) { + File file = new File(filename); + String basename = file.getName(); + return sendPath + DirInterface.SEPARATOR + basename; + } + return FileUtils.consolidatePath(Configuration.configuration.outPath, + filename); + } + + /** + * Get the full path from archivePath + * + * @param filename + * @return the full String path + * @throws OpenR66ProtocolSystemException + */ + public String setArchivePath(String filename) + throws OpenR66ProtocolSystemException { + if (archivePath != null) { + return archivePath + DirInterface.SEPARATOR + filename; + } + return FileUtils.consolidatePath( + Configuration.configuration.archivePath, filename); + } + + /** + * Get the full path from workPath + * + * @param filename + * @return the full String path + * @throws OpenR66ProtocolSystemException + */ + public String setWorkingPath(String filename) + throws OpenR66ProtocolSystemException { + if (workPath != null) { + return workPath + DirInterface.SEPARATOR + filename + + Configuration.EXT_R66; + } + return FileUtils.consolidatePath( + Configuration.configuration.workingPath, filename); + } + + /** + * Check if the given hostTo is in the allowed list + * + * @param hostId + * @return True if allow, else False + */ + public boolean checkHostAllow(String hostId) { + if (idsArray == null || idsArray.length == 0) { + return true; // always true in this case + } + for (String element : idsArray) { + if (element.equalsIgnoreCase(hostId)) { + return true; + } + } + return false; + } + + /** + * + * @return True if this rule is adapted for SENDMODE + */ + public boolean isSendMode() { + return (!RequestPacket.isRecvMode(mode)); + } + + /** + * + * @return True if this rule is adapted for RECVMODE + */ + public boolean isRecvMode() { + return RequestPacket.isRecvMode(mode); + } + + /** + * Object to String + * + * @return the string that displays this object + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Rule Name:" + idRule + " IDS:" + ids + " MODETRANS: " + + RequestPacket.TRANSFERMODE.values()[mode].toString() + + " RECV:" + recvPath + " SEND:" + sendPath + " ARCHIVE:" + + archivePath + " WORK:" + workPath + + "\nRPRET:" + rpreTasks + "\nRPOST:" + rpostTasks + "\nRERROR:" + rerrorTasks + + "\nSPRET:" + spreTasks + "\nSPOST:" + spostTasks + "\nSERROR:" + serrorTasks; + } + + /** + * + * @param isSender + * @param step + * @return a string that prints (debug) the tasks to execute + */ + public String printTasks(boolean isSender, TASKSTEP step) { + if (isSender) { + switch (step) { + case PRETASK: + return "S:" + spreTasks; + case POSTTASK: + return "S:" + spostTasks; + case ERRORTASK: + return "S:" + serrorTasks; + default: + return "S:no task"; + } + } else { + switch (step) { + case PRETASK: + return "R:" + rpreTasks; + case POSTTASK: + return "R:" + rpostTasks; + case ERRORTASK: + return "R:" + rerrorTasks; + default: + return "R:no task"; + } + } + } + + /** + * Object to String + * + * @return the string that displays this object + * @see java.lang.Object#toString() + */ + public String toShortString() { + return "Rule Name:" + idRule + " MODETRANS: " + + RequestPacket.TRANSFERMODE.values()[mode].toString(); + } + + /** + * + * @param session + * @param rule + * @param mode + * @return the DbPreparedStatement according to the filter + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getFilterPrepareStament(DbSession session, + String rule, int mode) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "SELECT " + selectAllFields + " FROM " + table; + String condition = null; + if (rule != null) { + condition = " WHERE " + Columns.IDRULE.name() + " LIKE '%" + rule + "%' "; + } + if (mode >= 0) { + if (condition != null) { + condition += " AND "; + } else { + condition = " WHERE "; + } + condition += Columns.MODETRANS.name() + " = ?"; + } else { + condition = ""; + } + preparedStatement.createPrepareStatement(request + condition + + " ORDER BY " + Columns.IDRULE.name()); + if (mode >= 0) { + try { + preparedStatement.getPreparedStatement().setInt(1, mode); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } + return preparedStatement; + } + + /** + * @param session + * @param body + * @return the runner in Html format specified by body by replacing all instance of fields + */ + public String toSpecializedHtml(R66Session session, String body) { + StringBuilder builder = new StringBuilder(body); + WaarpStringUtils.replace(builder, "XXXRULEXXX", idRule); + WaarpStringUtils.replace(builder, "XXXIDSXXX", ids == null ? "" : ids); + if (mode == RequestPacket.TRANSFERMODE.RECVMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXRECVXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.SENDMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXSENDXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXRECVMXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXSENDMXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXRECVTXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXSENDTXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXRECVMTXXX", "checked"); + } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal()) { + WaarpStringUtils.replace(builder, "XXXSENDMTXXX", "checked"); + } + WaarpStringUtils.replace(builder, "XXXRPXXX", recvPath == null ? "" : recvPath); + WaarpStringUtils.replace(builder, "XXXSPXXX", sendPath == null ? "" : sendPath); + WaarpStringUtils.replace(builder, "XXXAPXXX", archivePath == null ? "" : archivePath); + WaarpStringUtils.replace(builder, "XXXWPXXX", workPath == null ? "" : workPath); + WaarpStringUtils.replace(builder, "XXXRPTXXX", rpreTasks == null ? "" : rpreTasks); + WaarpStringUtils.replace(builder, "XXXRSTXXX", rpostTasks == null ? "" : rpostTasks); + WaarpStringUtils.replace(builder, "XXXRETXXX", rerrorTasks == null ? "" : rerrorTasks); + WaarpStringUtils.replace(builder, "XXXSPTXXX", spreTasks == null ? "" : spreTasks); + WaarpStringUtils.replace(builder, "XXXSSTXXX", spostTasks == null ? "" : spostTasks); + WaarpStringUtils.replace(builder, "XXXSETXXX", serrorTasks == null ? "" : serrorTasks); + return builder.toString(); + } + +} diff --git a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java index dcc29e6cb..e964bd8b4 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java +++ b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java @@ -1,3731 +1,3731 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.data; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.concurrent.atomic.AtomicLong; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.SAXReader; -import org.dom4j.io.XMLWriter; -import org.dom4j.tree.DefaultElement; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.data.DbValue; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.openr66.commander.CommanderNoDb; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.task.AbstractTask; -import org.waarp.openr66.context.task.TaskType; -import org.waarp.openr66.context.task.exception.OpenR66RunnerEndTasksException; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.model.DbModelFactory; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.NbAndSpecialId; -import org.waarp.openr66.protocol.utils.R66Future; -import org.xml.sax.SAXException; - -/** - * Task Runner from pre operation to transfer to post operation, except in case of error - * - * @author Frederic Bregier - * - */ -public class DbTaskRunner extends AbstractDbData { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(DbTaskRunner.class); - - public static enum Columns { - GLOBALSTEP, - GLOBALLASTSTEP, - STEP, - RANK, - STEPSTATUS, - RETRIEVEMODE, - FILENAME, - ISMOVED, - IDRULE, - BLOCKSZ, - ORIGINALNAME, - FILEINFO, - MODETRANS, - STARTTRANS, - STOPTRANS, - INFOSTATUS, - UPDATEDINFO, - OWNERREQ, - REQUESTER, - REQUESTED, - SPECIALID; - } - - public static final int[] dbTypes = { - Types.INTEGER, Types.INTEGER, Types.INTEGER, - Types.INTEGER, - Types.CHAR, Types.BIT, Types.VARCHAR, Types.BIT, Types.VARCHAR, - Types.INTEGER, Types.VARCHAR, Types.LONGVARCHAR, Types.INTEGER, - Types.TIMESTAMP, Types.TIMESTAMP, Types.CHAR, Types.INTEGER, - Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BIGINT }; - - public static final String table = " RUNNER "; - - public static final String fieldseq = "RUNSEQ"; - - public static final Columns[] indexes = { - Columns.STARTTRANS, Columns.OWNERREQ, - Columns.STEPSTATUS, Columns.UPDATEDINFO, - Columns.GLOBALSTEP, Columns.INFOSTATUS, Columns.SPECIALID - }; - - public static final String XMLRUNNERS = "taskrunners"; - public static final String XMLRUNNER = "runner"; - public static final String XMLEXTENSION = "_singlerunner.xml"; - - /** - * GlobalStep Value - */ - public static enum TASKSTEP { - NOTASK, PRETASK, TRANSFERTASK, POSTTASK, ALLDONETASK, ERRORTASK; - } - - // Values - private DbRule rule; - - private R66Session session; - - /** - * Last step - */ - private int globalstep = TASKSTEP.NOTASK.ordinal(); - /** - * Last global step (only changes in case of success) - */ - private int globallaststep = TASKSTEP.NOTASK.ordinal(); - /** - * Step in the current globalstep - */ - private int step = -1; - - private int rank = 0; - - /** - * Last step action status error code - */ - private ErrorCode status = ErrorCode.Unknown; - - private long specialId; - - private boolean isSender; - - private String filename; - - private boolean isFileMoved = false; - - private String ruleId; - - private int blocksize; - - private String originalFilename; - - private String fileInformation; - - private int mode; - - private String ownerRequest; - - private String requesterHostId; - - private String requestedHostId; - - private Timestamp start; - - private Timestamp stop; - - /** - * Info status error code - */ - private ErrorCode infostatus = ErrorCode.Unknown; - - /** - * The global status for running - */ - private int updatedInfo = UpdatedInfo.UNKNOWN.ordinal(); - - private volatile boolean continueTransfer = true; - - private volatile boolean rescheduledTransfer = false; - - private LocalChannelReference localChannelReference = null; - - private boolean isRecvThrough = false; - private boolean isSendThrough = false; - private long originalSize = -1; - - /** - * Special For DbTaskRunner - */ - public static final int NBPRKEY = 4; - // ALL TABLE SHOULD IMPLEMENT THIS - - protected static final String selectAllFields = Columns.GLOBALSTEP.name() + - "," - + Columns.GLOBALLASTSTEP.name() - + "," + Columns.STEP.name() + - "," + Columns.RANK.name() + "," - + Columns.STEPSTATUS.name() - + "," + - Columns.RETRIEVEMODE.name() - + "," + Columns.FILENAME.name() - + "," + - Columns.ISMOVED.name() + "," - + Columns.IDRULE.name() + "," + - Columns.BLOCKSZ.name() + "," - + Columns.ORIGINALNAME.name() - + "," + - Columns.FILEINFO.name() + "," - + Columns.MODETRANS.name() - + "," + - Columns.STARTTRANS.name() + "," - + Columns.STOPTRANS.name() - + "," + - Columns.INFOSTATUS.name() + "," - + Columns.UPDATEDINFO.name() - + "," + - Columns.OWNERREQ.name() + "," - + Columns.REQUESTER.name() - + "," + - Columns.REQUESTED.name() + "," - + Columns.SPECIALID.name(); - - protected static final String updateAllFields = Columns.GLOBALSTEP.name() + - "=?," - + Columns.GLOBALLASTSTEP.name() - + "=?," + - Columns.STEP.name() + "=?," - + Columns.RANK.name() + "=?," + - Columns.STEPSTATUS.name() - + "=?," - + Columns.RETRIEVEMODE.name() + - "=?," + Columns.FILENAME.name() - + "=?," - + Columns.ISMOVED.name() + - "=?," + Columns.IDRULE.name() - + "=?," - + Columns.BLOCKSZ.name() + - "=?," - + Columns.ORIGINALNAME.name() - + "=?," + - Columns.FILEINFO.name() + "=?," - + Columns.MODETRANS.name() - + "=?," + - Columns.STARTTRANS.name() - + "=?," - + Columns.STOPTRANS.name() + - "=?," - + Columns.INFOSTATUS.name() - + "=?," - + Columns.UPDATEDINFO.name() - + "=?"; - - protected static final String insertAllValues = " (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; - - private static final AtomicLong clientNoDbSpecialIdLast = - new AtomicLong( - System.currentTimeMillis()); - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#initObject() - */ - @Override - protected void initObject() { - primaryKey = new DbValue[] { - new DbValue(ownerRequest, Columns.OWNERREQ.name()), - new DbValue(requesterHostId, Columns.REQUESTER.name()), - new DbValue(requestedHostId, Columns.REQUESTED.name()), - new DbValue(specialId, Columns.SPECIALID.name()) }; - otherFields = new DbValue[] { - // GLOBALSTEP, GLOBALLASTSTEP, STEP, RANK, STEPSTATUS, RETRIEVEMODE, - // FILENAME, ISMOVED, IDRULE, - // BLOCKSZ, ORIGINALNAME, FILEINFO, MODETRANS, - // STARTTRANS, STOPTRANS - // INFOSTATUS, UPDATEDINFO - new DbValue(globalstep, Columns.GLOBALSTEP.name()), - new DbValue(globallaststep, Columns.GLOBALLASTSTEP.name()), - new DbValue(step, Columns.STEP.name()), - new DbValue(rank, Columns.RANK.name()), - new DbValue(ErrorCode.Unknown.getCode(), Columns.STEPSTATUS.name()), // status.getCode() - new DbValue(isSender, Columns.RETRIEVEMODE.name()), - new DbValue(filename, Columns.FILENAME.name()), - new DbValue(isFileMoved, Columns.ISMOVED.name()), - new DbValue(ruleId, Columns.IDRULE.name()), - new DbValue(blocksize, Columns.BLOCKSZ.name()), - new DbValue(originalFilename, Columns.ORIGINALNAME.name()), - new DbValue(fileInformation, Columns.FILEINFO.name(), true), - new DbValue(mode, Columns.MODETRANS.name()), - new DbValue(start, Columns.STARTTRANS.name()), - new DbValue(stop, Columns.STOPTRANS.name()), - new DbValue(ErrorCode.Unknown.getCode(), Columns.INFOSTATUS.name()),// infostatus.getCode() - new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; - allFields = new DbValue[] { - otherFields[0], otherFields[1], otherFields[2], otherFields[3], - otherFields[4], otherFields[5], otherFields[6], otherFields[7], - otherFields[8], otherFields[9], otherFields[10], otherFields[11], - otherFields[12], otherFields[13], otherFields[14], otherFields[15], - otherFields[16], - primaryKey[0], primaryKey[1], primaryKey[2], primaryKey[3] }; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() - */ - @Override - protected String getSelectAllFields() { - return selectAllFields; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getTable() - */ - @Override - protected String getTable() { - return table; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() - */ - @Override - protected String getInsertAllValues() { - return insertAllValues; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() - */ - @Override - protected String getUpdateAllFields() { - return updateAllFields; - } - - @Override - protected void setToArray() { - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - allFields[Columns.STEP.ordinal()].setValue(step); - allFields[Columns.RANK.ordinal()].setValue(rank); - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - allFields[Columns.RETRIEVEMODE.ordinal()].setValue(isSender); - allFields[Columns.FILENAME.ordinal()].setValue(filename); - allFields[Columns.ISMOVED.ordinal()].setValue(isFileMoved); - allFields[Columns.IDRULE.ordinal()].setValue(ruleId); - allFields[Columns.BLOCKSZ.ordinal()].setValue(blocksize); - allFields[Columns.ORIGINALNAME.ordinal()].setValue(originalFilename); - allFields[Columns.FILEINFO.ordinal()].setValue(fileInformation); - allFields[Columns.MODETRANS.ordinal()].setValue(mode); - allFields[Columns.STARTTRANS.ordinal()].setValue(start); - stop = new Timestamp(System.currentTimeMillis()); - allFields[Columns.STOPTRANS.ordinal()].setValue(stop); - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - allFields[Columns.OWNERREQ.ordinal()].setValue(ownerRequest); - allFields[Columns.REQUESTER.ordinal()].setValue(requesterHostId); - allFields[Columns.REQUESTED.ordinal()].setValue(requestedHostId); - allFields[Columns.SPECIALID.ordinal()].setValue(specialId); - } - - @Override - protected void setFromArray() throws WaarpDatabaseSqlException { - globalstep = (Integer) allFields[Columns.GLOBALSTEP.ordinal()] - .getValue(); - globallaststep = (Integer) allFields[Columns.GLOBALLASTSTEP.ordinal()] - .getValue(); - step = (Integer) allFields[Columns.STEP.ordinal()].getValue(); - rank = (Integer) allFields[Columns.RANK.ordinal()].getValue(); - status = ErrorCode.getFromCode((String) allFields[Columns.STEPSTATUS - .ordinal()].getValue()); - isSender = (Boolean) allFields[Columns.RETRIEVEMODE.ordinal()] - .getValue(); - filename = (String) allFields[Columns.FILENAME.ordinal()].getValue(); - isFileMoved = (Boolean) allFields[Columns.ISMOVED.ordinal()].getValue(); - ruleId = (String) allFields[Columns.IDRULE.ordinal()].getValue(); - blocksize = (Integer) allFields[Columns.BLOCKSZ.ordinal()].getValue(); - originalFilename = (String) allFields[Columns.ORIGINALNAME.ordinal()] - .getValue(); - fileInformation = (String) allFields[Columns.FILEINFO.ordinal()] - .getValue(); - mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); - start = (Timestamp) allFields[Columns.STARTTRANS.ordinal()].getValue(); - stop = (Timestamp) allFields[Columns.STOPTRANS.ordinal()].getValue(); - infostatus = ErrorCode.getFromCode((String) allFields[Columns.INFOSTATUS - .ordinal()].getValue()); - updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] - .getValue(); - ownerRequest = (String) allFields[Columns.OWNERREQ.ordinal()] - .getValue(); - requesterHostId = (String) allFields[Columns.REQUESTER.ordinal()] - .getValue(); - requestedHostId = (String) allFields[Columns.REQUESTED.ordinal()] - .getValue(); - specialId = (Long) allFields[Columns.SPECIALID.ordinal()].getValue(); - } - - /** - * - * @return The Where condition on Primary Key - */ - protected String getWherePrimaryKey() { - return primaryKey[0].column + " = ? AND " + - primaryKey[1].column + " = ? AND " + - primaryKey[2].column + " = ? AND " + - primaryKey[3].column + " = ? "; - } - - /** - * Set the primary Key as current value - */ - protected void setPrimaryKey() { - primaryKey[0].setValue(ownerRequest); - primaryKey[1].setValue(requesterHostId); - primaryKey[2].setValue(requestedHostId); - primaryKey[3].setValue(specialId); - } - - /** - * - * @param session - * @param requestPacket - * @return The associated requested Host Id - */ - public static String getRequested(R66Session session, - RequestPacket requestPacket) { - if (requestPacket.isToValidate()) { - // the request is initiated and sent by the requester - try { - return Configuration.configuration.getHostId(session.getAuth() - .isSsl()); - } catch (OpenR66ProtocolNoSslException e) { - return Configuration.configuration.HOST_ID; - } - } else { - // the request is sent after acknowledge by the requested - return session.getAuth().getUser(); - } - } - - /** - * - * @param session - * @param requestPacket - * @return The associated requester Host Id - */ - public static String getRequester(R66Session session, - RequestPacket requestPacket) { - if (requestPacket.isToValidate()) { - return session.getAuth().getUser(); - } else { - try { - return Configuration.configuration.getHostId(session.getAuth() - .isSsl()); - } catch (OpenR66ProtocolNoSslException e) { - return Configuration.configuration.HOST_ID; - } - } - } - - public void checkThroughMode() { - isRecvThrough = RequestPacket.isRecvThroughMode(this.mode, isSelfRequested()); - isSendThrough = RequestPacket.isSendThroughMode(this.mode, isSelfRequested()); - if (localChannelReference != null) { - if (localChannelReference.isRecvThroughMode()) { - isRecvThrough = true; - } - if (localChannelReference.isSendThroughMode()) { - isSendThrough = true; - } - if (isRecvThrough && !localChannelReference.isRecvThroughMode()) { - // Cannot be a RecvThrough - isRecvThrough = false; - } - if (isSendThrough && !localChannelReference.isSendThroughMode()) { - isSendThrough = false; - } - } - logger.debug("DbTask " + mode + " isRecvThrough: " + isRecvThrough + " isSendThrough: " - + isSendThrough); - } - - /** - * Constructor for submission (no transfer session), from database. It is created, so with a new - * specialId if necessary - * - * @param dbSession - * @param rule - * @param isSender - * @param requestPacket - * @param requested - * @param startTime - * @throws WaarpDatabaseException - */ - public DbTaskRunner(DbSession dbSession, DbRule rule, boolean isSender, - RequestPacket requestPacket, String requested, Timestamp startTime) - throws WaarpDatabaseException { - super(dbSession); - this.session = null; - this.rule = rule; - ruleId = this.rule.idRule; - rank = requestPacket.getRank(); - status = ErrorCode.Unknown; - infostatus = ErrorCode.Unknown; - this.isSender = isSender; - filename = requestPacket.getFilename(); - blocksize = requestPacket.getBlocksize(); - originalFilename = requestPacket.getFilename(); - fileInformation = requestPacket.getFileInformation(); - mode = requestPacket.getMode(); - originalSize = requestPacket.getOriginalSize(); - // itself but according to SSL - requesterHostId = Configuration.configuration.getHostId(dbSession, - requested); - // given one - requestedHostId = requested; - // always itself - ownerRequest = Configuration.configuration.HOST_ID; - - if (startTime != null) { - start = startTime; - } else { - start = new Timestamp(System.currentTimeMillis()); - } - setToArray(); - isSaved = false; - specialId = requestPacket.getSpecialId(); - if (this.rule == null) { - this.rule = new DbRule(this.dbSession, ruleId); - } - if (mode != rule.mode) { - if (RequestPacket.isMD5Mode(mode)) { - mode = RequestPacket.getModeMD5(rule.mode); - } else { - mode = rule.mode; - } - } - checkThroughMode(); - create(); - } - - /** - * Constructor from a request with a valid Special Id to be inserted into database - * - * @param dbSession - * @param session - * @param rule - * @param isSender - * @param requestPacket - * @throws WaarpDatabaseException - */ - public DbTaskRunner(DbSession dbSession, R66Session session, DbRule rule, - boolean isSender, RequestPacket requestPacket) - throws WaarpDatabaseException { - super(dbSession); - this.session = session; - this.localChannelReference = session.getLocalChannelReference(); - this.rule = rule; - ruleId = this.rule.idRule; - rank = requestPacket.getRank(); - status = ErrorCode.Unknown; - infostatus = ErrorCode.Unknown; - this.isSender = isSender; - filename = requestPacket.getFilename(); - blocksize = requestPacket.getBlocksize(); - originalFilename = requestPacket.getFilename(); - fileInformation = requestPacket.getFileInformation(); - mode = requestPacket.getMode(); - originalSize = requestPacket.getOriginalSize(); - requesterHostId = getRequester(session, requestPacket); - requestedHostId = getRequested(session, requestPacket); - // always itself - ownerRequest = Configuration.configuration.HOST_ID; - - start = new Timestamp(System.currentTimeMillis()); - setToArray(); - isSaved = false; - specialId = requestPacket.getSpecialId(); - if (this.rule == null) { - this.rule = new DbRule(this.dbSession, ruleId); - } - if (mode != rule.mode) { - if (RequestPacket.isMD5Mode(mode)) { - mode = RequestPacket.getModeMD5(rule.mode); - } else { - mode = rule.mode; - } - } - checkThroughMode(); - insert(); - } - - /** - * Constructor from a request with a valid Special Id so loaded from database - * - * @param dbSession - * @param session - * @param rule - * @param id - * @param requester - * @param requested - * @throws WaarpDatabaseException - */ - public DbTaskRunner(DbSession dbSession, R66Session session, DbRule rule, - long id, String requester, String requested) - throws WaarpDatabaseException { - super(dbSession); - this.session = session; - if (this.session != null) { - this.localChannelReference = session.getLocalChannelReference(); - } - this.rule = rule; - - specialId = id; - // retrieving a task should be made from the requester, but the caller - // is responsible of this - requestedHostId = requested; - requesterHostId = requester; - // always itself - ownerRequest = Configuration.configuration.HOST_ID; - - select(); - if (rule != null) { - if (!ruleId.equals(rule.idRule)) { - throw new WaarpDatabaseNoDataException( - "Rule does not correspond"); - } - } - } - - /** - * Constructor to initiate a request with a valid previous Special Id so loaded from database. - * - * This object cannot be used except to retrieve information. - * - * @param dbSession - * @param id - * @param requested - * @throws WaarpDatabaseException - */ - public DbTaskRunner(DbSession dbSession, long id, String requested) - throws WaarpDatabaseException { - super(dbSession); - - specialId = id; - // retrieving a task should be made from the requester, but the caller - // is responsible of this - requestedHostId = requested; - requesterHostId = Configuration.configuration.getHostId(dbSession, - requested); - // always itself - ownerRequest = Configuration.configuration.HOST_ID; - - select(); - } - - /** - * - * @return the condition to limit access to the row concerned by the Host - */ - private static String getLimitWhereCondition() { - return " " + Columns.OWNERREQ + " = '" + Configuration.configuration.HOST_ID + "' "; - } - - /** - * Create a Special Id for NoDb client - */ - private void createNoDbSpecialId() { - synchronized (clientNoDbSpecialIdLast) { - // New SpecialId is not possible with No Database Model - specialId = System.currentTimeMillis(); - if (clientNoDbSpecialIdLast.get() >= specialId) { - specialId = clientNoDbSpecialIdLast.incrementAndGet(); - } else { - clientNoDbSpecialIdLast.set(specialId); - } - return; - } - } - - /** - * Remove a Spcieal Id for NoDb Client - */ - private void removeNoDbSpecialId() { - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() - */ - @Override - public void delete() throws WaarpDatabaseException { - if (dbSession == null) { - removeNoDbSpecialId(); - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - deleteXmlWorkNoDb(); - } - return; - } - super.delete(); - } - - private void addNoDb() { - DbTaskRunner runner = new DbTaskRunner(null); - this.setToArray(); - DbValue[] temp = runner.allFields; - runner.allFields = this.allFields; - try { - runner.setFromArray(); - } catch (WaarpDatabaseSqlException e) { - } - runner.allFields = temp; - runner.setToArray(); - runner.isRecvThrough = this.isRecvThrough; - runner.isSendThrough = this.isSendThrough; - runner.rule = this.rule; - runner.isSaved = true; - CommanderNoDb.todoList.add(runner); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() - */ - @Override - public void insert() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - if (specialId == DbConstant.ILLEGALVALUE) { - // New SpecialId is not possible with No Database Model - createNoDbSpecialId(); - } - isSaved = true; - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - try { - setToArray(); - this.writeXmlWorkNoDb(); - } catch (OpenR66ProtocolBusinessException e) { - // Ignore - } - } - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - addNoDb(); - } - return; - } - // First need to find a new id if id is not ok - if (specialId == DbConstant.ILLEGALVALUE) { - specialId = DbModelFactory.dbModel.nextSequence(dbSession); - logger.debug("Try Insert create a new Id from sequence: " + - specialId); - setPrimaryKey(); - } - super.insert(); - } - - /** - * As insert but with the ability to change the SpecialId - * - * @throws WaarpDatabaseException - */ - public void create() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - if (specialId == DbConstant.ILLEGALVALUE) { - // New SpecialId is not possible with No Database Model - createNoDbSpecialId(); - } - isSaved = true; - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - try { - setToArray(); - this.writeXmlWorkNoDb(); - } catch (OpenR66ProtocolBusinessException e) { - // Ignore - } - } - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - addNoDb(); - } - return; - } - // First need to find a new id if id is not ok - if (specialId == DbConstant.ILLEGALVALUE) { - specialId = DbModelFactory.dbModel.nextSequence(dbSession); - logger.info("Try Insert create a new Id from sequence: " + - specialId); - setPrimaryKey(); - } - setToArray(); - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement("INSERT INTO " + table + - " (" + selectAllFields + ") VALUES " + insertAllValues); - setValues(preparedStatement, allFields); - try { - int count = preparedStatement.executeUpdate(); - if (count <= 0) { - throw new WaarpDatabaseNoDataException("No row found"); - } - } catch (WaarpDatabaseSqlException e) { - logger.error("Problem while inserting", e); - DbPreparedStatement find = new DbPreparedStatement(dbSession); - try { - find.createPrepareStatement("SELECT MAX(" + - primaryKey[3].column + ") FROM " + table + " WHERE " + - primaryKey[0].column + " = ? AND " + - primaryKey[1].column + " = ? AND " + - primaryKey[2].column + " = ? AND " + - primaryKey[3].column + " != ? "); - setPrimaryKey(); - setValues(find, primaryKey); - find.executeQuery(); - if (find.getNext()) { - long result; - try { - result = find.getResultSet().getLong(1); - } catch (SQLException e1) { - throw new WaarpDatabaseSqlException(e1); - } - specialId = result + 1; - DbModelFactory.dbModel.resetSequence(dbSession, specialId + 1); - setToArray(); - preparedStatement.close(); - setValues(preparedStatement, allFields); - int count = preparedStatement.executeUpdate(); - if (count <= 0) { - throw new WaarpDatabaseNoDataException("No row found"); - } - } else { - throw new WaarpDatabaseNoDataException("No row found"); - } - } finally { - find.realClose(); - } - } - isSaved = true; - } finally { - preparedStatement.realClose(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() - */ - @Override - public boolean exist() throws WaarpDatabaseException { - if (dbSession == null) { - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - return existXmlWorkNoDb(); - } - return false; - } - return super.exist(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() - */ - @Override - public void select() throws WaarpDatabaseException { - if (dbSession == null) { - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - try { - this.loadXmlWorkNoDb(); - setFromArray(); - } catch (OpenR66ProtocolBusinessException e) { - throw new WaarpDatabaseNoDataException("No file found"); - } - if (rule == null) { - rule = new DbRule(this.dbSession, ruleId); - } - isSaved = true; - checkThroughMode(); - return; - } - throw new WaarpDatabaseNoDataException("No row found"); - } - super.select(); - if (rule == null) { - rule = new DbRule(this.dbSession, ruleId); - } - checkThroughMode(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() - */ - @Override - public void update() throws WaarpDatabaseException { - if (isSaved) { - return; - } - if (dbSession == null) { - isSaved = true; - if (Configuration.configuration.saveTaskRunnerWithNoDb) { - try { - setToArray(); - this.writeXmlWorkNoDb(); - } catch (OpenR66ProtocolBusinessException e) { - // Ignore - } - } - if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { - addNoDb(); - } - return; - } - // SNMP notification - if (updatedInfo == UpdatedInfo.INERROR.ordinal() || - updatedInfo == UpdatedInfo.INTERRUPTED.ordinal()) { - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyInfoTask( - "Task is " + UpdatedInfo.values()[updatedInfo].name(), this); - } - } else { - if (globalstep != TASKSTEP.TRANSFERTASK.ordinal() || - (globalstep == TASKSTEP.TRANSFERTASK.ordinal() && - (rank % 100 == 0))) { - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyTask( - "Task is currently " + UpdatedInfo.values()[updatedInfo].name(), this); - } - } - } - // FIX SelfRequest - if (isSelfRequest()) { - if (RequestPacket.isCompatibleMode(mode, - isSender ? RequestPacket.TRANSFERMODE.RECVMODE.ordinal() : - RequestPacket.TRANSFERMODE.SENDMODE.ordinal())) { - super.update(); - } - } else { - super.update(); - } - } - - /** - * Partial set from another runner (infostatus, rank, status, step, stop, filename, - * globallastep, globalstep, isFileMoved) - * - * @param runner - */ - public void setFrom(DbTaskRunner runner) { - if (runner != null) { - this.infostatus = runner.infostatus; - this.rank = runner.rank; - this.status = runner.status; - this.step = runner.step; - this.stop = runner.stop; - this.filename = runner.filename; - this.globallaststep = runner.globallaststep; - this.globalstep = runner.globalstep; - this.isFileMoved = runner.isFileMoved; - } - } - - public boolean isRecvThrough() { - return isRecvThrough; - } - - public boolean isSendThrough() { - return isSendThrough; - } - - /** - * Private constructor for Commander only - * - * @param session - */ - private DbTaskRunner(DbSession dBsession) { - super(dBsession); - session = null; - rule = null; - } - - /** - * Set a localChannelReference - * - * @param localChannelReference - */ - public void setLocalChannelReference(LocalChannelReference localChannelReference) { - this.localChannelReference = localChannelReference; - } - - /** - * @return the localChannelReference - */ - public LocalChannelReference getLocalChannelReference() { - return localChannelReference; - } - - /** - * For instance from Commander when getting updated information - * - * @param preparedStatement - * @return the next updated DbTaskRunner - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbTaskRunner getFromStatement( - DbPreparedStatement preparedStatement) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbTaskRunner dbTaskRunner = new DbTaskRunner(preparedStatement - .getDbSession()); - dbTaskRunner.getValues(preparedStatement, dbTaskRunner.allFields); - dbTaskRunner.setFromArray(); - if (dbTaskRunner.rule == null) { - try { - dbTaskRunner.rule = new DbRule(dbTaskRunner.dbSession, dbTaskRunner.ruleId); - } catch (WaarpDatabaseException e) { - throw new WaarpDatabaseSqlException(e); - } - } - dbTaskRunner.checkThroughMode(); - dbTaskRunner.isSaved = true; - return dbTaskRunner; - } - - /** - * @param session - * @param status - * @param limit - * limit the number of rows - * @return the DbPreparedStatement for getting Runner according to status ordered by start - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getStatusPrepareStatement( - DbSession session, ErrorCode status, int limit) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields + " FROM " + table; - if (status != null) { - request += " WHERE " + Columns.STEPSTATUS.name() + " = '" + - status.getCode() + "' AND " + getLimitWhereCondition(); - } else { - request += " WHERE " + getLimitWhereCondition(); - } - request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; - request = DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); - return new DbPreparedStatement(session, request); - } - - /** - * @param session - * @param globalstep - * @param limit - * limit the number of rows - * @return the DbPreparedStatement for getting Runner according to globalstep ordered by start - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getStepPrepareStatement(DbSession session, - TASKSTEP globalstep, int limit) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields + " FROM " + table; - if (globalstep != null) { - request += " WHERE (" + Columns.GLOBALSTEP.name() + " = " + - globalstep.ordinal(); - if (globalstep == TASKSTEP.ERRORTASK) { - request += " OR " + Columns.UPDATEDINFO.name() + " = " + - UpdatedInfo.INERROR.ordinal() + ") AND "; - } else { - request += ") AND "; - } - request += getLimitWhereCondition(); - } else { - request += " WHERE " + getLimitWhereCondition(); - } - request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; - request = DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); - return new DbPreparedStatement(session, request); - } - - /** - * - * @param preparedStatement - * @param srcrequest - * @param limit - * @param orderby - * @param startid - * @param stopid - * @param start - * @param stop - * @param rule - * @param req - * @param pending - * @param transfer - * @param error - * @param done - * @param all - * @return The DbPreparedStatement already prepared according to select or delete command - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - private static DbPreparedStatement getFilterCondition( - DbPreparedStatement preparedStatement, String srcrequest, int limit, - String orderby, String startid, String stopid, Timestamp start, Timestamp stop, - String rule, - String req, boolean pending, boolean transfer, boolean error, - boolean done, boolean all) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - String request = srcrequest; - if (startid == null && stopid == null && - start == null && stop == null && rule == null && req == null && all) { - // finish - if (limit > 0) { - request = DbModelFactory.dbModel.limitRequest(selectAllFields, - request + orderby, limit); - } else { - request = request + orderby; - } - preparedStatement.createPrepareStatement(request); - return preparedStatement; - } - request += " WHERE "; - StringBuilder scondition = new StringBuilder(); - boolean hasCondition = false; - if (start != null & stop != null) { - scondition.append(Columns.STARTTRANS.name()); - scondition.append(" >= ? AND "); - scondition.append(Columns.STARTTRANS.name()); - scondition.append(" <= ? "); - hasCondition = true; - } else if (start != null) { - scondition.append(Columns.STARTTRANS.name()); - scondition.append(" >= ? "); - hasCondition = true; - } else if (stop != null) { - scondition.append(Columns.STARTTRANS.name()); - scondition.append(" <= ? "); - hasCondition = true; - } - if (startid != null) { - if (hasCondition) { - scondition.append(" AND "); - } - hasCondition = true; - scondition.append(Columns.SPECIALID.name()); - scondition.append(" >= ? "); - } - if (stopid != null) { - if (hasCondition) { - scondition.append(" AND "); - } - hasCondition = true; - scondition.append(Columns.SPECIALID.name()); - scondition.append(" <= ? "); - } - if (rule != null) { - if (hasCondition) { - scondition.append(" AND "); - } - hasCondition = true; - scondition.append(Columns.IDRULE.name()); - scondition.append(" LIKE '%"); - scondition.append(rule); - scondition.append("%' "); - } - if (req != null) { - if (hasCondition) { - scondition.append(" AND "); - } - hasCondition = true; - scondition.append("( "); - scondition.append(Columns.REQUESTED.name()); - scondition.append(" LIKE '%"); - scondition.append(req); - scondition.append("%' OR "); - scondition.append(Columns.REQUESTER.name()); - scondition.append(" LIKE '%"); - scondition.append(req); - scondition.append("%' )"); - } - if (!all) { - if (hasCondition) { - scondition.append(" AND "); - } - hasCondition = true; - scondition.append("( "); - boolean hasone = false; - if (pending) { - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" = "); - scondition.append(UpdatedInfo.TOSUBMIT.ordinal()); - hasone = true; - } - if (transfer) { - if (hasone) { - scondition.append(" OR "); - } - scondition.append("( "); - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" = "); - scondition.append(UpdatedInfo.RUNNING.ordinal()); - scondition.append(" )"); - hasone = true; - } - if (error) { - if (hasone) { - scondition.append(" OR "); - } - scondition.append(Columns.GLOBALSTEP.name()); - scondition.append(" = "); - scondition.append(TASKSTEP.ERRORTASK.ordinal()); - scondition.append(" OR "); - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" = "); - scondition.append(UpdatedInfo.INERROR.ordinal()); - scondition.append(" OR "); - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" = "); - scondition.append(UpdatedInfo.INTERRUPTED.ordinal()); - hasone = true; - } - if (done) { - if (hasone) { - scondition.append(" OR "); - } - scondition.append(Columns.GLOBALSTEP.name()); - scondition.append(" = "); - scondition.append(TASKSTEP.ALLDONETASK.ordinal()); - scondition.append(" OR "); - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" = "); - scondition.append(UpdatedInfo.DONE.ordinal()); - } - if (scondition.length() <= 3) { - scondition.append(Columns.UPDATEDINFO.name()); - scondition.append(" IS NOT NULL "); - } - scondition.append(" )"); - } - if (limit > 0) { - scondition.insert(0, request); - scondition.append(orderby); - request = scondition.toString(); - request = DbModelFactory.dbModel.limitRequest(selectAllFields, - request, limit); - } else { - scondition.insert(0, request); - scondition.append(orderby); - request = scondition.toString(); - } - preparedStatement.createPrepareStatement(request); - int rank = 1; - try { - if (start != null & stop != null) { - preparedStatement.getPreparedStatement().setTimestamp(rank, - start); - rank++; - preparedStatement.getPreparedStatement().setTimestamp(rank, - stop); - rank++; - } else if (start != null) { - preparedStatement.getPreparedStatement().setTimestamp(rank, - start); - rank++; - } else if (stop != null) { - preparedStatement.getPreparedStatement().setTimestamp(rank, - stop); - rank++; - } - if (startid != null) { - long value = DbConstant.ILLEGALVALUE; - try { - value = Long.parseLong(startid); - } catch (NumberFormatException e) { - // ignore then - } - preparedStatement.getPreparedStatement().setLong(rank, - value); - rank++; - } - if (stopid != null) { - long value = Long.MAX_VALUE; - try { - value = Long.parseLong(stopid); - } catch (NumberFormatException e) { - // ignore then - } - preparedStatement.getPreparedStatement().setLong(rank, - value); - rank++; - } - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - return preparedStatement; - } - - /** - * - * @param session - * @param limit - * @param orderBySpecialId - * @param startid - * @param stopid - * @param start - * @param stop - * @param rule - * @param req - * @param pending - * @param transfer - * @param error - * @param done - * @param all - * @return the DbPreparedStatement according to the filter - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getFilterPrepareStatement( - DbSession session, int limit, boolean orderBySpecialId, String startid, String stopid, - Timestamp start, Timestamp stop, String rule, - String req, boolean pending, boolean transfer, boolean error, - boolean done, boolean all) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "SELECT " + selectAllFields + " FROM " + table; - String orderby; - if (startid == null && stopid == null && - start == null && stop == null && rule == null && req == null && all) { - orderby = " WHERE " + getLimitWhereCondition(); - } else { - orderby = " AND " + getLimitWhereCondition(); - } - if (orderBySpecialId) { - orderby += " ORDER BY " + Columns.SPECIALID.name() + " DESC "; - } else { - orderby += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; - } - return getFilterCondition(preparedStatement, request, limit, orderby, - startid, stopid, start, stop, rule, - req, pending, transfer, error, done, all); - } - - /** - * - * @param session - * @param info - * @param orderByStart - * If true, sort on Start ; If false, does not set the limit on start - * @param limit - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getSelectFromInfoPrepareStatement(DbSession session, - UpdatedInfo info, boolean orderByStart, int limit) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT " + selectAllFields + - " FROM " + table + " WHERE " + Columns.UPDATEDINFO.name() + - " = " + info.ordinal() + - " AND " + Columns.STARTTRANS.name() + " <= ? AND " + getLimitWhereCondition(); - if (orderByStart) { - request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; - } - request = - DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); - DbPreparedStatement pstt = new DbPreparedStatement(session, request); - return pstt; - } - - /** - * - * @param session - * @return the DbPreparedStatement for getting Updated Object - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountInfoPrepareStatement(DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + - ") FROM " + table + " WHERE " + - Columns.STARTTRANS.name() + " >= ? AND " + getLimitWhereCondition() + - " AND " + Columns.UPDATEDINFO.name() + " = ? "; - DbPreparedStatement pstt = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(pstt); - return pstt; - } - - /** - * - * @param pstt - * @param info - * @param time - * @return the number of elements (COUNT) from the statement - */ - public static long getResultCountPrepareStatement(DbPreparedStatement pstt, UpdatedInfo info, - long time) { - long result = 0; - try { - finishSelectOrCountPrepareStatement(pstt, time); - pstt.getPreparedStatement().setInt(2, info.ordinal()); - pstt.executeQuery(); - if (pstt.getNext()) { - result = pstt.getResultSet().getLong(1); - } - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } catch (SQLException e) { - } finally { - pstt.close(); - } - return result; - } - - /** - * @param session - * @param globalstep - * @return the DbPreparedStatement for getting Runner according to globalstep ordered by start - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountStepPrepareStatement(DbSession session, - TASKSTEP globalstep) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; - if (globalstep != null) { - request += " WHERE " + Columns.GLOBALSTEP.name() + " = " + - globalstep.ordinal() + " AND "; - request += Columns.STARTTRANS.name() + " >= ? AND " + getLimitWhereCondition(); - } else { - request += " WHERE " + Columns.STARTTRANS.name() + " >= ? AND " - + getLimitWhereCondition(); - } - DbPreparedStatement prep = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(prep); - return prep; - } - - /** - * @param session - * @return the DbPreparedStatement for getting Runner according to status ordered by start - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountStatusPrepareStatement( - DbSession session) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; - request += " WHERE " + Columns.STARTTRANS.name() + " >= ? "; - request += " AND " + Columns.INFOSTATUS.name() + " = ? AND " + getLimitWhereCondition(); - DbPreparedStatement prep = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(prep); - return prep; - } - - /** - * - * @param pstt - * @param error - * @param time - * @return the number of elements (COUNT) from the statement - */ - public static long getResultCountPrepareStatement(DbPreparedStatement pstt, ErrorCode error, - long time) { - long result = 0; - try { - finishSelectOrCountPrepareStatement(pstt, time); - pstt.getPreparedStatement().setString(2, error.getCode()); - pstt.executeQuery(); - if (pstt.getNext()) { - result = pstt.getResultSet().getLong(1); - } - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } catch (SQLException e) { - } finally { - pstt.close(); - } - return result; - } - - /** - * Only running transfers - * - * @param session - * @param status - * @return the DbPreparedStatement for getting Runner according to status ordered by start - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountStatusRunningPrepareStatement( - DbSession session, ErrorCode status) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; - if (status != null) { - request += " WHERE " + Columns.STEPSTATUS.name() + " = '" + - status.getCode() + "' AND " + getLimitWhereCondition(); - } else { - request += " WHERE " + getLimitWhereCondition(); - } - request += " AND " + Columns.STARTTRANS.name() + " >= ? "; - request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.RUNNING.ordinal(); - DbPreparedStatement prep = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(prep); - return prep; - } - - /** - * Running or not transfers are concerned - * - * @param session - * @param in - * True for Incoming, False for Outgoing - * @return the DbPreparedStatement for getting Runner according to in or out going way and Error - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountInOutErrorPrepareStatement( - DbSession session, boolean in) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; - String requesterd; - String from = Configuration.configuration.HOST_ID; - String sfrom = Configuration.configuration.HOST_SSLID; - if (in) { - requesterd = Columns.REQUESTED.name(); - } else { - requesterd = Columns.REQUESTER.name(); - } - if (from != null & sfrom != null) { - request += " WHERE ((" + requesterd + " = '" + - from + "' OR " + requesterd + " = '" + sfrom + "') "; - } else if (from != null) { - request += " WHERE (" + requesterd + " = '" + from + "' "; - } else { - request += " WHERE (" + requesterd + " = '" + sfrom + "' "; - } - request += " AND " + getLimitWhereCondition() + ") "; - request += " AND " + Columns.STARTTRANS.name() + " >= ? "; - request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.INERROR.ordinal(); - DbPreparedStatement prep = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(prep); - return prep; - } - - /** - * Running or not transfers are concerned - * - * @param session - * @param in - * True for Incoming, False for Outgoing - * @param running - * True for Running only, False for all - * @return the DbPreparedStatement for getting Runner according to in or out going way - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getCountInOutRunningPrepareStatement( - DbSession session, boolean in, boolean running) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; - String requesterd; - String from = Configuration.configuration.HOST_ID; - String sfrom = Configuration.configuration.HOST_SSLID; - if (in) { - requesterd = Columns.REQUESTED.name(); - } else { - requesterd = Columns.REQUESTER.name(); - } - if (from != null & sfrom != null) { - request += " WHERE ((" + requesterd + " = '" + - from + "' OR " + requesterd + " = '" + sfrom + "') "; - } else if (from != null) { - request += " WHERE (" + requesterd + " = '" + from + "' "; - } else { - request += " WHERE (" + requesterd + " = '" + sfrom + "' "; - } - request += " AND " + getLimitWhereCondition() + ") "; - request += " AND " + Columns.STARTTRANS.name() + " >= ? "; - if (running) { - request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.RUNNING.ordinal(); - } - DbPreparedStatement prep = new DbPreparedStatement(session, request); - session.addLongTermPreparedStatement(prep); - return prep; - } - - /** - * - * @param pstt - * @return the number of elements (COUNT) from the statement - */ - public static long getResultCountPrepareStatement(DbPreparedStatement pstt) { - long result = 0; - try { - pstt.executeQuery(); - if (pstt.getNext()) { - result = pstt.getResultSet().getLong(1); - } - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } catch (SQLException e) { - } finally { - pstt.close(); - } - return result; - } - - /** - * Set the current time in the given updatedPreparedStatement - * - * @param pstt - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static void finishSelectOrCountPrepareStatement(DbPreparedStatement pstt) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - finishSelectOrCountPrepareStatement(pstt, System.currentTimeMillis()); - } - - /** - * Set the current time in the given updatedPreparedStatement - * - * @param pstt - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static void finishSelectOrCountPrepareStatement(DbPreparedStatement pstt, long time) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - Timestamp startlimit = new Timestamp(time); - try { - pstt.getPreparedStatement().setTimestamp(1, startlimit); - } catch (SQLException e) { - logger.error("Database SQL Error: Cannot set timestamp", e); - throw new WaarpDatabaseSqlException("Cannot set timestamp", e); - } - } - - /** - * - * @param session - * @param start - * @param stop - * @return the DbPreparedStatement for getting Selected Object, whatever their status - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static DbPreparedStatement getLogPrepareStatement(DbSession session, - Timestamp start, Timestamp stop) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "SELECT " + selectAllFields + " FROM " + table; - if (start != null & stop != null) { - request += " WHERE " + Columns.STARTTRANS.name() + " >= ? AND " + - Columns.STARTTRANS.name() + " <= ? AND " + getLimitWhereCondition() + - " ORDER BY " + Columns.SPECIALID.name() + " DESC "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, start); - preparedStatement.getPreparedStatement().setTimestamp(2, stop); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else if (start != null) { - request += " WHERE " + Columns.STARTTRANS.name() + - " >= ? AND " + getLimitWhereCondition() + - " ORDER BY " + Columns.SPECIALID.name() + " DESC "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, start); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else if (stop != null) { - request += " WHERE " + Columns.STARTTRANS.name() + - " <= ? AND " + getLimitWhereCondition() + - " ORDER BY " + Columns.SPECIALID.name() + " DESC "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, stop); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else { - request += " WHERE " + getLimitWhereCondition() + - " ORDER BY " + Columns.SPECIALID.name() + " DESC "; - preparedStatement.createPrepareStatement(request); - } - return preparedStatement; - } - - /** - * purge in same interval all runners with globallaststep as ALLDONETASK or UpdatedInfo as Done - * - * @param session - * @param start - * @param stop - * @return the number of log purged - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static int purgeLogPrepareStatement(DbSession session, - Timestamp start, Timestamp stop) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "DELETE FROM " + table + " WHERE (" + - Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + - Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + - ") AND " + getLimitWhereCondition(); - try { - if (start != null & stop != null) { - request += " AND " + Columns.STARTTRANS.name() + " >= ? AND " + - Columns.STOPTRANS.name() + " <= ? "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, start); - preparedStatement.getPreparedStatement().setTimestamp(2, stop); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else if (start != null) { - request += " AND " + Columns.STARTTRANS.name() + " >= ? "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, start); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else if (stop != null) { - request += " AND " + Columns.STOPTRANS.name() + " <= ? "; - preparedStatement.createPrepareStatement(request); - try { - preparedStatement.getPreparedStatement().setTimestamp(1, stop); - } catch (SQLException e) { - preparedStatement.realClose(); - throw new WaarpDatabaseSqlException(e); - } - } else { - preparedStatement.createPrepareStatement(request); - } - int nb = preparedStatement.executeUpdate(); - logger.info("Purge " + nb + " from " + request); - return nb; - } finally { - preparedStatement.realClose(); - } - } - - /** - * - * @param session - * @param startid - * @param stopid - * @param start - * @param stop - * @param rule - * @param req - * @param pending - * @param transfer - * @param error - * @param done - * @param all - * @return the DbPreparedStatement according to the filter and ALLDONE, ERROR globallaststep - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - public static int purgeLogPrepareStatement( - DbSession session, String startid, String stopid, - Timestamp start, Timestamp stop, String rule, - String req, boolean pending, boolean transfer, boolean error, - boolean done, boolean all) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - DbPreparedStatement preparedStatement = new DbPreparedStatement(session); - String request = "DELETE FROM " + table; - String orderby; - if (startid == null && stopid == null && start == null && stop == null && - rule == null && req == null && all) { - orderby = " WHERE (" + - Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + - Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + - ") AND " + getLimitWhereCondition(); - } else { - if (all) { - orderby = " AND (" + - Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + - Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + " OR " + - Columns.UPDATEDINFO + " = " + UpdatedInfo.INERROR.ordinal() + - ") AND " + getLimitWhereCondition(); - } else { - orderby = " AND " + - Columns.UPDATEDINFO + " <> " + UpdatedInfo.RUNNING.ordinal() + - " AND " + getLimitWhereCondition();// limit by field - } - } - int nb = 0; - try { - preparedStatement = getFilterCondition(preparedStatement, request, 0, - orderby, startid, stopid, start, stop, rule, - req, pending, transfer, error, done, all); - nb = preparedStatement.executeUpdate(); - logger.info("Purge " + nb + " from " + request); - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - return nb; - } - - /** - * Change RUNNING, INTERRUPTED to TOSUBMIT TaskRunner from database. This method is to be used - * when the commander is starting the very first time, in order to be ready to rerun tasks that - * are pending. - * - * @param session - * @throws WaarpDatabaseNoConnectionException - */ - public static void resetToSubmit(DbSession session) - throws WaarpDatabaseNoConnectionException { - // Change RUNNING and INTERRUPTED to TOSUBMIT since they should be ready - String request = "UPDATE " + table + " SET " + - Columns.UPDATEDINFO.name() + "=" + - AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + - " WHERE (" + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.RUNNING.ordinal() + - " OR " + Columns.UPDATEDINFO.name() + " = " + - AbstractDbData.UpdatedInfo.INTERRUPTED.ordinal() + ") AND " + - getLimitWhereCondition(); - DbPreparedStatement initial = new DbPreparedStatement(session); - try { - initial.createPrepareStatement(request); - initial.executeUpdate(); - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } finally { - initial.close(); - } - } - - /** - * Change CompleteOk+ALLDONETASK to Updated = DONE TaskRunner from database. This method is a - * clean function to be used for instance before log export or at the very beginning of the - * commander. - * - * @param session - * @throws WaarpDatabaseNoConnectionException - */ - public static void changeFinishedToDone(DbSession session) - throws WaarpDatabaseNoConnectionException { - // Update all UpdatedInfo to DONE where GlobalLastStep = ALLDONETASK and - // status = CompleteOk - String request = "UPDATE " + table + " SET " + - Columns.UPDATEDINFO.name() + "=" + - AbstractDbData.UpdatedInfo.DONE.ordinal() + - " WHERE " + Columns.UPDATEDINFO.name() + " <> " + - AbstractDbData.UpdatedInfo.DONE.ordinal() + " AND " + - Columns.UPDATEDINFO.name() + " > 0 AND " + - Columns.GLOBALLASTSTEP.name() + " = " + - TASKSTEP.ALLDONETASK.ordinal() + " AND " + - Columns.STEPSTATUS.name() + " = '" + - ErrorCode.CompleteOk.getCode() + "' AND " + - getLimitWhereCondition(); - DbPreparedStatement initial = new DbPreparedStatement(session); - try { - initial.createPrepareStatement(request); - initial.executeUpdate(); - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Database No Connection Error: Cannot execute Commander", e); - return; - } catch (WaarpDatabaseSqlException e) { - logger.error("Database SQL Error: Cannot execute Commander", e); - return; - } finally { - initial.realClose(); - } - } - - /** - * Reset the runner (ready to be run again) - * - * @return True if OK, False if already finished - */ - public boolean reset() { - // Reset the status if already stopped and not finished - if (this.getStatus() != ErrorCode.CompleteOk) { - // restart - switch (TASKSTEP.values()[this.getGloballaststep()]) { - case PRETASK: - // restart - this.setPreTask(); - this.setExecutionStatus(ErrorCode.InitOk); - break; - case TRANSFERTASK: - // continue - int newrank = this.getRank(); - this.setTransferTask(newrank); - this.setExecutionStatus(ErrorCode.PreProcessingOk); - break; - case POSTTASK: - // restart - this.setPostTask(); - this.setExecutionStatus(ErrorCode.TransferOk); - break; - case ALLDONETASK: - break; - case ERRORTASK: - break; - case NOTASK: - setInitialTask(); - this.setExecutionStatus(ErrorCode.Unknown); - break; - default: - break; - } - this.changeUpdatedInfo(UpdatedInfo.UNKNOWN); - this.setErrorExecutionStatus(this.status); - return true; - } else { - // Already finished - return false; - } - } - - /** - * Decrease if necessary the rank - */ - public void restartRank() { - if (!this.isSender) { - int newrank = this.getRank(); - if (newrank > 0) { - logger.debug("Decrease Rank Restart of -" + Configuration.RANKRESTART + - " from " + newrank); - newrank -= Configuration.RANKRESTART; - if (newrank <= 0) { - newrank = 1; - } - if (this.getRank() != newrank) { - logger.warn("Decreased Rank Restart at rank: " + newrank + " for {}", this); - } - } - this.setTransferTask(newrank); - } - } - - /** - * Make this Runner ready for restart - * - * @param submit - * True to resubmit this task, else False to keep it as running (only reset) - * @return True if OK or False if Already finished or if submitted and the request is a - * selfRequested and is not ready to restart locally - */ - public boolean restart(boolean submit) { - // Restart if not Requested - if (submit) { - if (isSelfRequested() && (this.globallaststep < TASKSTEP.POSTTASK.ordinal())) { - return false; - } - } - // Restart if already stopped and not finished - if (reset()) { - // if not submit and transfertask and receiver AND not requester - // If requester and receiver => rank is already decreased when request is sent - if ((!submit) && (this.globalstep == TASKSTEP.TRANSFERTASK.ordinal()) && - (!this.isSender) && (this.isSelfRequested())) { - logger.debug("Will try to restart transfer {}", this); - this.restartRank(); - logger.debug("New restart for transfer is {}", this); - } - if (submit) { - this.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - } else { - this.changeUpdatedInfo(UpdatedInfo.RUNNING); - } - return true; - } else { - // Already finished so DONE - this.setAllDone(); - this.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); - this.forceSaveStatus(); - return false; - } - } - - /** - * Stop or Cancel a Runner from database point of view - * - * @param code - * @return True if correctly stopped or canceled - */ - public boolean stopOrCancelRunner(ErrorCode code) { - if (!isFinished()) { - reset(); - switch (code) { - case CanceledTransfer: - case StoppedTransfer: - case RemoteShutdown: - this.changeUpdatedInfo(UpdatedInfo.INERROR); - break; - default: - this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); - } - forceSaveStatus(); - logger.warn("StopOrCancel: {}\n {}", code.mesg, this.toShortString()); - return true; - } else { - // is finished so do nothing - } - return false; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) - */ - @Override - public void changeUpdatedInfo(UpdatedInfo info) { - updatedInfo = info.ordinal(); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); - isSaved = false; - } - - /** - * Set the ErrorCode for the UpdatedInfo - * - * @param code - */ - public void setErrorExecutionStatus(ErrorCode code) { - if (infostatus != code) { - infostatus = code; - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - isSaved = false; - } - } - - /** - * - * @return The current UpdatedInfo value - */ - public UpdatedInfo getUpdatedInfo() { - return UpdatedInfo.values()[updatedInfo]; - } - - /** - * - * @return the error code associated with the Updated Info - */ - public ErrorCode getErrorInfo() { - return infostatus; - } - - /** - * @return the step - */ - public int getStep() { - return step; - } - - /** - * @return the rescheduledTransfer - */ - public boolean isRescheduledTransfer() { - return rescheduledTransfer; - } - - /** - * Set this DbTaskRunner as rescheduled (valid only while still in memory) - */ - public void setRescheduledTransfer() { - this.rescheduledTransfer = true; - } - - /** - * To set the rank at startup of the request if the request specify a specific rank - * - * @param rank - * the rank to set - */ - public void setRankAtStartup(int rank) { - if (this.rank > rank) { - this.rank = rank; - allFields[Columns.RANK.ordinal()].setValue(this.rank); - isSaved = false; - } - } - - /** - * @param filename - * the filename to set - */ - public void setFilename(String filename) { - if (!this.filename.equals(filename)) { - this.filename = filename; - allFields[Columns.FILENAME.ordinal()].setValue(this.filename); - isSaved = false; - } - } - - /** - * @param newFilename - * the new Filename to set - * @param isFileMoved - * the isFileMoved to set - */ - public void setFileMoved(String newFilename, boolean isFileMoved) { - if (this.isFileMoved != isFileMoved) { - this.isFileMoved = isFileMoved; - allFields[Columns.ISMOVED.ordinal()].setValue(this.isFileMoved); - isSaved = false; - } - this.setFilename(newFilename); - } - - /** - * @param originalFilename - * the originalFilename to set - */ - public void setOriginalFilename(String originalFilename) { - if (!this.originalFilename.equals(originalFilename)) { - this.originalFilename = originalFilename; - allFields[Columns.ORIGINALNAME.ordinal()] - .setValue(this.originalFilename); - isSaved = false; - } - } - - /** - * @return the rank - */ - public int getRank() { - return rank; - } - - /** - * Change the status from Task Execution - * - * @param status - */ - public void setExecutionStatus(ErrorCode status) { - this.status = status; - allFields[Columns.STEPSTATUS.ordinal()].setValue(this.status.getCode()); - isSaved = false; - } - - /** - * @return the status - */ - public ErrorCode getStatus() { - return status; - } - - /** - * @return the isSender - */ - public boolean isSender() { - return isSender; - } - - /** - * @return the isFileMoved - */ - public boolean isFileMoved() { - return isFileMoved; - } - - /** - * @return the blocksize - */ - public int getBlocksize() { - return blocksize; - } - - /** - * @return the filename - */ - public String getFilename() { - return filename; - } - - /** - * @return the originalFilename - */ - public String getOriginalFilename() { - return originalFilename; - } - - /** - * @return the fileInformation - */ - public String getFileInformation() { - return fileInformation; - } - - /** - * Set a new File information for this transfer - * @param newFileInformation - */ - public void setFileInformation(String newFileInformation) { - fileInformation = newFileInformation; - allFields[Columns.FILEINFO.ordinal()].setValue(this.fileInformation); - isSaved = false; - } - - /** - * @return the specialId - */ - public long getSpecialId() { - return specialId; - } - - /** - * @return the rule - */ - public DbRule getRule() { - if (rule == null) { - if (ruleId != null) { - try { - rule = new DbRule(dbSession, ruleId); - } catch (WaarpDatabaseException e) { - } - } - } - return rule; - } - - /** - * @return the ruleId - */ - public String getRuleId() { - return ruleId; - } - - /** - * @return the mode - */ - public int getMode() { - return mode; - } - - /** - * @return the globallaststep - */ - public int getGloballaststep() { - return globallaststep; - } - - /** - * - * @return True if this runner is ready for transfer or post operation - */ - public boolean ready() { - return globalstep > TASKSTEP.PRETASK.ordinal(); - } - - /** - * - * @return True if the runner is currently in transfer - */ - public boolean isInTransfer() { - return globalstep == TASKSTEP.TRANSFERTASK.ordinal(); - } - - /** - * - * @return True if this runner is finished, either in success or in error - */ - public boolean isFinished() { - return isAllDone() || isInError(); - } - - /** - * - * @return True if this runner is in error and no more running - */ - public boolean isInError() { - return (globalstep == TASKSTEP.ERRORTASK.ordinal() && status != ErrorCode.Running); - } - - /** - * - * @return True if the runner is finished in success - */ - public boolean isAllDone() { - return globalstep == TASKSTEP.ALLDONETASK.ordinal(); - } - - /** - * To be called before executing Pre execution - * - * @return True if the task is going to run PRE task from the first action - */ - public boolean isPreTaskStarting() { - if (globallaststep == TASKSTEP.PRETASK.ordinal() || - globallaststep == TASKSTEP.NOTASK.ordinal()) { - return (step - 1 <= 0); - } - return false; - } - - - /** - * Set the Initial Task step (before Pre task) - * - */ - public void setInitialTask() { - globalstep = TASKSTEP.NOTASK.ordinal(); - globallaststep = TASKSTEP.NOTASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - step = -1; - allFields[Columns.STEP.ordinal()].setValue(this.step); - status = ErrorCode.Running; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - this.changeUpdatedInfo(UpdatedInfo.RUNNING); - this.setErrorExecutionStatus(ErrorCode.Unknown); - isSaved = false; - } - - /** - * Set Pre Task step - * - */ - public void setPreTask() { - globalstep = TASKSTEP.PRETASK.ordinal(); - globallaststep = TASKSTEP.PRETASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - if (step <= 0) { - this.step = 0; - } else { - this.step--; - } - allFields[Columns.STEP.ordinal()].setValue(this.step); - status = ErrorCode.Running; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - this.changeUpdatedInfo(UpdatedInfo.RUNNING); - this.setErrorExecutionStatus(ErrorCode.InitOk); - isSaved = false; - } - - /** - * Set Transfer rank - * - * @param rank - */ - public void setTransferTask(int rank) { - globalstep = TASKSTEP.TRANSFERTASK.ordinal(); - globallaststep = TASKSTEP.TRANSFERTASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - if (this.rank > rank) { - this.rank = rank; - } - allFields[Columns.RANK.ordinal()].setValue(this.rank); - status = ErrorCode.Running; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - this.setErrorExecutionStatus(ErrorCode.PreProcessingOk); - isSaved = false; - } - - /** - * Set the status of the transfer - * - * @param code - * TransferOk if success - * @return the current rank of transfer - */ - public int finishTransferTask(ErrorCode code) { - if (code == ErrorCode.TransferOk) { - this.status = code; - this.setErrorExecutionStatus(code); - } else { - continueTransfer = false; - if (this.infostatus == ErrorCode.InitOk || - this.infostatus == ErrorCode.PostProcessingOk || - this.infostatus == ErrorCode.PreProcessingOk || - this.infostatus == ErrorCode.Running || - this.infostatus == ErrorCode.TransferOk) { - this.setErrorExecutionStatus(code); - } - if (this.updatedInfo != UpdatedInfo.INTERRUPTED.ordinal()) { - this.changeUpdatedInfo(UpdatedInfo.INERROR); - } - } - allFields[Columns.STEPSTATUS.ordinal()].setValue(this.status.getCode()); - isSaved = false; - return rank; - } - - /** - * - * @return True if the transfer is valid to continue - */ - public boolean continueTransfer() { - return continueTransfer; - } - - /** - * Set the Post Task step - * - */ - public void setPostTask() { - globalstep = TASKSTEP.POSTTASK.ordinal(); - globallaststep = TASKSTEP.POSTTASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - if (step <= 0) { - this.step = 0; - } else { - this.step--; - } - allFields[Columns.STEP.ordinal()].setValue(this.step); - status = ErrorCode.Running; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - this.setErrorExecutionStatus(ErrorCode.TransferOk); - isSaved = false; - } - - /** - * Set the Error Task step - * - * @param localChannelReference - * (to get session) - */ - public void setErrorTask(LocalChannelReference localChannelReference) { - if (this.session == null && localChannelReference != null) { - this.session = localChannelReference.getSession(); - } - if (this.session != null) { - if (this.session.getRunner() == null) - this.session.setNoSessionRunner(this, localChannelReference); - } - globalstep = TASKSTEP.ERRORTASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - this.step = 0; - allFields[Columns.STEP.ordinal()].setValue(this.step); - status = ErrorCode.Running; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - isSaved = false; - } - - /** - * Set the global step as finished (after post task in success) - */ - public void setAllDone() { - globalstep = TASKSTEP.ALLDONETASK.ordinal(); - globallaststep = TASKSTEP.ALLDONETASK.ordinal(); - allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); - step = 0; - allFields[Columns.STEP.ordinal()].setValue(step); - status = ErrorCode.CompleteOk; - allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); - infostatus = ErrorCode.CompleteOk; - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - changeUpdatedInfo(UpdatedInfo.DONE); - isSaved = false; - } - - /** - * Run the task from the given task information (from rule) - * - * @param tasks - * @return The future of the operation (in success or not) - * @throws OpenR66RunnerEndTasksException - * @throws OpenR66RunnerErrorException - */ - private R66Future runNextTask(String[][] tasks) - throws OpenR66RunnerEndTasksException, OpenR66RunnerErrorException { - logger.debug((session == null) + ":" - + (session == null ? "norunner" : (this.session.getRunner() == null)) + ":" - + this.toLogRunStep() + ":" + step + ":" + (tasks == null ? "null" : tasks.length) - + "\nSender: " + this.isSender + " " + this.rule.printTasks(isSender, - TASKSTEP.values()[globalstep])); - if (tasks == null) { - throw new OpenR66RunnerEndTasksException("No tasks!"); - } - R66Session tempSession = this.session; - if (tempSession == null) { - tempSession = new R66Session(); - if (tempSession.getRunner() == null) { - tempSession.setNoSessionRunner(this, localChannelReference); - } - } else { - if (tempSession.getRunner() == null) { - tempSession.setNoSessionRunner(this, tempSession.getLocalChannelReference()); - } - } - this.session = tempSession; - if (this.session.getLocalChannelReference().getCurrentCode() == ErrorCode.Unknown) { - this.session.getLocalChannelReference().setErrorMessage(this.infostatus.mesg, - this.infostatus); - } - if (tasks.length <= step) { - throw new OpenR66RunnerEndTasksException(); - } - String name = tasks[step][0]; - String arg = tasks[step][1]; - int delay = 0; - try { - delay = Integer.parseInt(tasks[step][2]); - } catch (NumberFormatException e) { - logger.warn("Malformed task so stop the execution: " + this.toShortString()); - throw new OpenR66RunnerErrorException("Malformed task so stop the execution"); - } - AbstractTask task = TaskType.getTaskFromId(name, arg, delay, tempSession); - logger.debug(this.toLogRunStep() + " Task: " + task.getClass().getName()); - task.run(); - try { - task.getFutureCompletion().await(); - } catch (InterruptedException e) { - } - if (name.equals(TaskType.RESCHEDULE.name)) { - // Special case : must test if exec is OK since it must be the last - if (this.isRescheduledTransfer()) { - throw new OpenR66RunnerEndTasksException(); - } - } - return task.getFutureCompletion(); - } - - /** - * - * @return the future of the task run - * @throws OpenR66RunnerEndTasksException - * @throws OpenR66RunnerErrorException - * @throws OpenR66RunnerEndTasksException - */ - private R66Future runNext() throws OpenR66RunnerErrorException, - OpenR66RunnerEndTasksException { - logger.debug(this.toLogRunStep() + "\nSender: " + this.isSender + " " - + this.rule.printTasks(isSender, - TASKSTEP.values()[globalstep])); - if (rule == null) { - if (ruleId != null) { - try { - rule = new DbRule(dbSession, ruleId); - } catch (WaarpDatabaseException e) { - rule = null; - } - } - if (rule == null) { - throw new OpenR66RunnerErrorException("Rule Object not initialized"); - } - } - switch (TASKSTEP.values()[globalstep]) { - case PRETASK: - try { - if (this.isSender) { - return runNextTask(rule.spreTasksArray); - } else { - return runNextTask(rule.rpreTasksArray); - } - } catch (OpenR66RunnerEndTasksException e) { - if (status == ErrorCode.Running) { - infostatus = status = ErrorCode.PreProcessingOk; - } - throw e; - } - case POSTTASK: - try { - if (this.isSender) { - return runNextTask(rule.spostTasksArray); - } else { - return runNextTask(rule.rpostTasksArray); - } - } catch (OpenR66RunnerEndTasksException e) { - if (status == ErrorCode.Running) { - infostatus = status = ErrorCode.PostProcessingOk; - } - throw e; - } - case ERRORTASK: - try { - if (this.isSender) { - return runNextTask(rule.serrorTasksArray); - } else { - return runNextTask(rule.rerrorTasksArray); - } - } catch (OpenR66RunnerEndTasksException e) { - if (status == ErrorCode.Running) { - status = infostatus; - } - throw e; - } - default: - throw new OpenR66RunnerErrorException("Global Step unknown"); - } - } - - /** - * Run all task from current status (globalstep and step) - * - * @throws OpenR66RunnerErrorException - */ - public void run() throws OpenR66RunnerErrorException { - R66Future future; - logger.debug(this.toLogRunStep() + " Status: " + status + "\nSender: " + this.isSender - + " " + this.rule.printTasks(isSender, - TASKSTEP.values()[globalstep])); - if (status != ErrorCode.Running) { - throw new OpenR66RunnerErrorException( - "Current global STEP not ready to run: " + this.toString()); - } - while (true) { - logger.debug(this.toLogRunStep()); - try { - future = runNext(); - } catch (OpenR66RunnerEndTasksException e) { - step = 0; - allFields[Columns.STEP.ordinal()].setValue(step); - allFields[Columns.STEPSTATUS.ordinal()].setValue(status - .getCode()); - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - isSaved = false; - this.saveStatus(); - return; - } catch (OpenR66RunnerErrorException e) { - infostatus = ErrorCode.ExternalOp; - allFields[Columns.STEP.ordinal()].setValue(step); - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - isSaved = false; - this.setErrorExecutionStatus(infostatus); - this.saveStatus(); - throw new OpenR66RunnerErrorException("Runner is in error: " + - e.getMessage(), e); - } - if ((!future.isDone()) || future.isFailed()) { - R66Result result = future.getResult(); - if (result != null) { - infostatus = future.getResult().code; - } else { - infostatus = ErrorCode.ExternalOp; - } - this.setErrorExecutionStatus(infostatus); - allFields[Columns.STEP.ordinal()].setValue(step); - allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); - isSaved = false; - this.saveStatus(); - logger.info("Future is failed: " + infostatus.mesg); - if (future.getCause() != null) { - throw new OpenR66RunnerErrorException("Runner is failed: " + - future.getCause().getMessage(), future.getCause()); - } else { - throw new OpenR66RunnerErrorException("Runner is failed: " + - infostatus.mesg); - } - } - step++; - } - } - - /** - * Once the transfer is over, finalize the Runner by running the error or post operation - * according to the status. - * - * @param localChannelReference - * @param file - * @param finalValue - * @param status - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - */ - public void finalizeTransfer(LocalChannelReference localChannelReference, R66File file, - R66Result finalValue, boolean status) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { - logger.debug("status" + status + ":" + finalValue); - - if (session == null) { - this.session = localChannelReference.getSession(); - } - if (status) { - // First move the file - if (this.isSender()) { - // Nothing to do since it is the original file - this.setPostTask(); - } else { - int poststep = this.step; - this.setPostTask(); - this.saveStatus(); - if (!isRecvThrough()) { - if (this.globalstep == TASKSTEP.TRANSFERTASK.ordinal() || - (this.globalstep == TASKSTEP.POSTTASK.ordinal() && - poststep == 0)) { - // Result file moves - String finalpath = R66Dir.getFinalUniqueFilename(file); - logger.debug("Will move file {}", finalpath); - try { - file.renameTo(this.getRule().setRecvPath(finalpath)); - } catch (OpenR66ProtocolSystemException e) { - R66Result result = new R66Result(e, session, false, - ErrorCode.FinalOp, this); - result.file = file; - result.runner = this; - if (localChannelReference != null) { - localChannelReference.invalidateRequest(result); - } - throw e; - } catch (CommandAbstractException e) { - R66Result result = new R66Result( - new OpenR66RunnerErrorException(e), session, - false, ErrorCode.FinalOp, this); - result.file = file; - result.runner = this; - if (localChannelReference != null) { - localChannelReference.invalidateRequest(result); - } - throw (OpenR66RunnerErrorException) result.exception; - } - logger.debug("File finally moved: {}", file); - try { - this.setFilename(file.getFile()); - } catch (CommandAbstractException e) { - } - // check if possible once more the hash - String hash = localChannelReference.getHashComputeDuringTransfer(); - if (hash != null) { - // we can compute it once more - try { - if (! FilesystemBasedDigest.getHex(FilesystemBasedDigest.getHash(file.getTrueFile(), true, Configuration.configuration.digest)).equals(hash)) { - // KO - R66Result result = new R66Result( - new OpenR66RunnerErrorException("Bad final digest on receive operation"), session, - false, ErrorCode.FinalOp, this); - result.file = file; - result.runner = this; - if (localChannelReference != null) { - localChannelReference.invalidateRequest(result); - } - throw (OpenR66RunnerErrorException) result.exception; - } - } catch (IOException e) { - R66Result result = new R66Result( - new OpenR66RunnerErrorException("Bad final digest on receive operation", e), session, - false, ErrorCode.FinalOp, this); - result.file = file; - result.runner = this; - if (localChannelReference != null) { - localChannelReference.invalidateRequest(result); - } - throw (OpenR66RunnerErrorException) result.exception; - } - } - } - } - } - this.saveStatus(); - if (isRecvThrough() || isSendThrough()) { - // File could not exist - } else if (this.step == 0) { - // File must exist - try { - if (!file.exists()) { - // error - R66Result error = - new R66Result(this.session, finalValue.isAnswered, - ErrorCode.FileNotFound, this); - this.setErrorExecutionStatus(ErrorCode.FileNotFound); - errorTransfer(error, file, localChannelReference); - return; - } - } catch (CommandAbstractException e) { - // error - R66Result error = - new R66Result(this.session, finalValue.isAnswered, - ErrorCode.FileNotFound, this); - this.setErrorExecutionStatus(ErrorCode.FileNotFound); - errorTransfer(error, file, localChannelReference); - return; - } - } - try { - this.run(); - } catch (OpenR66RunnerErrorException e1) { - R66Result result = new R66Result(e1, this.session, false, - ErrorCode.ExternalOp, this); - result.file = file; - result.runner = this; - this.changeUpdatedInfo(UpdatedInfo.INERROR); - this.saveStatus(); - errorTransfer(result, file, localChannelReference); - if (localChannelReference != null) { - localChannelReference.invalidateRequest(result); - } - throw e1; - } - this.saveStatus(); - /* - * Done later on after EndRequest this.setAllDone(); this.saveStatus(); - */ - logger.info("Transfer done on {} at RANK {}", file != null ? file : "no file", rank); - if (localChannelReference != null) { - localChannelReference.validateEndTransfer(finalValue); - } - } else { - logger.debug("ContinueTransfer: " + continueTransfer + " status:" + status + ":" - + finalValue); - /* - * if (!continueTransfer) { // already setup return; } - */ - errorTransfer(finalValue, file, localChannelReference); - } - } - - /** - * Finalize a transfer in error - * - * @param finalValue - * @param file - * @param localChannelReference - * @throws OpenR66RunnerErrorException - */ - private void errorTransfer(R66Result finalValue, R66File file, - LocalChannelReference localChannelReference) throws OpenR66RunnerErrorException { - // error or not ? - ErrorCode runnerStatus = this.getErrorInfo(); - if (finalValue.exception != null) { - logger.error("Transfer KO on " + file + " due to " + finalValue.exception.getMessage()); - } else { - logger.error("Transfer KO on " + file + " due to " + finalValue.toString()); - } - if (runnerStatus == ErrorCode.CanceledTransfer) { - // delete file, reset runner - this.setRankAtStartup(0); - this.deleteTempFile(); - this.changeUpdatedInfo(UpdatedInfo.INERROR); - this.saveStatus(); - finalValue.isAnswered = true; - } else if (runnerStatus == ErrorCode.StoppedTransfer) { - // just save runner and stop - this.changeUpdatedInfo(UpdatedInfo.INERROR); - this.saveStatus(); - finalValue.isAnswered = true; - } else if (runnerStatus == ErrorCode.Shutdown) { - // just save runner and stop - this.changeUpdatedInfo(UpdatedInfo.INERROR); - this.saveStatus(); - finalValue.isAnswered = true; - } - logger.debug("status: " + status + " wasNotError:" - + (this.globalstep != TASKSTEP.ERRORTASK.ordinal()) + - ":" + finalValue); - if (this.globalstep != TASKSTEP.ERRORTASK.ordinal()) { - // errorstep was not already executed - // real error - localChannelReference.setErrorMessage(finalValue.getMessage(), finalValue.code); - // First send error mesg - if (!finalValue.isAnswered) { - localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket errorPacket = new ErrorPacket(finalValue - .getMessage(), - finalValue.code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - errorPacket, true); - finalValue.isAnswered = true; - } catch (OpenR66ProtocolPacketException e1) { - // should not be - } - } - // now run error task - this.setErrorTask(localChannelReference); - this.saveStatus(); - try { - this.run(); - } catch (OpenR66RunnerErrorException e1) { - this.changeUpdatedInfo(UpdatedInfo.INERROR); - this.setErrorExecutionStatus(runnerStatus); - this.saveStatus(); - if (localChannelReference != null) { - localChannelReference.invalidateRequest(finalValue); - } - throw e1; - } - } - if (! this.isRescheduledTransfer()) { - this.changeUpdatedInfo(UpdatedInfo.INERROR); - } - if (RequestPacket.isThroughMode(this.getMode())) { - this.setErrorExecutionStatus(runnerStatus); - this.saveStatus(); - if (localChannelReference != null) { - localChannelReference.invalidateRequest(finalValue); - } - return; - } - // re set the original status - this.setErrorExecutionStatus(runnerStatus); - this.saveStatus(); - if (localChannelReference != null) { - localChannelReference.invalidateRequest(finalValue); - } - } - - /** - * Increment the rank of the transfer - * - * @throws OpenR66ProtocolPacketException - */ - public void incrementRank() throws OpenR66ProtocolPacketException { - rank++; - allFields[Columns.RANK.ordinal()].setValue(rank); - isSaved = false; - if (rank % 10 == 0) { - // Save each 10 blocks - try { - update(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot update Runner: {}", e.getMessage()); - } - } - } - - /** - * This method is to be called each time an operation is happening on Runner - * - * @throws OpenR66RunnerErrorException - */ - public void saveStatus() throws OpenR66RunnerErrorException { - try { - update(); - } catch (WaarpDatabaseException e) { - throw new OpenR66RunnerErrorException(e); - } - } - - /** - * This method is to be called each time an operation is happening on Runner and it is forced - * (for SelfRequest handling) - * @return True if saved - * @throws OpenR66RunnerErrorException - */ - public boolean forceSaveStatus() { - boolean isSender = isSender(); - setSenderForUpdate(); - boolean status = true; - try { - saveStatus(); - } catch (OpenR66RunnerErrorException e) { - status = false; - } - setSender(isSender); - return status; - } - - /** - * Clear the runner - */ - public void clear() { - - } - - /** - * Delete the temporary empty file (retrieved file at rank 0) - */ - public void deleteTempFile() { - if ((!isSender()) && getRank() == 0) { - try { - if (session != null) { - R66File file = session.getFile(); - if (file != null) { - file.delete(); - } - } - } catch (CommandAbstractException e1) { - logger.warn("Cannot delete temporary empty file", e1); - } - } - } - - @Override - public String toString() { - return "Run: " + (rule != null ? rule.toString() : ruleId) + " on " + - filename + " STEP: " + TASKSTEP.values()[globalstep] + "(" + - TASKSTEP.values()[globallaststep] + "):" + step + ":" + - status.mesg + " Transfer Rank: " + rank + " Blocksize: " + blocksize + - " SpecialId: " + - specialId + " isSender: " + isSender + " isMoved: " + - isFileMoved + " Mode: " + TRANSFERMODE.values()[mode] + - " Requester: " + requesterHostId + " Requested: " + - requestedHostId + " Start: " + start + " Stop: " + stop + - " Internal: " + UpdatedInfo.values()[updatedInfo].name() + - ":" + infostatus.mesg + " OriginalSize: " + originalSize + - " Fileinfo: " + fileInformation; - } - - public String toLogRunStep() { - return "Run: " + ruleId + " on " + - filename + " STEP: " + TASKSTEP.values()[globalstep] + "(" + - TASKSTEP.values()[globallaststep] + "):" + step + ":" + - status.mesg; - } - - public String toShortNoHtmlString(String newline) { - return "Run: " + ruleId + " on " + - filename + newline + " STEP: " + TASKSTEP.values()[globalstep] + "(" + - TASKSTEP.values()[globallaststep] + "):" + step + ":" + - status.mesg + newline + " Transfer Rank: " + rank + " Blocksize: " + blocksize + - " SpecialId: " + - specialId + " isSender: " + isSender + " isMoved: " + - isFileMoved + " Mode: " + TRANSFERMODE.values()[mode] + - newline + " Requester: " + requesterHostId + " Requested: " + - requestedHostId + " Start: " + start + " Stop: " + stop + - newline + " Internal: " + UpdatedInfo.values()[updatedInfo].name() + - ":" + infostatus.mesg + " OriginalSize: " + originalSize + - newline + " Fileinfo: " + fileInformation; - } - - public String toShortString() { - return "" + ruleId + "" + specialId + "" + - filename + "\n " + TASKSTEP.values()[globalstep] + - "(" + TASKSTEP.values()[globallaststep] + "):" + step + ":" + - status.mesg + "" + rank + "" + blocksize + - "\n " + - isSender + "" + isFileMoved + "" + - TRANSFERMODE.values()[mode] + "\n " + - requesterHostId + "" + requestedHostId + - "\n " + start + "" + stop + - "\n " + UpdatedInfo.values()[updatedInfo].name() - + " : " + infostatus.mesg + "" + originalSize +"\n " + - fileInformation + ""; - } - - /** - * - * @return the header for a table of runners in Html format - */ - public static String headerHtml() { - return "
"; - } - - /** - * @param session - * @return The associated freespace of the current directory - */ - public long freespace(R66Session session) { - long freespace = -1; - DbRule rule = null; - try { - rule = (this.rule != null) ? this.rule : new DbRule(this.dbSession, - this.ruleId); - } catch (WaarpDatabaseException e) { - } - if (this.rule == null) { - this.rule = rule; - } - if (rule != null) { - if (!this.isSender) { - try { - String sdir; - if (this.globallaststep == TASKSTEP.ALLDONETASK.ordinal()) { - // all finished - sdir = rule.recvPath; - } else if (this.globallaststep == TASKSTEP.POSTTASK - .ordinal()) { - // Post task - sdir = rule.recvPath; - } else { - // are we in sending or receive - sdir = rule.workPath; - } - R66Dir dir; - if (session.dirsFromSession.containsKey(sdir)) { - dir = session.dirsFromSession.get(sdir); - } else { - dir = new R66Dir(session); - dir.changeDirectory(sdir); - session.dirsFromSession.put(sdir, dir); - } - freespace = dir.getFreeSpace() / 0x100000L; - } catch (CommandAbstractException e) { - logger.warn("Error while freespace compute {}", e.getMessage(), e); - } - } - } - return freespace; - } - - private String bandwidth() { - double drank = (rank <= 0 ? 1 : rank); - double dblocksize = blocksize * 8; - double size = drank * dblocksize; - double time = (stop.getTime() + 1 - start.getTime()); - double result = size / time / ((double) 0x100000L) * ((double) 1000); - return String.format("%,.2f", result); - } - - private String getHtmlColor() { - String color; - switch (TASKSTEP.values()[globalstep]) { - case NOTASK: - color = "Orange"; - break; - case PRETASK: - color = "Yellow"; - break; - case TRANSFERTASK: - color = "LightGreen"; - break; - case POSTTASK: - color = "Turquoise"; - break; - case ERRORTASK: - color = "Red"; - break; - case ALLDONETASK: - color = "Cyan"; - break; - default: - color = ""; - } - return color; - } - - private String getInfoHtmlColor() { - String color; - switch (UpdatedInfo.values()[updatedInfo]) { - case DONE: - color = "Cyan"; - break; - case INERROR: - color = "Red"; - break; - case INTERRUPTED: - color = "Orange"; - break; - case NOTUPDATED: - color = "Yellow"; - break; - case RUNNING: - color = "LightGreen"; - break; - case TOSUBMIT: - color = "Turquoise"; - break; - case UNKNOWN: - color = "Turquoise"; - break; - default: - color = ""; - } - return color; - } - - /** - * @param session - * @param running - * special info - * @return the runner in Html format compatible with the header from headerHtml method - */ - public String toHtml(R66Session session, String running) { - long freespace = freespace(session); - String color = getHtmlColor(); - String updcolor = getInfoHtmlColor(); - return "" + ""; - } - - /** - * @param session - * @param body - * @param running - * special info - * @return the runner in Html format specified by body by replacing all instance of fields - */ - public String toSpecializedHtml(R66Session session, String body, String running) { - long freespace = freespace(session); - StringBuilder builder = new StringBuilder(body); - WaarpStringUtils.replaceAll(builder, "XXXSpecIdXXX", Long.toString(specialId)); - WaarpStringUtils.replace(builder, "XXXRulXXX", (rule != null ? rule.toShortString() - : ruleId)); - WaarpStringUtils.replace(builder, "XXXFileXXX", filename); - WaarpStringUtils.replace(builder, "XXXInfoXXX", fileInformation); - WaarpStringUtils.replace(builder, "XXXStepXXX", TASKSTEP.values()[globalstep] + " (" + - TASKSTEP.values()[globallaststep] + ")"); - WaarpStringUtils.replace(builder, "XXXCOLXXX", getHtmlColor()); - WaarpStringUtils.replace(builder, "XXXActXXX", Integer.toString(step)); - WaarpStringUtils.replace(builder, "XXXStatXXX", status.mesg); - WaarpStringUtils.replace(builder, "XXXRunningXXX", running); - WaarpStringUtils.replace(builder, "XXXInternXXX", UpdatedInfo.values()[updatedInfo].name() + - " : " + infostatus.mesg); - WaarpStringUtils.replace(builder, "XXXUPDCOLXXX", getInfoHtmlColor()); - WaarpStringUtils.replace(builder, "XXXBloXXX", Integer.toString(rank)); - WaarpStringUtils.replace(builder, "XXXisSendXXX", Boolean.toString(isSender)); - WaarpStringUtils.replace(builder, "XXXisMovXXX", Boolean.toString(isFileMoved)); - WaarpStringUtils.replace(builder, "XXXModXXX", TRANSFERMODE.values()[mode].toString()); - WaarpStringUtils.replaceAll(builder, "XXXReqrXXX", requesterHostId); - WaarpStringUtils.replaceAll(builder, "XXXReqdXXX", requestedHostId); - WaarpStringUtils.replace(builder, "XXXStarXXX", start.toString()); - WaarpStringUtils.replace(builder, "XXXStopXXX", stop.toString()); - WaarpStringUtils.replace(builder, "XXXBandXXX", bandwidth()); - WaarpStringUtils.replace(builder, "XXXFreeXXX", Long.toString(freespace)); - return builder.toString(); - } - - /** - * - * @return True if the current host is the requested host (to prevent request to itself) - */ - public boolean isSelfRequested() { - if (this.requestedHostId.equals(Configuration.configuration.HOST_ID) || - this.requestedHostId.equals(Configuration.configuration.HOST_SSLID)) { - // check if not calling itself - return (! this.requesterHostId.equals(Configuration.configuration.HOST_ID) && - ! this.requesterHostId.equals(Configuration.configuration.HOST_SSLID)); - } - return false; - } - - - /** - * - * @return True if the request is a self request (same host on both side) - */ - public boolean isSelfRequest() { - return ((this.requestedHostId.equals(Configuration.configuration.HOST_ID) || - this.requestedHostId.equals(Configuration.configuration.HOST_SSLID)) && - (this.requesterHostId.equals(Configuration.configuration.HOST_ID) || - this.requesterHostId.equals(Configuration.configuration.HOST_SSLID))); - } - - /** - * - * @return the requested HostId - */ - public String getRequested() { - return this.requestedHostId; - } - - /** - * - * @return the requester HostId - */ - public String getRequester() { - return this.requesterHostId; - } - - /** - * @return the start - */ - public Timestamp getStart() { - return start; - } - - /** - * @param start - * new Start time to apply when reschedule - */ - public void setStart(Timestamp start) { - this.start = start; - allFields[Columns.STARTTRANS.ordinal()].setValue(this.start); - } - - /** - * @return the stop - */ - public Timestamp getStop() { - return stop; - } - - /** - * - * @return the associated request - */ - public RequestPacket getRequest() { - return new RequestPacket(ruleId, mode, originalFilename, blocksize, - rank, specialId, fileInformation, originalSize); - } - - /** - * Used internally - * - * @return a Key representing the primary key as a unique string - */ - public String getKey() { - return requestedHostId + " " + requesterHostId + " " + specialId; - } - - /** - * Construct a new Element with value - * - * @param name - * @param value - * @return the new Element - */ - private static Element newElement(String name, String value) { - Element node = new DefaultElement(name); - if (value != null) { - node.addText(value); - } - return node; - } - - /** - * Need to call 'setToArray' before - * - * @param runner - * @return The Element representing the given Runner - * @throws WaarpDatabaseSqlException - */ - private static Element getElementFromRunner(DbTaskRunner runner) - throws WaarpDatabaseSqlException { - Element root = new DefaultElement(XMLRUNNER); - for (DbValue value : runner.allFields) { - if (value.column.equals(Columns.UPDATEDINFO.name())) { - continue; - } - root.add(newElement(value.column.toLowerCase(), value - .getValueAsString())); - } - return root; - } - - /** - * Set the given runner from the root element of the runner itself (XMLRUNNER but not - * XMLRUNNERS). Need to call 'setFromArray' after. - * - * @param runner - * @param root - * @throws WaarpDatabaseSqlException - */ - private static void setRunnerFromElement(DbTaskRunner runner, Element root) - throws WaarpDatabaseSqlException { - for (DbValue value : runner.allFields) { - if (value.column.equals(Columns.UPDATEDINFO.name())) { - continue; - } - Element elt = (Element) root.selectSingleNode(value.column.toLowerCase()); - if (elt != null) { - String newValue = elt.getText(); - value.setValueFromString(newValue); - } - } - } - - /** - * Write the selected TaskRunners from PrepareStatement to a XMLWriter - * - * @param preparedStatement - * ready to be executed - * @param xmlWriter - * @return the NbAndSpecialId for the number of transfer and higher rank found - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - * @throws OpenR66ProtocolBusinessException - */ - public static NbAndSpecialId writeXML(DbPreparedStatement preparedStatement, XMLWriter xmlWriter) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, - OpenR66ProtocolBusinessException { - Element root = new DefaultElement(XMLRUNNERS); - NbAndSpecialId nbAndSpecialId = new NbAndSpecialId(); - try { - xmlWriter.writeOpen(root); - Element node; - while (preparedStatement.getNext()) { - DbTaskRunner runner = DbTaskRunner - .getFromStatement(preparedStatement); - if (nbAndSpecialId.higherSpecialId < runner.specialId) { - nbAndSpecialId.higherSpecialId = runner.specialId; - } - node = DbTaskRunner.getElementFromRunner(runner); - xmlWriter.write(node); - xmlWriter.flush(); - nbAndSpecialId.nb++; - } - xmlWriter.writeClose(root); - } catch (IOException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Cannot write file: " + e.getMessage()); - } - return nbAndSpecialId; - } - - /** - * Write selected TaskRunners to an XML file using an XMLWriter - * - * @param preparedStatement - * @param filename - * @return the NbAndSpecialId for the number of transfer and higher rank found - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - * @throws OpenR66ProtocolBusinessException - */ - public static NbAndSpecialId writeXMLWriter(DbPreparedStatement preparedStatement, - String filename) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, - OpenR66ProtocolBusinessException { - NbAndSpecialId nbAndSpecialId = null; - OutputStream outputStream = null; - XMLWriter xmlWriter = null; - try { - outputStream = new FileOutputStream(filename); - OutputFormat format = OutputFormat.createPrettyPrint(); - format.setEncoding("ISO-8859-1"); - xmlWriter = new XMLWriter(outputStream, format); - preparedStatement.executeQuery(); - nbAndSpecialId = writeXML(preparedStatement, xmlWriter); - } catch (FileNotFoundException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("File not found"); - } catch (UnsupportedEncodingException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } finally { - if (xmlWriter != null) { - try { - xmlWriter.endDocument(); - xmlWriter.flush(); - xmlWriter.close(); - } catch (SAXException e) { - try { - outputStream.close(); - } catch (IOException e2) { - } - File file = new File(filename); - file.delete(); - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } catch (IOException e) { - try { - outputStream.close(); - } catch (IOException e2) { - } - File file = new File(filename); - file.delete(); - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } - } else if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException e) { - } - File file = new File(filename); - file.delete(); - } - } - return nbAndSpecialId; - } - - /** - * Write all TaskRunners to an XML file using an XMLWriter - * - * @param filename - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - * @throws OpenR66ProtocolBusinessException - */ - public static void writeXMLWriter(String filename) - throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, - OpenR66ProtocolBusinessException { - String request = "SELECT " + DbTaskRunner.selectAllFields + " FROM " + - DbTaskRunner.table + " WHERE " + getLimitWhereCondition(); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = new DbPreparedStatement( - DbConstant.admin.session); - preparedStatement.createPrepareStatement(request); - writeXMLWriter(preparedStatement, filename); - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - } - - /** - * - * @return the backend XML filename for the current TaskRunner in NoDb Client mode - */ - public String backendXmlFilename() { - return Configuration.configuration.baseDirectory + - Configuration.configuration.archivePath + R66Dir.SEPARATOR + - this.requesterHostId + "_" + this.requestedHostId + "_" + this.ruleId + "_" - + this.specialId - + XMLEXTENSION; - } - - /** - * Method to write the current DbTaskRunner for NoDb client instead of updating DB. 'setToArray' - * must be called priorly to be able to store the values. - * - * @throws OpenR66ProtocolBusinessException - */ - public void writeXmlWorkNoDb() throws OpenR66ProtocolBusinessException { - String filename = backendXmlFilename(); - OutputStream outputStream = null; - XMLWriter xmlWriter = null; - try { - outputStream = new FileOutputStream(filename); - OutputFormat format = OutputFormat.createPrettyPrint(); - format.setEncoding("ISO-8859-1"); - xmlWriter = new XMLWriter(outputStream, format); - Element root = new DefaultElement(XMLRUNNERS); - try { - xmlWriter.writeOpen(root); - Element node; - node = DbTaskRunner.getElementFromRunner(this); - xmlWriter.write(node); - xmlWriter.flush(); - xmlWriter.writeClose(root); - } catch (IOException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Cannot write file: " + e.getMessage()); - } catch (WaarpDatabaseSqlException e) { - logger.error("Cannot write Data", e); - throw new OpenR66ProtocolBusinessException("Cannot write Data: " + e.getMessage()); - } - } catch (FileNotFoundException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("File not found"); - } catch (UnsupportedEncodingException e) { - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } finally { - if (xmlWriter != null) { - try { - xmlWriter.endDocument(); - xmlWriter.flush(); - xmlWriter.close(); - } catch (SAXException e) { - try { - outputStream.close(); - } catch (IOException e2) { - } - File file = new File(filename); - file.delete(); - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } catch (IOException e) { - try { - outputStream.close(); - } catch (IOException e2) { - } - File file = new File(filename); - file.delete(); - logger.error("Cannot write XML file", e); - throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); - } - } else if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException e) { - } - File file = new File(filename); - file.delete(); - } - } - } - - /** - * Method to load a previous existing DbTaskRunner for NoDb client from File instead of from DB. - * 'setFromArray' must be called after. - * - * @throws OpenR66ProtocolBusinessException - */ - public void loadXmlWorkNoDb() throws OpenR66ProtocolBusinessException { - String filename = backendXmlFilename(); - File file = new File(filename); - if (!file.canRead()) { - throw new OpenR66ProtocolBusinessException("Backend XML file cannot be read"); - } - SAXReader reader = new SAXReader(); - Document document; - try { - document = reader.read(file); - } catch (DocumentException e) { - throw new OpenR66ProtocolBusinessException( - "Backend XML file cannot be read as an XML file"); - } - Element root = (Element) document.selectSingleNode("/" + XMLRUNNERS + "/" + XMLRUNNER); - try { - setRunnerFromElement(this, root); - } catch (WaarpDatabaseSqlException e) { - throw new OpenR66ProtocolBusinessException( - "Backend XML file is not conform to the model"); - } - } - - /** - * - * @return True if the backend XML for NoDb client is available for this TaskRunner - */ - public boolean existXmlWorkNoDb() { - String filename = backendXmlFilename(); - File file = new File(filename); - return file.canRead(); - } - - /** - * Delete the backend XML file for the current TaskRunner for NoDb Client - */ - public void deleteXmlWorkNoDb() { - File file = new File(backendXmlFilename()); - file.delete(); - } - - /** - * Utility for "self request" mode only - * @param sender - */ - public void setSender(boolean sender) { - this.isSender = sender; - } - /** - * Helper - * @param request - * @return isSender according to request - */ - public static boolean getSenderByRequestPacket(RequestPacket request) { - if (request.isToValidate()) { - return RequestPacket.isRecvMode(request.getMode()); - } - return ! RequestPacket.isRecvMode(request.getMode()); - } - /** - * Utility for "self request" - * @param requestToValidate - */ - public void setSenderByRequestToValidate(boolean requestToValidate) { - this.isSender = RequestPacket.isRecvMode(mode); - if (! requestToValidate) { - this.isSender = ! this.isSender; - } - } - /** - * Utility to force "update" - */ - private void setSenderForUpdate() { - if (isSelfRequest()) { - isSender = RequestPacket.isRecvMode(mode); - } - } - - /** - * @return the originalSize - */ - public long getOriginalSize() { - return originalSize; - } - - /** - * @param originalSize the originalSize to set - */ - public void setOriginalSize(long originalSize) { - this.originalSize = originalSize; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.data; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.concurrent.atomic.AtomicLong; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.SAXReader; +import org.dom4j.io.XMLWriter; +import org.dom4j.tree.DefaultElement; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.data.DbValue; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.openr66.commander.CommanderNoDb; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.task.AbstractTask; +import org.waarp.openr66.context.task.TaskType; +import org.waarp.openr66.context.task.exception.OpenR66RunnerEndTasksException; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.model.DbModelFactory; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.NbAndSpecialId; +import org.waarp.openr66.protocol.utils.R66Future; +import org.xml.sax.SAXException; + +/** + * Task Runner from pre operation to transfer to post operation, except in case of error + * + * @author Frederic Bregier + * + */ +public class DbTaskRunner extends AbstractDbData { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(DbTaskRunner.class); + + public static enum Columns { + GLOBALSTEP, + GLOBALLASTSTEP, + STEP, + RANK, + STEPSTATUS, + RETRIEVEMODE, + FILENAME, + ISMOVED, + IDRULE, + BLOCKSZ, + ORIGINALNAME, + FILEINFO, + MODETRANS, + STARTTRANS, + STOPTRANS, + INFOSTATUS, + UPDATEDINFO, + OWNERREQ, + REQUESTER, + REQUESTED, + SPECIALID; + } + + public static final int[] dbTypes = { + Types.INTEGER, Types.INTEGER, Types.INTEGER, + Types.INTEGER, + Types.CHAR, Types.BIT, Types.VARCHAR, Types.BIT, Types.VARCHAR, + Types.INTEGER, Types.VARCHAR, Types.LONGVARCHAR, Types.INTEGER, + Types.TIMESTAMP, Types.TIMESTAMP, Types.CHAR, Types.INTEGER, + Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BIGINT }; + + public static final String table = " RUNNER "; + + public static final String fieldseq = "RUNSEQ"; + + public static final Columns[] indexes = { + Columns.STARTTRANS, Columns.OWNERREQ, + Columns.STEPSTATUS, Columns.UPDATEDINFO, + Columns.GLOBALSTEP, Columns.INFOSTATUS, Columns.SPECIALID + }; + + public static final String XMLRUNNERS = "taskrunners"; + public static final String XMLRUNNER = "runner"; + public static final String XMLEXTENSION = "_singlerunner.xml"; + + /** + * GlobalStep Value + */ + public static enum TASKSTEP { + NOTASK, PRETASK, TRANSFERTASK, POSTTASK, ALLDONETASK, ERRORTASK; + } + + // Values + private DbRule rule; + + private R66Session session; + + /** + * Last step + */ + private int globalstep = TASKSTEP.NOTASK.ordinal(); + /** + * Last global step (only changes in case of success) + */ + private int globallaststep = TASKSTEP.NOTASK.ordinal(); + /** + * Step in the current globalstep + */ + private int step = -1; + + private int rank = 0; + + /** + * Last step action status error code + */ + private ErrorCode status = ErrorCode.Unknown; + + private long specialId; + + private boolean isSender; + + private String filename; + + private boolean isFileMoved = false; + + private String ruleId; + + private int blocksize; + + private String originalFilename; + + private String fileInformation; + + private int mode; + + private String ownerRequest; + + private String requesterHostId; + + private String requestedHostId; + + private Timestamp start; + + private Timestamp stop; + + /** + * Info status error code + */ + private ErrorCode infostatus = ErrorCode.Unknown; + + /** + * The global status for running + */ + private int updatedInfo = UpdatedInfo.UNKNOWN.ordinal(); + + private volatile boolean continueTransfer = true; + + private volatile boolean rescheduledTransfer = false; + + private LocalChannelReference localChannelReference = null; + + private boolean isRecvThrough = false; + private boolean isSendThrough = false; + private long originalSize = -1; + + /** + * Special For DbTaskRunner + */ + public static final int NBPRKEY = 4; + // ALL TABLE SHOULD IMPLEMENT THIS + + protected static final String selectAllFields = Columns.GLOBALSTEP.name() + + "," + + Columns.GLOBALLASTSTEP.name() + + "," + Columns.STEP.name() + + "," + Columns.RANK.name() + "," + + Columns.STEPSTATUS.name() + + "," + + Columns.RETRIEVEMODE.name() + + "," + Columns.FILENAME.name() + + "," + + Columns.ISMOVED.name() + "," + + Columns.IDRULE.name() + "," + + Columns.BLOCKSZ.name() + "," + + Columns.ORIGINALNAME.name() + + "," + + Columns.FILEINFO.name() + "," + + Columns.MODETRANS.name() + + "," + + Columns.STARTTRANS.name() + "," + + Columns.STOPTRANS.name() + + "," + + Columns.INFOSTATUS.name() + "," + + Columns.UPDATEDINFO.name() + + "," + + Columns.OWNERREQ.name() + "," + + Columns.REQUESTER.name() + + "," + + Columns.REQUESTED.name() + "," + + Columns.SPECIALID.name(); + + protected static final String updateAllFields = Columns.GLOBALSTEP.name() + + "=?," + + Columns.GLOBALLASTSTEP.name() + + "=?," + + Columns.STEP.name() + "=?," + + Columns.RANK.name() + "=?," + + Columns.STEPSTATUS.name() + + "=?," + + Columns.RETRIEVEMODE.name() + + "=?," + Columns.FILENAME.name() + + "=?," + + Columns.ISMOVED.name() + + "=?," + Columns.IDRULE.name() + + "=?," + + Columns.BLOCKSZ.name() + + "=?," + + Columns.ORIGINALNAME.name() + + "=?," + + Columns.FILEINFO.name() + "=?," + + Columns.MODETRANS.name() + + "=?," + + Columns.STARTTRANS.name() + + "=?," + + Columns.STOPTRANS.name() + + "=?," + + Columns.INFOSTATUS.name() + + "=?," + + Columns.UPDATEDINFO.name() + + "=?"; + + protected static final String insertAllValues = " (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + + private static final AtomicLong clientNoDbSpecialIdLast = + new AtomicLong( + System.currentTimeMillis()); + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#initObject() + */ + @Override + protected void initObject() { + primaryKey = new DbValue[] { + new DbValue(ownerRequest, Columns.OWNERREQ.name()), + new DbValue(requesterHostId, Columns.REQUESTER.name()), + new DbValue(requestedHostId, Columns.REQUESTED.name()), + new DbValue(specialId, Columns.SPECIALID.name()) }; + otherFields = new DbValue[] { + // GLOBALSTEP, GLOBALLASTSTEP, STEP, RANK, STEPSTATUS, RETRIEVEMODE, + // FILENAME, ISMOVED, IDRULE, + // BLOCKSZ, ORIGINALNAME, FILEINFO, MODETRANS, + // STARTTRANS, STOPTRANS + // INFOSTATUS, UPDATEDINFO + new DbValue(globalstep, Columns.GLOBALSTEP.name()), + new DbValue(globallaststep, Columns.GLOBALLASTSTEP.name()), + new DbValue(step, Columns.STEP.name()), + new DbValue(rank, Columns.RANK.name()), + new DbValue(ErrorCode.Unknown.getCode(), Columns.STEPSTATUS.name()), // status.getCode() + new DbValue(isSender, Columns.RETRIEVEMODE.name()), + new DbValue(filename, Columns.FILENAME.name()), + new DbValue(isFileMoved, Columns.ISMOVED.name()), + new DbValue(ruleId, Columns.IDRULE.name()), + new DbValue(blocksize, Columns.BLOCKSZ.name()), + new DbValue(originalFilename, Columns.ORIGINALNAME.name()), + new DbValue(fileInformation, Columns.FILEINFO.name(), true), + new DbValue(mode, Columns.MODETRANS.name()), + new DbValue(start, Columns.STARTTRANS.name()), + new DbValue(stop, Columns.STOPTRANS.name()), + new DbValue(ErrorCode.Unknown.getCode(), Columns.INFOSTATUS.name()),// infostatus.getCode() + new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) }; + allFields = new DbValue[] { + otherFields[0], otherFields[1], otherFields[2], otherFields[3], + otherFields[4], otherFields[5], otherFields[6], otherFields[7], + otherFields[8], otherFields[9], otherFields[10], otherFields[11], + otherFields[12], otherFields[13], otherFields[14], otherFields[15], + otherFields[16], + primaryKey[0], primaryKey[1], primaryKey[2], primaryKey[3] }; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getSelectAllFields() + */ + @Override + protected String getSelectAllFields() { + return selectAllFields; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getTable() + */ + @Override + protected String getTable() { + return table; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getInsertAllValues() + */ + @Override + protected String getInsertAllValues() { + return insertAllValues; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.database.data.AbstractDbData#getUpdateAllFields() + */ + @Override + protected String getUpdateAllFields() { + return updateAllFields; + } + + @Override + protected void setToArray() { + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + allFields[Columns.STEP.ordinal()].setValue(step); + allFields[Columns.RANK.ordinal()].setValue(rank); + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + allFields[Columns.RETRIEVEMODE.ordinal()].setValue(isSender); + allFields[Columns.FILENAME.ordinal()].setValue(filename); + allFields[Columns.ISMOVED.ordinal()].setValue(isFileMoved); + allFields[Columns.IDRULE.ordinal()].setValue(ruleId); + allFields[Columns.BLOCKSZ.ordinal()].setValue(blocksize); + allFields[Columns.ORIGINALNAME.ordinal()].setValue(originalFilename); + allFields[Columns.FILEINFO.ordinal()].setValue(fileInformation); + allFields[Columns.MODETRANS.ordinal()].setValue(mode); + allFields[Columns.STARTTRANS.ordinal()].setValue(start); + stop = new Timestamp(System.currentTimeMillis()); + allFields[Columns.STOPTRANS.ordinal()].setValue(stop); + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + allFields[Columns.OWNERREQ.ordinal()].setValue(ownerRequest); + allFields[Columns.REQUESTER.ordinal()].setValue(requesterHostId); + allFields[Columns.REQUESTED.ordinal()].setValue(requestedHostId); + allFields[Columns.SPECIALID.ordinal()].setValue(specialId); + } + + @Override + protected void setFromArray() throws WaarpDatabaseSqlException { + globalstep = (Integer) allFields[Columns.GLOBALSTEP.ordinal()] + .getValue(); + globallaststep = (Integer) allFields[Columns.GLOBALLASTSTEP.ordinal()] + .getValue(); + step = (Integer) allFields[Columns.STEP.ordinal()].getValue(); + rank = (Integer) allFields[Columns.RANK.ordinal()].getValue(); + status = ErrorCode.getFromCode((String) allFields[Columns.STEPSTATUS + .ordinal()].getValue()); + isSender = (Boolean) allFields[Columns.RETRIEVEMODE.ordinal()] + .getValue(); + filename = (String) allFields[Columns.FILENAME.ordinal()].getValue(); + isFileMoved = (Boolean) allFields[Columns.ISMOVED.ordinal()].getValue(); + ruleId = (String) allFields[Columns.IDRULE.ordinal()].getValue(); + blocksize = (Integer) allFields[Columns.BLOCKSZ.ordinal()].getValue(); + originalFilename = (String) allFields[Columns.ORIGINALNAME.ordinal()] + .getValue(); + fileInformation = (String) allFields[Columns.FILEINFO.ordinal()] + .getValue(); + mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue(); + start = (Timestamp) allFields[Columns.STARTTRANS.ordinal()].getValue(); + stop = (Timestamp) allFields[Columns.STOPTRANS.ordinal()].getValue(); + infostatus = ErrorCode.getFromCode((String) allFields[Columns.INFOSTATUS + .ordinal()].getValue()); + updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()] + .getValue(); + ownerRequest = (String) allFields[Columns.OWNERREQ.ordinal()] + .getValue(); + requesterHostId = (String) allFields[Columns.REQUESTER.ordinal()] + .getValue(); + requestedHostId = (String) allFields[Columns.REQUESTED.ordinal()] + .getValue(); + specialId = (Long) allFields[Columns.SPECIALID.ordinal()].getValue(); + } + + /** + * + * @return The Where condition on Primary Key + */ + protected String getWherePrimaryKey() { + return primaryKey[0].column + " = ? AND " + + primaryKey[1].column + " = ? AND " + + primaryKey[2].column + " = ? AND " + + primaryKey[3].column + " = ? "; + } + + /** + * Set the primary Key as current value + */ + protected void setPrimaryKey() { + primaryKey[0].setValue(ownerRequest); + primaryKey[1].setValue(requesterHostId); + primaryKey[2].setValue(requestedHostId); + primaryKey[3].setValue(specialId); + } + + /** + * + * @param session + * @param requestPacket + * @return The associated requested Host Id + */ + public static String getRequested(R66Session session, + RequestPacket requestPacket) { + if (requestPacket.isToValidate()) { + // the request is initiated and sent by the requester + try { + return Configuration.configuration.getHostId(session.getAuth() + .isSsl()); + } catch (OpenR66ProtocolNoSslException e) { + return Configuration.configuration.HOST_ID; + } + } else { + // the request is sent after acknowledge by the requested + return session.getAuth().getUser(); + } + } + + /** + * + * @param session + * @param requestPacket + * @return The associated requester Host Id + */ + public static String getRequester(R66Session session, + RequestPacket requestPacket) { + if (requestPacket.isToValidate()) { + return session.getAuth().getUser(); + } else { + try { + return Configuration.configuration.getHostId(session.getAuth() + .isSsl()); + } catch (OpenR66ProtocolNoSslException e) { + return Configuration.configuration.HOST_ID; + } + } + } + + public void checkThroughMode() { + isRecvThrough = RequestPacket.isRecvThroughMode(this.mode, isSelfRequested()); + isSendThrough = RequestPacket.isSendThroughMode(this.mode, isSelfRequested()); + if (localChannelReference != null) { + if (localChannelReference.isRecvThroughMode()) { + isRecvThrough = true; + } + if (localChannelReference.isSendThroughMode()) { + isSendThrough = true; + } + if (isRecvThrough && !localChannelReference.isRecvThroughMode()) { + // Cannot be a RecvThrough + isRecvThrough = false; + } + if (isSendThrough && !localChannelReference.isSendThroughMode()) { + isSendThrough = false; + } + } + logger.debug("DbTask " + mode + " isRecvThrough: " + isRecvThrough + " isSendThrough: " + + isSendThrough); + } + + /** + * Constructor for submission (no transfer session), from database. It is created, so with a new + * specialId if necessary + * + * @param dbSession + * @param rule + * @param isSender + * @param requestPacket + * @param requested + * @param startTime + * @throws WaarpDatabaseException + */ + public DbTaskRunner(DbSession dbSession, DbRule rule, boolean isSender, + RequestPacket requestPacket, String requested, Timestamp startTime) + throws WaarpDatabaseException { + super(dbSession); + this.session = null; + this.rule = rule; + ruleId = this.rule.idRule; + rank = requestPacket.getRank(); + status = ErrorCode.Unknown; + infostatus = ErrorCode.Unknown; + this.isSender = isSender; + filename = requestPacket.getFilename(); + blocksize = requestPacket.getBlocksize(); + originalFilename = requestPacket.getFilename(); + fileInformation = requestPacket.getFileInformation(); + mode = requestPacket.getMode(); + originalSize = requestPacket.getOriginalSize(); + // itself but according to SSL + requesterHostId = Configuration.configuration.getHostId(dbSession, + requested); + // given one + requestedHostId = requested; + // always itself + ownerRequest = Configuration.configuration.HOST_ID; + + if (startTime != null) { + start = startTime; + } else { + start = new Timestamp(System.currentTimeMillis()); + } + setToArray(); + isSaved = false; + specialId = requestPacket.getSpecialId(); + if (this.rule == null) { + this.rule = new DbRule(this.dbSession, ruleId); + } + if (mode != rule.mode) { + if (RequestPacket.isMD5Mode(mode)) { + mode = RequestPacket.getModeMD5(rule.mode); + } else { + mode = rule.mode; + } + } + checkThroughMode(); + create(); + } + + /** + * Constructor from a request with a valid Special Id to be inserted into database + * + * @param dbSession + * @param session + * @param rule + * @param isSender + * @param requestPacket + * @throws WaarpDatabaseException + */ + public DbTaskRunner(DbSession dbSession, R66Session session, DbRule rule, + boolean isSender, RequestPacket requestPacket) + throws WaarpDatabaseException { + super(dbSession); + this.session = session; + this.localChannelReference = session.getLocalChannelReference(); + this.rule = rule; + ruleId = this.rule.idRule; + rank = requestPacket.getRank(); + status = ErrorCode.Unknown; + infostatus = ErrorCode.Unknown; + this.isSender = isSender; + filename = requestPacket.getFilename(); + blocksize = requestPacket.getBlocksize(); + originalFilename = requestPacket.getFilename(); + fileInformation = requestPacket.getFileInformation(); + mode = requestPacket.getMode(); + originalSize = requestPacket.getOriginalSize(); + requesterHostId = getRequester(session, requestPacket); + requestedHostId = getRequested(session, requestPacket); + // always itself + ownerRequest = Configuration.configuration.HOST_ID; + + start = new Timestamp(System.currentTimeMillis()); + setToArray(); + isSaved = false; + specialId = requestPacket.getSpecialId(); + if (this.rule == null) { + this.rule = new DbRule(this.dbSession, ruleId); + } + if (mode != rule.mode) { + if (RequestPacket.isMD5Mode(mode)) { + mode = RequestPacket.getModeMD5(rule.mode); + } else { + mode = rule.mode; + } + } + checkThroughMode(); + insert(); + } + + /** + * Constructor from a request with a valid Special Id so loaded from database + * + * @param dbSession + * @param session + * @param rule + * @param id + * @param requester + * @param requested + * @throws WaarpDatabaseException + */ + public DbTaskRunner(DbSession dbSession, R66Session session, DbRule rule, + long id, String requester, String requested) + throws WaarpDatabaseException { + super(dbSession); + this.session = session; + if (this.session != null) { + this.localChannelReference = session.getLocalChannelReference(); + } + this.rule = rule; + + specialId = id; + // retrieving a task should be made from the requester, but the caller + // is responsible of this + requestedHostId = requested; + requesterHostId = requester; + // always itself + ownerRequest = Configuration.configuration.HOST_ID; + + select(); + if (rule != null) { + if (!ruleId.equals(rule.idRule)) { + throw new WaarpDatabaseNoDataException( + "Rule does not correspond"); + } + } + } + + /** + * Constructor to initiate a request with a valid previous Special Id so loaded from database. + * + * This object cannot be used except to retrieve information. + * + * @param dbSession + * @param id + * @param requested + * @throws WaarpDatabaseException + */ + public DbTaskRunner(DbSession dbSession, long id, String requested) + throws WaarpDatabaseException { + super(dbSession); + + specialId = id; + // retrieving a task should be made from the requester, but the caller + // is responsible of this + requestedHostId = requested; + requesterHostId = Configuration.configuration.getHostId(dbSession, + requested); + // always itself + ownerRequest = Configuration.configuration.HOST_ID; + + select(); + } + + /** + * + * @return the condition to limit access to the row concerned by the Host + */ + private static String getLimitWhereCondition() { + return " " + Columns.OWNERREQ + " = '" + Configuration.configuration.HOST_ID + "' "; + } + + /** + * Create a Special Id for NoDb client + */ + private void createNoDbSpecialId() { + synchronized (clientNoDbSpecialIdLast) { + // New SpecialId is not possible with No Database Model + specialId = System.currentTimeMillis(); + if (clientNoDbSpecialIdLast.get() >= specialId) { + specialId = clientNoDbSpecialIdLast.incrementAndGet(); + } else { + clientNoDbSpecialIdLast.set(specialId); + } + return; + } + } + + /** + * Remove a Spcieal Id for NoDb Client + */ + private void removeNoDbSpecialId() { + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#delete() + */ + @Override + public void delete() throws WaarpDatabaseException { + if (dbSession == null) { + removeNoDbSpecialId(); + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + deleteXmlWorkNoDb(); + } + return; + } + super.delete(); + } + + private void addNoDb() { + DbTaskRunner runner = new DbTaskRunner(null); + this.setToArray(); + DbValue[] temp = runner.allFields; + runner.allFields = this.allFields; + try { + runner.setFromArray(); + } catch (WaarpDatabaseSqlException e) { + } + runner.allFields = temp; + runner.setToArray(); + runner.isRecvThrough = this.isRecvThrough; + runner.isSendThrough = this.isSendThrough; + runner.rule = this.rule; + runner.isSaved = true; + CommanderNoDb.todoList.add(runner); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#insert() + */ + @Override + public void insert() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + if (specialId == DbConstant.ILLEGALVALUE) { + // New SpecialId is not possible with No Database Model + createNoDbSpecialId(); + } + isSaved = true; + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + try { + setToArray(); + this.writeXmlWorkNoDb(); + } catch (OpenR66ProtocolBusinessException e) { + // Ignore + } + } + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + addNoDb(); + } + return; + } + // First need to find a new id if id is not ok + if (specialId == DbConstant.ILLEGALVALUE) { + specialId = DbModelFactory.dbModel.nextSequence(dbSession); + logger.debug("Try Insert create a new Id from sequence: " + + specialId); + setPrimaryKey(); + } + super.insert(); + } + + /** + * As insert but with the ability to change the SpecialId + * + * @throws WaarpDatabaseException + */ + public void create() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + if (specialId == DbConstant.ILLEGALVALUE) { + // New SpecialId is not possible with No Database Model + createNoDbSpecialId(); + } + isSaved = true; + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + try { + setToArray(); + this.writeXmlWorkNoDb(); + } catch (OpenR66ProtocolBusinessException e) { + // Ignore + } + } + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + addNoDb(); + } + return; + } + // First need to find a new id if id is not ok + if (specialId == DbConstant.ILLEGALVALUE) { + specialId = DbModelFactory.dbModel.nextSequence(dbSession); + logger.info("Try Insert create a new Id from sequence: " + + specialId); + setPrimaryKey(); + } + setToArray(); + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement("INSERT INTO " + table + + " (" + selectAllFields + ") VALUES " + insertAllValues); + setValues(preparedStatement, allFields); + try { + int count = preparedStatement.executeUpdate(); + if (count <= 0) { + throw new WaarpDatabaseNoDataException("No row found"); + } + } catch (WaarpDatabaseSqlException e) { + logger.error("Problem while inserting", e); + DbPreparedStatement find = new DbPreparedStatement(dbSession); + try { + find.createPrepareStatement("SELECT MAX(" + + primaryKey[3].column + ") FROM " + table + " WHERE " + + primaryKey[0].column + " = ? AND " + + primaryKey[1].column + " = ? AND " + + primaryKey[2].column + " = ? AND " + + primaryKey[3].column + " != ? "); + setPrimaryKey(); + setValues(find, primaryKey); + find.executeQuery(); + if (find.getNext()) { + long result; + try { + result = find.getResultSet().getLong(1); + } catch (SQLException e1) { + throw new WaarpDatabaseSqlException(e1); + } + specialId = result + 1; + DbModelFactory.dbModel.resetSequence(dbSession, specialId + 1); + setToArray(); + preparedStatement.close(); + setValues(preparedStatement, allFields); + int count = preparedStatement.executeUpdate(); + if (count <= 0) { + throw new WaarpDatabaseNoDataException("No row found"); + } + } else { + throw new WaarpDatabaseNoDataException("No row found"); + } + } finally { + find.realClose(); + } + } + isSaved = true; + } finally { + preparedStatement.realClose(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#exist() + */ + @Override + public boolean exist() throws WaarpDatabaseException { + if (dbSession == null) { + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + return existXmlWorkNoDb(); + } + return false; + } + return super.exist(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#select() + */ + @Override + public void select() throws WaarpDatabaseException { + if (dbSession == null) { + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + try { + this.loadXmlWorkNoDb(); + setFromArray(); + } catch (OpenR66ProtocolBusinessException e) { + throw new WaarpDatabaseNoDataException("No file found"); + } + if (rule == null) { + rule = new DbRule(this.dbSession, ruleId); + } + isSaved = true; + checkThroughMode(); + return; + } + throw new WaarpDatabaseNoDataException("No row found"); + } + super.select(); + if (rule == null) { + rule = new DbRule(this.dbSession, ruleId); + } + checkThroughMode(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#update() + */ + @Override + public void update() throws WaarpDatabaseException { + if (isSaved) { + return; + } + if (dbSession == null) { + isSaved = true; + if (Configuration.configuration.saveTaskRunnerWithNoDb) { + try { + setToArray(); + this.writeXmlWorkNoDb(); + } catch (OpenR66ProtocolBusinessException e) { + // Ignore + } + } + if (this.updatedInfo == UpdatedInfo.TOSUBMIT.ordinal()) { + addNoDb(); + } + return; + } + // SNMP notification + if (updatedInfo == UpdatedInfo.INERROR.ordinal() || + updatedInfo == UpdatedInfo.INTERRUPTED.ordinal()) { + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyInfoTask( + "Task is " + UpdatedInfo.values()[updatedInfo].name(), this); + } + } else { + if (globalstep != TASKSTEP.TRANSFERTASK.ordinal() || + (globalstep == TASKSTEP.TRANSFERTASK.ordinal() && + (rank % 100 == 0))) { + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyTask( + "Task is currently " + UpdatedInfo.values()[updatedInfo].name(), this); + } + } + } + // FIX SelfRequest + if (isSelfRequest()) { + if (RequestPacket.isCompatibleMode(mode, + isSender ? RequestPacket.TRANSFERMODE.RECVMODE.ordinal() : + RequestPacket.TRANSFERMODE.SENDMODE.ordinal())) { + super.update(); + } + } else { + super.update(); + } + } + + /** + * Partial set from another runner (infostatus, rank, status, step, stop, filename, + * globallastep, globalstep, isFileMoved) + * + * @param runner + */ + public void setFrom(DbTaskRunner runner) { + if (runner != null) { + this.infostatus = runner.infostatus; + this.rank = runner.rank; + this.status = runner.status; + this.step = runner.step; + this.stop = runner.stop; + this.filename = runner.filename; + this.globallaststep = runner.globallaststep; + this.globalstep = runner.globalstep; + this.isFileMoved = runner.isFileMoved; + } + } + + public boolean isRecvThrough() { + return isRecvThrough; + } + + public boolean isSendThrough() { + return isSendThrough; + } + + /** + * Private constructor for Commander only + * + * @param session + */ + private DbTaskRunner(DbSession dBsession) { + super(dBsession); + session = null; + rule = null; + } + + /** + * Set a localChannelReference + * + * @param localChannelReference + */ + public void setLocalChannelReference(LocalChannelReference localChannelReference) { + this.localChannelReference = localChannelReference; + } + + /** + * @return the localChannelReference + */ + public LocalChannelReference getLocalChannelReference() { + return localChannelReference; + } + + /** + * For instance from Commander when getting updated information + * + * @param preparedStatement + * @return the next updated DbTaskRunner + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbTaskRunner getFromStatement( + DbPreparedStatement preparedStatement) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbTaskRunner dbTaskRunner = new DbTaskRunner(preparedStatement + .getDbSession()); + dbTaskRunner.getValues(preparedStatement, dbTaskRunner.allFields); + dbTaskRunner.setFromArray(); + if (dbTaskRunner.rule == null) { + try { + dbTaskRunner.rule = new DbRule(dbTaskRunner.dbSession, dbTaskRunner.ruleId); + } catch (WaarpDatabaseException e) { + throw new WaarpDatabaseSqlException(e); + } + } + dbTaskRunner.checkThroughMode(); + dbTaskRunner.isSaved = true; + return dbTaskRunner; + } + + /** + * @param session + * @param status + * @param limit + * limit the number of rows + * @return the DbPreparedStatement for getting Runner according to status ordered by start + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getStatusPrepareStatement( + DbSession session, ErrorCode status, int limit) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields + " FROM " + table; + if (status != null) { + request += " WHERE " + Columns.STEPSTATUS.name() + " = '" + + status.getCode() + "' AND " + getLimitWhereCondition(); + } else { + request += " WHERE " + getLimitWhereCondition(); + } + request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; + request = DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); + return new DbPreparedStatement(session, request); + } + + /** + * @param session + * @param globalstep + * @param limit + * limit the number of rows + * @return the DbPreparedStatement for getting Runner according to globalstep ordered by start + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getStepPrepareStatement(DbSession session, + TASKSTEP globalstep, int limit) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields + " FROM " + table; + if (globalstep != null) { + request += " WHERE (" + Columns.GLOBALSTEP.name() + " = " + + globalstep.ordinal(); + if (globalstep == TASKSTEP.ERRORTASK) { + request += " OR " + Columns.UPDATEDINFO.name() + " = " + + UpdatedInfo.INERROR.ordinal() + ") AND "; + } else { + request += ") AND "; + } + request += getLimitWhereCondition(); + } else { + request += " WHERE " + getLimitWhereCondition(); + } + request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; + request = DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); + return new DbPreparedStatement(session, request); + } + + /** + * + * @param preparedStatement + * @param srcrequest + * @param limit + * @param orderby + * @param startid + * @param stopid + * @param start + * @param stop + * @param rule + * @param req + * @param pending + * @param transfer + * @param error + * @param done + * @param all + * @return The DbPreparedStatement already prepared according to select or delete command + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + private static DbPreparedStatement getFilterCondition( + DbPreparedStatement preparedStatement, String srcrequest, int limit, + String orderby, String startid, String stopid, Timestamp start, Timestamp stop, + String rule, + String req, boolean pending, boolean transfer, boolean error, + boolean done, boolean all) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + String request = srcrequest; + if (startid == null && stopid == null && + start == null && stop == null && rule == null && req == null && all) { + // finish + if (limit > 0) { + request = DbModelFactory.dbModel.limitRequest(selectAllFields, + request + orderby, limit); + } else { + request = request + orderby; + } + preparedStatement.createPrepareStatement(request); + return preparedStatement; + } + request += " WHERE "; + StringBuilder scondition = new StringBuilder(); + boolean hasCondition = false; + if (start != null & stop != null) { + scondition.append(Columns.STARTTRANS.name()); + scondition.append(" >= ? AND "); + scondition.append(Columns.STARTTRANS.name()); + scondition.append(" <= ? "); + hasCondition = true; + } else if (start != null) { + scondition.append(Columns.STARTTRANS.name()); + scondition.append(" >= ? "); + hasCondition = true; + } else if (stop != null) { + scondition.append(Columns.STARTTRANS.name()); + scondition.append(" <= ? "); + hasCondition = true; + } + if (startid != null) { + if (hasCondition) { + scondition.append(" AND "); + } + hasCondition = true; + scondition.append(Columns.SPECIALID.name()); + scondition.append(" >= ? "); + } + if (stopid != null) { + if (hasCondition) { + scondition.append(" AND "); + } + hasCondition = true; + scondition.append(Columns.SPECIALID.name()); + scondition.append(" <= ? "); + } + if (rule != null) { + if (hasCondition) { + scondition.append(" AND "); + } + hasCondition = true; + scondition.append(Columns.IDRULE.name()); + scondition.append(" LIKE '%"); + scondition.append(rule); + scondition.append("%' "); + } + if (req != null) { + if (hasCondition) { + scondition.append(" AND "); + } + hasCondition = true; + scondition.append("( "); + scondition.append(Columns.REQUESTED.name()); + scondition.append(" LIKE '%"); + scondition.append(req); + scondition.append("%' OR "); + scondition.append(Columns.REQUESTER.name()); + scondition.append(" LIKE '%"); + scondition.append(req); + scondition.append("%' )"); + } + if (!all) { + if (hasCondition) { + scondition.append(" AND "); + } + hasCondition = true; + scondition.append("( "); + boolean hasone = false; + if (pending) { + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" = "); + scondition.append(UpdatedInfo.TOSUBMIT.ordinal()); + hasone = true; + } + if (transfer) { + if (hasone) { + scondition.append(" OR "); + } + scondition.append("( "); + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" = "); + scondition.append(UpdatedInfo.RUNNING.ordinal()); + scondition.append(" )"); + hasone = true; + } + if (error) { + if (hasone) { + scondition.append(" OR "); + } + scondition.append(Columns.GLOBALSTEP.name()); + scondition.append(" = "); + scondition.append(TASKSTEP.ERRORTASK.ordinal()); + scondition.append(" OR "); + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" = "); + scondition.append(UpdatedInfo.INERROR.ordinal()); + scondition.append(" OR "); + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" = "); + scondition.append(UpdatedInfo.INTERRUPTED.ordinal()); + hasone = true; + } + if (done) { + if (hasone) { + scondition.append(" OR "); + } + scondition.append(Columns.GLOBALSTEP.name()); + scondition.append(" = "); + scondition.append(TASKSTEP.ALLDONETASK.ordinal()); + scondition.append(" OR "); + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" = "); + scondition.append(UpdatedInfo.DONE.ordinal()); + } + if (scondition.length() <= 3) { + scondition.append(Columns.UPDATEDINFO.name()); + scondition.append(" IS NOT NULL "); + } + scondition.append(" )"); + } + if (limit > 0) { + scondition.insert(0, request); + scondition.append(orderby); + request = scondition.toString(); + request = DbModelFactory.dbModel.limitRequest(selectAllFields, + request, limit); + } else { + scondition.insert(0, request); + scondition.append(orderby); + request = scondition.toString(); + } + preparedStatement.createPrepareStatement(request); + int rank = 1; + try { + if (start != null & stop != null) { + preparedStatement.getPreparedStatement().setTimestamp(rank, + start); + rank++; + preparedStatement.getPreparedStatement().setTimestamp(rank, + stop); + rank++; + } else if (start != null) { + preparedStatement.getPreparedStatement().setTimestamp(rank, + start); + rank++; + } else if (stop != null) { + preparedStatement.getPreparedStatement().setTimestamp(rank, + stop); + rank++; + } + if (startid != null) { + long value = DbConstant.ILLEGALVALUE; + try { + value = Long.parseLong(startid); + } catch (NumberFormatException e) { + // ignore then + } + preparedStatement.getPreparedStatement().setLong(rank, + value); + rank++; + } + if (stopid != null) { + long value = Long.MAX_VALUE; + try { + value = Long.parseLong(stopid); + } catch (NumberFormatException e) { + // ignore then + } + preparedStatement.getPreparedStatement().setLong(rank, + value); + rank++; + } + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + return preparedStatement; + } + + /** + * + * @param session + * @param limit + * @param orderBySpecialId + * @param startid + * @param stopid + * @param start + * @param stop + * @param rule + * @param req + * @param pending + * @param transfer + * @param error + * @param done + * @param all + * @return the DbPreparedStatement according to the filter + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getFilterPrepareStatement( + DbSession session, int limit, boolean orderBySpecialId, String startid, String stopid, + Timestamp start, Timestamp stop, String rule, + String req, boolean pending, boolean transfer, boolean error, + boolean done, boolean all) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "SELECT " + selectAllFields + " FROM " + table; + String orderby; + if (startid == null && stopid == null && + start == null && stop == null && rule == null && req == null && all) { + orderby = " WHERE " + getLimitWhereCondition(); + } else { + orderby = " AND " + getLimitWhereCondition(); + } + if (orderBySpecialId) { + orderby += " ORDER BY " + Columns.SPECIALID.name() + " DESC "; + } else { + orderby += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; + } + return getFilterCondition(preparedStatement, request, limit, orderby, + startid, stopid, start, stop, rule, + req, pending, transfer, error, done, all); + } + + /** + * + * @param session + * @param info + * @param orderByStart + * If true, sort on Start ; If false, does not set the limit on start + * @param limit + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getSelectFromInfoPrepareStatement(DbSession session, + UpdatedInfo info, boolean orderByStart, int limit) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT " + selectAllFields + + " FROM " + table + " WHERE " + Columns.UPDATEDINFO.name() + + " = " + info.ordinal() + + " AND " + Columns.STARTTRANS.name() + " <= ? AND " + getLimitWhereCondition(); + if (orderByStart) { + request += " ORDER BY " + Columns.STARTTRANS.name() + " DESC "; + } + request = + DbModelFactory.dbModel.limitRequest(selectAllFields, request, limit); + DbPreparedStatement pstt = new DbPreparedStatement(session, request); + return pstt; + } + + /** + * + * @param session + * @return the DbPreparedStatement for getting Updated Object + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountInfoPrepareStatement(DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + + ") FROM " + table + " WHERE " + + Columns.STARTTRANS.name() + " >= ? AND " + getLimitWhereCondition() + + " AND " + Columns.UPDATEDINFO.name() + " = ? "; + DbPreparedStatement pstt = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(pstt); + return pstt; + } + + /** + * + * @param pstt + * @param info + * @param time + * @return the number of elements (COUNT) from the statement + */ + public static long getResultCountPrepareStatement(DbPreparedStatement pstt, UpdatedInfo info, + long time) { + long result = 0; + try { + finishSelectOrCountPrepareStatement(pstt, time); + pstt.getPreparedStatement().setInt(2, info.ordinal()); + pstt.executeQuery(); + if (pstt.getNext()) { + result = pstt.getResultSet().getLong(1); + } + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } catch (SQLException e) { + } finally { + pstt.close(); + } + return result; + } + + /** + * @param session + * @param globalstep + * @return the DbPreparedStatement for getting Runner according to globalstep ordered by start + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountStepPrepareStatement(DbSession session, + TASKSTEP globalstep) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; + if (globalstep != null) { + request += " WHERE " + Columns.GLOBALSTEP.name() + " = " + + globalstep.ordinal() + " AND "; + request += Columns.STARTTRANS.name() + " >= ? AND " + getLimitWhereCondition(); + } else { + request += " WHERE " + Columns.STARTTRANS.name() + " >= ? AND " + + getLimitWhereCondition(); + } + DbPreparedStatement prep = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(prep); + return prep; + } + + /** + * @param session + * @return the DbPreparedStatement for getting Runner according to status ordered by start + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountStatusPrepareStatement( + DbSession session) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; + request += " WHERE " + Columns.STARTTRANS.name() + " >= ? "; + request += " AND " + Columns.INFOSTATUS.name() + " = ? AND " + getLimitWhereCondition(); + DbPreparedStatement prep = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(prep); + return prep; + } + + /** + * + * @param pstt + * @param error + * @param time + * @return the number of elements (COUNT) from the statement + */ + public static long getResultCountPrepareStatement(DbPreparedStatement pstt, ErrorCode error, + long time) { + long result = 0; + try { + finishSelectOrCountPrepareStatement(pstt, time); + pstt.getPreparedStatement().setString(2, error.getCode()); + pstt.executeQuery(); + if (pstt.getNext()) { + result = pstt.getResultSet().getLong(1); + } + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } catch (SQLException e) { + } finally { + pstt.close(); + } + return result; + } + + /** + * Only running transfers + * + * @param session + * @param status + * @return the DbPreparedStatement for getting Runner according to status ordered by start + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountStatusRunningPrepareStatement( + DbSession session, ErrorCode status) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; + if (status != null) { + request += " WHERE " + Columns.STEPSTATUS.name() + " = '" + + status.getCode() + "' AND " + getLimitWhereCondition(); + } else { + request += " WHERE " + getLimitWhereCondition(); + } + request += " AND " + Columns.STARTTRANS.name() + " >= ? "; + request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.RUNNING.ordinal(); + DbPreparedStatement prep = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(prep); + return prep; + } + + /** + * Running or not transfers are concerned + * + * @param session + * @param in + * True for Incoming, False for Outgoing + * @return the DbPreparedStatement for getting Runner according to in or out going way and Error + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountInOutErrorPrepareStatement( + DbSession session, boolean in) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; + String requesterd; + String from = Configuration.configuration.HOST_ID; + String sfrom = Configuration.configuration.HOST_SSLID; + if (in) { + requesterd = Columns.REQUESTED.name(); + } else { + requesterd = Columns.REQUESTER.name(); + } + if (from != null & sfrom != null) { + request += " WHERE ((" + requesterd + " = '" + + from + "' OR " + requesterd + " = '" + sfrom + "') "; + } else if (from != null) { + request += " WHERE (" + requesterd + " = '" + from + "' "; + } else { + request += " WHERE (" + requesterd + " = '" + sfrom + "' "; + } + request += " AND " + getLimitWhereCondition() + ") "; + request += " AND " + Columns.STARTTRANS.name() + " >= ? "; + request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.INERROR.ordinal(); + DbPreparedStatement prep = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(prep); + return prep; + } + + /** + * Running or not transfers are concerned + * + * @param session + * @param in + * True for Incoming, False for Outgoing + * @param running + * True for Running only, False for all + * @return the DbPreparedStatement for getting Runner according to in or out going way + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getCountInOutRunningPrepareStatement( + DbSession session, boolean in, boolean running) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + String request = "SELECT COUNT(" + Columns.SPECIALID.name() + ") FROM " + table; + String requesterd; + String from = Configuration.configuration.HOST_ID; + String sfrom = Configuration.configuration.HOST_SSLID; + if (in) { + requesterd = Columns.REQUESTED.name(); + } else { + requesterd = Columns.REQUESTER.name(); + } + if (from != null & sfrom != null) { + request += " WHERE ((" + requesterd + " = '" + + from + "' OR " + requesterd + " = '" + sfrom + "') "; + } else if (from != null) { + request += " WHERE (" + requesterd + " = '" + from + "' "; + } else { + request += " WHERE (" + requesterd + " = '" + sfrom + "' "; + } + request += " AND " + getLimitWhereCondition() + ") "; + request += " AND " + Columns.STARTTRANS.name() + " >= ? "; + if (running) { + request += " AND " + Columns.UPDATEDINFO.name() + " = " + UpdatedInfo.RUNNING.ordinal(); + } + DbPreparedStatement prep = new DbPreparedStatement(session, request); + session.addLongTermPreparedStatement(prep); + return prep; + } + + /** + * + * @param pstt + * @return the number of elements (COUNT) from the statement + */ + public static long getResultCountPrepareStatement(DbPreparedStatement pstt) { + long result = 0; + try { + pstt.executeQuery(); + if (pstt.getNext()) { + result = pstt.getResultSet().getLong(1); + } + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } catch (SQLException e) { + } finally { + pstt.close(); + } + return result; + } + + /** + * Set the current time in the given updatedPreparedStatement + * + * @param pstt + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static void finishSelectOrCountPrepareStatement(DbPreparedStatement pstt) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + finishSelectOrCountPrepareStatement(pstt, System.currentTimeMillis()); + } + + /** + * Set the current time in the given updatedPreparedStatement + * + * @param pstt + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static void finishSelectOrCountPrepareStatement(DbPreparedStatement pstt, long time) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + Timestamp startlimit = new Timestamp(time); + try { + pstt.getPreparedStatement().setTimestamp(1, startlimit); + } catch (SQLException e) { + logger.error("Database SQL Error: Cannot set timestamp", e); + throw new WaarpDatabaseSqlException("Cannot set timestamp", e); + } + } + + /** + * + * @param session + * @param start + * @param stop + * @return the DbPreparedStatement for getting Selected Object, whatever their status + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static DbPreparedStatement getLogPrepareStatement(DbSession session, + Timestamp start, Timestamp stop) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "SELECT " + selectAllFields + " FROM " + table; + if (start != null & stop != null) { + request += " WHERE " + Columns.STARTTRANS.name() + " >= ? AND " + + Columns.STARTTRANS.name() + " <= ? AND " + getLimitWhereCondition() + + " ORDER BY " + Columns.SPECIALID.name() + " DESC "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, start); + preparedStatement.getPreparedStatement().setTimestamp(2, stop); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else if (start != null) { + request += " WHERE " + Columns.STARTTRANS.name() + + " >= ? AND " + getLimitWhereCondition() + + " ORDER BY " + Columns.SPECIALID.name() + " DESC "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, start); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else if (stop != null) { + request += " WHERE " + Columns.STARTTRANS.name() + + " <= ? AND " + getLimitWhereCondition() + + " ORDER BY " + Columns.SPECIALID.name() + " DESC "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, stop); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else { + request += " WHERE " + getLimitWhereCondition() + + " ORDER BY " + Columns.SPECIALID.name() + " DESC "; + preparedStatement.createPrepareStatement(request); + } + return preparedStatement; + } + + /** + * purge in same interval all runners with globallaststep as ALLDONETASK or UpdatedInfo as Done + * + * @param session + * @param start + * @param stop + * @return the number of log purged + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static int purgeLogPrepareStatement(DbSession session, + Timestamp start, Timestamp stop) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "DELETE FROM " + table + " WHERE (" + + Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + + Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + + ") AND " + getLimitWhereCondition(); + try { + if (start != null & stop != null) { + request += " AND " + Columns.STARTTRANS.name() + " >= ? AND " + + Columns.STOPTRANS.name() + " <= ? "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, start); + preparedStatement.getPreparedStatement().setTimestamp(2, stop); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else if (start != null) { + request += " AND " + Columns.STARTTRANS.name() + " >= ? "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, start); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else if (stop != null) { + request += " AND " + Columns.STOPTRANS.name() + " <= ? "; + preparedStatement.createPrepareStatement(request); + try { + preparedStatement.getPreparedStatement().setTimestamp(1, stop); + } catch (SQLException e) { + preparedStatement.realClose(); + throw new WaarpDatabaseSqlException(e); + } + } else { + preparedStatement.createPrepareStatement(request); + } + int nb = preparedStatement.executeUpdate(); + logger.info("Purge " + nb + " from " + request); + return nb; + } finally { + preparedStatement.realClose(); + } + } + + /** + * + * @param session + * @param startid + * @param stopid + * @param start + * @param stop + * @param rule + * @param req + * @param pending + * @param transfer + * @param error + * @param done + * @param all + * @return the DbPreparedStatement according to the filter and ALLDONE, ERROR globallaststep + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + public static int purgeLogPrepareStatement( + DbSession session, String startid, String stopid, + Timestamp start, Timestamp stop, String rule, + String req, boolean pending, boolean transfer, boolean error, + boolean done, boolean all) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + DbPreparedStatement preparedStatement = new DbPreparedStatement(session); + String request = "DELETE FROM " + table; + String orderby; + if (startid == null && stopid == null && start == null && stop == null && + rule == null && req == null && all) { + orderby = " WHERE (" + + Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + + Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + + ") AND " + getLimitWhereCondition(); + } else { + if (all) { + orderby = " AND (" + + Columns.GLOBALLASTSTEP + " = " + TASKSTEP.ALLDONETASK.ordinal() + " OR " + + Columns.UPDATEDINFO + " = " + UpdatedInfo.DONE.ordinal() + " OR " + + Columns.UPDATEDINFO + " = " + UpdatedInfo.INERROR.ordinal() + + ") AND " + getLimitWhereCondition(); + } else { + orderby = " AND " + + Columns.UPDATEDINFO + " <> " + UpdatedInfo.RUNNING.ordinal() + + " AND " + getLimitWhereCondition();// limit by field + } + } + int nb = 0; + try { + preparedStatement = getFilterCondition(preparedStatement, request, 0, + orderby, startid, stopid, start, stop, rule, + req, pending, transfer, error, done, all); + nb = preparedStatement.executeUpdate(); + logger.info("Purge " + nb + " from " + request); + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + return nb; + } + + /** + * Change RUNNING, INTERRUPTED to TOSUBMIT TaskRunner from database. This method is to be used + * when the commander is starting the very first time, in order to be ready to rerun tasks that + * are pending. + * + * @param session + * @throws WaarpDatabaseNoConnectionException + */ + public static void resetToSubmit(DbSession session) + throws WaarpDatabaseNoConnectionException { + // Change RUNNING and INTERRUPTED to TOSUBMIT since they should be ready + String request = "UPDATE " + table + " SET " + + Columns.UPDATEDINFO.name() + "=" + + AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal() + + " WHERE (" + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.RUNNING.ordinal() + + " OR " + Columns.UPDATEDINFO.name() + " = " + + AbstractDbData.UpdatedInfo.INTERRUPTED.ordinal() + ") AND " + + getLimitWhereCondition(); + DbPreparedStatement initial = new DbPreparedStatement(session); + try { + initial.createPrepareStatement(request); + initial.executeUpdate(); + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } finally { + initial.close(); + } + } + + /** + * Change CompleteOk+ALLDONETASK to Updated = DONE TaskRunner from database. This method is a + * clean function to be used for instance before log export or at the very beginning of the + * commander. + * + * @param session + * @throws WaarpDatabaseNoConnectionException + */ + public static void changeFinishedToDone(DbSession session) + throws WaarpDatabaseNoConnectionException { + // Update all UpdatedInfo to DONE where GlobalLastStep = ALLDONETASK and + // status = CompleteOk + String request = "UPDATE " + table + " SET " + + Columns.UPDATEDINFO.name() + "=" + + AbstractDbData.UpdatedInfo.DONE.ordinal() + + " WHERE " + Columns.UPDATEDINFO.name() + " <> " + + AbstractDbData.UpdatedInfo.DONE.ordinal() + " AND " + + Columns.UPDATEDINFO.name() + " > 0 AND " + + Columns.GLOBALLASTSTEP.name() + " = " + + TASKSTEP.ALLDONETASK.ordinal() + " AND " + + Columns.STEPSTATUS.name() + " = '" + + ErrorCode.CompleteOk.getCode() + "' AND " + + getLimitWhereCondition(); + DbPreparedStatement initial = new DbPreparedStatement(session); + try { + initial.createPrepareStatement(request); + initial.executeUpdate(); + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Database No Connection Error: Cannot execute Commander", e); + return; + } catch (WaarpDatabaseSqlException e) { + logger.error("Database SQL Error: Cannot execute Commander", e); + return; + } finally { + initial.realClose(); + } + } + + /** + * Reset the runner (ready to be run again) + * + * @return True if OK, False if already finished + */ + public boolean reset() { + // Reset the status if already stopped and not finished + if (this.getStatus() != ErrorCode.CompleteOk) { + // restart + switch (TASKSTEP.values()[this.getGloballaststep()]) { + case PRETASK: + // restart + this.setPreTask(); + this.setExecutionStatus(ErrorCode.InitOk); + break; + case TRANSFERTASK: + // continue + int newrank = this.getRank(); + this.setTransferTask(newrank); + this.setExecutionStatus(ErrorCode.PreProcessingOk); + break; + case POSTTASK: + // restart + this.setPostTask(); + this.setExecutionStatus(ErrorCode.TransferOk); + break; + case ALLDONETASK: + break; + case ERRORTASK: + break; + case NOTASK: + setInitialTask(); + this.setExecutionStatus(ErrorCode.Unknown); + break; + default: + break; + } + this.changeUpdatedInfo(UpdatedInfo.UNKNOWN); + this.setErrorExecutionStatus(this.status); + return true; + } else { + // Already finished + return false; + } + } + + /** + * Decrease if necessary the rank + */ + public void restartRank() { + if (!this.isSender) { + int newrank = this.getRank(); + if (newrank > 0) { + logger.debug("Decrease Rank Restart of -" + Configuration.RANKRESTART + + " from " + newrank); + newrank -= Configuration.RANKRESTART; + if (newrank <= 0) { + newrank = 1; + } + if (this.getRank() != newrank) { + logger.warn("Decreased Rank Restart at rank: " + newrank + " for {}", this); + } + } + this.setTransferTask(newrank); + } + } + + /** + * Make this Runner ready for restart + * + * @param submit + * True to resubmit this task, else False to keep it as running (only reset) + * @return True if OK or False if Already finished or if submitted and the request is a + * selfRequested and is not ready to restart locally + */ + public boolean restart(boolean submit) { + // Restart if not Requested + if (submit) { + if (isSelfRequested() && (this.globallaststep < TASKSTEP.POSTTASK.ordinal())) { + return false; + } + } + // Restart if already stopped and not finished + if (reset()) { + // if not submit and transfertask and receiver AND not requester + // If requester and receiver => rank is already decreased when request is sent + if ((!submit) && (this.globalstep == TASKSTEP.TRANSFERTASK.ordinal()) && + (!this.isSender) && (this.isSelfRequested())) { + logger.debug("Will try to restart transfer {}", this); + this.restartRank(); + logger.debug("New restart for transfer is {}", this); + } + if (submit) { + this.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + } else { + this.changeUpdatedInfo(UpdatedInfo.RUNNING); + } + return true; + } else { + // Already finished so DONE + this.setAllDone(); + this.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); + this.forceSaveStatus(); + return false; + } + } + + /** + * Stop or Cancel a Runner from database point of view + * + * @param code + * @return True if correctly stopped or canceled + */ + public boolean stopOrCancelRunner(ErrorCode code) { + if (!isFinished()) { + reset(); + switch (code) { + case CanceledTransfer: + case StoppedTransfer: + case RemoteShutdown: + this.changeUpdatedInfo(UpdatedInfo.INERROR); + break; + default: + this.changeUpdatedInfo(UpdatedInfo.INTERRUPTED); + } + forceSaveStatus(); + logger.warn("StopOrCancel: {}\n {}", code.mesg, this.toShortString()); + return true; + } else { + // is finished so do nothing + } + return false; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo) + */ + @Override + public void changeUpdatedInfo(UpdatedInfo info) { + updatedInfo = info.ordinal(); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo); + isSaved = false; + } + + /** + * Set the ErrorCode for the UpdatedInfo + * + * @param code + */ + public void setErrorExecutionStatus(ErrorCode code) { + if (infostatus != code) { + infostatus = code; + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + isSaved = false; + } + } + + /** + * + * @return The current UpdatedInfo value + */ + public UpdatedInfo getUpdatedInfo() { + return UpdatedInfo.values()[updatedInfo]; + } + + /** + * + * @return the error code associated with the Updated Info + */ + public ErrorCode getErrorInfo() { + return infostatus; + } + + /** + * @return the step + */ + public int getStep() { + return step; + } + + /** + * @return the rescheduledTransfer + */ + public boolean isRescheduledTransfer() { + return rescheduledTransfer; + } + + /** + * Set this DbTaskRunner as rescheduled (valid only while still in memory) + */ + public void setRescheduledTransfer() { + this.rescheduledTransfer = true; + } + + /** + * To set the rank at startup of the request if the request specify a specific rank + * + * @param rank + * the rank to set + */ + public void setRankAtStartup(int rank) { + if (this.rank > rank) { + this.rank = rank; + allFields[Columns.RANK.ordinal()].setValue(this.rank); + isSaved = false; + } + } + + /** + * @param filename + * the filename to set + */ + public void setFilename(String filename) { + if (!this.filename.equals(filename)) { + this.filename = filename; + allFields[Columns.FILENAME.ordinal()].setValue(this.filename); + isSaved = false; + } + } + + /** + * @param newFilename + * the new Filename to set + * @param isFileMoved + * the isFileMoved to set + */ + public void setFileMoved(String newFilename, boolean isFileMoved) { + if (this.isFileMoved != isFileMoved) { + this.isFileMoved = isFileMoved; + allFields[Columns.ISMOVED.ordinal()].setValue(this.isFileMoved); + isSaved = false; + } + this.setFilename(newFilename); + } + + /** + * @param originalFilename + * the originalFilename to set + */ + public void setOriginalFilename(String originalFilename) { + if (!this.originalFilename.equals(originalFilename)) { + this.originalFilename = originalFilename; + allFields[Columns.ORIGINALNAME.ordinal()] + .setValue(this.originalFilename); + isSaved = false; + } + } + + /** + * @return the rank + */ + public int getRank() { + return rank; + } + + /** + * Change the status from Task Execution + * + * @param status + */ + public void setExecutionStatus(ErrorCode status) { + this.status = status; + allFields[Columns.STEPSTATUS.ordinal()].setValue(this.status.getCode()); + isSaved = false; + } + + /** + * @return the status + */ + public ErrorCode getStatus() { + return status; + } + + /** + * @return the isSender + */ + public boolean isSender() { + return isSender; + } + + /** + * @return the isFileMoved + */ + public boolean isFileMoved() { + return isFileMoved; + } + + /** + * @return the blocksize + */ + public int getBlocksize() { + return blocksize; + } + + /** + * @return the filename + */ + public String getFilename() { + return filename; + } + + /** + * @return the originalFilename + */ + public String getOriginalFilename() { + return originalFilename; + } + + /** + * @return the fileInformation + */ + public String getFileInformation() { + return fileInformation; + } + + /** + * Set a new File information for this transfer + * @param newFileInformation + */ + public void setFileInformation(String newFileInformation) { + fileInformation = newFileInformation; + allFields[Columns.FILEINFO.ordinal()].setValue(this.fileInformation); + isSaved = false; + } + + /** + * @return the specialId + */ + public long getSpecialId() { + return specialId; + } + + /** + * @return the rule + */ + public DbRule getRule() { + if (rule == null) { + if (ruleId != null) { + try { + rule = new DbRule(dbSession, ruleId); + } catch (WaarpDatabaseException e) { + } + } + } + return rule; + } + + /** + * @return the ruleId + */ + public String getRuleId() { + return ruleId; + } + + /** + * @return the mode + */ + public int getMode() { + return mode; + } + + /** + * @return the globallaststep + */ + public int getGloballaststep() { + return globallaststep; + } + + /** + * + * @return True if this runner is ready for transfer or post operation + */ + public boolean ready() { + return globalstep > TASKSTEP.PRETASK.ordinal(); + } + + /** + * + * @return True if the runner is currently in transfer + */ + public boolean isInTransfer() { + return globalstep == TASKSTEP.TRANSFERTASK.ordinal(); + } + + /** + * + * @return True if this runner is finished, either in success or in error + */ + public boolean isFinished() { + return isAllDone() || isInError(); + } + + /** + * + * @return True if this runner is in error and no more running + */ + public boolean isInError() { + return (globalstep == TASKSTEP.ERRORTASK.ordinal() && status != ErrorCode.Running); + } + + /** + * + * @return True if the runner is finished in success + */ + public boolean isAllDone() { + return globalstep == TASKSTEP.ALLDONETASK.ordinal(); + } + + /** + * To be called before executing Pre execution + * + * @return True if the task is going to run PRE task from the first action + */ + public boolean isPreTaskStarting() { + if (globallaststep == TASKSTEP.PRETASK.ordinal() || + globallaststep == TASKSTEP.NOTASK.ordinal()) { + return (step - 1 <= 0); + } + return false; + } + + + /** + * Set the Initial Task step (before Pre task) + * + */ + public void setInitialTask() { + globalstep = TASKSTEP.NOTASK.ordinal(); + globallaststep = TASKSTEP.NOTASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + step = -1; + allFields[Columns.STEP.ordinal()].setValue(this.step); + status = ErrorCode.Running; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + this.changeUpdatedInfo(UpdatedInfo.RUNNING); + this.setErrorExecutionStatus(ErrorCode.Unknown); + isSaved = false; + } + + /** + * Set Pre Task step + * + */ + public void setPreTask() { + globalstep = TASKSTEP.PRETASK.ordinal(); + globallaststep = TASKSTEP.PRETASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + if (step <= 0) { + this.step = 0; + } else { + this.step--; + } + allFields[Columns.STEP.ordinal()].setValue(this.step); + status = ErrorCode.Running; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + this.changeUpdatedInfo(UpdatedInfo.RUNNING); + this.setErrorExecutionStatus(ErrorCode.InitOk); + isSaved = false; + } + + /** + * Set Transfer rank + * + * @param rank + */ + public void setTransferTask(int rank) { + globalstep = TASKSTEP.TRANSFERTASK.ordinal(); + globallaststep = TASKSTEP.TRANSFERTASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + if (this.rank > rank) { + this.rank = rank; + } + allFields[Columns.RANK.ordinal()].setValue(this.rank); + status = ErrorCode.Running; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + this.setErrorExecutionStatus(ErrorCode.PreProcessingOk); + isSaved = false; + } + + /** + * Set the status of the transfer + * + * @param code + * TransferOk if success + * @return the current rank of transfer + */ + public int finishTransferTask(ErrorCode code) { + if (code == ErrorCode.TransferOk) { + this.status = code; + this.setErrorExecutionStatus(code); + } else { + continueTransfer = false; + if (this.infostatus == ErrorCode.InitOk || + this.infostatus == ErrorCode.PostProcessingOk || + this.infostatus == ErrorCode.PreProcessingOk || + this.infostatus == ErrorCode.Running || + this.infostatus == ErrorCode.TransferOk) { + this.setErrorExecutionStatus(code); + } + if (this.updatedInfo != UpdatedInfo.INTERRUPTED.ordinal()) { + this.changeUpdatedInfo(UpdatedInfo.INERROR); + } + } + allFields[Columns.STEPSTATUS.ordinal()].setValue(this.status.getCode()); + isSaved = false; + return rank; + } + + /** + * + * @return True if the transfer is valid to continue + */ + public boolean continueTransfer() { + return continueTransfer; + } + + /** + * Set the Post Task step + * + */ + public void setPostTask() { + globalstep = TASKSTEP.POSTTASK.ordinal(); + globallaststep = TASKSTEP.POSTTASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + if (step <= 0) { + this.step = 0; + } else { + this.step--; + } + allFields[Columns.STEP.ordinal()].setValue(this.step); + status = ErrorCode.Running; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + this.setErrorExecutionStatus(ErrorCode.TransferOk); + isSaved = false; + } + + /** + * Set the Error Task step + * + * @param localChannelReference + * (to get session) + */ + public void setErrorTask(LocalChannelReference localChannelReference) { + if (this.session == null && localChannelReference != null) { + this.session = localChannelReference.getSession(); + } + if (this.session != null) { + if (this.session.getRunner() == null) + this.session.setNoSessionRunner(this, localChannelReference); + } + globalstep = TASKSTEP.ERRORTASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + this.step = 0; + allFields[Columns.STEP.ordinal()].setValue(this.step); + status = ErrorCode.Running; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + isSaved = false; + } + + /** + * Set the global step as finished (after post task in success) + */ + public void setAllDone() { + globalstep = TASKSTEP.ALLDONETASK.ordinal(); + globallaststep = TASKSTEP.ALLDONETASK.ordinal(); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(globalstep); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(globallaststep); + step = 0; + allFields[Columns.STEP.ordinal()].setValue(step); + status = ErrorCode.CompleteOk; + allFields[Columns.STEPSTATUS.ordinal()].setValue(status.getCode()); + infostatus = ErrorCode.CompleteOk; + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + changeUpdatedInfo(UpdatedInfo.DONE); + isSaved = false; + } + + /** + * Run the task from the given task information (from rule) + * + * @param tasks + * @return The future of the operation (in success or not) + * @throws OpenR66RunnerEndTasksException + * @throws OpenR66RunnerErrorException + */ + private R66Future runNextTask(String[][] tasks) + throws OpenR66RunnerEndTasksException, OpenR66RunnerErrorException { + logger.debug((session == null) + ":" + + (session == null ? "norunner" : (this.session.getRunner() == null)) + ":" + + this.toLogRunStep() + ":" + step + ":" + (tasks == null ? "null" : tasks.length) + + "\nSender: " + this.isSender + " " + this.rule.printTasks(isSender, + TASKSTEP.values()[globalstep])); + if (tasks == null) { + throw new OpenR66RunnerEndTasksException("No tasks!"); + } + R66Session tempSession = this.session; + if (tempSession == null) { + tempSession = new R66Session(); + if (tempSession.getRunner() == null) { + tempSession.setNoSessionRunner(this, localChannelReference); + } + } else { + if (tempSession.getRunner() == null) { + tempSession.setNoSessionRunner(this, tempSession.getLocalChannelReference()); + } + } + this.session = tempSession; + if (this.session.getLocalChannelReference().getCurrentCode() == ErrorCode.Unknown) { + this.session.getLocalChannelReference().setErrorMessage(this.infostatus.mesg, + this.infostatus); + } + if (tasks.length <= step) { + throw new OpenR66RunnerEndTasksException(); + } + String name = tasks[step][0]; + String arg = tasks[step][1]; + int delay = 0; + try { + delay = Integer.parseInt(tasks[step][2]); + } catch (NumberFormatException e) { + logger.warn("Malformed task so stop the execution: " + this.toShortString()); + throw new OpenR66RunnerErrorException("Malformed task so stop the execution"); + } + AbstractTask task = TaskType.getTaskFromId(name, arg, delay, tempSession); + logger.debug(this.toLogRunStep() + " Task: " + task.getClass().getName()); + task.run(); + try { + task.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + if (name.equals(TaskType.RESCHEDULE.name)) { + // Special case : must test if exec is OK since it must be the last + if (this.isRescheduledTransfer()) { + throw new OpenR66RunnerEndTasksException(); + } + } + return task.getFutureCompletion(); + } + + /** + * + * @return the future of the task run + * @throws OpenR66RunnerEndTasksException + * @throws OpenR66RunnerErrorException + * @throws OpenR66RunnerEndTasksException + */ + private R66Future runNext() throws OpenR66RunnerErrorException, + OpenR66RunnerEndTasksException { + logger.debug(this.toLogRunStep() + "\nSender: " + this.isSender + " " + + this.rule.printTasks(isSender, + TASKSTEP.values()[globalstep])); + if (rule == null) { + if (ruleId != null) { + try { + rule = new DbRule(dbSession, ruleId); + } catch (WaarpDatabaseException e) { + rule = null; + } + } + if (rule == null) { + throw new OpenR66RunnerErrorException("Rule Object not initialized"); + } + } + switch (TASKSTEP.values()[globalstep]) { + case PRETASK: + try { + if (this.isSender) { + return runNextTask(rule.spreTasksArray); + } else { + return runNextTask(rule.rpreTasksArray); + } + } catch (OpenR66RunnerEndTasksException e) { + if (status == ErrorCode.Running) { + infostatus = status = ErrorCode.PreProcessingOk; + } + throw e; + } + case POSTTASK: + try { + if (this.isSender) { + return runNextTask(rule.spostTasksArray); + } else { + return runNextTask(rule.rpostTasksArray); + } + } catch (OpenR66RunnerEndTasksException e) { + if (status == ErrorCode.Running) { + infostatus = status = ErrorCode.PostProcessingOk; + } + throw e; + } + case ERRORTASK: + try { + if (this.isSender) { + return runNextTask(rule.serrorTasksArray); + } else { + return runNextTask(rule.rerrorTasksArray); + } + } catch (OpenR66RunnerEndTasksException e) { + if (status == ErrorCode.Running) { + status = infostatus; + } + throw e; + } + default: + throw new OpenR66RunnerErrorException("Global Step unknown"); + } + } + + /** + * Run all task from current status (globalstep and step) + * + * @throws OpenR66RunnerErrorException + */ + public void run() throws OpenR66RunnerErrorException { + R66Future future; + logger.debug(this.toLogRunStep() + " Status: " + status + "\nSender: " + this.isSender + + " " + this.rule.printTasks(isSender, + TASKSTEP.values()[globalstep])); + if (status != ErrorCode.Running) { + throw new OpenR66RunnerErrorException( + "Current global STEP not ready to run: " + this.toString()); + } + while (true) { + logger.debug(this.toLogRunStep()); + try { + future = runNext(); + } catch (OpenR66RunnerEndTasksException e) { + step = 0; + allFields[Columns.STEP.ordinal()].setValue(step); + allFields[Columns.STEPSTATUS.ordinal()].setValue(status + .getCode()); + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + isSaved = false; + this.saveStatus(); + return; + } catch (OpenR66RunnerErrorException e) { + infostatus = ErrorCode.ExternalOp; + allFields[Columns.STEP.ordinal()].setValue(step); + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + isSaved = false; + this.setErrorExecutionStatus(infostatus); + this.saveStatus(); + throw new OpenR66RunnerErrorException("Runner is in error: " + + e.getMessage(), e); + } + if ((!future.isDone()) || future.isFailed()) { + R66Result result = future.getResult(); + if (result != null) { + infostatus = future.getResult().code; + } else { + infostatus = ErrorCode.ExternalOp; + } + this.setErrorExecutionStatus(infostatus); + allFields[Columns.STEP.ordinal()].setValue(step); + allFields[Columns.INFOSTATUS.ordinal()].setValue(infostatus.getCode()); + isSaved = false; + this.saveStatus(); + logger.info("Future is failed: " + infostatus.mesg); + if (future.getCause() != null) { + throw new OpenR66RunnerErrorException("Runner is failed: " + + future.getCause().getMessage(), future.getCause()); + } else { + throw new OpenR66RunnerErrorException("Runner is failed: " + + infostatus.mesg); + } + } + step++; + } + } + + /** + * Once the transfer is over, finalize the Runner by running the error or post operation + * according to the status. + * + * @param localChannelReference + * @param file + * @param finalValue + * @param status + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + */ + public void finalizeTransfer(LocalChannelReference localChannelReference, R66File file, + R66Result finalValue, boolean status) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { + logger.debug("status" + status + ":" + finalValue); + + if (session == null) { + this.session = localChannelReference.getSession(); + } + if (status) { + // First move the file + if (this.isSender()) { + // Nothing to do since it is the original file + this.setPostTask(); + } else { + int poststep = this.step; + this.setPostTask(); + this.saveStatus(); + if (!isRecvThrough()) { + if (this.globalstep == TASKSTEP.TRANSFERTASK.ordinal() || + (this.globalstep == TASKSTEP.POSTTASK.ordinal() && + poststep == 0)) { + // Result file moves + String finalpath = R66Dir.getFinalUniqueFilename(file); + logger.debug("Will move file {}", finalpath); + try { + file.renameTo(this.getRule().setRecvPath(finalpath)); + } catch (OpenR66ProtocolSystemException e) { + R66Result result = new R66Result(e, session, false, + ErrorCode.FinalOp, this); + result.file = file; + result.runner = this; + if (localChannelReference != null) { + localChannelReference.invalidateRequest(result); + } + throw e; + } catch (CommandAbstractException e) { + R66Result result = new R66Result( + new OpenR66RunnerErrorException(e), session, + false, ErrorCode.FinalOp, this); + result.file = file; + result.runner = this; + if (localChannelReference != null) { + localChannelReference.invalidateRequest(result); + } + throw (OpenR66RunnerErrorException) result.exception; + } + logger.debug("File finally moved: {}", file); + try { + this.setFilename(file.getFile()); + } catch (CommandAbstractException e) { + } + // check if possible once more the hash + String hash = localChannelReference.getHashComputeDuringTransfer(); + if (hash != null) { + // we can compute it once more + try { + if (! FilesystemBasedDigest.getHex(FilesystemBasedDigest.getHash(file.getTrueFile(), true, Configuration.configuration.digest)).equals(hash)) { + // KO + R66Result result = new R66Result( + new OpenR66RunnerErrorException("Bad final digest on receive operation"), session, + false, ErrorCode.FinalOp, this); + result.file = file; + result.runner = this; + if (localChannelReference != null) { + localChannelReference.invalidateRequest(result); + } + throw (OpenR66RunnerErrorException) result.exception; + } + } catch (IOException e) { + R66Result result = new R66Result( + new OpenR66RunnerErrorException("Bad final digest on receive operation", e), session, + false, ErrorCode.FinalOp, this); + result.file = file; + result.runner = this; + if (localChannelReference != null) { + localChannelReference.invalidateRequest(result); + } + throw (OpenR66RunnerErrorException) result.exception; + } + } + } + } + } + this.saveStatus(); + if (isRecvThrough() || isSendThrough()) { + // File could not exist + } else if (this.step == 0) { + // File must exist + try { + if (!file.exists()) { + // error + R66Result error = + new R66Result(this.session, finalValue.isAnswered, + ErrorCode.FileNotFound, this); + this.setErrorExecutionStatus(ErrorCode.FileNotFound); + errorTransfer(error, file, localChannelReference); + return; + } + } catch (CommandAbstractException e) { + // error + R66Result error = + new R66Result(this.session, finalValue.isAnswered, + ErrorCode.FileNotFound, this); + this.setErrorExecutionStatus(ErrorCode.FileNotFound); + errorTransfer(error, file, localChannelReference); + return; + } + } + try { + this.run(); + } catch (OpenR66RunnerErrorException e1) { + R66Result result = new R66Result(e1, this.session, false, + ErrorCode.ExternalOp, this); + result.file = file; + result.runner = this; + this.changeUpdatedInfo(UpdatedInfo.INERROR); + this.saveStatus(); + errorTransfer(result, file, localChannelReference); + if (localChannelReference != null) { + localChannelReference.invalidateRequest(result); + } + throw e1; + } + this.saveStatus(); + /* + * Done later on after EndRequest this.setAllDone(); this.saveStatus(); + */ + logger.info("Transfer done on {} at RANK {}", file != null ? file : "no file", rank); + if (localChannelReference != null) { + localChannelReference.validateEndTransfer(finalValue); + } + } else { + logger.debug("ContinueTransfer: " + continueTransfer + " status:" + status + ":" + + finalValue); + /* + * if (!continueTransfer) { // already setup return; } + */ + errorTransfer(finalValue, file, localChannelReference); + } + } + + /** + * Finalize a transfer in error + * + * @param finalValue + * @param file + * @param localChannelReference + * @throws OpenR66RunnerErrorException + */ + private void errorTransfer(R66Result finalValue, R66File file, + LocalChannelReference localChannelReference) throws OpenR66RunnerErrorException { + // error or not ? + ErrorCode runnerStatus = this.getErrorInfo(); + if (finalValue.exception != null) { + logger.error("Transfer KO on " + file + " due to " + finalValue.exception.getMessage()); + } else { + logger.error("Transfer KO on " + file + " due to " + finalValue.toString()); + } + if (runnerStatus == ErrorCode.CanceledTransfer) { + // delete file, reset runner + this.setRankAtStartup(0); + this.deleteTempFile(); + this.changeUpdatedInfo(UpdatedInfo.INERROR); + this.saveStatus(); + finalValue.isAnswered = true; + } else if (runnerStatus == ErrorCode.StoppedTransfer) { + // just save runner and stop + this.changeUpdatedInfo(UpdatedInfo.INERROR); + this.saveStatus(); + finalValue.isAnswered = true; + } else if (runnerStatus == ErrorCode.Shutdown) { + // just save runner and stop + this.changeUpdatedInfo(UpdatedInfo.INERROR); + this.saveStatus(); + finalValue.isAnswered = true; + } + logger.debug("status: " + status + " wasNotError:" + + (this.globalstep != TASKSTEP.ERRORTASK.ordinal()) + + ":" + finalValue); + if (this.globalstep != TASKSTEP.ERRORTASK.ordinal()) { + // errorstep was not already executed + // real error + localChannelReference.setErrorMessage(finalValue.getMessage(), finalValue.code); + // First send error mesg + if (!finalValue.isAnswered) { + localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket errorPacket = new ErrorPacket(finalValue + .getMessage(), + finalValue.code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + errorPacket, true); + finalValue.isAnswered = true; + } catch (OpenR66ProtocolPacketException e1) { + // should not be + } + } + // now run error task + this.setErrorTask(localChannelReference); + this.saveStatus(); + try { + this.run(); + } catch (OpenR66RunnerErrorException e1) { + this.changeUpdatedInfo(UpdatedInfo.INERROR); + this.setErrorExecutionStatus(runnerStatus); + this.saveStatus(); + if (localChannelReference != null) { + localChannelReference.invalidateRequest(finalValue); + } + throw e1; + } + } + if (! this.isRescheduledTransfer()) { + this.changeUpdatedInfo(UpdatedInfo.INERROR); + } + if (RequestPacket.isThroughMode(this.getMode())) { + this.setErrorExecutionStatus(runnerStatus); + this.saveStatus(); + if (localChannelReference != null) { + localChannelReference.invalidateRequest(finalValue); + } + return; + } + // re set the original status + this.setErrorExecutionStatus(runnerStatus); + this.saveStatus(); + if (localChannelReference != null) { + localChannelReference.invalidateRequest(finalValue); + } + } + + /** + * Increment the rank of the transfer + * + * @throws OpenR66ProtocolPacketException + */ + public void incrementRank() throws OpenR66ProtocolPacketException { + rank++; + allFields[Columns.RANK.ordinal()].setValue(rank); + isSaved = false; + if (rank % 10 == 0) { + // Save each 10 blocks + try { + update(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot update Runner: {}", e.getMessage()); + } + } + } + + /** + * This method is to be called each time an operation is happening on Runner + * + * @throws OpenR66RunnerErrorException + */ + public void saveStatus() throws OpenR66RunnerErrorException { + try { + update(); + } catch (WaarpDatabaseException e) { + throw new OpenR66RunnerErrorException(e); + } + } + + /** + * This method is to be called each time an operation is happening on Runner and it is forced + * (for SelfRequest handling) + * @return True if saved + * @throws OpenR66RunnerErrorException + */ + public boolean forceSaveStatus() { + boolean isSender = isSender(); + setSenderForUpdate(); + boolean status = true; + try { + saveStatus(); + } catch (OpenR66RunnerErrorException e) { + status = false; + } + setSender(isSender); + return status; + } + + /** + * Clear the runner + */ + public void clear() { + + } + + /** + * Delete the temporary empty file (retrieved file at rank 0) + */ + public void deleteTempFile() { + if ((!isSender()) && getRank() == 0) { + try { + if (session != null) { + R66File file = session.getFile(); + if (file != null) { + file.delete(); + } + } + } catch (CommandAbstractException e1) { + logger.warn("Cannot delete temporary empty file", e1); + } + } + } + + @Override + public String toString() { + return "Run: " + (rule != null ? rule.toString() : ruleId) + " on " + + filename + " STEP: " + TASKSTEP.values()[globalstep] + "(" + + TASKSTEP.values()[globallaststep] + "):" + step + ":" + + status.mesg + " Transfer Rank: " + rank + " Blocksize: " + blocksize + + " SpecialId: " + + specialId + " isSender: " + isSender + " isMoved: " + + isFileMoved + " Mode: " + TRANSFERMODE.values()[mode] + + " Requester: " + requesterHostId + " Requested: " + + requestedHostId + " Start: " + start + " Stop: " + stop + + " Internal: " + UpdatedInfo.values()[updatedInfo].name() + + ":" + infostatus.mesg + " OriginalSize: " + originalSize + + " Fileinfo: " + fileInformation; + } + + public String toLogRunStep() { + return "Run: " + ruleId + " on " + + filename + " STEP: " + TASKSTEP.values()[globalstep] + "(" + + TASKSTEP.values()[globallaststep] + "):" + step + ":" + + status.mesg; + } + + public String toShortNoHtmlString(String newline) { + return "Run: " + ruleId + " on " + + filename + newline + " STEP: " + TASKSTEP.values()[globalstep] + "(" + + TASKSTEP.values()[globallaststep] + "):" + step + ":" + + status.mesg + newline + " Transfer Rank: " + rank + " Blocksize: " + blocksize + + " SpecialId: " + + specialId + " isSender: " + isSender + " isMoved: " + + isFileMoved + " Mode: " + TRANSFERMODE.values()[mode] + + newline + " Requester: " + requesterHostId + " Requested: " + + requestedHostId + " Start: " + start + " Stop: " + stop + + newline + " Internal: " + UpdatedInfo.values()[updatedInfo].name() + + ":" + infostatus.mesg + " OriginalSize: " + originalSize + + newline + " Fileinfo: " + fileInformation; + } + + public String toShortString() { + return "" + ruleId + "" + specialId + "" + + filename + "\n " + TASKSTEP.values()[globalstep] + + "(" + TASKSTEP.values()[globallaststep] + "):" + step + ":" + + status.mesg + "" + rank + "" + blocksize + + "\n " + + isSender + "" + isFileMoved + "" + + TRANSFERMODE.values()[mode] + "\n " + + requesterHostId + "" + requestedHostId + + "\n " + start + "" + stop + + "\n " + UpdatedInfo.values()[updatedInfo].name() + + " : " + infostatus.mesg + "" + originalSize +"\n " + + fileInformation + ""; + } + + /** + * + * @return the header for a table of runners in Html format + */ + public static String headerHtml() { + return ""; + } + + /** + * @param session + * @return The associated freespace of the current directory + */ + public long freespace(R66Session session) { + long freespace = -1; + DbRule rule = null; + try { + rule = (this.rule != null) ? this.rule : new DbRule(this.dbSession, + this.ruleId); + } catch (WaarpDatabaseException e) { + } + if (this.rule == null) { + this.rule = rule; + } + if (rule != null) { + if (!this.isSender) { + try { + String sdir; + if (this.globallaststep == TASKSTEP.ALLDONETASK.ordinal()) { + // all finished + sdir = rule.recvPath; + } else if (this.globallaststep == TASKSTEP.POSTTASK + .ordinal()) { + // Post task + sdir = rule.recvPath; + } else { + // are we in sending or receive + sdir = rule.workPath; + } + R66Dir dir; + if (session.dirsFromSession.containsKey(sdir)) { + dir = session.dirsFromSession.get(sdir); + } else { + dir = new R66Dir(session); + dir.changeDirectory(sdir); + session.dirsFromSession.put(sdir, dir); + } + freespace = dir.getFreeSpace() / 0x100000L; + } catch (CommandAbstractException e) { + logger.warn("Error while freespace compute {}", e.getMessage(), e); + } + } + } + return freespace; + } + + private String bandwidth() { + double drank = (rank <= 0 ? 1 : rank); + double dblocksize = blocksize * 8; + double size = drank * dblocksize; + double time = (stop.getTime() + 1 - start.getTime()); + double result = size / time / ((double) 0x100000L) * ((double) 1000); + return String.format("%,.2f", result); + } + + private String getHtmlColor() { + String color; + switch (TASKSTEP.values()[globalstep]) { + case NOTASK: + color = "Orange"; + break; + case PRETASK: + color = "Yellow"; + break; + case TRANSFERTASK: + color = "LightGreen"; + break; + case POSTTASK: + color = "Turquoise"; + break; + case ERRORTASK: + color = "Red"; + break; + case ALLDONETASK: + color = "Cyan"; + break; + default: + color = ""; + } + return color; + } + + private String getInfoHtmlColor() { + String color; + switch (UpdatedInfo.values()[updatedInfo]) { + case DONE: + color = "Cyan"; + break; + case INERROR: + color = "Red"; + break; + case INTERRUPTED: + color = "Orange"; + break; + case NOTUPDATED: + color = "Yellow"; + break; + case RUNNING: + color = "LightGreen"; + break; + case TOSUBMIT: + color = "Turquoise"; + break; + case UNKNOWN: + color = "Turquoise"; + break; + default: + color = ""; + } + return color; + } + + /** + * @param session + * @param running + * special info + * @return the runner in Html format compatible with the header from headerHtml method + */ + public String toHtml(R66Session session, String running) { + long freespace = freespace(session); + String color = getHtmlColor(); + String updcolor = getInfoHtmlColor(); + return "" + ""; + } + + /** + * @param session + * @param body + * @param running + * special info + * @return the runner in Html format specified by body by replacing all instance of fields + */ + public String toSpecializedHtml(R66Session session, String body, String running) { + long freespace = freespace(session); + StringBuilder builder = new StringBuilder(body); + WaarpStringUtils.replaceAll(builder, "XXXSpecIdXXX", Long.toString(specialId)); + WaarpStringUtils.replace(builder, "XXXRulXXX", (rule != null ? rule.toShortString() + : ruleId)); + WaarpStringUtils.replace(builder, "XXXFileXXX", filename); + WaarpStringUtils.replace(builder, "XXXInfoXXX", fileInformation); + WaarpStringUtils.replace(builder, "XXXStepXXX", TASKSTEP.values()[globalstep] + " (" + + TASKSTEP.values()[globallaststep] + ")"); + WaarpStringUtils.replace(builder, "XXXCOLXXX", getHtmlColor()); + WaarpStringUtils.replace(builder, "XXXActXXX", Integer.toString(step)); + WaarpStringUtils.replace(builder, "XXXStatXXX", status.mesg); + WaarpStringUtils.replace(builder, "XXXRunningXXX", running); + WaarpStringUtils.replace(builder, "XXXInternXXX", UpdatedInfo.values()[updatedInfo].name() + + " : " + infostatus.mesg); + WaarpStringUtils.replace(builder, "XXXUPDCOLXXX", getInfoHtmlColor()); + WaarpStringUtils.replace(builder, "XXXBloXXX", Integer.toString(rank)); + WaarpStringUtils.replace(builder, "XXXisSendXXX", Boolean.toString(isSender)); + WaarpStringUtils.replace(builder, "XXXisMovXXX", Boolean.toString(isFileMoved)); + WaarpStringUtils.replace(builder, "XXXModXXX", TRANSFERMODE.values()[mode].toString()); + WaarpStringUtils.replaceAll(builder, "XXXReqrXXX", requesterHostId); + WaarpStringUtils.replaceAll(builder, "XXXReqdXXX", requestedHostId); + WaarpStringUtils.replace(builder, "XXXStarXXX", start.toString()); + WaarpStringUtils.replace(builder, "XXXStopXXX", stop.toString()); + WaarpStringUtils.replace(builder, "XXXBandXXX", bandwidth()); + WaarpStringUtils.replace(builder, "XXXFreeXXX", Long.toString(freespace)); + return builder.toString(); + } + + /** + * + * @return True if the current host is the requested host (to prevent request to itself) + */ + public boolean isSelfRequested() { + if (this.requestedHostId.equals(Configuration.configuration.HOST_ID) || + this.requestedHostId.equals(Configuration.configuration.HOST_SSLID)) { + // check if not calling itself + return (! this.requesterHostId.equals(Configuration.configuration.HOST_ID) && + ! this.requesterHostId.equals(Configuration.configuration.HOST_SSLID)); + } + return false; + } + + + /** + * + * @return True if the request is a self request (same host on both side) + */ + public boolean isSelfRequest() { + return ((this.requestedHostId.equals(Configuration.configuration.HOST_ID) || + this.requestedHostId.equals(Configuration.configuration.HOST_SSLID)) && + (this.requesterHostId.equals(Configuration.configuration.HOST_ID) || + this.requesterHostId.equals(Configuration.configuration.HOST_SSLID))); + } + + /** + * + * @return the requested HostId + */ + public String getRequested() { + return this.requestedHostId; + } + + /** + * + * @return the requester HostId + */ + public String getRequester() { + return this.requesterHostId; + } + + /** + * @return the start + */ + public Timestamp getStart() { + return start; + } + + /** + * @param start + * new Start time to apply when reschedule + */ + public void setStart(Timestamp start) { + this.start = start; + allFields[Columns.STARTTRANS.ordinal()].setValue(this.start); + } + + /** + * @return the stop + */ + public Timestamp getStop() { + return stop; + } + + /** + * + * @return the associated request + */ + public RequestPacket getRequest() { + return new RequestPacket(ruleId, mode, originalFilename, blocksize, + rank, specialId, fileInformation, originalSize); + } + + /** + * Used internally + * + * @return a Key representing the primary key as a unique string + */ + public String getKey() { + return requestedHostId + " " + requesterHostId + " " + specialId; + } + + /** + * Construct a new Element with value + * + * @param name + * @param value + * @return the new Element + */ + private static Element newElement(String name, String value) { + Element node = new DefaultElement(name); + if (value != null) { + node.addText(value); + } + return node; + } + + /** + * Need to call 'setToArray' before + * + * @param runner + * @return The Element representing the given Runner + * @throws WaarpDatabaseSqlException + */ + private static Element getElementFromRunner(DbTaskRunner runner) + throws WaarpDatabaseSqlException { + Element root = new DefaultElement(XMLRUNNER); + for (DbValue value : runner.allFields) { + if (value.column.equals(Columns.UPDATEDINFO.name())) { + continue; + } + root.add(newElement(value.column.toLowerCase(), value + .getValueAsString())); + } + return root; + } + + /** + * Set the given runner from the root element of the runner itself (XMLRUNNER but not + * XMLRUNNERS). Need to call 'setFromArray' after. + * + * @param runner + * @param root + * @throws WaarpDatabaseSqlException + */ + private static void setRunnerFromElement(DbTaskRunner runner, Element root) + throws WaarpDatabaseSqlException { + for (DbValue value : runner.allFields) { + if (value.column.equals(Columns.UPDATEDINFO.name())) { + continue; + } + Element elt = (Element) root.selectSingleNode(value.column.toLowerCase()); + if (elt != null) { + String newValue = elt.getText(); + value.setValueFromString(newValue); + } + } + } + + /** + * Write the selected TaskRunners from PrepareStatement to a XMLWriter + * + * @param preparedStatement + * ready to be executed + * @param xmlWriter + * @return the NbAndSpecialId for the number of transfer and higher rank found + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + * @throws OpenR66ProtocolBusinessException + */ + public static NbAndSpecialId writeXML(DbPreparedStatement preparedStatement, XMLWriter xmlWriter) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, + OpenR66ProtocolBusinessException { + Element root = new DefaultElement(XMLRUNNERS); + NbAndSpecialId nbAndSpecialId = new NbAndSpecialId(); + try { + xmlWriter.writeOpen(root); + Element node; + while (preparedStatement.getNext()) { + DbTaskRunner runner = DbTaskRunner + .getFromStatement(preparedStatement); + if (nbAndSpecialId.higherSpecialId < runner.specialId) { + nbAndSpecialId.higherSpecialId = runner.specialId; + } + node = DbTaskRunner.getElementFromRunner(runner); + xmlWriter.write(node); + xmlWriter.flush(); + nbAndSpecialId.nb++; + } + xmlWriter.writeClose(root); + } catch (IOException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Cannot write file: " + e.getMessage()); + } + return nbAndSpecialId; + } + + /** + * Write selected TaskRunners to an XML file using an XMLWriter + * + * @param preparedStatement + * @param filename + * @return the NbAndSpecialId for the number of transfer and higher rank found + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + * @throws OpenR66ProtocolBusinessException + */ + public static NbAndSpecialId writeXMLWriter(DbPreparedStatement preparedStatement, + String filename) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, + OpenR66ProtocolBusinessException { + NbAndSpecialId nbAndSpecialId = null; + OutputStream outputStream = null; + XMLWriter xmlWriter = null; + try { + outputStream = new FileOutputStream(filename); + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding("ISO-8859-1"); + xmlWriter = new XMLWriter(outputStream, format); + preparedStatement.executeQuery(); + nbAndSpecialId = writeXML(preparedStatement, xmlWriter); + } catch (FileNotFoundException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("File not found"); + } catch (UnsupportedEncodingException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } finally { + if (xmlWriter != null) { + try { + xmlWriter.endDocument(); + xmlWriter.flush(); + xmlWriter.close(); + } catch (SAXException e) { + try { + outputStream.close(); + } catch (IOException e2) { + } + File file = new File(filename); + file.delete(); + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } catch (IOException e) { + try { + outputStream.close(); + } catch (IOException e2) { + } + File file = new File(filename); + file.delete(); + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } + } else if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + } + File file = new File(filename); + file.delete(); + } + } + return nbAndSpecialId; + } + + /** + * Write all TaskRunners to an XML file using an XMLWriter + * + * @param filename + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + * @throws OpenR66ProtocolBusinessException + */ + public static void writeXMLWriter(String filename) + throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, + OpenR66ProtocolBusinessException { + String request = "SELECT " + DbTaskRunner.selectAllFields + " FROM " + + DbTaskRunner.table + " WHERE " + getLimitWhereCondition(); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = new DbPreparedStatement( + DbConstant.admin.session); + preparedStatement.createPrepareStatement(request); + writeXMLWriter(preparedStatement, filename); + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + } + + /** + * + * @return the backend XML filename for the current TaskRunner in NoDb Client mode + */ + public String backendXmlFilename() { + return Configuration.configuration.baseDirectory + + Configuration.configuration.archivePath + R66Dir.SEPARATOR + + this.requesterHostId + "_" + this.requestedHostId + "_" + this.ruleId + "_" + + this.specialId + + XMLEXTENSION; + } + + /** + * Method to write the current DbTaskRunner for NoDb client instead of updating DB. 'setToArray' + * must be called priorly to be able to store the values. + * + * @throws OpenR66ProtocolBusinessException + */ + public void writeXmlWorkNoDb() throws OpenR66ProtocolBusinessException { + String filename = backendXmlFilename(); + OutputStream outputStream = null; + XMLWriter xmlWriter = null; + try { + outputStream = new FileOutputStream(filename); + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding("ISO-8859-1"); + xmlWriter = new XMLWriter(outputStream, format); + Element root = new DefaultElement(XMLRUNNERS); + try { + xmlWriter.writeOpen(root); + Element node; + node = DbTaskRunner.getElementFromRunner(this); + xmlWriter.write(node); + xmlWriter.flush(); + xmlWriter.writeClose(root); + } catch (IOException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Cannot write file: " + e.getMessage()); + } catch (WaarpDatabaseSqlException e) { + logger.error("Cannot write Data", e); + throw new OpenR66ProtocolBusinessException("Cannot write Data: " + e.getMessage()); + } + } catch (FileNotFoundException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("File not found"); + } catch (UnsupportedEncodingException e) { + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } finally { + if (xmlWriter != null) { + try { + xmlWriter.endDocument(); + xmlWriter.flush(); + xmlWriter.close(); + } catch (SAXException e) { + try { + outputStream.close(); + } catch (IOException e2) { + } + File file = new File(filename); + file.delete(); + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } catch (IOException e) { + try { + outputStream.close(); + } catch (IOException e2) { + } + File file = new File(filename); + file.delete(); + logger.error("Cannot write XML file", e); + throw new OpenR66ProtocolBusinessException("Unsupported Encoding"); + } + } else if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + } + File file = new File(filename); + file.delete(); + } + } + } + + /** + * Method to load a previous existing DbTaskRunner for NoDb client from File instead of from DB. + * 'setFromArray' must be called after. + * + * @throws OpenR66ProtocolBusinessException + */ + public void loadXmlWorkNoDb() throws OpenR66ProtocolBusinessException { + String filename = backendXmlFilename(); + File file = new File(filename); + if (!file.canRead()) { + throw new OpenR66ProtocolBusinessException("Backend XML file cannot be read"); + } + SAXReader reader = new SAXReader(); + Document document; + try { + document = reader.read(file); + } catch (DocumentException e) { + throw new OpenR66ProtocolBusinessException( + "Backend XML file cannot be read as an XML file"); + } + Element root = (Element) document.selectSingleNode("/" + XMLRUNNERS + "/" + XMLRUNNER); + try { + setRunnerFromElement(this, root); + } catch (WaarpDatabaseSqlException e) { + throw new OpenR66ProtocolBusinessException( + "Backend XML file is not conform to the model"); + } + } + + /** + * + * @return True if the backend XML for NoDb client is available for this TaskRunner + */ + public boolean existXmlWorkNoDb() { + String filename = backendXmlFilename(); + File file = new File(filename); + return file.canRead(); + } + + /** + * Delete the backend XML file for the current TaskRunner for NoDb Client + */ + public void deleteXmlWorkNoDb() { + File file = new File(backendXmlFilename()); + file.delete(); + } + + /** + * Utility for "self request" mode only + * @param sender + */ + public void setSender(boolean sender) { + this.isSender = sender; + } + /** + * Helper + * @param request + * @return isSender according to request + */ + public static boolean getSenderByRequestPacket(RequestPacket request) { + if (request.isToValidate()) { + return RequestPacket.isRecvMode(request.getMode()); + } + return ! RequestPacket.isRecvMode(request.getMode()); + } + /** + * Utility for "self request" + * @param requestToValidate + */ + public void setSenderByRequestToValidate(boolean requestToValidate) { + this.isSender = RequestPacket.isRecvMode(mode); + if (! requestToValidate) { + this.isSender = ! this.isSender; + } + } + /** + * Utility to force "update" + */ + private void setSenderForUpdate() { + if (isSelfRequest()) { + isSender = RequestPacket.isRecvMode(mode); + } + } + + /** + * @return the originalSize + */ + public long getOriginalSize() { + return originalSize; + } + + /** + * @param originalSize the originalSize to set + */ + public void setOriginalSize(long originalSize) { + this.originalSize = originalSize; + } + +} diff --git a/src/main/java/org/waarp/openr66/database/data/package-info.java b/src/main/java/org/waarp/openr66/database/data/package-info.java index 94ad96a3d..347cca84c 100644 --- a/src/main/java/org/waarp/openr66/database/data/package-info.java +++ b/src/main/java/org/waarp/openr66/database/data/package-info.java @@ -1,8 +1,8 @@ -/** - * Classes implementing Database Data model - * - * @apiviz.landmark - * @apiviz.uses {@link org.waarp.openr66.database} - */ -package org.waarp.openr66.database.data; - +/** + * Classes implementing Database Data model + * + * @apiviz.landmark + * @apiviz.uses {@link org.waarp.openr66.database} + */ +package org.waarp.openr66.database.data; + diff --git a/src/main/java/org/waarp/openr66/database/model/DbModelFactory.java b/src/main/java/org/waarp/openr66/database/model/DbModelFactory.java index 3bf67c2e6..db749d6e5 100644 --- a/src/main/java/org/waarp/openr66/database/model/DbModelFactory.java +++ b/src/main/java/org/waarp/openr66/database/model/DbModelFactory.java @@ -1,66 +1,66 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.model; - -import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.model.DbType; - -/** - * Factory to store the Database Model object - * - * @author Frederic Bregier - * - */ -public class DbModelFactory extends org.waarp.common.database.model.DbModelFactory { - - /** - * Initialize the Database Model according to arguments. - * - * @param dbdriver - * @param dbserver - * @param dbuser - * @param dbpasswd - * @param write - * @throws WaarpDatabaseNoConnectionException - */ - public static DbAdmin initialize(String dbdriver, String dbserver, - String dbuser, String dbpasswd, boolean write) - throws WaarpDatabaseNoConnectionException { - DbType type = DbType.getFromDriver(dbdriver); - switch (type) { - case H2: - dbModel = new DbModelH2(dbserver, dbuser, dbpasswd); - break; - case Oracle: - dbModel = new DbModelOracle(dbserver, dbuser, dbpasswd); - break; - case PostGreSQL: - dbModel = new DbModelPostgresql(); - break; - case MySQL: - dbModel = new DbModelMysql(dbserver, dbuser, dbpasswd); - break; - default: - throw new WaarpDatabaseNoConnectionException( - "TypeDriver unknown: " + type); - } - return new DbAdmin(type, dbserver, dbuser, dbpasswd, - write); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.model; + +import org.waarp.common.database.DbAdmin; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.model.DbType; + +/** + * Factory to store the Database Model object + * + * @author Frederic Bregier + * + */ +public class DbModelFactory extends org.waarp.common.database.model.DbModelFactory { + + /** + * Initialize the Database Model according to arguments. + * + * @param dbdriver + * @param dbserver + * @param dbuser + * @param dbpasswd + * @param write + * @throws WaarpDatabaseNoConnectionException + */ + public static DbAdmin initialize(String dbdriver, String dbserver, + String dbuser, String dbpasswd, boolean write) + throws WaarpDatabaseNoConnectionException { + DbType type = DbType.getFromDriver(dbdriver); + switch (type) { + case H2: + dbModel = new DbModelH2(dbserver, dbuser, dbpasswd); + break; + case Oracle: + dbModel = new DbModelOracle(dbserver, dbuser, dbpasswd); + break; + case PostGreSQL: + dbModel = new DbModelPostgresql(); + break; + case MySQL: + dbModel = new DbModelMysql(dbserver, dbuser, dbpasswd); + break; + default: + throw new WaarpDatabaseNoConnectionException( + "TypeDriver unknown: " + type); + } + return new DbAdmin(type, dbserver, dbuser, dbpasswd, + write); + } +} diff --git a/src/main/java/org/waarp/openr66/database/model/DbModelH2.java b/src/main/java/org/waarp/openr66/database/model/DbModelH2.java index 25e7bd761..5c9390c31 100644 --- a/src/main/java/org/waarp/openr66/database/model/DbModelH2.java +++ b/src/main/java/org/waarp/openr66/database/model/DbModelH2.java @@ -1,312 +1,312 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.model; - -import java.sql.SQLException; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbRequest; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.data.DbMultipleMonitor; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * H2 Database Model implementation - * - * @author Frederic Bregier - * - */ -public class DbModelH2 extends org.waarp.common.database.model.DbModelH2 { - /** - * Create the object and initialize if necessary the driver - * - * @param dbserver - * @param dbuser - * @param dbpasswd - * @throws WaarpDatabaseNoConnectionException - */ - public DbModelH2(String dbserver, String dbuser, String dbpasswd) - throws WaarpDatabaseNoConnectionException { - super(dbserver, dbuser, dbpasswd); - } - - @Override - public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { - // Create tables: configuration, hosts, rules, runner, cptrunner - String createTableH2 = "CREATE TABLE IF NOT EXISTS "; - String primaryKey = " PRIMARY KEY "; - String notNull = " NOT NULL "; - - // Multiple Mode - String action = createTableH2 + DbMultipleMonitor.table + "("; - DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns - .values(); - for (int i = 0; i < mcolumns.length - 1; i++) { - action += mcolumns[i].name() + - DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + - ", "; - } - action += mcolumns[mcolumns.length - 1].name() + - DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, - Configuration.configuration.HOST_ID, 0, 0, 0); - try { - if (!multipleMonitor.exist()) - multipleMonitor.insert(); - } catch (WaarpDatabaseException e1) { - e1.printStackTrace(); - } - - // Configuration - action = createTableH2 + DbConfiguration.table + "("; - DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns - .values(); - for (int i = 0; i < ccolumns.length - 1; i++) { - action += ccolumns[i].name() + - DBType.getType(DbConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += ccolumns[ccolumns.length - 1].name() + - DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // HostConfiguration - action = createTableH2 + DbHostConfiguration.table + "("; - DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns - .values(); - for (int i = 0; i < chcolumns.length - 1; i++) { - action += chcolumns[i].name() + - DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += chcolumns[chcolumns.length - 1].name() + - DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // hosts - action = createTableH2 + DbHostAuth.table + "("; - DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); - for (int i = 0; i < hcolumns.length - 1; i++) { - action += hcolumns[i].name() + - DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; - } - action += hcolumns[hcolumns.length - 1].name() + - DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // rules - action = createTableH2 + DbRule.table + "("; - DbRule.Columns[] rcolumns = DbRule.Columns.values(); - for (int i = 0; i < rcolumns.length - 1; i++) { - action += rcolumns[i].name() + - DBType.getType(DbRule.dbTypes[i]) + ", "; - } - action += rcolumns[rcolumns.length - 1].name() + - DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // runner - action = createTableH2 + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); - for (int i = 0; i < acolumns.length; i++) { - action += acolumns[i].name() + - DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; - } - // Several columns for primary key - action += " CONSTRAINT runner_pk " + primaryKey + "("; - for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { - action += acolumns[acolumns.length - i].name() + ","; - } - action += acolumns[acolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - // Index Runner - action = "CREATE INDEX IF NOT EXISTS IDX_RUNNER ON " + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; - for (int i = 0; i < icolumns.length - 1; i++) { - action += icolumns[i].name() + ", "; - } - action += icolumns[icolumns.length - 1].name() + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // cptrunner - action = "CREATE SEQUENCE IF NOT EXISTS " + DbTaskRunner.fieldseq + - " START WITH " + (DbConstant.ILLEGALVALUE + 1); - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() - */ - @Override - public void resetSequence(DbSession session, long newvalue) - throws WaarpDatabaseNoConnectionException { - String action = "ALTER SEQUENCE " + DbTaskRunner.fieldseq + - " RESTART WITH " + newvalue; - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - return; - } finally { - request.close(); - } - System.out.println(action); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() - */ - @Override - public long nextSequence(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException { - long result = DbConstant.ILLEGALVALUE; - String action = "SELECT NEXTVAL('" + DbTaskRunner.fieldseq + "')"; - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement(action); - // Limit the search - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - try { - result = preparedStatement.getResultSet().getLong(1); - } catch (SQLException e) { - throw new WaarpDatabaseSqlException(e); - } - return result; - } else { - throw new WaarpDatabaseNoDataException( - "No sequence found. Must be initialized first"); - } - } finally { - preparedStatement.realClose(); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.model; + +import java.sql.SQLException; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbRequest; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.data.DbMultipleMonitor; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * H2 Database Model implementation + * + * @author Frederic Bregier + * + */ +public class DbModelH2 extends org.waarp.common.database.model.DbModelH2 { + /** + * Create the object and initialize if necessary the driver + * + * @param dbserver + * @param dbuser + * @param dbpasswd + * @throws WaarpDatabaseNoConnectionException + */ + public DbModelH2(String dbserver, String dbuser, String dbpasswd) + throws WaarpDatabaseNoConnectionException { + super(dbserver, dbuser, dbpasswd); + } + + @Override + public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { + // Create tables: configuration, hosts, rules, runner, cptrunner + String createTableH2 = "CREATE TABLE IF NOT EXISTS "; + String primaryKey = " PRIMARY KEY "; + String notNull = " NOT NULL "; + + // Multiple Mode + String action = createTableH2 + DbMultipleMonitor.table + "("; + DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns + .values(); + for (int i = 0; i < mcolumns.length - 1; i++) { + action += mcolumns[i].name() + + DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + + ", "; + } + action += mcolumns[mcolumns.length - 1].name() + + DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, + Configuration.configuration.HOST_ID, 0, 0, 0); + try { + if (!multipleMonitor.exist()) + multipleMonitor.insert(); + } catch (WaarpDatabaseException e1) { + e1.printStackTrace(); + } + + // Configuration + action = createTableH2 + DbConfiguration.table + "("; + DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns + .values(); + for (int i = 0; i < ccolumns.length - 1; i++) { + action += ccolumns[i].name() + + DBType.getType(DbConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += ccolumns[ccolumns.length - 1].name() + + DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // HostConfiguration + action = createTableH2 + DbHostConfiguration.table + "("; + DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns + .values(); + for (int i = 0; i < chcolumns.length - 1; i++) { + action += chcolumns[i].name() + + DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += chcolumns[chcolumns.length - 1].name() + + DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // hosts + action = createTableH2 + DbHostAuth.table + "("; + DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); + for (int i = 0; i < hcolumns.length - 1; i++) { + action += hcolumns[i].name() + + DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; + } + action += hcolumns[hcolumns.length - 1].name() + + DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // rules + action = createTableH2 + DbRule.table + "("; + DbRule.Columns[] rcolumns = DbRule.Columns.values(); + for (int i = 0; i < rcolumns.length - 1; i++) { + action += rcolumns[i].name() + + DBType.getType(DbRule.dbTypes[i]) + ", "; + } + action += rcolumns[rcolumns.length - 1].name() + + DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // runner + action = createTableH2 + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); + for (int i = 0; i < acolumns.length; i++) { + action += acolumns[i].name() + + DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; + } + // Several columns for primary key + action += " CONSTRAINT runner_pk " + primaryKey + "("; + for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { + action += acolumns[acolumns.length - i].name() + ","; + } + action += acolumns[acolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + // Index Runner + action = "CREATE INDEX IF NOT EXISTS IDX_RUNNER ON " + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; + for (int i = 0; i < icolumns.length - 1; i++) { + action += icolumns[i].name() + ", "; + } + action += icolumns[icolumns.length - 1].name() + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // cptrunner + action = "CREATE SEQUENCE IF NOT EXISTS " + DbTaskRunner.fieldseq + + " START WITH " + (DbConstant.ILLEGALVALUE + 1); + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() + */ + @Override + public void resetSequence(DbSession session, long newvalue) + throws WaarpDatabaseNoConnectionException { + String action = "ALTER SEQUENCE " + DbTaskRunner.fieldseq + + " RESTART WITH " + newvalue; + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + return; + } finally { + request.close(); + } + System.out.println(action); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() + */ + @Override + public long nextSequence(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException { + long result = DbConstant.ILLEGALVALUE; + String action = "SELECT NEXTVAL('" + DbTaskRunner.fieldseq + "')"; + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement(action); + // Limit the search + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + try { + result = preparedStatement.getResultSet().getLong(1); + } catch (SQLException e) { + throw new WaarpDatabaseSqlException(e); + } + return result; + } else { + throw new WaarpDatabaseNoDataException( + "No sequence found. Must be initialized first"); + } + } finally { + preparedStatement.realClose(); + } + } +} diff --git a/src/main/java/org/waarp/openr66/database/model/DbModelMysql.java b/src/main/java/org/waarp/openr66/database/model/DbModelMysql.java index bc78a104a..b8dab92cc 100644 --- a/src/main/java/org/waarp/openr66/database/model/DbModelMysql.java +++ b/src/main/java/org/waarp/openr66/database/model/DbModelMysql.java @@ -1,359 +1,359 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.model; - -import java.sql.SQLException; -import java.util.concurrent.locks.ReentrantLock; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbRequest; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.data.DbMultipleMonitor; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * MySQL Database Model implementation - * - * @author Frederic Bregier - * - */ -public class DbModelMysql extends org.waarp.common.database.model.DbModelMysql { - /** - * Create the object and initialize if necessary the driver - * - * @param dbserver - * @param dbuser - * @param dbpasswd - * @throws WaarpDatabaseNoConnectionException - */ - public DbModelMysql(String dbserver, String dbuser, String dbpasswd) - throws WaarpDatabaseNoConnectionException { - super(dbserver, dbuser, dbpasswd); - } - - private final ReentrantLock lock = new ReentrantLock(); - - @Override - public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { - // Create tables: configuration, hosts, rules, runner, cptrunner - String createTableH2 = "CREATE TABLE IF NOT EXISTS "; - String primaryKey = " PRIMARY KEY "; - String notNull = " NOT NULL "; - - // Multiple Mode - String action = createTableH2 + DbMultipleMonitor.table + "("; - DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns - .values(); - for (int i = 0; i < mcolumns.length - 1; i++) { - action += mcolumns[i].name() + - DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + - ", "; - } - action += mcolumns[mcolumns.length - 1].name() + - DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, - Configuration.configuration.HOST_ID, 0, 0, 0); - try { - if (!multipleMonitor.exist()) - multipleMonitor.insert(); - } catch (WaarpDatabaseException e1) { - e1.printStackTrace(); - } - - // Configuration - action = createTableH2 + DbConfiguration.table + "("; - DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns - .values(); - for (int i = 0; i < ccolumns.length - 1; i++) { - action += ccolumns[i].name() + - DBType.getType(DbConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += ccolumns[ccolumns.length - 1].name() + - DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // HostConfiguration - action = createTableH2 + DbHostConfiguration.table + "("; - DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns - .values(); - for (int i = 0; i < chcolumns.length - 1; i++) { - action += chcolumns[i].name() + - DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += chcolumns[chcolumns.length - 1].name() + - DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // hosts - action = createTableH2 + DbHostAuth.table + "("; - DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); - for (int i = 0; i < hcolumns.length - 1; i++) { - action += hcolumns[i].name() + - DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; - } - action += hcolumns[hcolumns.length - 1].name() + - DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // rules - action = createTableH2 + DbRule.table + "("; - DbRule.Columns[] rcolumns = DbRule.Columns.values(); - for (int i = 0; i < rcolumns.length - 1; i++) { - action += rcolumns[i].name() + - DBType.getType(DbRule.dbTypes[i]) + ", "; - } - action += rcolumns[rcolumns.length - 1].name() + - DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // runner - action = createTableH2 + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); - for (int i = 0; i < acolumns.length; i++) { - action += acolumns[i].name() + - DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; - } - // Several columns for primary key - action += " CONSTRAINT runner_pk " + primaryKey + "("; - for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { - action += acolumns[acolumns.length - i].name() + ","; - } - action += acolumns[acolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - // Index Runner - action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; - for (int i = 0; i < icolumns.length - 1; i++) { - action += icolumns[i].name() + ", "; - } - action += icolumns[icolumns.length - 1].name() + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // cptrunner - /* - * # Table to handle any number of sequences: CREATE TABLE Sequences ( name VARCHAR(22) NOT - * NULL, seq INT UNSIGNED NOT NULL, # (or BIGINT) PRIMARY KEY name ); # Create a Sequence: - * INSERT INTO Sequences (name, seq) VALUES (?, 0); # Drop a Sequence: DELETE FROM Sequences - * WHERE name = ?; # Get a sequence number: UPDATE Sequences SET seq = LAST_INSERT_ID(seq + - * 1) WHERE name = ?; $seq = $db->LastInsertId(); - */ - action = "CREATE TABLE Sequences (name VARCHAR(22) NOT NULL PRIMARY KEY," + - "seq BIGINT NOT NULL)"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - action = "INSERT INTO Sequences (name, seq) VALUES ('" + DbTaskRunner.fieldseq + "', " + - (DbConstant.ILLEGALVALUE + 1) + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() - */ - @Override - public void resetSequence(DbSession session, long newvalue) - throws WaarpDatabaseNoConnectionException { - String action = "UPDATE Sequences SET seq = " + newvalue + - " WHERE name = '" + DbTaskRunner.fieldseq + "'"; - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - return; - } finally { - request.close(); - } - System.out.println(action); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() - */ - @Override - public synchronized long nextSequence(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException { - lock.lock(); - try { - long result = DbConstant.ILLEGALVALUE; - String action = "SELECT seq FROM Sequences WHERE name = '" + - DbTaskRunner.fieldseq + "' FOR UPDATE"; - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - dbSession.conn.setAutoCommit(false); - } catch (SQLException e1) { - } - try { - preparedStatement.createPrepareStatement(action); - // Limit the search - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - try { - result = preparedStatement.getResultSet().getLong(1); - } catch (SQLException e) { - throw new WaarpDatabaseSqlException(e); - } - } else { - throw new WaarpDatabaseNoDataException( - "No sequence found. Must be initialized first"); - } - } finally { - preparedStatement.realClose(); - } - action = "UPDATE Sequences SET seq = " + (result + 1) + - " WHERE name = '" + DbTaskRunner.fieldseq + "'"; - try { - preparedStatement.createPrepareStatement(action); - // Limit the search - preparedStatement.executeUpdate(); - } finally { - preparedStatement.realClose(); - } - return result; - } finally { - try { - dbSession.conn.setAutoCommit(true); - } catch (SQLException e1) { - } - lock.unlock(); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.model; + +import java.sql.SQLException; +import java.util.concurrent.locks.ReentrantLock; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbRequest; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.data.DbMultipleMonitor; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * MySQL Database Model implementation + * + * @author Frederic Bregier + * + */ +public class DbModelMysql extends org.waarp.common.database.model.DbModelMysql { + /** + * Create the object and initialize if necessary the driver + * + * @param dbserver + * @param dbuser + * @param dbpasswd + * @throws WaarpDatabaseNoConnectionException + */ + public DbModelMysql(String dbserver, String dbuser, String dbpasswd) + throws WaarpDatabaseNoConnectionException { + super(dbserver, dbuser, dbpasswd); + } + + private final ReentrantLock lock = new ReentrantLock(); + + @Override + public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { + // Create tables: configuration, hosts, rules, runner, cptrunner + String createTableH2 = "CREATE TABLE IF NOT EXISTS "; + String primaryKey = " PRIMARY KEY "; + String notNull = " NOT NULL "; + + // Multiple Mode + String action = createTableH2 + DbMultipleMonitor.table + "("; + DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns + .values(); + for (int i = 0; i < mcolumns.length - 1; i++) { + action += mcolumns[i].name() + + DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + + ", "; + } + action += mcolumns[mcolumns.length - 1].name() + + DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, + Configuration.configuration.HOST_ID, 0, 0, 0); + try { + if (!multipleMonitor.exist()) + multipleMonitor.insert(); + } catch (WaarpDatabaseException e1) { + e1.printStackTrace(); + } + + // Configuration + action = createTableH2 + DbConfiguration.table + "("; + DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns + .values(); + for (int i = 0; i < ccolumns.length - 1; i++) { + action += ccolumns[i].name() + + DBType.getType(DbConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += ccolumns[ccolumns.length - 1].name() + + DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // HostConfiguration + action = createTableH2 + DbHostConfiguration.table + "("; + DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns + .values(); + for (int i = 0; i < chcolumns.length - 1; i++) { + action += chcolumns[i].name() + + DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += chcolumns[chcolumns.length - 1].name() + + DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // hosts + action = createTableH2 + DbHostAuth.table + "("; + DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); + for (int i = 0; i < hcolumns.length - 1; i++) { + action += hcolumns[i].name() + + DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; + } + action += hcolumns[hcolumns.length - 1].name() + + DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // rules + action = createTableH2 + DbRule.table + "("; + DbRule.Columns[] rcolumns = DbRule.Columns.values(); + for (int i = 0; i < rcolumns.length - 1; i++) { + action += rcolumns[i].name() + + DBType.getType(DbRule.dbTypes[i]) + ", "; + } + action += rcolumns[rcolumns.length - 1].name() + + DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // runner + action = createTableH2 + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); + for (int i = 0; i < acolumns.length; i++) { + action += acolumns[i].name() + + DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; + } + // Several columns for primary key + action += " CONSTRAINT runner_pk " + primaryKey + "("; + for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { + action += acolumns[acolumns.length - i].name() + ","; + } + action += acolumns[acolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + // Index Runner + action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; + for (int i = 0; i < icolumns.length - 1; i++) { + action += icolumns[i].name() + ", "; + } + action += icolumns[icolumns.length - 1].name() + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // cptrunner + /* + * # Table to handle any number of sequences: CREATE TABLE Sequences ( name VARCHAR(22) NOT + * NULL, seq INT UNSIGNED NOT NULL, # (or BIGINT) PRIMARY KEY name ); # Create a Sequence: + * INSERT INTO Sequences (name, seq) VALUES (?, 0); # Drop a Sequence: DELETE FROM Sequences + * WHERE name = ?; # Get a sequence number: UPDATE Sequences SET seq = LAST_INSERT_ID(seq + + * 1) WHERE name = ?; $seq = $db->LastInsertId(); + */ + action = "CREATE TABLE Sequences (name VARCHAR(22) NOT NULL PRIMARY KEY," + + "seq BIGINT NOT NULL)"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + action = "INSERT INTO Sequences (name, seq) VALUES ('" + DbTaskRunner.fieldseq + "', " + + (DbConstant.ILLEGALVALUE + 1) + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() + */ + @Override + public void resetSequence(DbSession session, long newvalue) + throws WaarpDatabaseNoConnectionException { + String action = "UPDATE Sequences SET seq = " + newvalue + + " WHERE name = '" + DbTaskRunner.fieldseq + "'"; + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + return; + } finally { + request.close(); + } + System.out.println(action); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() + */ + @Override + public synchronized long nextSequence(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException { + lock.lock(); + try { + long result = DbConstant.ILLEGALVALUE; + String action = "SELECT seq FROM Sequences WHERE name = '" + + DbTaskRunner.fieldseq + "' FOR UPDATE"; + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + dbSession.conn.setAutoCommit(false); + } catch (SQLException e1) { + } + try { + preparedStatement.createPrepareStatement(action); + // Limit the search + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + try { + result = preparedStatement.getResultSet().getLong(1); + } catch (SQLException e) { + throw new WaarpDatabaseSqlException(e); + } + } else { + throw new WaarpDatabaseNoDataException( + "No sequence found. Must be initialized first"); + } + } finally { + preparedStatement.realClose(); + } + action = "UPDATE Sequences SET seq = " + (result + 1) + + " WHERE name = '" + DbTaskRunner.fieldseq + "'"; + try { + preparedStatement.createPrepareStatement(action); + // Limit the search + preparedStatement.executeUpdate(); + } finally { + preparedStatement.realClose(); + } + return result; + } finally { + try { + dbSession.conn.setAutoCommit(true); + } catch (SQLException e1) { + } + lock.unlock(); + } + } +} diff --git a/src/main/java/org/waarp/openr66/database/model/DbModelOracle.java b/src/main/java/org/waarp/openr66/database/model/DbModelOracle.java index 39bcb527b..ebb43c9a0 100644 --- a/src/main/java/org/waarp/openr66/database/model/DbModelOracle.java +++ b/src/main/java/org/waarp/openr66/database/model/DbModelOracle.java @@ -1,324 +1,324 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.model; - -import java.sql.SQLException; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbRequest; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.data.DbMultipleMonitor; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Oracle Database Model implementation - * - * @author Frederic Bregier - * - */ -public class DbModelOracle extends org.waarp.common.database.model.DbModelOracle { - /** - * Create the object and initialize if necessary the driver - * - * @param dbserver - * @param dbuser - * @param dbpasswd - * @throws WaarpDatabaseNoConnectionException - */ - public DbModelOracle(String dbserver, String dbuser, String dbpasswd) - throws WaarpDatabaseNoConnectionException { - super(dbserver, dbuser, dbpasswd); - } - - @Override - public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { - // Create tables: configuration, hosts, rules, runner, cptrunner - String createTableH2 = "CREATE TABLE "; - String constraint = " CONSTRAINT "; - String primaryKey = " PRIMARY KEY "; - String notNull = " NOT NULL "; - - // Multiple Mode - String action = createTableH2 + DbMultipleMonitor.table + "("; - DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns - .values(); - for (int i = 0; i < mcolumns.length - 1; i++) { - action += mcolumns[i].name() + - DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + - ", "; - } - action += mcolumns[mcolumns.length - 1].name() + - DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + - notNull + ","; - action += constraint + " conf_pk " + primaryKey + "(" - + mcolumns[mcolumns.length - 1].name() + "))"; - System.out.println(action); - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, - Configuration.configuration.HOST_ID, 0, 0, 0); - try { - if (!multipleMonitor.exist()) { - multipleMonitor.insert(); - } - } catch (WaarpDatabaseException e1) { - e1.printStackTrace(); - } - - // Configuration - action = createTableH2 + DbConfiguration.table + "("; - DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns - .values(); - for (int i = 0; i < ccolumns.length - 1; i++) { - action += ccolumns[i].name() + - DBType.getType(DbConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += ccolumns[ccolumns.length - 1].name() + - DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + - notNull + ","; - action += constraint + " conf_pk " + primaryKey + "(" - + ccolumns[ccolumns.length - 1].name() + "))"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // HostConfiguration - action = createTableH2 + DbHostConfiguration.table + "("; - DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns - .values(); - for (int i = 0; i < chcolumns.length - 1; i++) { - action += chcolumns[i].name() + - DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += chcolumns[chcolumns.length - 1].name() + - DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + - notNull + ","; - action += constraint + " conf_pk " + primaryKey + "(" - + chcolumns[chcolumns.length - 1].name() + "))"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // hosts - action = createTableH2 + DbHostAuth.table + "("; - DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); - for (int i = 0; i < hcolumns.length - 1; i++) { - action += hcolumns[i].name() + - DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; - } - action += hcolumns[hcolumns.length - 1].name() + - DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + - notNull + ","; - action += constraint + " host_pk " + primaryKey + "(" - + hcolumns[hcolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // rules - action = createTableH2 + DbRule.table + "("; - DbRule.Columns[] rcolumns = DbRule.Columns.values(); - for (int i = 0; i < rcolumns.length - 1; i++) { - action += rcolumns[i].name() + - DBType.getType(DbRule.dbTypes[i]) + ", "; - } - action += rcolumns[rcolumns.length - 1].name() + - DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + - notNull + ","; - action += constraint + " rule_pk " + primaryKey + "(" - + rcolumns[rcolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // runner - action = createTableH2 + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); - for (int i = 0; i < acolumns.length; i++) { - action += acolumns[i].name() + - DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; - } - // Several columns for primary key - action += constraint + " runner_pk " + primaryKey + "("; - for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { - action += acolumns[acolumns.length - i].name() + ","; - } - action += acolumns[acolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - // Index Runner - action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; - for (int i = 0; i < icolumns.length - 1; i++) { - action += icolumns[i].name() + ", "; - } - action += icolumns[icolumns.length - 1].name() + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // cptrunner - action = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + - " MINVALUE " + (DbConstant.ILLEGALVALUE + 1) + - " START WITH " + (DbConstant.ILLEGALVALUE + 1); - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - return; - } finally { - request.close(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() - */ - @Override - public void resetSequence(DbSession session, long newvalue) - throws WaarpDatabaseNoConnectionException { - String action = "DROP SEQUENCE " + DbTaskRunner.fieldseq; - String action2 = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + - " MINVALUE " + (DbConstant.ILLEGALVALUE + 1) + - " START WITH " + (newvalue); - DbRequest request = new DbRequest(session); - try { - request.query(action); - request.query(action2); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - return; - } finally { - request.close(); - } - - System.out.println(action); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() - */ - @Override - public long nextSequence(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException { - long result = DbConstant.ILLEGALVALUE; - String action = "SELECT " + DbTaskRunner.fieldseq + ".NEXTVAL FROM DUAL"; - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement(action); - // Limit the search - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - try { - result = preparedStatement.getResultSet().getLong(1); - } catch (SQLException e) { - throw new WaarpDatabaseSqlException(e); - } - return result; - } else { - throw new WaarpDatabaseNoDataException( - "No sequence found. Must be initialized first"); - } - } finally { - preparedStatement.realClose(); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.model; + +import java.sql.SQLException; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbRequest; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.data.DbMultipleMonitor; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Oracle Database Model implementation + * + * @author Frederic Bregier + * + */ +public class DbModelOracle extends org.waarp.common.database.model.DbModelOracle { + /** + * Create the object and initialize if necessary the driver + * + * @param dbserver + * @param dbuser + * @param dbpasswd + * @throws WaarpDatabaseNoConnectionException + */ + public DbModelOracle(String dbserver, String dbuser, String dbpasswd) + throws WaarpDatabaseNoConnectionException { + super(dbserver, dbuser, dbpasswd); + } + + @Override + public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { + // Create tables: configuration, hosts, rules, runner, cptrunner + String createTableH2 = "CREATE TABLE "; + String constraint = " CONSTRAINT "; + String primaryKey = " PRIMARY KEY "; + String notNull = " NOT NULL "; + + // Multiple Mode + String action = createTableH2 + DbMultipleMonitor.table + "("; + DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns + .values(); + for (int i = 0; i < mcolumns.length - 1; i++) { + action += mcolumns[i].name() + + DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + + ", "; + } + action += mcolumns[mcolumns.length - 1].name() + + DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + + notNull + ","; + action += constraint + " conf_pk " + primaryKey + "(" + + mcolumns[mcolumns.length - 1].name() + "))"; + System.out.println(action); + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, + Configuration.configuration.HOST_ID, 0, 0, 0); + try { + if (!multipleMonitor.exist()) { + multipleMonitor.insert(); + } + } catch (WaarpDatabaseException e1) { + e1.printStackTrace(); + } + + // Configuration + action = createTableH2 + DbConfiguration.table + "("; + DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns + .values(); + for (int i = 0; i < ccolumns.length - 1; i++) { + action += ccolumns[i].name() + + DBType.getType(DbConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += ccolumns[ccolumns.length - 1].name() + + DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + + notNull + ","; + action += constraint + " conf_pk " + primaryKey + "(" + + ccolumns[ccolumns.length - 1].name() + "))"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // HostConfiguration + action = createTableH2 + DbHostConfiguration.table + "("; + DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns + .values(); + for (int i = 0; i < chcolumns.length - 1; i++) { + action += chcolumns[i].name() + + DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += chcolumns[chcolumns.length - 1].name() + + DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + + notNull + ","; + action += constraint + " conf_pk " + primaryKey + "(" + + chcolumns[chcolumns.length - 1].name() + "))"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // hosts + action = createTableH2 + DbHostAuth.table + "("; + DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); + for (int i = 0; i < hcolumns.length - 1; i++) { + action += hcolumns[i].name() + + DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; + } + action += hcolumns[hcolumns.length - 1].name() + + DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + + notNull + ","; + action += constraint + " host_pk " + primaryKey + "(" + + hcolumns[hcolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // rules + action = createTableH2 + DbRule.table + "("; + DbRule.Columns[] rcolumns = DbRule.Columns.values(); + for (int i = 0; i < rcolumns.length - 1; i++) { + action += rcolumns[i].name() + + DBType.getType(DbRule.dbTypes[i]) + ", "; + } + action += rcolumns[rcolumns.length - 1].name() + + DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + + notNull + ","; + action += constraint + " rule_pk " + primaryKey + "(" + + rcolumns[rcolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // runner + action = createTableH2 + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); + for (int i = 0; i < acolumns.length; i++) { + action += acolumns[i].name() + + DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; + } + // Several columns for primary key + action += constraint + " runner_pk " + primaryKey + "("; + for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { + action += acolumns[acolumns.length - i].name() + ","; + } + action += acolumns[acolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + // Index Runner + action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; + for (int i = 0; i < icolumns.length - 1; i++) { + action += icolumns[i].name() + ", "; + } + action += icolumns[icolumns.length - 1].name() + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // cptrunner + action = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + + " MINVALUE " + (DbConstant.ILLEGALVALUE + 1) + + " START WITH " + (DbConstant.ILLEGALVALUE + 1); + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + return; + } finally { + request.close(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() + */ + @Override + public void resetSequence(DbSession session, long newvalue) + throws WaarpDatabaseNoConnectionException { + String action = "DROP SEQUENCE " + DbTaskRunner.fieldseq; + String action2 = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + + " MINVALUE " + (DbConstant.ILLEGALVALUE + 1) + + " START WITH " + (newvalue); + DbRequest request = new DbRequest(session); + try { + request.query(action); + request.query(action2); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + return; + } finally { + request.close(); + } + + System.out.println(action); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() + */ + @Override + public long nextSequence(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException { + long result = DbConstant.ILLEGALVALUE; + String action = "SELECT " + DbTaskRunner.fieldseq + ".NEXTVAL FROM DUAL"; + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement(action); + // Limit the search + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + try { + result = preparedStatement.getResultSet().getLong(1); + } catch (SQLException e) { + throw new WaarpDatabaseSqlException(e); + } + return result; + } else { + throw new WaarpDatabaseNoDataException( + "No sequence found. Must be initialized first"); + } + } finally { + preparedStatement.realClose(); + } + } +} diff --git a/src/main/java/org/waarp/openr66/database/model/DbModelPostgresql.java b/src/main/java/org/waarp/openr66/database/model/DbModelPostgresql.java index bfdecfe05..d427a3ca7 100644 --- a/src/main/java/org/waarp/openr66/database/model/DbModelPostgresql.java +++ b/src/main/java/org/waarp/openr66/database/model/DbModelPostgresql.java @@ -1,308 +1,308 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.database.model; - -import java.sql.SQLException; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbRequest; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbConfiguration; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.data.DbMultipleMonitor; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * PostGreSQL Database Model implementation - * - * @author Frederic Bregier - * - */ -public class DbModelPostgresql extends org.waarp.common.database.model.DbModelPostgresql { - /** - * Create the object and initialize if necessary the driver - * - * @throws WaarpDatabaseNoConnectionException - */ - public DbModelPostgresql() throws WaarpDatabaseNoConnectionException { - super(); - } - - @Override - public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { - // Create tables: configuration, hosts, rules, runner, cptrunner - String createTableH2 = "CREATE TABLE "; - String primaryKey = " PRIMARY KEY "; - String notNull = " NOT NULL "; - - // Multiple Mode - String action = createTableH2 + DbMultipleMonitor.table + "("; - DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns - .values(); - for (int i = 0; i < mcolumns.length - 1; i++) { - action += mcolumns[i].name() + - DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + - ", "; - } - action += mcolumns[mcolumns.length - 1].name() + - DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, - Configuration.configuration.HOST_ID, 0, 0, 0); - try { - if (!multipleMonitor.exist()) - multipleMonitor.insert(); - } catch (WaarpDatabaseException e1) { - e1.printStackTrace(); - } - - // Configuration - action = createTableH2 + DbConfiguration.table + "("; - DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns - .values(); - for (int i = 0; i < ccolumns.length - 1; i++) { - action += ccolumns[i].name() + - DBType.getType(DbConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += ccolumns[ccolumns.length - 1].name() + - DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // HostConfiguration - action = createTableH2 + DbHostConfiguration.table + "("; - DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns - .values(); - for (int i = 0; i < chcolumns.length - 1; i++) { - action += chcolumns[i].name() + - DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + - ", "; - } - action += chcolumns[chcolumns.length - 1].name() + - DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // hosts - action = createTableH2 + DbHostAuth.table + "("; - DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); - for (int i = 0; i < hcolumns.length - 1; i++) { - action += hcolumns[i].name() + - DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; - } - action += hcolumns[hcolumns.length - 1].name() + - DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // rules - action = createTableH2 + DbRule.table + "("; - DbRule.Columns[] rcolumns = DbRule.Columns.values(); - for (int i = 0; i < rcolumns.length - 1; i++) { - action += rcolumns[i].name() + - DBType.getType(DbRule.dbTypes[i]) + ", "; - } - action += rcolumns[rcolumns.length - 1].name() + - DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + - primaryKey + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - - // runner - action = createTableH2 + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); - for (int i = 0; i < acolumns.length; i++) { - action += acolumns[i].name() + - DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; - } - // Several columns for primary key - action += " CONSTRAINT runner_pk " + primaryKey + "("; - for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { - action += acolumns[acolumns.length - i].name() + ","; - } - action += acolumns[acolumns.length - 1].name() + "))"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - // Index Runner - action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; - DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; - for (int i = 0; i < icolumns.length - 1; i++) { - action += icolumns[i].name() + ", "; - } - action += icolumns[icolumns.length - 1].name() + ")"; - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - // XXX FIX no return; - } finally { - request.close(); - } - - // cptrunner - action = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + - " MINVALUE " + (DbConstant.ILLEGALVALUE + 1); - System.out.println(action); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - // XXX FIX no return; - } finally { - request.close(); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() - */ - @Override - public void resetSequence(DbSession session, long newvalue) - throws WaarpDatabaseNoConnectionException { - String action = "ALTER SEQUENCE " + DbTaskRunner.fieldseq + - " RESTART WITH " + newvalue; - DbRequest request = new DbRequest(session); - try { - request.query(action); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - return; - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - return; - } finally { - request.close(); - } - System.out.println(action); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() - */ - @Override - public long nextSequence(DbSession dbSession) - throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException, WaarpDatabaseNoDataException { - long result = DbConstant.ILLEGALVALUE; - String action = "SELECT NEXTVAL('" + DbTaskRunner.fieldseq + "')"; - DbPreparedStatement preparedStatement = new DbPreparedStatement( - dbSession); - try { - preparedStatement.createPrepareStatement(action); - // Limit the search - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - try { - result = preparedStatement.getResultSet().getLong(1); - } catch (SQLException e) { - throw new WaarpDatabaseSqlException(e); - } - return result; - } else { - throw new WaarpDatabaseNoDataException( - "No sequence found. Must be initialized first"); - } - } finally { - preparedStatement.realClose(); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.database.model; + +import java.sql.SQLException; + +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbRequest; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbConfiguration; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.data.DbMultipleMonitor; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * PostGreSQL Database Model implementation + * + * @author Frederic Bregier + * + */ +public class DbModelPostgresql extends org.waarp.common.database.model.DbModelPostgresql { + /** + * Create the object and initialize if necessary the driver + * + * @throws WaarpDatabaseNoConnectionException + */ + public DbModelPostgresql() throws WaarpDatabaseNoConnectionException { + super(); + } + + @Override + public void createTables(DbSession session) throws WaarpDatabaseNoConnectionException { + // Create tables: configuration, hosts, rules, runner, cptrunner + String createTableH2 = "CREATE TABLE "; + String primaryKey = " PRIMARY KEY "; + String notNull = " NOT NULL "; + + // Multiple Mode + String action = createTableH2 + DbMultipleMonitor.table + "("; + DbMultipleMonitor.Columns[] mcolumns = DbMultipleMonitor.Columns + .values(); + for (int i = 0; i < mcolumns.length - 1; i++) { + action += mcolumns[i].name() + + DBType.getType(DbMultipleMonitor.dbTypes[i]) + notNull + + ", "; + } + action += mcolumns[mcolumns.length - 1].name() + + DBType.getType(DbMultipleMonitor.dbTypes[mcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + DbMultipleMonitor multipleMonitor = new DbMultipleMonitor(session, + Configuration.configuration.HOST_ID, 0, 0, 0); + try { + if (!multipleMonitor.exist()) + multipleMonitor.insert(); + } catch (WaarpDatabaseException e1) { + e1.printStackTrace(); + } + + // Configuration + action = createTableH2 + DbConfiguration.table + "("; + DbConfiguration.Columns[] ccolumns = DbConfiguration.Columns + .values(); + for (int i = 0; i < ccolumns.length - 1; i++) { + action += ccolumns[i].name() + + DBType.getType(DbConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += ccolumns[ccolumns.length - 1].name() + + DBType.getType(DbConfiguration.dbTypes[ccolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // HostConfiguration + action = createTableH2 + DbHostConfiguration.table + "("; + DbHostConfiguration.Columns[] chcolumns = DbHostConfiguration.Columns + .values(); + for (int i = 0; i < chcolumns.length - 1; i++) { + action += chcolumns[i].name() + + DBType.getType(DbHostConfiguration.dbTypes[i]) + notNull + + ", "; + } + action += chcolumns[chcolumns.length - 1].name() + + DBType.getType(DbHostConfiguration.dbTypes[chcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // hosts + action = createTableH2 + DbHostAuth.table + "("; + DbHostAuth.Columns[] hcolumns = DbHostAuth.Columns.values(); + for (int i = 0; i < hcolumns.length - 1; i++) { + action += hcolumns[i].name() + + DBType.getType(DbHostAuth.dbTypes[i]) + notNull + ", "; + } + action += hcolumns[hcolumns.length - 1].name() + + DBType.getType(DbHostAuth.dbTypes[hcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // rules + action = createTableH2 + DbRule.table + "("; + DbRule.Columns[] rcolumns = DbRule.Columns.values(); + for (int i = 0; i < rcolumns.length - 1; i++) { + action += rcolumns[i].name() + + DBType.getType(DbRule.dbTypes[i]) + ", "; + } + action += rcolumns[rcolumns.length - 1].name() + + DBType.getType(DbRule.dbTypes[rcolumns.length - 1]) + + primaryKey + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + + // runner + action = createTableH2 + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] acolumns = DbTaskRunner.Columns.values(); + for (int i = 0; i < acolumns.length; i++) { + action += acolumns[i].name() + + DBType.getType(DbTaskRunner.dbTypes[i]) + notNull + ", "; + } + // Several columns for primary key + action += " CONSTRAINT runner_pk " + primaryKey + "("; + for (int i = DbTaskRunner.NBPRKEY; i > 1; i--) { + action += acolumns[acolumns.length - i].name() + ","; + } + action += acolumns[acolumns.length - 1].name() + "))"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + // Index Runner + action = "CREATE INDEX IDX_RUNNER ON " + DbTaskRunner.table + "("; + DbTaskRunner.Columns[] icolumns = DbTaskRunner.indexes; + for (int i = 0; i < icolumns.length - 1; i++) { + action += icolumns[i].name() + ", "; + } + action += icolumns[icolumns.length - 1].name() + ")"; + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + // XXX FIX no return; + } finally { + request.close(); + } + + // cptrunner + action = "CREATE SEQUENCE " + DbTaskRunner.fieldseq + + " MINVALUE " + (DbConstant.ILLEGALVALUE + 1); + System.out.println(action); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + // XXX FIX no return; + } finally { + request.close(); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#resetSequence() + */ + @Override + public void resetSequence(DbSession session, long newvalue) + throws WaarpDatabaseNoConnectionException { + String action = "ALTER SEQUENCE " + DbTaskRunner.fieldseq + + " RESTART WITH " + newvalue; + DbRequest request = new DbRequest(session); + try { + request.query(action); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + return; + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + return; + } finally { + request.close(); + } + System.out.println(action); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.databaseold.model.DbModel#nextSequence() + */ + @Override + public long nextSequence(DbSession dbSession) + throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException, WaarpDatabaseNoDataException { + long result = DbConstant.ILLEGALVALUE; + String action = "SELECT NEXTVAL('" + DbTaskRunner.fieldseq + "')"; + DbPreparedStatement preparedStatement = new DbPreparedStatement( + dbSession); + try { + preparedStatement.createPrepareStatement(action); + // Limit the search + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + try { + result = preparedStatement.getResultSet().getLong(1); + } catch (SQLException e) { + throw new WaarpDatabaseSqlException(e); + } + return result; + } else { + throw new WaarpDatabaseNoDataException( + "No sequence found. Must be initialized first"); + } + } finally { + preparedStatement.realClose(); + } + } +} diff --git a/src/main/java/org/waarp/openr66/database/model/package-info.java b/src/main/java/org/waarp/openr66/database/model/package-info.java index 32ee299a7..428b9fa09 100644 --- a/src/main/java/org/waarp/openr66/database/model/package-info.java +++ b/src/main/java/org/waarp/openr66/database/model/package-info.java @@ -1,8 +1,8 @@ -/** - * Classes implementing Database Model (H2, Oracle, PostgreSQL, MySQL) - * - * @apiviz.landmark - * @apiviz.uses {@link org.waarp.openr66.database} - */ -package org.waarp.openr66.database.model; - +/** + * Classes implementing Database Model (H2, Oracle, PostgreSQL, MySQL) + * + * @apiviz.landmark + * @apiviz.uses {@link org.waarp.openr66.database} + */ +package org.waarp.openr66.database.model; + diff --git a/src/main/java/org/waarp/openr66/database/package-info.java b/src/main/java/org/waarp/openr66/database/package-info.java index e6e77b981..c6dacfbb0 100644 --- a/src/main/java/org/waarp/openr66/database/package-info.java +++ b/src/main/java/org/waarp/openr66/database/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Database access - * - * @apiviz.landmark - */ -package org.waarp.openr66.database; - +/** + * Classes implementing Database access + * + * @apiviz.landmark + */ +package org.waarp.openr66.database; + diff --git a/src/main/java/org/waarp/openr66/package-info.java b/src/main/java/org/waarp/openr66/package-info.java index cb444ae27..a9cf3b101 100644 --- a/src/main/java/org/waarp/openr66/package-info.java +++ b/src/main/java/org/waarp/openr66/package-info.java @@ -1,22 +1,22 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -/** - * @author "Frederic Bregier" - * - */ +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +/** + * @author "Frederic Bregier" + * + */ package org.waarp.openr66; \ No newline at end of file diff --git a/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java b/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java index 72adb076d..494f45005 100644 --- a/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java +++ b/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java @@ -1,1129 +1,1129 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.configuration; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.HashSet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.group.ChannelGroup; -import org.jboss.netty.channel.group.DefaultChannelGroup; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; -import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.jboss.netty.util.HashedWheelTimer; -import org.jboss.netty.util.ObjectSizeEstimator; -import org.jboss.netty.util.Timer; -import org.jboss.netty.util.internal.ExecutorUtil; -import org.waarp.common.crypto.Des; -import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; -import org.waarp.common.crypto.ssl.WaarpSslContextFactory; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; -import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; -import org.waarp.common.future.WaarpFuture; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.role.RoleDefault; -import org.waarp.common.utility.SystemPropertyUtil; -import org.waarp.common.utility.WaarpShutdownHook.ShutdownConfiguration; -import org.waarp.common.utility.WaarpThreadFactory; -import org.waarp.openr66.commander.InternalRunner; -import org.waarp.openr66.context.R66BusinessFactoryInterface; -import org.waarp.openr66.context.R66DefaultBusinessFactory; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.http.HttpPipelineFactory; -import org.waarp.openr66.protocol.http.adminssl.HttpSslPipelineFactory; -import org.waarp.openr66.protocol.localhandler.LocalTransaction; -import org.waarp.openr66.protocol.localhandler.Monitoring; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketSizeEstimator; -import org.waarp.openr66.protocol.networkhandler.ChannelTrafficHandler; -import org.waarp.openr66.protocol.networkhandler.GlobalTrafficHandler; -import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; -import org.waarp.openr66.protocol.networkhandler.R66ConstraintLimitHandler; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketSizeEstimator; -import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; -import org.waarp.openr66.protocol.snmp.R66PrivateMib; -import org.waarp.openr66.protocol.snmp.R66VariableFactory; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; -import org.waarp.openr66.protocol.utils.Version; -import org.waarp.openr66.thrift.R66ThriftServerService; -import org.waarp.snmp.WaarpMOFactory; -import org.waarp.snmp.WaarpSnmpAgent; - -/** - * Configuration class - * - * @author Frederic Bregier - */ -public class Configuration { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(Configuration.class); - - // Static values - /** - * General Configuration object - */ - public static Configuration configuration = new Configuration(); - - public static final String SnmpName = "Waarp OpenR66 SNMP"; - public static final int SnmpPrivateId = 66666; - public static final int SnmpR66Id = 66; - public static final String SnmpDefaultAuthor = "Frederic Bregier"; - public static final String SnmpVersion = "Waarp OpenR66 " - + Version.ID; - public static final String SnmpDefaultLocalization = "Paris, France"; - public static final int SnmpService = 72; - /** - * Time elapse for retry in ms - */ - public static final long RETRYINMS = 10; - - /** - * Number of retry before error - */ - public static final int RETRYNB = 3; - - /** - * Hack to say Windows or Unix (USR1 not OK on Windows) - */ - public static boolean ISUNIX; - - /** - * Default size for buffers (NIO) - */ - public static final int BUFFERSIZEDEFAULT = 0x10000; // 64K - - /** - * Time elapse for WRITE OR CLOSE WAIT elaps in ms - */ - public static final long WAITFORNETOP = 1000; - - /** - * Extension of file during transfer - */ - public static final String EXT_R66 = ".r66"; - - /** - * Rank to redo when a restart occurs - */ - public static int RANKRESTART = 30; - - /** - * FileParameter - */ - private static final FilesystemBasedFileParameterImpl fileParameter = - new FilesystemBasedFileParameterImpl(); - - public R66BusinessFactoryInterface r66BusinessFactory = new R66DefaultBusinessFactory(); - // Global Dynamic values - /** - * Version validation - */ - public boolean extendedProtocol = true; - /** - * Global digest - */ - public boolean globalDigest = true; - /** - * White List of allowed Partners to use Business Requests - */ - public HashSet businessWhiteSet = new HashSet(); - /** - * Roles list for identified partners - */ - public HashMap roles = new HashMap(); - /** - * Aliases list for identified partners - */ - public HashMap aliases = new HashMap(); - /** - * Actual Host ID - */ - public String HOST_ID; - /** - * Actual SSL Host ID - */ - public String HOST_SSLID; - /** - * Requester Host ID - */ - public String REQER_HOST_ID; - /** - * Requested Host ID - */ - public String REQED_HOST_ID; - - /** - * Server Administration user name - */ - public String ADMINNAME = null; - /** - * Server Administration Key - */ - private byte[] SERVERADMINKEY = null; - /** - * Server Administration Key file - */ - public String serverKeyFile = null; - /** - * Server Actual Authentication - */ - public DbHostAuth HOST_AUTH; - /** - * Server Actual SSL Authentication - */ - public DbHostAuth HOST_SSLAUTH; - - /** - * Default number of threads in pool for Server (true network listeners). Server will change - * this value on startup if not set. The value should be closed to the number of CPU. - */ - public int SERVER_THREAD = 8; - - /** - * Default number of threads in pool for Client. The value is for true client for Executor in - * the Pipeline for Business logic. The value does not indicate a limit of concurrent clients, - * but a limit on truly packet concurrent actions. - */ - public int CLIENT_THREAD = 80; - - /** - * Default session limit 64Mbit, so up to 16 full simultaneous clients - */ - public final long DEFAULT_SESSION_LIMIT = 0x800000L; - - /** - * Default global limit 1024Mbit - */ - public final long DEFAULT_GLOBAL_LIMIT = 0x8000000L; - - /** - * Default server port - */ - public int SERVER_PORT = 6666; - - /** - * Default SSL server port - */ - public int SERVER_SSLPORT = 6667; - - /** - * Default HTTP server port - */ - public int SERVER_HTTPPORT = 8066; - - /** - * Default HTTP server port - */ - public int SERVER_HTTPSPORT = 8067; - - /** - * Nb of milliseconds after connection is in timeout - */ - public long TIMEOUTCON = 30000; - - /** - * Size by default of block size for receive/sending files. Should be a multiple of 8192 - * (maximum = 2^30K due to block limitation to 4 bytes) - */ - public int BLOCKSIZE = 0x10000; // 64K - - /** - * Max global memory limit: default is 4GB - */ - public long maxGlobalMemory = 0x100000000L; - - /** - * Base Directory - */ - public String baseDirectory; - - /** - * In path (receive) - */ - public String inPath = null; - - /** - * Out path (send, copy, pending) - */ - public String outPath = null; - - /** - * Archive path - */ - public String archivePath = null; - - /** - * Working path - */ - public String workingPath = null; - - /** - * Config path - */ - public String configPath = null; - - /** - * Http Admin base - */ - public String httpBasePath = "src/main/admin/"; - - /** - * True if the service is going to shutdown - */ - public volatile boolean isShutdown = false; - - /** - * Limit in Write byte/s to apply globally to the FTP Server - */ - public long serverGlobalWriteLimit = DEFAULT_GLOBAL_LIMIT; - - /** - * Limit in Read byte/s to apply globally to the FTP Server - */ - public long serverGlobalReadLimit = DEFAULT_GLOBAL_LIMIT; - - /** - * Limit in Write byte/s to apply by session to the FTP Server - */ - public long serverChannelWriteLimit = DEFAULT_SESSION_LIMIT; - - /** - * Limit in Read byte/s to apply by session to the FTP Server - */ - public long serverChannelReadLimit = DEFAULT_SESSION_LIMIT; - - /** - * Any limitation on bandwidth active? - */ - public boolean anyBandwidthLimitation = false; - /** - * Delay in ms between two checks - */ - public long delayLimit = 10000; - - /** - * Does this OpenR66 server will use and accept SSL connections - */ - public boolean useSSL = false; - /** - * Does this OpenR66 server will use and accept non SSL connections - */ - public boolean useNOSSL = true; - /** - * Algorithm to use for Digest - */ - public FilesystemBasedDigest.DigestAlgo digest = DigestAlgo.MD5; - - /** - * Does this OpenR66 server will try to compress HTTP connections - */ - public boolean useHttpCompression = false; - - /** - * Does this OpenR66 server will use Waarp LocalExec Daemon for ExecTask and ExecMoveTask - */ - public boolean useLocalExec = false; - - /** - * Crypto Key - */ - public Des cryptoKey = null; - /** - * Associated file for CryptoKey - */ - public String cryptoFile = null; - - /** - * List of all Server Channels to enable the close call on them using Netty ChannelGroup - */ - protected ChannelGroup serverChannelGroup = null; - /** - * Does the current program running as Server - */ - public boolean isServer = false; - - /** - * ExecutorService Server Boss - */ - protected ExecutorService execServerBoss = Executors - .newCachedThreadPool(); - - /** - * ExecutorService Server Worker - */ - protected ExecutorService execServerWorker = Executors - .newCachedThreadPool(); - - /** - * ExecutorService Other Worker - */ - protected ExecutorService execOtherWorker = Executors - .newCachedThreadPool(); - - /** - * ChannelFactory for Server part - */ - protected ChannelFactory serverChannelFactory = null; - - /** - * ThreadPoolExecutor for Server - */ - protected volatile OrderedMemoryAwareThreadPoolExecutor serverPipelineExecutor; - - /** - * ThreadPoolExecutor for LocalServer - */ - private volatile OrderedMemoryAwareThreadPoolExecutor localPipelineExecutor; - - /** - * ThreadPoolExecutor for LocalClient - */ - private volatile OrderedMemoryAwareThreadPoolExecutor localClientPipelineExecutor; - - /** - * ThreadPoolExecutor for Http and Https Server - */ - protected volatile OrderedMemoryAwareThreadPoolExecutor httpPipelineExecutor; - - /** - * Bootstrap for server - */ - protected ServerBootstrap serverBootstrap = null; - - /** - * Bootstrap for SSL server - */ - protected ServerBootstrap serverSslBootstrap = null; - /** - * Factory for NON SSL Server - */ - protected NetworkServerPipelineFactory networkServerPipelineFactory; - /** - * Factory for SSL Server - */ - protected NetworkSslServerPipelineFactory networkSslServerPipelineFactory; - - /** - * Bootstrap for Http server - */ - protected ServerBootstrap httpBootstrap = null; - /** - * Bootstrap for Https server - */ - protected ServerBootstrap httpsBootstrap = null; - /** - * ChannelFactory for HttpServer part - */ - protected ChannelFactory httpChannelFactory = null; - /** - * ChannelFactory for HttpsServer part - */ - protected ChannelFactory httpsChannelFactory = null; - /** - * List of all Http Channels to enable the close call on them using Netty ChannelGroup - */ - protected ChannelGroup httpChannelGroup = null; - - /** - * Timer for CloseOpertations - */ - private Timer timerCloseOperations = - new HashedWheelTimer( - new WaarpThreadFactory( - "TimerClose"), - 50, - TimeUnit.MILLISECONDS, - 1024); - - /** - * Timer for TrafficCounter - */ - protected Timer timerTrafficCounter = - new HashedWheelTimer( - new WaarpThreadFactory( - "TimerTraffic"), - 10, - TimeUnit.MILLISECONDS, - 1024); - /** - * Global TrafficCounter (set from global configuration) - */ - protected volatile GlobalTrafficHandler globalTrafficShapingHandler = null; - - /** - * ObjectSizeEstimator - */ - protected ObjectSizeEstimator objectSizeEstimator = null; - - /** - * LocalTransaction - */ - protected LocalTransaction localTransaction; - /** - * InternalRunner - */ - private InternalRunner internalRunner; - /** - * Maximum number of concurrent active transfer by submission. - */ - public int RUNNER_THREAD = 1000; - /** - * Delay in ms between two steps of Commander - */ - public long delayCommander = 5000; - /** - * Delay in ms between two retries - */ - public long delayRetry = 30000; - /** - * Constraint Limit Handler on CPU usage and Connection limitation - */ - public R66ConstraintLimitHandler constraintLimitHandler = - new R66ConstraintLimitHandler(); - /** - * Do we check Remote Address from DbHost - */ - public boolean checkRemoteAddress = false; - /** - * Do we check address even for Client - */ - public boolean checkClientAddress = false; - /** - * For No Db client, do we saved TaskRunner in a XML - */ - public boolean saveTaskRunnerWithNoDb = false; - /** - * In case of Multiple OpenR66 monitor servers behing a load balancer (HA solution) - */ - public int multipleMonitors = 1; - /** - * Monitoring object - */ - public Monitoring monitoring = null; - /** - * Monitoring: how long in ms to get back in monitoring - */ - public long pastLimit = 86400000; // 24H - /** - * Monitoring: minimal interval in ms before redo real monitoring - */ - public long minimalDelay = 5000; // 5 - // seconds - /** - * Monitoring: snmp configuration file (empty means no snmp support) - */ - public String snmpConfig = null; - /** - * SNMP Agent (if any) - */ - public WaarpSnmpAgent agentSnmp = null; - /** - * Associated MIB - */ - public R66PrivateMib r66Mib = null; - - protected volatile boolean configured = false; - - public static WaarpSecureKeyStore WaarpSecureKeyStore; - - public static WaarpSslContextFactory waarpSslContextFactory; - /** - * Thrift support - */ - public R66ThriftServerService thriftService; - public int thriftport = -1; - - public boolean isExecuteErrorBeforeTransferAllowed = true; - - public ShutdownConfiguration shutdownConfiguration = new ShutdownConfiguration(); - - public Configuration() { - // Init signal handler - shutdownConfiguration.timeout = TIMEOUTCON; - new R66ShutdownHook(shutdownConfiguration); - computeNbThreads(); - // Init FiniteStates - R66FiniteDualStates.initR66FiniteStates(); - boolean value = SystemPropertyUtil.getBoolean("openr66.executebeforetransferred", true); - isExecuteErrorBeforeTransferAllowed = value; - } - - /** - * Configure the pipeline for client (to be called ony once) - */ - public void pipelineInit() { - if (configured) { - return; - } - localTransaction = new LocalTransaction(); - InternalLoggerFactory.setDefaultFactory(InternalLoggerFactory - .getDefaultFactory()); - objectSizeEstimator = new NetworkPacketSizeEstimator(); - httpPipelineInit(); - logger.warn("Server Thread: " + SERVER_THREAD + " Client Thread: " + CLIENT_THREAD - + " Runner Thread: " + RUNNER_THREAD); - serverPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( - CLIENT_THREAD, maxGlobalMemory / 10, maxGlobalMemory, 1000, - TimeUnit.MILLISECONDS, objectSizeEstimator, - new WaarpThreadFactory("ServerExecutor")); - localPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( - CLIENT_THREAD * 100, maxGlobalMemory / 10, maxGlobalMemory, - 1000, TimeUnit.MILLISECONDS, new LocalPacketSizeEstimator(), - new WaarpThreadFactory("LocalExecutor")); - localClientPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( - CLIENT_THREAD * 100, maxGlobalMemory / 10, maxGlobalMemory, - 1000, TimeUnit.MILLISECONDS, new LocalPacketSizeEstimator(), - new WaarpThreadFactory("LocalClientExecutor")); - if (useLocalExec) { - LocalExecClient.initialize(); - } - configured = true; - } - - public void httpPipelineInit() { - httpPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( - CLIENT_THREAD, maxGlobalMemory / 10, maxGlobalMemory, 1000, - TimeUnit.MILLISECONDS, objectSizeEstimator, new WaarpThreadFactory("HttpExecutor")); - } - - /** - * Startup the server - * - * @throws WaarpDatabaseSqlException - * @throws WaarpDatabaseNoConnectionException - */ - public void serverStartup() throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - isServer = true; - shutdownConfiguration.timeout = TIMEOUTCON; - R66ShutdownHook.addShutdownHook(); - if ((!useNOSSL) && (!useSSL)) { - logger.error("OpenR66 has neither NOSSL nor SSL support included! Stop here!"); - System.exit(-1); - } - pipelineInit(); - r66Startup(); - startHttpSupport(); - startMonitoring(); - } - - public void r66Startup() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { - logger.debug("Start R66: " + SERVER_PORT + ":" + useNOSSL + " " + SERVER_SSLPORT + ":" - + useSSL + ":" + HOST_SSLID); - // add into configuration - this.constraintLimitHandler.setServer(true); - // Global Server - serverChannelGroup = new DefaultChannelGroup("OpenR66"); - - serverChannelFactory = new NioServerSocketChannelFactory( - execServerBoss, execServerWorker, SERVER_THREAD); - if (useNOSSL) { - serverBootstrap = new ServerBootstrap(serverChannelFactory); - networkServerPipelineFactory = new NetworkServerPipelineFactory(true); - serverBootstrap.setPipelineFactory(networkServerPipelineFactory); - serverBootstrap.setOption("child.tcpNoDelay", true); - serverBootstrap.setOption("child.keepAlive", true); - serverBootstrap.setOption("child.reuseAddress", true); - serverBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); - serverBootstrap.setOption("tcpNoDelay", true); - serverBootstrap.setOption("reuseAddress", true); - serverBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); - - serverChannelGroup.add(serverBootstrap.bind(new InetSocketAddress( - SERVER_PORT))); - } else { - networkServerPipelineFactory = null; - logger.warn("NOSSL mode is deactivated"); - } - - if (useSSL && HOST_SSLID != null) { - serverSslBootstrap = new ServerBootstrap(serverChannelFactory); - networkSslServerPipelineFactory = new NetworkSslServerPipelineFactory(false, - execServerWorker); - serverSslBootstrap.setPipelineFactory(networkSslServerPipelineFactory); - serverSslBootstrap.setOption("child.tcpNoDelay", true); - serverSslBootstrap.setOption("child.keepAlive", true); - serverSslBootstrap.setOption("child.reuseAddress", true); - serverSslBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); - serverSslBootstrap.setOption("tcpNoDelay", true); - serverSslBootstrap.setOption("reuseAddress", true); - serverSslBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); - - serverChannelGroup.add(serverSslBootstrap.bind(new InetSocketAddress( - SERVER_SSLPORT))); - } else { - networkSslServerPipelineFactory = null; - logger.warn("SSL mode is desactivated"); - } - - // Factory for TrafficShapingHandler - globalTrafficShapingHandler = new GlobalTrafficHandler( - objectSizeEstimator, timerTrafficCounter, - serverGlobalWriteLimit, serverGlobalReadLimit, delayLimit); - this.constraintLimitHandler.setHandler(globalTrafficShapingHandler); - - // Now start the InternalRunner - internalRunner = new InternalRunner(); - - if (thriftport > 0) { - thriftService = new R66ThriftServerService(new WaarpFuture(true), thriftport); - execOtherWorker.execute(thriftService); - thriftService.awaitInitialization(); - } else { - thriftService = null; - } - } - - public void startHttpSupport() { - // Now start the HTTP support - httpChannelGroup = new DefaultChannelGroup("HttpOpenR66"); - // Configure the server. - httpChannelFactory = new NioServerSocketChannelFactory( - execServerBoss, - execServerWorker, - SERVER_THREAD); - httpBootstrap = new ServerBootstrap( - httpChannelFactory); - // Set up the event pipeline factory. - httpBootstrap.setPipelineFactory(new HttpPipelineFactory(useHttpCompression)); - httpBootstrap.setOption("child.tcpNoDelay", true); - httpBootstrap.setOption("child.keepAlive", true); - httpBootstrap.setOption("child.reuseAddress", true); - httpBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); - httpBootstrap.setOption("tcpNoDelay", true); - httpBootstrap.setOption("reuseAddress", true); - httpBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); - // Bind and start to accept incoming connections. - httpChannelGroup.add(httpBootstrap.bind(new InetSocketAddress(SERVER_HTTPPORT))); - - // Now start the HTTPS support - // Configure the server. - httpsChannelFactory = new NioServerSocketChannelFactory( - execServerBoss, - execServerWorker, - SERVER_THREAD); - httpsBootstrap = new ServerBootstrap( - httpsChannelFactory); - // Set up the event pipeline factory. - httpsBootstrap.setPipelineFactory(new HttpSslPipelineFactory(useHttpCompression, - false, execServerWorker)); - httpsBootstrap.setOption("child.tcpNoDelay", true); - httpsBootstrap.setOption("child.keepAlive", true); - httpsBootstrap.setOption("child.reuseAddress", true); - httpsBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); - httpsBootstrap.setOption("tcpNoDelay", true); - httpsBootstrap.setOption("reuseAddress", true); - httpsBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); - // Bind and start to accept incoming connections. - httpChannelGroup.add(httpsBootstrap.bind(new InetSocketAddress(SERVER_HTTPSPORT))); - } - - public void startMonitoring() throws WaarpDatabaseSqlException { - monitoring = new Monitoring(pastLimit, minimalDelay, null); - if (snmpConfig != null) { - int snmpPortShow = (useNOSSL ? SERVER_PORT : SERVER_SSLPORT); - r66Mib = - new R66PrivateMib(SnmpName, - snmpPortShow, - SnmpPrivateId, - SnmpR66Id, - SnmpDefaultAuthor, - SnmpVersion, - SnmpDefaultLocalization, - SnmpService); - WaarpMOFactory.factory = new R66VariableFactory(); - agentSnmp = new WaarpSnmpAgent(new File(snmpConfig), monitoring, r66Mib); - try { - agentSnmp.start(); - } catch (IOException e) { - throw new WaarpDatabaseSqlException("AgentSnmp Error while starting", e); - } - } - } - - public InternalRunner getInternalRunner() { - return internalRunner; - } - - /** - * Prepare the server to stop - * - * To be called early before other stuff will be closed - */ - public void prepareServerStop() { - if (thriftService != null) { - thriftService.releaseResources(); - } - if (internalRunner != null) { - internalRunner.prepareStopInternalRunner(); - } - } - - /** - * Stops the server - * - * To be called after all other stuff are closed (channels, connections) - */ - public void serverStop() { - WaarpSslUtility.forceCloseAllSslChannels(); - if (internalRunner != null) { - internalRunner.stopInternalRunner(); - } - if (agentSnmp != null) { - agentSnmp.stop(); - } else if (monitoring != null) { - monitoring.releaseResources(); - monitoring = null; - } - if (execServerBoss != null) { - ExecutorUtil.terminate(execServerBoss); - execServerBoss = null; - } - if (execServerWorker != null) { - ExecutorUtil.terminate(execServerWorker); - execServerWorker = null; - } - if (execOtherWorker != null) { - execOtherWorker.shutdownNow(); - execOtherWorker = null; - } - if (timerTrafficCounter != null) { - timerTrafficCounter.stop(); - } - if (timerCloseOperations != null) { - timerCloseOperations.stop(); - } - } - - /** - * To be called after all other stuff are closed for Client - */ - public void clientStop() { - WaarpSslUtility.forceCloseAllSslChannels(); - if (localTransaction != null) { - localTransaction.closeAll(); - localTransaction = null; - } - if (serverPipelineExecutor != null) { - ExecutorUtil.terminate(serverPipelineExecutor); - serverPipelineExecutor = null; - } - if (localPipelineExecutor != null) { - ExecutorUtil.terminate(localPipelineExecutor); - localPipelineExecutor = null; - } - if (localClientPipelineExecutor != null) { - ExecutorUtil.terminate(localClientPipelineExecutor); - localClientPipelineExecutor = null; - } - if (httpPipelineExecutor != null) { - ExecutorUtil.terminate(httpPipelineExecutor); - httpPipelineExecutor = null; - } - if (useLocalExec) { - LocalExecClient.releaseResources(); - } - if (timerTrafficCounter != null) { - timerTrafficCounter.stop(); - } - if (timerCloseOperations != null) { - timerCloseOperations.stop(); - } - r66BusinessFactory.releaseResources(); - } - - /** - * Try to reload the Commander - * - * @return True if reloaded, else in error - */ - public boolean reloadCommanderDelay() { - if (internalRunner != null) { - try { - internalRunner.reloadInternalRunner(); - return true; - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } - } - return false; - } - - /** - * Reset the global monitor for bandwidth limitation and change future channel monitors - * - * @param writeGlobalLimit - * @param readGlobalLimit - * @param writeSessionLimit - * @param readSessionLimit - * @param delayLimit - */ - public void changeNetworkLimit(long writeGlobalLimit, long readGlobalLimit, - long writeSessionLimit, long readSessionLimit, long delayLimit) { - long newWriteLimit = writeGlobalLimit > 1024 ? writeGlobalLimit - : serverGlobalWriteLimit; - if (writeGlobalLimit <= 0) { - newWriteLimit = 0; - } - long newReadLimit = readGlobalLimit > 1024 ? readGlobalLimit - : serverGlobalReadLimit; - if (readGlobalLimit <= 0) { - newReadLimit = 0; - } - serverGlobalReadLimit = newReadLimit; - serverGlobalWriteLimit = newWriteLimit; - this.delayLimit = delayLimit; - if (globalTrafficShapingHandler != null) { - globalTrafficShapingHandler.configure(serverGlobalWriteLimit, serverGlobalReadLimit, - delayLimit); - logger.warn("Bandwidth limits change: {}", globalTrafficShapingHandler); - } - newWriteLimit = writeSessionLimit > 1024 ? writeSessionLimit - : serverChannelWriteLimit; - if (writeSessionLimit <= 0) { - newWriteLimit = 0; - } - newReadLimit = readSessionLimit > 1024 ? readSessionLimit - : serverChannelReadLimit; - if (readSessionLimit <= 0) { - newReadLimit = 0; - } - serverChannelReadLimit = newReadLimit; - serverChannelWriteLimit = newWriteLimit; - anyBandwidthLimitation = (serverGlobalReadLimit > 0 || serverGlobalWriteLimit > 0 || - serverChannelReadLimit > 0 || serverChannelWriteLimit > 0); - } - - /** - * Compute number of threads for both client and server from the real number of available - * processors (double + 1) if the value is less than 32 threads else (available +1). - */ - public void computeNbThreads() { - int nb = Runtime.getRuntime().availableProcessors() * 2 + 1; - if (nb > 32) { - nb = Runtime.getRuntime().availableProcessors() + 1; - } - if (SERVER_THREAD < nb) { - logger.info("Change default number of threads to " + nb); - SERVER_THREAD = nb; - CLIENT_THREAD = SERVER_THREAD * 10; - } - } - - /** - * @return a new ChannelTrafficShapingHandler - * @throws OpenR66ProtocolNoDataException - */ - public ChannelTrafficShapingHandler newChannelTrafficShapingHandler() - throws OpenR66ProtocolNoDataException { - if (serverChannelReadLimit == 0 && serverChannelWriteLimit == 0) { - throw new OpenR66ProtocolNoDataException("No limit for channel"); - } - return new ChannelTrafficHandler(objectSizeEstimator, - timerTrafficCounter, serverChannelWriteLimit, - serverChannelReadLimit, delayLimit); - } - - /** - * - * @return an executorService to be used for any thread - */ - public ExecutorService getExecutorService() { - return execOtherWorker; - } - - /** - * @return the timer - */ - public Timer getTimerTraffic() { - return timerTrafficCounter; - } - - public Timer getTimerClose() { - return timerCloseOperations; - } - - /** - * @return the globalTrafficShapingHandler - */ - public GlobalTrafficShapingHandler getGlobalTrafficShapingHandler() { - return globalTrafficShapingHandler; - } - - /** - * @return the serverChannelGroup - */ - public ChannelGroup getServerChannelGroup() { - return serverChannelGroup; - } - - /** - * @return the serverChannelFactory - */ - public ChannelFactory getServerChannelFactory() { - return serverChannelFactory; - } - - /** - * @return the httpChannelGroup - */ - public ChannelGroup getHttpChannelGroup() { - return httpChannelGroup; - } - - /** - * @return the httpChannelFactory - */ - public ChannelFactory getHttpChannelFactory() { - return httpChannelFactory; - } - - /** - * @return the httpsChannelFactory - */ - public ChannelFactory getHttpsChannelFactory() { - return httpsChannelFactory; - } - - /** - * @return the serverPipelineExecutor - */ - public OrderedMemoryAwareThreadPoolExecutor getServerPipelineExecutor() { - return serverPipelineExecutor; - } - - /** - * @return the localPipelineExecutor - */ - public OrderedMemoryAwareThreadPoolExecutor getLocalPipelineExecutor() { - return localPipelineExecutor; - } - - /** - * @return the localPipelineExecutor - */ - public OrderedMemoryAwareThreadPoolExecutor getLocalClientPipelineExecutor() { - return localClientPipelineExecutor; - } - - /** - * @return the httpPipelineExecutor - */ - public OrderedMemoryAwareThreadPoolExecutor getHttpPipelineExecutor() { - return httpPipelineExecutor; - } - - /** - * @return the localTransaction - */ - public LocalTransaction getLocalTransaction() { - return localTransaction; - } - - /** - * - * @return the FilesystemBasedFileParameterImpl - */ - public static FilesystemBasedFileParameterImpl getFileParameter() { - return fileParameter; - } - - /** - * @return the SERVERADMINKEY - */ - public byte[] getSERVERADMINKEY() { - return SERVERADMINKEY; - } - - /** - * Is the given key a valid one - * - * @param newkey - * @return True if the key is valid (or any key is valid) - */ - public boolean isKeyValid(byte[] newkey) { - if (newkey == null) { - return false; - } - return FilesystemBasedDigest.equalPasswd(SERVERADMINKEY, newkey); - } - - /** - * @param serverkey - * the SERVERADMINKEY to set - */ - public void setSERVERKEY(byte[] serverkey) { - SERVERADMINKEY = serverkey; - } - - /** - * - * @param isSSL - * @return the HostId according to SSL - * @throws OpenR66ProtocolNoSslException - */ - public String getHostId(boolean isSSL) throws OpenR66ProtocolNoSslException { - if (isSSL) { - if (HOST_SSLID == null) { - throw new OpenR66ProtocolNoSslException("No SSL support"); - } - return HOST_SSLID; - } else { - return HOST_ID; - } - } - - /** - * - * @param dbSession - * @param remoteHost - * @return the HostId according to remoteHost (and its SSL status) - * @throws WaarpDatabaseException - */ - public String getHostId(DbSession dbSession, String remoteHost) throws WaarpDatabaseException { - DbHostAuth hostAuth = new DbHostAuth(dbSession, remoteHost); - try { - return Configuration.configuration.getHostId(hostAuth.isSsl()); - } catch (OpenR66ProtocolNoSslException e) { - throw new WaarpDatabaseException(e); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.configuration; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.HashSet; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.group.ChannelGroup; +import org.jboss.netty.channel.group.DefaultChannelGroup; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.jboss.netty.util.HashedWheelTimer; +import org.jboss.netty.util.ObjectSizeEstimator; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.internal.ExecutorUtil; +import org.waarp.common.crypto.Des; +import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; +import org.waarp.common.crypto.ssl.WaarpSslContextFactory; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo; +import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; +import org.waarp.common.future.WaarpFuture; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.role.RoleDefault; +import org.waarp.common.utility.SystemPropertyUtil; +import org.waarp.common.utility.WaarpShutdownHook.ShutdownConfiguration; +import org.waarp.common.utility.WaarpThreadFactory; +import org.waarp.openr66.commander.InternalRunner; +import org.waarp.openr66.context.R66BusinessFactoryInterface; +import org.waarp.openr66.context.R66DefaultBusinessFactory; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.http.HttpPipelineFactory; +import org.waarp.openr66.protocol.http.adminssl.HttpSslPipelineFactory; +import org.waarp.openr66.protocol.localhandler.LocalTransaction; +import org.waarp.openr66.protocol.localhandler.Monitoring; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketSizeEstimator; +import org.waarp.openr66.protocol.networkhandler.ChannelTrafficHandler; +import org.waarp.openr66.protocol.networkhandler.GlobalTrafficHandler; +import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; +import org.waarp.openr66.protocol.networkhandler.R66ConstraintLimitHandler; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketSizeEstimator; +import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; +import org.waarp.openr66.protocol.snmp.R66PrivateMib; +import org.waarp.openr66.protocol.snmp.R66VariableFactory; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; +import org.waarp.openr66.protocol.utils.Version; +import org.waarp.openr66.thrift.R66ThriftServerService; +import org.waarp.snmp.WaarpMOFactory; +import org.waarp.snmp.WaarpSnmpAgent; + +/** + * Configuration class + * + * @author Frederic Bregier + */ +public class Configuration { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(Configuration.class); + + // Static values + /** + * General Configuration object + */ + public static Configuration configuration = new Configuration(); + + public static final String SnmpName = "Waarp OpenR66 SNMP"; + public static final int SnmpPrivateId = 66666; + public static final int SnmpR66Id = 66; + public static final String SnmpDefaultAuthor = "Frederic Bregier"; + public static final String SnmpVersion = "Waarp OpenR66 " + + Version.ID; + public static final String SnmpDefaultLocalization = "Paris, France"; + public static final int SnmpService = 72; + /** + * Time elapse for retry in ms + */ + public static final long RETRYINMS = 10; + + /** + * Number of retry before error + */ + public static final int RETRYNB = 3; + + /** + * Hack to say Windows or Unix (USR1 not OK on Windows) + */ + public static boolean ISUNIX; + + /** + * Default size for buffers (NIO) + */ + public static final int BUFFERSIZEDEFAULT = 0x10000; // 64K + + /** + * Time elapse for WRITE OR CLOSE WAIT elaps in ms + */ + public static final long WAITFORNETOP = 1000; + + /** + * Extension of file during transfer + */ + public static final String EXT_R66 = ".r66"; + + /** + * Rank to redo when a restart occurs + */ + public static int RANKRESTART = 30; + + /** + * FileParameter + */ + private static final FilesystemBasedFileParameterImpl fileParameter = + new FilesystemBasedFileParameterImpl(); + + public R66BusinessFactoryInterface r66BusinessFactory = new R66DefaultBusinessFactory(); + // Global Dynamic values + /** + * Version validation + */ + public boolean extendedProtocol = true; + /** + * Global digest + */ + public boolean globalDigest = true; + /** + * White List of allowed Partners to use Business Requests + */ + public HashSet businessWhiteSet = new HashSet(); + /** + * Roles list for identified partners + */ + public HashMap roles = new HashMap(); + /** + * Aliases list for identified partners + */ + public HashMap aliases = new HashMap(); + /** + * Actual Host ID + */ + public String HOST_ID; + /** + * Actual SSL Host ID + */ + public String HOST_SSLID; + /** + * Requester Host ID + */ + public String REQER_HOST_ID; + /** + * Requested Host ID + */ + public String REQED_HOST_ID; + + /** + * Server Administration user name + */ + public String ADMINNAME = null; + /** + * Server Administration Key + */ + private byte[] SERVERADMINKEY = null; + /** + * Server Administration Key file + */ + public String serverKeyFile = null; + /** + * Server Actual Authentication + */ + public DbHostAuth HOST_AUTH; + /** + * Server Actual SSL Authentication + */ + public DbHostAuth HOST_SSLAUTH; + + /** + * Default number of threads in pool for Server (true network listeners). Server will change + * this value on startup if not set. The value should be closed to the number of CPU. + */ + public int SERVER_THREAD = 8; + + /** + * Default number of threads in pool for Client. The value is for true client for Executor in + * the Pipeline for Business logic. The value does not indicate a limit of concurrent clients, + * but a limit on truly packet concurrent actions. + */ + public int CLIENT_THREAD = 80; + + /** + * Default session limit 64Mbit, so up to 16 full simultaneous clients + */ + public final long DEFAULT_SESSION_LIMIT = 0x800000L; + + /** + * Default global limit 1024Mbit + */ + public final long DEFAULT_GLOBAL_LIMIT = 0x8000000L; + + /** + * Default server port + */ + public int SERVER_PORT = 6666; + + /** + * Default SSL server port + */ + public int SERVER_SSLPORT = 6667; + + /** + * Default HTTP server port + */ + public int SERVER_HTTPPORT = 8066; + + /** + * Default HTTP server port + */ + public int SERVER_HTTPSPORT = 8067; + + /** + * Nb of milliseconds after connection is in timeout + */ + public long TIMEOUTCON = 30000; + + /** + * Size by default of block size for receive/sending files. Should be a multiple of 8192 + * (maximum = 2^30K due to block limitation to 4 bytes) + */ + public int BLOCKSIZE = 0x10000; // 64K + + /** + * Max global memory limit: default is 4GB + */ + public long maxGlobalMemory = 0x100000000L; + + /** + * Base Directory + */ + public String baseDirectory; + + /** + * In path (receive) + */ + public String inPath = null; + + /** + * Out path (send, copy, pending) + */ + public String outPath = null; + + /** + * Archive path + */ + public String archivePath = null; + + /** + * Working path + */ + public String workingPath = null; + + /** + * Config path + */ + public String configPath = null; + + /** + * Http Admin base + */ + public String httpBasePath = "src/main/admin/"; + + /** + * True if the service is going to shutdown + */ + public volatile boolean isShutdown = false; + + /** + * Limit in Write byte/s to apply globally to the FTP Server + */ + public long serverGlobalWriteLimit = DEFAULT_GLOBAL_LIMIT; + + /** + * Limit in Read byte/s to apply globally to the FTP Server + */ + public long serverGlobalReadLimit = DEFAULT_GLOBAL_LIMIT; + + /** + * Limit in Write byte/s to apply by session to the FTP Server + */ + public long serverChannelWriteLimit = DEFAULT_SESSION_LIMIT; + + /** + * Limit in Read byte/s to apply by session to the FTP Server + */ + public long serverChannelReadLimit = DEFAULT_SESSION_LIMIT; + + /** + * Any limitation on bandwidth active? + */ + public boolean anyBandwidthLimitation = false; + /** + * Delay in ms between two checks + */ + public long delayLimit = 10000; + + /** + * Does this OpenR66 server will use and accept SSL connections + */ + public boolean useSSL = false; + /** + * Does this OpenR66 server will use and accept non SSL connections + */ + public boolean useNOSSL = true; + /** + * Algorithm to use for Digest + */ + public FilesystemBasedDigest.DigestAlgo digest = DigestAlgo.MD5; + + /** + * Does this OpenR66 server will try to compress HTTP connections + */ + public boolean useHttpCompression = false; + + /** + * Does this OpenR66 server will use Waarp LocalExec Daemon for ExecTask and ExecMoveTask + */ + public boolean useLocalExec = false; + + /** + * Crypto Key + */ + public Des cryptoKey = null; + /** + * Associated file for CryptoKey + */ + public String cryptoFile = null; + + /** + * List of all Server Channels to enable the close call on them using Netty ChannelGroup + */ + protected ChannelGroup serverChannelGroup = null; + /** + * Does the current program running as Server + */ + public boolean isServer = false; + + /** + * ExecutorService Server Boss + */ + protected ExecutorService execServerBoss = Executors + .newCachedThreadPool(); + + /** + * ExecutorService Server Worker + */ + protected ExecutorService execServerWorker = Executors + .newCachedThreadPool(); + + /** + * ExecutorService Other Worker + */ + protected ExecutorService execOtherWorker = Executors + .newCachedThreadPool(); + + /** + * ChannelFactory for Server part + */ + protected ChannelFactory serverChannelFactory = null; + + /** + * ThreadPoolExecutor for Server + */ + protected volatile OrderedMemoryAwareThreadPoolExecutor serverPipelineExecutor; + + /** + * ThreadPoolExecutor for LocalServer + */ + private volatile OrderedMemoryAwareThreadPoolExecutor localPipelineExecutor; + + /** + * ThreadPoolExecutor for LocalClient + */ + private volatile OrderedMemoryAwareThreadPoolExecutor localClientPipelineExecutor; + + /** + * ThreadPoolExecutor for Http and Https Server + */ + protected volatile OrderedMemoryAwareThreadPoolExecutor httpPipelineExecutor; + + /** + * Bootstrap for server + */ + protected ServerBootstrap serverBootstrap = null; + + /** + * Bootstrap for SSL server + */ + protected ServerBootstrap serverSslBootstrap = null; + /** + * Factory for NON SSL Server + */ + protected NetworkServerPipelineFactory networkServerPipelineFactory; + /** + * Factory for SSL Server + */ + protected NetworkSslServerPipelineFactory networkSslServerPipelineFactory; + + /** + * Bootstrap for Http server + */ + protected ServerBootstrap httpBootstrap = null; + /** + * Bootstrap for Https server + */ + protected ServerBootstrap httpsBootstrap = null; + /** + * ChannelFactory for HttpServer part + */ + protected ChannelFactory httpChannelFactory = null; + /** + * ChannelFactory for HttpsServer part + */ + protected ChannelFactory httpsChannelFactory = null; + /** + * List of all Http Channels to enable the close call on them using Netty ChannelGroup + */ + protected ChannelGroup httpChannelGroup = null; + + /** + * Timer for CloseOpertations + */ + private Timer timerCloseOperations = + new HashedWheelTimer( + new WaarpThreadFactory( + "TimerClose"), + 50, + TimeUnit.MILLISECONDS, + 1024); + + /** + * Timer for TrafficCounter + */ + protected Timer timerTrafficCounter = + new HashedWheelTimer( + new WaarpThreadFactory( + "TimerTraffic"), + 10, + TimeUnit.MILLISECONDS, + 1024); + /** + * Global TrafficCounter (set from global configuration) + */ + protected volatile GlobalTrafficHandler globalTrafficShapingHandler = null; + + /** + * ObjectSizeEstimator + */ + protected ObjectSizeEstimator objectSizeEstimator = null; + + /** + * LocalTransaction + */ + protected LocalTransaction localTransaction; + /** + * InternalRunner + */ + private InternalRunner internalRunner; + /** + * Maximum number of concurrent active transfer by submission. + */ + public int RUNNER_THREAD = 1000; + /** + * Delay in ms between two steps of Commander + */ + public long delayCommander = 5000; + /** + * Delay in ms between two retries + */ + public long delayRetry = 30000; + /** + * Constraint Limit Handler on CPU usage and Connection limitation + */ + public R66ConstraintLimitHandler constraintLimitHandler = + new R66ConstraintLimitHandler(); + /** + * Do we check Remote Address from DbHost + */ + public boolean checkRemoteAddress = false; + /** + * Do we check address even for Client + */ + public boolean checkClientAddress = false; + /** + * For No Db client, do we saved TaskRunner in a XML + */ + public boolean saveTaskRunnerWithNoDb = false; + /** + * In case of Multiple OpenR66 monitor servers behing a load balancer (HA solution) + */ + public int multipleMonitors = 1; + /** + * Monitoring object + */ + public Monitoring monitoring = null; + /** + * Monitoring: how long in ms to get back in monitoring + */ + public long pastLimit = 86400000; // 24H + /** + * Monitoring: minimal interval in ms before redo real monitoring + */ + public long minimalDelay = 5000; // 5 + // seconds + /** + * Monitoring: snmp configuration file (empty means no snmp support) + */ + public String snmpConfig = null; + /** + * SNMP Agent (if any) + */ + public WaarpSnmpAgent agentSnmp = null; + /** + * Associated MIB + */ + public R66PrivateMib r66Mib = null; + + protected volatile boolean configured = false; + + public static WaarpSecureKeyStore WaarpSecureKeyStore; + + public static WaarpSslContextFactory waarpSslContextFactory; + /** + * Thrift support + */ + public R66ThriftServerService thriftService; + public int thriftport = -1; + + public boolean isExecuteErrorBeforeTransferAllowed = true; + + public ShutdownConfiguration shutdownConfiguration = new ShutdownConfiguration(); + + public Configuration() { + // Init signal handler + shutdownConfiguration.timeout = TIMEOUTCON; + new R66ShutdownHook(shutdownConfiguration); + computeNbThreads(); + // Init FiniteStates + R66FiniteDualStates.initR66FiniteStates(); + boolean value = SystemPropertyUtil.getBoolean("openr66.executebeforetransferred", true); + isExecuteErrorBeforeTransferAllowed = value; + } + + /** + * Configure the pipeline for client (to be called ony once) + */ + public void pipelineInit() { + if (configured) { + return; + } + localTransaction = new LocalTransaction(); + InternalLoggerFactory.setDefaultFactory(InternalLoggerFactory + .getDefaultFactory()); + objectSizeEstimator = new NetworkPacketSizeEstimator(); + httpPipelineInit(); + logger.warn("Server Thread: " + SERVER_THREAD + " Client Thread: " + CLIENT_THREAD + + " Runner Thread: " + RUNNER_THREAD); + serverPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( + CLIENT_THREAD, maxGlobalMemory / 10, maxGlobalMemory, 1000, + TimeUnit.MILLISECONDS, objectSizeEstimator, + new WaarpThreadFactory("ServerExecutor")); + localPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( + CLIENT_THREAD * 100, maxGlobalMemory / 10, maxGlobalMemory, + 1000, TimeUnit.MILLISECONDS, new LocalPacketSizeEstimator(), + new WaarpThreadFactory("LocalExecutor")); + localClientPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( + CLIENT_THREAD * 100, maxGlobalMemory / 10, maxGlobalMemory, + 1000, TimeUnit.MILLISECONDS, new LocalPacketSizeEstimator(), + new WaarpThreadFactory("LocalClientExecutor")); + if (useLocalExec) { + LocalExecClient.initialize(); + } + configured = true; + } + + public void httpPipelineInit() { + httpPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor( + CLIENT_THREAD, maxGlobalMemory / 10, maxGlobalMemory, 1000, + TimeUnit.MILLISECONDS, objectSizeEstimator, new WaarpThreadFactory("HttpExecutor")); + } + + /** + * Startup the server + * + * @throws WaarpDatabaseSqlException + * @throws WaarpDatabaseNoConnectionException + */ + public void serverStartup() throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + isServer = true; + shutdownConfiguration.timeout = TIMEOUTCON; + R66ShutdownHook.addShutdownHook(); + if ((!useNOSSL) && (!useSSL)) { + logger.error("OpenR66 has neither NOSSL nor SSL support included! Stop here!"); + System.exit(-1); + } + pipelineInit(); + r66Startup(); + startHttpSupport(); + startMonitoring(); + } + + public void r66Startup() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { + logger.debug("Start R66: " + SERVER_PORT + ":" + useNOSSL + " " + SERVER_SSLPORT + ":" + + useSSL + ":" + HOST_SSLID); + // add into configuration + this.constraintLimitHandler.setServer(true); + // Global Server + serverChannelGroup = new DefaultChannelGroup("OpenR66"); + + serverChannelFactory = new NioServerSocketChannelFactory( + execServerBoss, execServerWorker, SERVER_THREAD); + if (useNOSSL) { + serverBootstrap = new ServerBootstrap(serverChannelFactory); + networkServerPipelineFactory = new NetworkServerPipelineFactory(true); + serverBootstrap.setPipelineFactory(networkServerPipelineFactory); + serverBootstrap.setOption("child.tcpNoDelay", true); + serverBootstrap.setOption("child.keepAlive", true); + serverBootstrap.setOption("child.reuseAddress", true); + serverBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); + serverBootstrap.setOption("tcpNoDelay", true); + serverBootstrap.setOption("reuseAddress", true); + serverBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); + + serverChannelGroup.add(serverBootstrap.bind(new InetSocketAddress( + SERVER_PORT))); + } else { + networkServerPipelineFactory = null; + logger.warn("NOSSL mode is deactivated"); + } + + if (useSSL && HOST_SSLID != null) { + serverSslBootstrap = new ServerBootstrap(serverChannelFactory); + networkSslServerPipelineFactory = new NetworkSslServerPipelineFactory(false, + execServerWorker); + serverSslBootstrap.setPipelineFactory(networkSslServerPipelineFactory); + serverSslBootstrap.setOption("child.tcpNoDelay", true); + serverSslBootstrap.setOption("child.keepAlive", true); + serverSslBootstrap.setOption("child.reuseAddress", true); + serverSslBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); + serverSslBootstrap.setOption("tcpNoDelay", true); + serverSslBootstrap.setOption("reuseAddress", true); + serverSslBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); + + serverChannelGroup.add(serverSslBootstrap.bind(new InetSocketAddress( + SERVER_SSLPORT))); + } else { + networkSslServerPipelineFactory = null; + logger.warn("SSL mode is desactivated"); + } + + // Factory for TrafficShapingHandler + globalTrafficShapingHandler = new GlobalTrafficHandler( + objectSizeEstimator, timerTrafficCounter, + serverGlobalWriteLimit, serverGlobalReadLimit, delayLimit); + this.constraintLimitHandler.setHandler(globalTrafficShapingHandler); + + // Now start the InternalRunner + internalRunner = new InternalRunner(); + + if (thriftport > 0) { + thriftService = new R66ThriftServerService(new WaarpFuture(true), thriftport); + execOtherWorker.execute(thriftService); + thriftService.awaitInitialization(); + } else { + thriftService = null; + } + } + + public void startHttpSupport() { + // Now start the HTTP support + httpChannelGroup = new DefaultChannelGroup("HttpOpenR66"); + // Configure the server. + httpChannelFactory = new NioServerSocketChannelFactory( + execServerBoss, + execServerWorker, + SERVER_THREAD); + httpBootstrap = new ServerBootstrap( + httpChannelFactory); + // Set up the event pipeline factory. + httpBootstrap.setPipelineFactory(new HttpPipelineFactory(useHttpCompression)); + httpBootstrap.setOption("child.tcpNoDelay", true); + httpBootstrap.setOption("child.keepAlive", true); + httpBootstrap.setOption("child.reuseAddress", true); + httpBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); + httpBootstrap.setOption("tcpNoDelay", true); + httpBootstrap.setOption("reuseAddress", true); + httpBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); + // Bind and start to accept incoming connections. + httpChannelGroup.add(httpBootstrap.bind(new InetSocketAddress(SERVER_HTTPPORT))); + + // Now start the HTTPS support + // Configure the server. + httpsChannelFactory = new NioServerSocketChannelFactory( + execServerBoss, + execServerWorker, + SERVER_THREAD); + httpsBootstrap = new ServerBootstrap( + httpsChannelFactory); + // Set up the event pipeline factory. + httpsBootstrap.setPipelineFactory(new HttpSslPipelineFactory(useHttpCompression, + false, execServerWorker)); + httpsBootstrap.setOption("child.tcpNoDelay", true); + httpsBootstrap.setOption("child.keepAlive", true); + httpsBootstrap.setOption("child.reuseAddress", true); + httpsBootstrap.setOption("child.connectTimeoutMillis", TIMEOUTCON); + httpsBootstrap.setOption("tcpNoDelay", true); + httpsBootstrap.setOption("reuseAddress", true); + httpsBootstrap.setOption("connectTimeoutMillis", TIMEOUTCON); + // Bind and start to accept incoming connections. + httpChannelGroup.add(httpsBootstrap.bind(new InetSocketAddress(SERVER_HTTPSPORT))); + } + + public void startMonitoring() throws WaarpDatabaseSqlException { + monitoring = new Monitoring(pastLimit, minimalDelay, null); + if (snmpConfig != null) { + int snmpPortShow = (useNOSSL ? SERVER_PORT : SERVER_SSLPORT); + r66Mib = + new R66PrivateMib(SnmpName, + snmpPortShow, + SnmpPrivateId, + SnmpR66Id, + SnmpDefaultAuthor, + SnmpVersion, + SnmpDefaultLocalization, + SnmpService); + WaarpMOFactory.factory = new R66VariableFactory(); + agentSnmp = new WaarpSnmpAgent(new File(snmpConfig), monitoring, r66Mib); + try { + agentSnmp.start(); + } catch (IOException e) { + throw new WaarpDatabaseSqlException("AgentSnmp Error while starting", e); + } + } + } + + public InternalRunner getInternalRunner() { + return internalRunner; + } + + /** + * Prepare the server to stop + * + * To be called early before other stuff will be closed + */ + public void prepareServerStop() { + if (thriftService != null) { + thriftService.releaseResources(); + } + if (internalRunner != null) { + internalRunner.prepareStopInternalRunner(); + } + } + + /** + * Stops the server + * + * To be called after all other stuff are closed (channels, connections) + */ + public void serverStop() { + WaarpSslUtility.forceCloseAllSslChannels(); + if (internalRunner != null) { + internalRunner.stopInternalRunner(); + } + if (agentSnmp != null) { + agentSnmp.stop(); + } else if (monitoring != null) { + monitoring.releaseResources(); + monitoring = null; + } + if (execServerBoss != null) { + ExecutorUtil.terminate(execServerBoss); + execServerBoss = null; + } + if (execServerWorker != null) { + ExecutorUtil.terminate(execServerWorker); + execServerWorker = null; + } + if (execOtherWorker != null) { + execOtherWorker.shutdownNow(); + execOtherWorker = null; + } + if (timerTrafficCounter != null) { + timerTrafficCounter.stop(); + } + if (timerCloseOperations != null) { + timerCloseOperations.stop(); + } + } + + /** + * To be called after all other stuff are closed for Client + */ + public void clientStop() { + WaarpSslUtility.forceCloseAllSslChannels(); + if (localTransaction != null) { + localTransaction.closeAll(); + localTransaction = null; + } + if (serverPipelineExecutor != null) { + ExecutorUtil.terminate(serverPipelineExecutor); + serverPipelineExecutor = null; + } + if (localPipelineExecutor != null) { + ExecutorUtil.terminate(localPipelineExecutor); + localPipelineExecutor = null; + } + if (localClientPipelineExecutor != null) { + ExecutorUtil.terminate(localClientPipelineExecutor); + localClientPipelineExecutor = null; + } + if (httpPipelineExecutor != null) { + ExecutorUtil.terminate(httpPipelineExecutor); + httpPipelineExecutor = null; + } + if (useLocalExec) { + LocalExecClient.releaseResources(); + } + if (timerTrafficCounter != null) { + timerTrafficCounter.stop(); + } + if (timerCloseOperations != null) { + timerCloseOperations.stop(); + } + r66BusinessFactory.releaseResources(); + } + + /** + * Try to reload the Commander + * + * @return True if reloaded, else in error + */ + public boolean reloadCommanderDelay() { + if (internalRunner != null) { + try { + internalRunner.reloadInternalRunner(); + return true; + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } + } + return false; + } + + /** + * Reset the global monitor for bandwidth limitation and change future channel monitors + * + * @param writeGlobalLimit + * @param readGlobalLimit + * @param writeSessionLimit + * @param readSessionLimit + * @param delayLimit + */ + public void changeNetworkLimit(long writeGlobalLimit, long readGlobalLimit, + long writeSessionLimit, long readSessionLimit, long delayLimit) { + long newWriteLimit = writeGlobalLimit > 1024 ? writeGlobalLimit + : serverGlobalWriteLimit; + if (writeGlobalLimit <= 0) { + newWriteLimit = 0; + } + long newReadLimit = readGlobalLimit > 1024 ? readGlobalLimit + : serverGlobalReadLimit; + if (readGlobalLimit <= 0) { + newReadLimit = 0; + } + serverGlobalReadLimit = newReadLimit; + serverGlobalWriteLimit = newWriteLimit; + this.delayLimit = delayLimit; + if (globalTrafficShapingHandler != null) { + globalTrafficShapingHandler.configure(serverGlobalWriteLimit, serverGlobalReadLimit, + delayLimit); + logger.warn("Bandwidth limits change: {}", globalTrafficShapingHandler); + } + newWriteLimit = writeSessionLimit > 1024 ? writeSessionLimit + : serverChannelWriteLimit; + if (writeSessionLimit <= 0) { + newWriteLimit = 0; + } + newReadLimit = readSessionLimit > 1024 ? readSessionLimit + : serverChannelReadLimit; + if (readSessionLimit <= 0) { + newReadLimit = 0; + } + serverChannelReadLimit = newReadLimit; + serverChannelWriteLimit = newWriteLimit; + anyBandwidthLimitation = (serverGlobalReadLimit > 0 || serverGlobalWriteLimit > 0 || + serverChannelReadLimit > 0 || serverChannelWriteLimit > 0); + } + + /** + * Compute number of threads for both client and server from the real number of available + * processors (double + 1) if the value is less than 32 threads else (available +1). + */ + public void computeNbThreads() { + int nb = Runtime.getRuntime().availableProcessors() * 2 + 1; + if (nb > 32) { + nb = Runtime.getRuntime().availableProcessors() + 1; + } + if (SERVER_THREAD < nb) { + logger.info("Change default number of threads to " + nb); + SERVER_THREAD = nb; + CLIENT_THREAD = SERVER_THREAD * 10; + } + } + + /** + * @return a new ChannelTrafficShapingHandler + * @throws OpenR66ProtocolNoDataException + */ + public ChannelTrafficShapingHandler newChannelTrafficShapingHandler() + throws OpenR66ProtocolNoDataException { + if (serverChannelReadLimit == 0 && serverChannelWriteLimit == 0) { + throw new OpenR66ProtocolNoDataException("No limit for channel"); + } + return new ChannelTrafficHandler(objectSizeEstimator, + timerTrafficCounter, serverChannelWriteLimit, + serverChannelReadLimit, delayLimit); + } + + /** + * + * @return an executorService to be used for any thread + */ + public ExecutorService getExecutorService() { + return execOtherWorker; + } + + /** + * @return the timer + */ + public Timer getTimerTraffic() { + return timerTrafficCounter; + } + + public Timer getTimerClose() { + return timerCloseOperations; + } + + /** + * @return the globalTrafficShapingHandler + */ + public GlobalTrafficShapingHandler getGlobalTrafficShapingHandler() { + return globalTrafficShapingHandler; + } + + /** + * @return the serverChannelGroup + */ + public ChannelGroup getServerChannelGroup() { + return serverChannelGroup; + } + + /** + * @return the serverChannelFactory + */ + public ChannelFactory getServerChannelFactory() { + return serverChannelFactory; + } + + /** + * @return the httpChannelGroup + */ + public ChannelGroup getHttpChannelGroup() { + return httpChannelGroup; + } + + /** + * @return the httpChannelFactory + */ + public ChannelFactory getHttpChannelFactory() { + return httpChannelFactory; + } + + /** + * @return the httpsChannelFactory + */ + public ChannelFactory getHttpsChannelFactory() { + return httpsChannelFactory; + } + + /** + * @return the serverPipelineExecutor + */ + public OrderedMemoryAwareThreadPoolExecutor getServerPipelineExecutor() { + return serverPipelineExecutor; + } + + /** + * @return the localPipelineExecutor + */ + public OrderedMemoryAwareThreadPoolExecutor getLocalPipelineExecutor() { + return localPipelineExecutor; + } + + /** + * @return the localPipelineExecutor + */ + public OrderedMemoryAwareThreadPoolExecutor getLocalClientPipelineExecutor() { + return localClientPipelineExecutor; + } + + /** + * @return the httpPipelineExecutor + */ + public OrderedMemoryAwareThreadPoolExecutor getHttpPipelineExecutor() { + return httpPipelineExecutor; + } + + /** + * @return the localTransaction + */ + public LocalTransaction getLocalTransaction() { + return localTransaction; + } + + /** + * + * @return the FilesystemBasedFileParameterImpl + */ + public static FilesystemBasedFileParameterImpl getFileParameter() { + return fileParameter; + } + + /** + * @return the SERVERADMINKEY + */ + public byte[] getSERVERADMINKEY() { + return SERVERADMINKEY; + } + + /** + * Is the given key a valid one + * + * @param newkey + * @return True if the key is valid (or any key is valid) + */ + public boolean isKeyValid(byte[] newkey) { + if (newkey == null) { + return false; + } + return FilesystemBasedDigest.equalPasswd(SERVERADMINKEY, newkey); + } + + /** + * @param serverkey + * the SERVERADMINKEY to set + */ + public void setSERVERKEY(byte[] serverkey) { + SERVERADMINKEY = serverkey; + } + + /** + * + * @param isSSL + * @return the HostId according to SSL + * @throws OpenR66ProtocolNoSslException + */ + public String getHostId(boolean isSSL) throws OpenR66ProtocolNoSslException { + if (isSSL) { + if (HOST_SSLID == null) { + throw new OpenR66ProtocolNoSslException("No SSL support"); + } + return HOST_SSLID; + } else { + return HOST_ID; + } + } + + /** + * + * @param dbSession + * @param remoteHost + * @return the HostId according to remoteHost (and its SSL status) + * @throws WaarpDatabaseException + */ + public String getHostId(DbSession dbSession, String remoteHost) throws WaarpDatabaseException { + DbHostAuth hostAuth = new DbHostAuth(dbSession, remoteHost); + try { + return Configuration.configuration.getHostId(hostAuth.isSsl()); + } catch (OpenR66ProtocolNoSslException e) { + throw new WaarpDatabaseException(e); + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/configuration/package-info.java b/src/main/java/org/waarp/openr66/protocol/configuration/package-info.java index 3e0333f13..74e855ef2 100644 --- a/src/main/java/org/waarp/openr66/protocol/configuration/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/configuration/package-info.java @@ -1,7 +1,7 @@ -/** - * Class implementing Configuration - * - * @apiviz.landmark - */ -package org.waarp.openr66.protocol.configuration; - +/** + * Class implementing Configuration + * + * @apiviz.landmark + */ +package org.waarp.openr66.protocol.configuration; + diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66DatabaseGlobalException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66DatabaseGlobalException.java index 42eb293b1..45bbc8955 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66DatabaseGlobalException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66DatabaseGlobalException.java @@ -1,62 +1,62 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * OpenR66 Database Mother Exception - * - * @author Frederic Bregier - * - */ -public class OpenR66DatabaseGlobalException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = -9185582146820950696L; - - /** - * - */ - public OpenR66DatabaseGlobalException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66DatabaseGlobalException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66DatabaseGlobalException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66DatabaseGlobalException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * OpenR66 Database Mother Exception + * + * @author Frederic Bregier + * + */ +public class OpenR66DatabaseGlobalException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = -9185582146820950696L; + + /** + * + */ + public OpenR66DatabaseGlobalException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66DatabaseGlobalException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66DatabaseGlobalException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66DatabaseGlobalException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66Exception.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66Exception.java index 19f1ce46c..ce6384d97 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66Exception.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66Exception.java @@ -1,57 +1,57 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Mother class of All OpenR66 Exceptions - * - * @author frederic bregier - */ -@SuppressWarnings("serial") -public abstract class OpenR66Exception extends Exception { - - /** - * - */ - public OpenR66Exception() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66Exception(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66Exception(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66Exception(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Mother class of All OpenR66 Exceptions + * + * @author frederic bregier + */ +@SuppressWarnings("serial") +public abstract class OpenR66Exception extends Exception { + + /** + * + */ + public OpenR66Exception() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66Exception(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66Exception(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66Exception(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ExceptionTrappedFactory.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ExceptionTrappedFactory.java index 94b04fe64..01f2b50c6 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ExceptionTrappedFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ExceptionTrappedFactory.java @@ -1,165 +1,165 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -import java.io.IOException; -import java.net.BindException; -import java.net.ConnectException; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.ClosedChannelException; -import java.util.concurrent.RejectedExecutionException; - -import javax.net.ssl.SSLException; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelException; -import org.jboss.netty.channel.ExceptionEvent; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Class that filter exceptions - * - * @author frederic bregier - */ -public class OpenR66ExceptionTrappedFactory { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(OpenR66ExceptionTrappedFactory.class); - - /** - * @param channel - * @param e - * @return the OpenR66Exception corresponding to the ExceptionEvent, or null if the exception - * should be ignored - */ - public static OpenR66Exception getExceptionFromTrappedException( - Channel channel, ExceptionEvent e) { - final Throwable e1 = e.getCause(); - if (e1 instanceof ConnectException) { - final ConnectException e2 = (ConnectException) e1; - logger.debug("Connection impossible since {} with Channel {}", e2 - .getMessage(), channel); - return new OpenR66ProtocolNoConnectionException( - "Connection impossible", e2); - } else if (e1 instanceof ChannelException) { - final ChannelException e2 = (ChannelException) e1; - logger - .info( - "Connection (example: timeout) impossible since {} with Channel {}", - e2.getMessage(), channel); - return new OpenR66ProtocolNetworkException( - "Connection (example: timeout) impossible", e2); - } else if (e1 instanceof CancelledKeyException) { - final CancelledKeyException e2 = (CancelledKeyException) e1; - logger.error("Connection aborted since {}", e2.getMessage()); - // Is it really what we should do ? - // Yes, No action - return null; - } else if (e1 instanceof ClosedChannelException) { - logger.debug("Connection closed before end"); - return new OpenR66ProtocolBusinessNoWriteBackException( - "Connection closed before end", e1); - } else if (e1 instanceof OpenR66ProtocolBusinessCancelException) { - final OpenR66ProtocolBusinessCancelException e2 = (OpenR66ProtocolBusinessCancelException) e1; - logger.debug("Request is canceled: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolBusinessStopException) { - final OpenR66ProtocolBusinessStopException e2 = (OpenR66ProtocolBusinessStopException) e1; - logger.debug("Request is stopped: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolBusinessQueryAlreadyFinishedException) { - final OpenR66ProtocolBusinessQueryAlreadyFinishedException e2 = - (OpenR66ProtocolBusinessQueryAlreadyFinishedException) e1; - logger.debug("Request is already finished: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolBusinessQueryStillRunningException) { - final OpenR66ProtocolBusinessQueryStillRunningException e2 = - (OpenR66ProtocolBusinessQueryStillRunningException) e1; - logger.debug("Request is still running: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolBusinessRemoteFileNotFoundException) { - final OpenR66ProtocolBusinessRemoteFileNotFoundException e2 = - (OpenR66ProtocolBusinessRemoteFileNotFoundException) e1; - logger.debug("Remote server did not find file: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolBusinessNoWriteBackException) { - final OpenR66ProtocolBusinessNoWriteBackException e2 = (OpenR66ProtocolBusinessNoWriteBackException) e1; - logger.error("Command Error Reply: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66ProtocolShutdownException) { - final OpenR66ProtocolShutdownException e2 = (OpenR66ProtocolShutdownException) e1; - logger.debug("Command Shutdown {}", e2.getMessage()); - return e2; - } else if (e1 instanceof OpenR66Exception) { - final OpenR66Exception e2 = (OpenR66Exception) e1; - logger.debug("Command Error Reply: {}", e2.getMessage()); - return e2; - } else if (e1 instanceof BindException) { - final BindException e2 = (BindException) e1; - logger.debug("Address already in use {}", e2.getMessage()); - return new OpenR66ProtocolNetworkException( - "Address already in use", e2); - } else if (e1 instanceof ConnectException) { - final ConnectException e2 = (ConnectException) e1; - logger.debug("Timeout occurs {}", e2.getMessage()); - return new OpenR66ProtocolNetworkException("Timeout occurs", e2); - } else if (e1 instanceof NullPointerException) { - final NullPointerException e2 = (NullPointerException) e1; - logger.error("Null pointer Exception", e2); - return new OpenR66ProtocolSystemException("Null Pointer Exception", - e2); - } else if (e1 instanceof SSLException) { - final SSLException e2 = (SSLException) e1; - logger.debug("Connection aborted since SSL Error {} with Channel {}", e2 - .getMessage(), channel); - return new OpenR66ProtocolBusinessNoWriteBackException("SSL Connection aborted", e2); - } else if (e1 instanceof IOException) { - final IOException e2 = (IOException) e1; - logger.debug("Connection aborted since {} with Channel {}", e2 - .getMessage(), channel); - if (channel.isConnected()) { - return new OpenR66ProtocolSystemException("Connection aborted due to " - + e2.getMessage(), e2); - } else { - return new OpenR66ProtocolBusinessNoWriteBackException("Connection aborted due to " - + e2.getMessage(), e2); - } - } else if (e1 instanceof RejectedExecutionException) { - final RejectedExecutionException e2 = (RejectedExecutionException) e1; - logger.debug("Connection aborted since {} with Channel {}", e2 - .getMessage(), channel); - if (channel.isConnected()) { - return new OpenR66ProtocolSystemException("Execution aborted", e2); - } else { - return new OpenR66ProtocolBusinessNoWriteBackException("Execution aborted", e2); - } - } else { - logger.error("Unexpected exception from downstream" + - " Ref Channel: " + channel.toString(), e1); - } - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "Unexpected exception", e1.getMessage()); - } - return new OpenR66ProtocolSystemException("Unexpected exception: " + e1.getMessage(), e1); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +import java.io.IOException; +import java.net.BindException; +import java.net.ConnectException; +import java.nio.channels.CancelledKeyException; +import java.nio.channels.ClosedChannelException; +import java.util.concurrent.RejectedExecutionException; + +import javax.net.ssl.SSLException; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelException; +import org.jboss.netty.channel.ExceptionEvent; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Class that filter exceptions + * + * @author frederic bregier + */ +public class OpenR66ExceptionTrappedFactory { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(OpenR66ExceptionTrappedFactory.class); + + /** + * @param channel + * @param e + * @return the OpenR66Exception corresponding to the ExceptionEvent, or null if the exception + * should be ignored + */ + public static OpenR66Exception getExceptionFromTrappedException( + Channel channel, ExceptionEvent e) { + final Throwable e1 = e.getCause(); + if (e1 instanceof ConnectException) { + final ConnectException e2 = (ConnectException) e1; + logger.debug("Connection impossible since {} with Channel {}", e2 + .getMessage(), channel); + return new OpenR66ProtocolNoConnectionException( + "Connection impossible", e2); + } else if (e1 instanceof ChannelException) { + final ChannelException e2 = (ChannelException) e1; + logger + .info( + "Connection (example: timeout) impossible since {} with Channel {}", + e2.getMessage(), channel); + return new OpenR66ProtocolNetworkException( + "Connection (example: timeout) impossible", e2); + } else if (e1 instanceof CancelledKeyException) { + final CancelledKeyException e2 = (CancelledKeyException) e1; + logger.error("Connection aborted since {}", e2.getMessage()); + // Is it really what we should do ? + // Yes, No action + return null; + } else if (e1 instanceof ClosedChannelException) { + logger.debug("Connection closed before end"); + return new OpenR66ProtocolBusinessNoWriteBackException( + "Connection closed before end", e1); + } else if (e1 instanceof OpenR66ProtocolBusinessCancelException) { + final OpenR66ProtocolBusinessCancelException e2 = (OpenR66ProtocolBusinessCancelException) e1; + logger.debug("Request is canceled: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolBusinessStopException) { + final OpenR66ProtocolBusinessStopException e2 = (OpenR66ProtocolBusinessStopException) e1; + logger.debug("Request is stopped: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolBusinessQueryAlreadyFinishedException) { + final OpenR66ProtocolBusinessQueryAlreadyFinishedException e2 = + (OpenR66ProtocolBusinessQueryAlreadyFinishedException) e1; + logger.debug("Request is already finished: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolBusinessQueryStillRunningException) { + final OpenR66ProtocolBusinessQueryStillRunningException e2 = + (OpenR66ProtocolBusinessQueryStillRunningException) e1; + logger.debug("Request is still running: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolBusinessRemoteFileNotFoundException) { + final OpenR66ProtocolBusinessRemoteFileNotFoundException e2 = + (OpenR66ProtocolBusinessRemoteFileNotFoundException) e1; + logger.debug("Remote server did not find file: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolBusinessNoWriteBackException) { + final OpenR66ProtocolBusinessNoWriteBackException e2 = (OpenR66ProtocolBusinessNoWriteBackException) e1; + logger.error("Command Error Reply: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66ProtocolShutdownException) { + final OpenR66ProtocolShutdownException e2 = (OpenR66ProtocolShutdownException) e1; + logger.debug("Command Shutdown {}", e2.getMessage()); + return e2; + } else if (e1 instanceof OpenR66Exception) { + final OpenR66Exception e2 = (OpenR66Exception) e1; + logger.debug("Command Error Reply: {}", e2.getMessage()); + return e2; + } else if (e1 instanceof BindException) { + final BindException e2 = (BindException) e1; + logger.debug("Address already in use {}", e2.getMessage()); + return new OpenR66ProtocolNetworkException( + "Address already in use", e2); + } else if (e1 instanceof ConnectException) { + final ConnectException e2 = (ConnectException) e1; + logger.debug("Timeout occurs {}", e2.getMessage()); + return new OpenR66ProtocolNetworkException("Timeout occurs", e2); + } else if (e1 instanceof NullPointerException) { + final NullPointerException e2 = (NullPointerException) e1; + logger.error("Null pointer Exception", e2); + return new OpenR66ProtocolSystemException("Null Pointer Exception", + e2); + } else if (e1 instanceof SSLException) { + final SSLException e2 = (SSLException) e1; + logger.debug("Connection aborted since SSL Error {} with Channel {}", e2 + .getMessage(), channel); + return new OpenR66ProtocolBusinessNoWriteBackException("SSL Connection aborted", e2); + } else if (e1 instanceof IOException) { + final IOException e2 = (IOException) e1; + logger.debug("Connection aborted since {} with Channel {}", e2 + .getMessage(), channel); + if (channel.isConnected()) { + return new OpenR66ProtocolSystemException("Connection aborted due to " + + e2.getMessage(), e2); + } else { + return new OpenR66ProtocolBusinessNoWriteBackException("Connection aborted due to " + + e2.getMessage(), e2); + } + } else if (e1 instanceof RejectedExecutionException) { + final RejectedExecutionException e2 = (RejectedExecutionException) e1; + logger.debug("Connection aborted since {} with Channel {}", e2 + .getMessage(), channel); + if (channel.isConnected()) { + return new OpenR66ProtocolSystemException("Execution aborted", e2); + } else { + return new OpenR66ProtocolBusinessNoWriteBackException("Execution aborted", e2); + } + } else { + logger.error("Unexpected exception from downstream" + + " Ref Channel: " + channel.toString(), e1); + } + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "Unexpected exception", e1.getMessage()); + } + return new OpenR66ProtocolSystemException("Unexpected exception: " + e1.getMessage(), e1); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessCancelException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessCancelException.java index e90b6b597..1c0c19d5a 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessCancelException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessCancelException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessCancelException extends OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = 2339971663355797702L; - - /** - * - */ - public OpenR66ProtocolBusinessCancelException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessCancelException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessCancelException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessCancelException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessCancelException extends OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = 2339971663355797702L; + + /** + * + */ + public OpenR66ProtocolBusinessCancelException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessCancelException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessCancelException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessCancelException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessException.java index 753842095..f9a5e6df2 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = -7827259682529953206L; - - /** - * - */ - public OpenR66ProtocolBusinessException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = -7827259682529953206L; + + /** + * + */ + public OpenR66ProtocolBusinessException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessNoWriteBackException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessNoWriteBackException.java index 393c2b330..387ce74e4 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessNoWriteBackException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessNoWriteBackException.java @@ -1,63 +1,63 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part without any write back action - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessNoWriteBackException extends - OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = -9088521827450885700L; - - /** - * - */ - public OpenR66ProtocolBusinessNoWriteBackException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessNoWriteBackException(String arg0, - Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessNoWriteBackException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessNoWriteBackException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part without any write back action + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessNoWriteBackException extends + OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = -9088521827450885700L; + + /** + * + */ + public OpenR66ProtocolBusinessNoWriteBackException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessNoWriteBackException(String arg0, + Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessNoWriteBackException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessNoWriteBackException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryAlreadyFinishedException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryAlreadyFinishedException.java index e8de9e602..2fe72bcb4 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryAlreadyFinishedException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryAlreadyFinishedException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part due to Query is already finished - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessQueryAlreadyFinishedException extends - OpenR66ProtocolBusinessException { - /** - * - */ - private static final long serialVersionUID = 1014687763768508552L; - - /** - * - */ - public OpenR66ProtocolBusinessQueryAlreadyFinishedException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessQueryAlreadyFinishedException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessQueryAlreadyFinishedException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessQueryAlreadyFinishedException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part due to Query is already finished + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessQueryAlreadyFinishedException extends + OpenR66ProtocolBusinessException { + /** + * + */ + private static final long serialVersionUID = 1014687763768508552L; + + /** + * + */ + public OpenR66ProtocolBusinessQueryAlreadyFinishedException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessQueryAlreadyFinishedException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessQueryAlreadyFinishedException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessQueryAlreadyFinishedException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryStillRunningException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryStillRunningException.java index ebf2a0963..f373a91e7 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryStillRunningException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessQueryStillRunningException.java @@ -1,62 +1,62 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part due to Query is still running - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessQueryStillRunningException extends - OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = -2795883096275770203L; - - /** - * - */ - public OpenR66ProtocolBusinessQueryStillRunningException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessQueryStillRunningException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessQueryStillRunningException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessQueryStillRunningException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part due to Query is still running + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessQueryStillRunningException extends + OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = -2795883096275770203L; + + /** + * + */ + public OpenR66ProtocolBusinessQueryStillRunningException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessQueryStillRunningException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessQueryStillRunningException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessQueryStillRunningException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessRemoteFileNotFoundException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessRemoteFileNotFoundException.java index 519247f58..60ac9ad92 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessRemoteFileNotFoundException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessRemoteFileNotFoundException.java @@ -1,62 +1,62 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part telling that remote host did not find the file. - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessRemoteFileNotFoundException extends - OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = -1515420982161281552L; - - /** - * - */ - public OpenR66ProtocolBusinessRemoteFileNotFoundException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessRemoteFileNotFoundException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessRemoteFileNotFoundException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessRemoteFileNotFoundException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part telling that remote host did not find the file. + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessRemoteFileNotFoundException extends + OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = -1515420982161281552L; + + /** + * + */ + public OpenR66ProtocolBusinessRemoteFileNotFoundException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessRemoteFileNotFoundException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessRemoteFileNotFoundException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessRemoteFileNotFoundException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessStopException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessStopException.java index f650795b3..72386ba80 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessStopException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolBusinessStopException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Business part - * - * @author frederic bregier - */ -public class OpenR66ProtocolBusinessStopException extends OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = 8865871263523164597L; - - /** - * - */ - public OpenR66ProtocolBusinessStopException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolBusinessStopException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessStopException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolBusinessStopException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Business part + * + * @author frederic bregier + */ +public class OpenR66ProtocolBusinessStopException extends OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = 8865871263523164597L; + + /** + * + */ + public OpenR66ProtocolBusinessStopException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolBusinessStopException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessStopException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolBusinessStopException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNetworkException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNetworkException.java index 9c53aa889..0c5bec6c8 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNetworkException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNetworkException.java @@ -1,60 +1,60 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception due to a network error - * - * @author frederic bregier - */ -public class OpenR66ProtocolNetworkException extends OpenR66Exception { - /** - * - */ - private static final long serialVersionUID = -623368703701931176L; - - /** - * - */ - public OpenR66ProtocolNetworkException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNetworkException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNetworkException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNetworkException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception due to a network error + * + * @author frederic bregier + */ +public class OpenR66ProtocolNetworkException extends OpenR66Exception { + /** + * + */ + private static final long serialVersionUID = -623368703701931176L; + + /** + * + */ + public OpenR66ProtocolNetworkException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNetworkException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNetworkException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNetworkException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoConnectionException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoConnectionException.java index 743591c7f..cdf1dc5a7 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoConnectionException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoConnectionException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol Exception when no connection is possible - * - * @author frederic bregier - */ -public class OpenR66ProtocolNoConnectionException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = -4525294313715038212L; - - /** - * - */ - public OpenR66ProtocolNoConnectionException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNoConnectionException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoConnectionException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoConnectionException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol Exception when no connection is possible + * + * @author frederic bregier + */ +public class OpenR66ProtocolNoConnectionException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = -4525294313715038212L; + + /** + * + */ + public OpenR66ProtocolNoConnectionException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNoConnectionException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoConnectionException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoConnectionException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoDataException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoDataException.java index 8eddf8d85..44e64b935 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoDataException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoDataException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception due to no Data exception - * - * @author Frederic Bregier - * - */ -public class OpenR66ProtocolNoDataException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 3797740371759917728L; - - /** - * - */ - public OpenR66ProtocolNoDataException() { - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNoDataException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoDataException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoDataException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception due to no Data exception + * + * @author Frederic Bregier + * + */ +public class OpenR66ProtocolNoDataException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 3797740371759917728L; + + /** + * + */ + public OpenR66ProtocolNoDataException() { + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNoDataException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoDataException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoDataException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoSslException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoSslException.java index a04bcfb15..db517a1b3 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoSslException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNoSslException.java @@ -1,60 +1,60 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol Exception when no SSL is supported - * - * @author frederic bregier - */ -public class OpenR66ProtocolNoSslException extends OpenR66Exception { - /** - * - */ - private static final long serialVersionUID = 765327612922240252L; - - /** - * - */ - public OpenR66ProtocolNoSslException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNoSslException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoSslException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNoSslException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol Exception when no SSL is supported + * + * @author frederic bregier + */ +public class OpenR66ProtocolNoSslException extends OpenR66Exception { + /** + * + */ + private static final long serialVersionUID = 765327612922240252L; + + /** + * + */ + public OpenR66ProtocolNoSslException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNoSslException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoSslException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNoSslException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotAuthenticatedException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotAuthenticatedException.java index ad5a2b3ab..cfab580a6 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotAuthenticatedException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotAuthenticatedException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Business Protocol exception due to no valid authentication - * - * @author frederic bregier - */ -public class OpenR66ProtocolNotAuthenticatedException extends OpenR66ProtocolBusinessException { - - /** - * - */ - private static final long serialVersionUID = 5671796883262590190L; - - /** - * - */ - public OpenR66ProtocolNotAuthenticatedException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNotAuthenticatedException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNotAuthenticatedException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNotAuthenticatedException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Business Protocol exception due to no valid authentication + * + * @author frederic bregier + */ +public class OpenR66ProtocolNotAuthenticatedException extends OpenR66ProtocolBusinessException { + + /** + * + */ + private static final long serialVersionUID = 5671796883262590190L; + + /** + * + */ + public OpenR66ProtocolNotAuthenticatedException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNotAuthenticatedException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNotAuthenticatedException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNotAuthenticatedException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotYetConnectionException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotYetConnectionException.java index 48c436aa3..38e78c03e 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotYetConnectionException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolNotYetConnectionException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol Exception when a connection is not yet possible but could be later on - * - * @author frederic bregier - */ -public class OpenR66ProtocolNotYetConnectionException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = -4985652825229717572L; - - /** - * - */ - public OpenR66ProtocolNotYetConnectionException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolNotYetConnectionException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNotYetConnectionException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolNotYetConnectionException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol Exception when a connection is not yet possible but could be later on + * + * @author frederic bregier + */ +public class OpenR66ProtocolNotYetConnectionException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = -4985652825229717572L; + + /** + * + */ + public OpenR66ProtocolNotYetConnectionException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolNotYetConnectionException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNotYetConnectionException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolNotYetConnectionException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolPacketException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolPacketException.java index f538f2e8d..612112699 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolPacketException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolPacketException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception on Packet - * - * @author frederic bregier - */ -public class OpenR66ProtocolPacketException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 325267029289992117L; - - /** - * - */ - public OpenR66ProtocolPacketException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolPacketException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolPacketException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolPacketException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception on Packet + * + * @author frederic bregier + */ +public class OpenR66ProtocolPacketException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 325267029289992117L; + + /** + * + */ + public OpenR66ProtocolPacketException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolPacketException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolPacketException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolPacketException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolRemoteShutdownException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolRemoteShutdownException.java index c46e53603..eb1ac9153 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolRemoteShutdownException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolRemoteShutdownException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol Exception for remote information of Shutdown - * - * @author frederic bregier - */ -public class OpenR66ProtocolRemoteShutdownException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 5871418368412513994L; - - /** - * - */ - public OpenR66ProtocolRemoteShutdownException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolRemoteShutdownException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolRemoteShutdownException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolRemoteShutdownException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol Exception for remote information of Shutdown + * + * @author frederic bregier + */ +public class OpenR66ProtocolRemoteShutdownException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 5871418368412513994L; + + /** + * + */ + public OpenR66ProtocolRemoteShutdownException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolRemoteShutdownException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolRemoteShutdownException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolRemoteShutdownException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolShutdownException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolShutdownException.java index 2dbc0526e..7667c39d0 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolShutdownException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolShutdownException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol Exception to enable Shutdown - * - * @author frederic bregier - */ -public class OpenR66ProtocolShutdownException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 9047867109141561841L; - - /** - * - */ - public OpenR66ProtocolShutdownException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolShutdownException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolShutdownException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolShutdownException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol Exception to enable Shutdown + * + * @author frederic bregier + */ +public class OpenR66ProtocolShutdownException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 9047867109141561841L; + + /** + * + */ + public OpenR66ProtocolShutdownException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolShutdownException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolShutdownException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolShutdownException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolSystemException.java b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolSystemException.java index f60c61a30..45b7b3058 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolSystemException.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/OpenR66ProtocolSystemException.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.exception; - -/** - * Protocol exception due to system error - * - * @author frederic bregier - */ -public class OpenR66ProtocolSystemException extends OpenR66Exception { - - /** - * - */ - private static final long serialVersionUID = 586197904468892052L; - - /** - * - */ - public OpenR66ProtocolSystemException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public OpenR66ProtocolSystemException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolSystemException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public OpenR66ProtocolSystemException(Throwable arg0) { - super(arg0); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.exception; + +/** + * Protocol exception due to system error + * + * @author frederic bregier + */ +public class OpenR66ProtocolSystemException extends OpenR66Exception { + + /** + * + */ + private static final long serialVersionUID = 586197904468892052L; + + /** + * + */ + public OpenR66ProtocolSystemException() { + super(); + } + + /** + * @param arg0 + * @param arg1 + */ + public OpenR66ProtocolSystemException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolSystemException(String arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public OpenR66ProtocolSystemException(Throwable arg0) { + super(arg0); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/exception/package-info.java b/src/main/java/org/waarp/openr66/protocol/exception/package-info.java index 3a6d7bb79..e6fbeb993 100644 --- a/src/main/java/org/waarp/openr66/protocol/exception/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/exception/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Exceptions - * - * @apiviz.exclude - */ -package org.waarp.openr66.protocol.exception; - +/** + * Classes implementing Exceptions + * + * @apiviz.exclude + */ +package org.waarp.openr66.protocol.exception; + diff --git a/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java b/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java index 8bd5e88d7..e172f52a5 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java @@ -1,745 +1,745 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.http; - -import java.io.IOException; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelFutureListener; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelUpstreamHandler; -import org.jboss.netty.channel.group.ChannelGroup; -import org.jboss.netty.handler.codec.http.Cookie; -import org.jboss.netty.handler.codec.http.CookieDecoder; -import org.jboss.netty.handler.codec.http.CookieEncoder; -import org.jboss.netty.handler.codec.http.DefaultHttpResponse; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.handler.codec.http.HttpMethod; -import org.jboss.netty.handler.codec.http.HttpRequest; -import org.jboss.netty.handler.codec.http.HttpResponse; -import org.jboss.netty.handler.codec.http.HttpResponseStatus; -import org.jboss.netty.handler.codec.http.HttpVersion; -import org.jboss.netty.handler.codec.http.QueryStringDecoder; -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.exception.FileTransferException; -import org.waarp.common.exception.InvalidArgumentException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; - -/** - * Handler for HTTP information support - * - * @author Frederic Bregier - * - */ -public class HttpFormattedHandler extends SimpleChannelUpstreamHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(HttpFormattedHandler.class); - - private static enum REQUEST { - index("index.html"), - active("monitoring_header.html", "monitoring_end.html"), - error("monitoring_header.html", "monitoring_end.html"), - done("monitoring_header.html", "monitoring_end.html"), - all("monitoring_header.html", "monitoring_end.html"), - status("monitoring_header.html", "monitoring_end.html"), - statusxml(""); - - private String header; - private String end; - - /** - * Constructor for a unique file - * - * @param uniquefile - */ - private REQUEST(String uniquefile) { - this.header = uniquefile; - this.end = uniquefile; - } - - /** - * @param header - * @param end - */ - private REQUEST(String header, String end) { - this.header = header; - this.end = end; - } - - /** - * Reader for a unique file - * - * @return the content of the unique file - */ - public String readFileUnique(HttpFormattedHandler handler) { - return handler.readFileHeader(Configuration.configuration.httpBasePath + "monitor/" - + this.header); - } - - public String readHeader(HttpFormattedHandler handler) { - return handler.readFileHeader(Configuration.configuration.httpBasePath + "monitor/" - + this.header); - } - - public String readEnd() { - return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + "monitor/" - + this.end); - } - } - - private static enum REPLACEMENT { - XXXHOSTIDXXX, XXXLOCACTIVEXXX, XXXNETACTIVEXXX, XXXBANDWIDTHXXX, XXXDATEXXX; - } - - public static final int LIMITROW = 60; // better - // if - // it - // can - // be - // divided - // by - // 4 - - public final R66Session authentHttp = new R66Session(); - - private volatile HttpRequest request; - - private final StringBuilder responseContent = new StringBuilder(); - - private volatile HttpResponseStatus status; - - private volatile String uriRequest; - - private static final String sINFO = "INFO", - sNB = "NB", sDETAIL = "DETAIL"; - - /** - * The Database connection attached to this NetworkChannel shared among all associated - * LocalChannels - */ - private DbSession dbSession; - - /** - * Does this dbSession is private and so should be closed - */ - private boolean isPrivateDbSession = false; - private boolean isCurrentRequestXml = false; - - private Map> params = null; - - private String readFileHeader(String filename) { - String value; - try { - value = WaarpStringUtils.readFileException(filename); - } catch (InvalidArgumentException e) { - logger.error("Error while trying to open: " + filename, e); - return ""; - } catch (FileTransferException e) { - logger.error("Error while trying to read: " + filename, e); - return ""; - } - StringBuilder builder = new StringBuilder(value); - - WaarpStringUtils.replace(builder, REPLACEMENT.XXXDATEXXX.toString(), - (new Date()).toString()); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXLOCACTIVEXXX.toString(), - Integer.toString( - Configuration.configuration.getLocalTransaction(). - getNumberLocalChannel())); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXNETACTIVEXXX.toString(), - Integer.toString( - DbAdmin.getNbConnection())); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), - Configuration.configuration.HOST_ID); - TrafficCounter trafficCounter = - Configuration.configuration.getGlobalTrafficShapingHandler().getTrafficCounter(); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXBANDWIDTHXXX.toString(), - "IN:" + (trafficCounter.getLastReadThroughput() / 131072) + - "Mbits  OUT:" + - (trafficCounter.getLastWriteThroughput() / 131072) + "Mbits"); - return builder.toString(); - } - - private String getTrimValue(String varname) { - String value = null; - try { - value = params.get(varname).get(0).trim(); - } catch (NullPointerException e) { - return null; - } - if (value.length() == 0) { - value = null; - } - return value; - } - - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) - throws Exception { - isCurrentRequestXml = false; - status = HttpResponseStatus.OK; - try { - if (DbConstant.admin.isConnected) { - this.dbSession = new DbSession(DbConstant.admin, false); - DbAdmin.nbHttpSession++; - this.isPrivateDbSession = true; - } - } catch (WaarpDatabaseNoConnectionException e1) { - // Cannot connect so use default connection - logger.warn("Use default database connection"); - this.dbSession = DbConstant.admin.session; - } - HttpRequest request = this.request = (HttpRequest) e.getMessage(); - QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request - .getUri()); - uriRequest = queryStringDecoder.getPath(); - logger.debug("Msg: " + uriRequest); - if (uriRequest.contains("gre/") || uriRequest.contains("img/") || - uriRequest.contains("res/")) { - HttpWriteCacheEnable.writeFile(request, - e.getChannel(), Configuration.configuration.httpBasePath + uriRequest, - "XYZR66NOSESSION"); - return; - } - char cval = 'z'; - long nb = LIMITROW; - // check the URI - if (uriRequest.equalsIgnoreCase("/active")) { - cval = '0'; - } else if (uriRequest.equalsIgnoreCase("/error")) { - cval = '1'; - } else if (uriRequest.equalsIgnoreCase("/done")) { - cval = '2'; - } else if (uriRequest.equalsIgnoreCase("/all")) { - cval = '3'; - } else if (uriRequest.equalsIgnoreCase("/status")) { - cval = '4'; - } else if (uriRequest.equalsIgnoreCase("/statusxml")) { - cval = '5'; - nb = 0; // since it could be the default or setup by request - isCurrentRequestXml = true; - } - // Get the params according to get or post - if (request.getMethod() == HttpMethod.GET) { - params = queryStringDecoder.getParameters(); - } else if (request.getMethod() == HttpMethod.POST) { - ChannelBuffer content = request.getContent(); - if (content.readable()) { - String param = content.toString(WaarpStringUtils.UTF8); - queryStringDecoder = new QueryStringDecoder("/?" + param); - } else { - responseContent.append(REQUEST.index.readFileUnique(this)); - writeResponse(e); - return; - } - params = queryStringDecoder.getParameters(); - } - boolean getMenu = (cval == 'z'); - boolean extraBoolean = false; - if (!params.isEmpty()) { - // if not uri, from get or post - if (getMenu) { - String info = getTrimValue(sINFO); - if (info != null) { - getMenu = false; - cval = info.charAt(0); - } else { - getMenu = true; - } - } - // search the nb param - String snb = getTrimValue(sNB); - if (snb != null) { - try { - nb = Long.parseLong(snb); - } catch (Exception e1) { - } - } - // search the detail param - String sdetail = getTrimValue(sDETAIL); - if (sdetail != null) { - try { - if (Integer.parseInt(sdetail) > 0) - extraBoolean = true; - } catch (Exception e1) { - } - } - } - if (getMenu) { - responseContent.append(REQUEST.index.readFileUnique(this)); - } else { - // Use value 0=Active 1=Error 2=Done 3=All - switch (cval) { - case '0': - active(ctx, (int) nb); - break; - case '1': - error(ctx, (int) nb); - break; - case '2': - done(ctx, (int) nb); - break; - case '3': - all(ctx, (int) nb); - break; - case '4': - status(ctx, (int) nb); - break; - case '5': - statusxml(ctx, nb, extraBoolean); - break; - default: - responseContent.append(REQUEST.index.readFileUnique(this)); - } - } - writeResponse(e); - } - - /** - * Add all runners from preparedStatement for type - * - * @param preparedStatement - * @param type - * @param nb - * @throws WaarpDatabaseNoConnectionException - * @throws WaarpDatabaseSqlException - */ - private void addRunners(DbPreparedStatement preparedStatement, String type, - int nb) throws WaarpDatabaseNoConnectionException, - WaarpDatabaseSqlException { - try { - preparedStatement.executeQuery(); - responseContent - .append("
+

 

+
+

Rules

+

You can edit Rules configuration from here.

+ +
+
+
+
+ Rule Helper +
+
+
+
+ +

 

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Rule IdModeHost IdsRecvPathSendPathArchivePathWorkPath
+

SEND + RECV
+ SENDMD5 + RECVMD5
+ SENDTHROUGH
+ RECVTHROUGH
+ SENDMD5THROUGH
+ RECVMD5THROUGH + help for Mode field +

+ The Mode used with a transfer with this rule. For instance, if SENDMD5, the transfer will be a send of file + from the requester to the requested host where each packet will be checked by a MD5. +

help for HostIds field +

+ If no Host is written, these rule is allowed for any Host. If some Hosts are specified, only those + will be accepted with this rule.

The format is as:

<hostids> + <hostid>hostid1</hostid> + <hostid>hostid2</hostid> +</hostids>

+

+ help for Recv Path field +

+ If not null, it specifies a sub path of server ROOT for final receive directory. +

+

+ help for Send Path field +

+ If not null, it specifies a sub path of server ROOT for send directory. +

+

+ help for Archive Path field +

+ If not null, it specifies a sub path of server ROOT for archive (export) directory. +

+

+ help for Working Path field +

+ If not null, it specifies a sub path of server ROOT for working (during receive) directory. +

Recv PreRecv PostRecv ErrorSend PreSend PostSend Error 
+help for Recv Pre Actions field +

+ It specifies all actions to do BEFORE the transfer operation as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Recv Post Actions field +

+ It specifies all actions to do AFTER the transfer operation as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Recv Error Actions field +

+ It specifies all actions to do AFTER AN ERROR OCCURS as receiver host(SEND and requested, + or RECV and requester).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Pre Actions field +

+ It specifies all actions to do BEFORE the transfer operation as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Post Actions field +

+ It specifies all actions to do AFTER the transfer operation as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+help for Send Error Actions field +

+ It specifies all actions to do AFTER AN ERROR OCCURS as sender host(SEND and requester, + or RECV and requested).

The format is as:

<tasks> + <task> + <type>NAME</type> + <path>path</path> + <delay>x</delay> + </task> +</tasks>where
+-type is one of LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE
+-path is a static argument where some replacement will be done
+-delay is usually the maximum delay of execution
+See the API or doc for the specific conditions.

+

+
+

 

+
+

Filter on Rule Id:

+
+ Filter on Mode: ALL + ALL SEND + ALL RECV + help for Mode Filter field +

+ Either you choose "ALL SEND", "ALL RECV" or "ALL" but none of specific (SEND, RECV, ...), + or you choose some specifics types of mode (SEND, SENDMD5, ...). +

+

  + SEND + RECV + SENDMD5 + RECVMD5 + SENDTHROUGH + RECVTHROUGH + SENDMD5THROUGH + RECVMD5THROUGH

+

                                                                +                +

+
+

 

diff --git a/src/main/admin2/System.html b/src/main/admin2/System.html index 976425dd4..7da7865ec 100644 --- a/src/main/admin2/System.html +++ b/src/main/admin2/System.html @@ -1,179 +1,179 @@ - - - - - - - - - - - -System - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

System

-

You can edit System configuration from here, disconnect from the Administrator or even shutdown the OpenR66 server.

-

 

-
- Bandwidth Session Read Limit (B/s): - - help for Session Limit field -

- The value (in Byte per second) specifies the limit of read bandwidth (in) per session. 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Session Write Limit (B/s): - - help for Session Limit field -

- The value (in Byte per second) specifies the limit of write bandwidth (out) per session. 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Global Read Limit (B/s):   - - help for Global Limit field -

- The value (in Byte per second) specifies the limit of read bandwidth (in) globally (cumulative). 0 means no limit. Must be greater than 1KBs. -


- Bandwidth Global Write Limit (B/s):   - - help for Global Limit field -

- The value (in Byte per second) specifies the limit of write bandwidth (out) globally (cumulative). 0 means no limit. Must be greater than 1KBs. -


- Delay for Commander (ms): - - help for Delay for Commander field -

- Delay for Commander between two acquires of new requested transfers in ms. Must be greater than 100ms. -


- Delay for Retry (ms):   - - help for Delay for Retry field -

- Delay for Retry between two retries for a currently active transfer in ms. Must be greater than 1000ms. -

-

 

-

                                                                -                -

-
-

 

-

 

-
- Export Config in Archive directory              - - help for ExportConfig -

- You can export Rules and Authentications to archive directory by clicking on this button. -

-
-

 

-

 

-
- Disconnect from OpenR66 Administrator      - - help for Disconnection -

- You can disconnect from this administrator by clicking on this button. -

-
-

 

-

 

-
- Shutdown OpenR66 Server                         - - help for Shutdown -

- By clicking on this button will result in the Shutdown process of the full OpenR66 Server (all active transfers - will be stopped in pause).. -

-
-

 

-
-

 

- + + + + + + + + + + + +System + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
+

System

+

You can edit System configuration from here, disconnect from the Administrator or even shutdown the OpenR66 server.

+

 

+
+ Bandwidth Session Read Limit (B/s): + + help for Session Limit field +

+ The value (in Byte per second) specifies the limit of read bandwidth (in) per session. 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Session Write Limit (B/s): + + help for Session Limit field +

+ The value (in Byte per second) specifies the limit of write bandwidth (out) per session. 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Global Read Limit (B/s):   + + help for Global Limit field +

+ The value (in Byte per second) specifies the limit of read bandwidth (in) globally (cumulative). 0 means no limit. Must be greater than 1KBs. +


+ Bandwidth Global Write Limit (B/s):   + + help for Global Limit field +

+ The value (in Byte per second) specifies the limit of write bandwidth (out) globally (cumulative). 0 means no limit. Must be greater than 1KBs. +


+ Delay for Commander (ms): + + help for Delay for Commander field +

+ Delay for Commander between two acquires of new requested transfers in ms. Must be greater than 100ms. +


+ Delay for Retry (ms):   + + help for Delay for Retry field +

+ Delay for Retry between two retries for a currently active transfer in ms. Must be greater than 1000ms. +

+

 

+

                                                                +                +

+
+

 

+

 

+
+ Export Config in Archive directory              + + help for ExportConfig +

+ You can export Rules and Authentications to archive directory by clicking on this button. +

+
+

 

+

 

+
+ Disconnect from OpenR66 Administrator      + + help for Disconnection +

+ You can disconnect from this administrator by clicking on this button. +

+
+

 

+

 

+
+ Shutdown OpenR66 Server                         + + help for Shutdown +

+ By clicking on this button will result in the Shutdown process of the full OpenR66 Server (all active transfers + will be stopped in pause).. +

+
+

 

+
+

 

+ \ No newline at end of file diff --git a/src/main/admin2/Transfers.html b/src/main/admin2/Transfers.html index 2b82d45e7..344c7ecd7 100644 --- a/src/main/admin2/Transfers.html +++ b/src/main/admin2/Transfers.html @@ -1,116 +1,116 @@ - - - - - - - - - - - -Transfers - - - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
Listing -Cancel-Restart -Export -
-

Transfers

-

In this menu, you can administrate transfers.

-
    -
  • -
    Listing helps you to list all transfers according to some criteria.
  • -
  • -
    Cancel-Restart helps you to stop (cancel) active transfers or to restart pending transfers.
  • -
  • -
    Export helps you to export to an XML file the current log of the transfers.
-
-

 

- - + + + + + + + + + + + +Transfers + + + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
Listing +Cancel-Restart +Export +
+

Transfers

+

In this menu, you can administrate transfers.

+
    +
  • +
    Listing helps you to list all transfers according to some criteria.
  • +
  • +
    Cancel-Restart helps you to stop (cancel) active transfers or to restart pending transfers.
  • +
  • +
    Export helps you to export to an XML file the current log of the transfers.
+
+

 

+ + diff --git a/src/main/admin2/error.html b/src/main/admin2/error.html index d22384f2d..e44b27cd9 100644 --- a/src/main/admin2/error.html +++ b/src/main/admin2/error.html @@ -1,97 +1,97 @@ - - - - - - - - - - - -Start - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
-
-

 

- -

- - - -
-

 

-
-

Start

-

-

An event occurs that forces to close the connection...

-

 

-

XXXERRORMESGXXX

-

 

-
-

 

- - + + + + + + + + + + + +Start + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
+
+

 

+ +

+ + + +
+

 

+
+

Start

+

+

An event occurs that forces to close the connection...

+

 

+

XXXERRORMESGXXX

+

 

+
+

 

+ + diff --git a/src/main/admin2/index.html b/src/main/admin2/index.html index 4766078d0..0cd8a885b 100644 --- a/src/main/admin2/index.html +++ b/src/main/admin2/index.html @@ -1,112 +1,112 @@ - - - - - - - - - - - -Start - - - - - - - -
OpenR66 -
-
- - - - - - - - - - - - - - - - - - - - - - - - - -
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
-
-

 

- -

- - - -
-

 

-
-

Start

-

-

This site is the Administrator site of OpenR66.

-

 

-

The current host is:

-

XXXHOSTIDXXX

-

 

-

The current administrator is:

-

XXXADMINXXX

-

 

-

 

-

 

-

 

-

 

-

 

-

OpenR66 is part of the Waarp Project: see the Web site http://waarp.github.com/Waarp/index.html

-

Version: XXXVERSIONXXX

-

Author: Frederic Bregier

-

 

-
-

 

- - + + + + + + + + + + + +Start + + + + + + + +
OpenR66 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
StartTransfersHostsRulesSystemLogon Local: 
XXXLOCALXXX
 Network: 
XXXNETWORKXXX
 Host: 
 XXXHOSTIDXXX 
 Authent: 
 XXXADMINXXX 
 XXXBANDWIDTHXXX 
+
+

 

+ +

+ + + +
+

 

+
+

Start

+

+

This site is the Administrator site of OpenR66.

+

 

+

The current host is:

+

XXXHOSTIDXXX

+

 

+

The current administrator is:

+

XXXADMINXXX

+

 

+

 

+

 

+

 

+

 

+

 

+

OpenR66 is part of the Waarp Project: see the Web site http://waarp.github.com/Waarp/index.html

+

Version: XXXVERSIONXXX

+

Author: Frederic Bregier

+

 

+
+

 

+ + diff --git a/src/main/admin2/monitor/index.html b/src/main/admin2/monitor/index.html index b4387fce7..0fe3aebc8 100644 --- a/src/main/admin2/monitor/index.html +++ b/src/main/admin2/monitor/index.html @@ -1,59 +1,59 @@ - - - OpenR66 Monitoring - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
-Default Monitoring:
- -
-Specific Monitoring:
-
-
-
One Choice Active Error Done -All:  - -
-
Number of runners (0 for all):    -               -
-
-
+ + + OpenR66 Monitoring + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+
+Default Monitoring:
+ +
+Specific Monitoring:
+
+
+
One Choice Active Error Done +All:  + +
+
Number of runners (0 for all):    +               +
+
+
\ No newline at end of file diff --git a/src/main/admin2/monitor/monitoring.html b/src/main/admin2/monitor/monitoring.html index c6fc4b1fe..61016f790 100644 --- a/src/main/admin2/monitor/monitoring.html +++ b/src/main/admin2/monitor/monitoring.html @@ -1,43 +1,43 @@ - - - OpenR66 Live Monitoring - - - - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
-

+ + + OpenR66 Live Monitoring + + + + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+
+

\ No newline at end of file diff --git a/src/main/admin2/monitor/monitoring_header.html b/src/main/admin2/monitor/monitoring_header.html index 3218826eb..872a6d4ac 100644 --- a/src/main/admin2/monitor/monitoring_header.html +++ b/src/main/admin2/monitor/monitoring_header.html @@ -1,42 +1,42 @@ - - - OpenR66 Live Monitoring - - - - - - - - - - - - - - - - - -
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX -
Number of local active -connections: XXXLOCACTIVEXXXNumber of network active -connections: XXXNETACTIVEXXX
-
+ + + OpenR66 Live Monitoring + + + + + + + + + + + + + + + + + +
XXXDATEXXXBandwidth: XXXBANDWIDTHXXX +
Number of local active +connections: XXXLOCACTIVEXXXNumber of network active +connections: XXXNETACTIVEXXX
+


\ No newline at end of file diff --git a/src/main/admin2/res/OpenR66Admin.css b/src/main/admin2/res/OpenR66Admin.css index fe6f708f0..07294611f 100644 --- a/src/main/admin2/res/OpenR66Admin.css +++ b/src/main/admin2/res/OpenR66Admin.css @@ -1,97 +1,97 @@ -p { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -table { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -div { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -li { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -.normal { - font-family:Verdana; - font-size:11px; - color:#000000; - font-weight:normal; - font-style:normal; - margin:0px; - padding:0px; -} -.h1 { - font-family:Arial,Verdana; - font-size:20px; - color:#333333; - font-weight:bold; - margin:12px 0px 4px 0px; - padding:0px; -} -.h2 { - font-family:Verdana; - font-size:14px; - color:#333333; - font-weight:bold; - margin:8px 0px 2px 0px; - padding:0px; -} -.h3 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:normal; - margin:4px 0px 0px 0px; - padding:0px; -} -.h4 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:italic; - margin:4px 0px 0px 0px; - padding:0px; -} -.h5 { - font-family:Arial,Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - font-style:italic; - margin:4px 0px 0px 0px; - padding:0px; -} -.h6 { - font-family:Verdana; - font-size:11px; - color:#333333; - font-weight:bold; - letter-spacing:1px; - margin:4px 0px 0px 0px; - padding:0px; -} +p { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +table { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +div { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +li { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +.normal { + font-family:Verdana; + font-size:11px; + color:#000000; + font-weight:normal; + font-style:normal; + margin:0px; + padding:0px; +} +.h1 { + font-family:Arial,Verdana; + font-size:20px; + color:#333333; + font-weight:bold; + margin:12px 0px 4px 0px; + padding:0px; +} +.h2 { + font-family:Verdana; + font-size:14px; + color:#333333; + font-weight:bold; + margin:8px 0px 2px 0px; + padding:0px; +} +.h3 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:normal; + margin:4px 0px 0px 0px; + padding:0px; +} +.h4 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:italic; + margin:4px 0px 0px 0px; + padding:0px; +} +.h5 { + font-family:Arial,Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + font-style:italic; + margin:4px 0px 0px 0px; + padding:0px; +} +.h6 { + font-family:Verdana; + font-size:11px; + color:#333333; + font-weight:bold; + letter-spacing:1px; + margin:4px 0px 0px 0px; + padding:0px; +} diff --git a/src/main/admin2/res/OpenR66TaskOptions.html b/src/main/admin2/res/OpenR66TaskOptions.html index 78f3713ba..405b3eb0a 100644 --- a/src/main/admin2/res/OpenR66TaskOptions.html +++ b/src/main/admin2/res/OpenR66TaskOptions.html @@ -1,421 +1,421 @@ - - - - - - - -Waarp - Waarp R66-TaskOptions - - -

Waarp R66-TaskOptions

-

We focus here on the several tasks that are possible to run before a transfer starts (pre action), after a transfer is finished correctly (post action) or after an error occurs (either in pre or post action or during transfer: error action).

-

 

-

Those actions are defined in one rule. Each rule contains 2 parts:

-
    -
  1. Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the requested on a RECV rule.
  2. - -
  3. -
    Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the requested on a SEND rule.
-

Each action could be on pre, post or error step, each step can have several actions.

-

 

-

It is defined with a unified form of XML:

-

 

-

        <tasks>

-

          <task>

-

             <type>NAME</type>

-

             <path>path</path>

-

             <delay>x</delay>

-

          </task>

-

          <task>

-

             <type>NAME</type>

-

             <path>path</path>

-

             <delay>x</delay>

-

          </task>

-

      </tasks>

-
    -
  • Type is the type of task to execute (see below the supported types)
  • - -
  • Path is a fixed argument for the task to execute. On this argument, string replacements are done when the following patterns are found:
      -
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • - -
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • - -
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • - -
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • - -
    • #FILESIZE# : File size if it exists
    • - -
    • #INPATH# : In (Receive) path 
    • - -
    • #OUTPATH# : Out (Send) path 
    • - -
    • #WORKPATH# : Working (while receiving) path 
    • - -
    • #ARCHPATH# : Archive path (for export Log)
    • - -
    • #HOMEPATH# : Home path (to enable for instance relative path commands) 
    • - -
    • #RULE# : Rule used during transfer 
    • - -
    • #DATE# : Current Date in yyyyMMdd format
    • - -
    • #HOUR# : Current Hour in HHmmss format
    • - -
    • #REMOTEHOST# : Remote host id (if not the initiator of the call)
    • - -
    • #REMOTEHOSTIP# : Remote host IP (if not the initiator of the call)
    • - -
    • #LOCALHOST# : Local host Id
    • - -
    • #LOCALHOSTIP# : Local host IP
    • - -
    • #TRANSFERID# : Transfer Id
    • - -
    • #REQUESTERHOST# : Requester host Id 
    • - -
    • #REQUESTEDHOST# : Requested host Id
    • - -
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST 
    • - -
    • #RANKTRANSFER# : Current or final RANK of block
    • - -
    • #BLOCKSIZE# : Block size used
    • - -
    • #ERRORMSG# : The current error message or NoError if no error occurs until this call
    • - -
    • #ERRORCODE# : The current error code or '-' (Unknown) if no error occurs until this call
    • - -
    • #ERRORSTRCODE# : The current error code message or "Unknown" if no error occurs until this call
    • - -
    • #NOWAIT# : Used by Exec type task to specify that the command will be executed in asynchronous mode, without waiting any result from it
    • - -
    • -
      #LOCALEXEC# : Used by Exec type task to specify that the command will be executed not locally (within the JVM) but outside using a LocalExec Daemon (specified in the global configuration)
  • - - -
  • Delay is generally the delay (if any) for execution before the execution becomes out of time.
  • - -
  • -
    Additionnaly, a task will use also the argument from the transfer itself (Transfer Information).
-

Each action is of one of the following items:

-
    -
  • -
    LOG
-
-

This task logs or writes to an external file some info:

-
    -
  • if delay is 0, no echo at all will be done
  • - -
  • if delay is 1, will echo some information in the normal log
  • - -
  • if delay is 2, will echo some information in the file (last deduced argument will be the full path for the file output)
  • - -
  • if delay is 3, will echo both in the normal log and in the file (last deduced argument will be the full path for the file output)
  • - -
  • -
    If first word of the log is one of debug, info, warn or error, this word will be used as the log level
-
    -
  • -
    MOVE
-
-

Move the file to the path designed by Path and Transfer Information arguments without renaming the filename (same basename).

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is marked as moved.

-
    -
  • -
    MOVERENAME
-
-

Move the file to the path designed by Path and Transfer Information arguments.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored. 

-

 

-

The file is marked as moved.

-
    -
  • -
    COPY
-
-

Copy the file to the path designed by Path argument without renaming the filename (same basename).

-

 

-

Delay and Transfer Information are ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    COPYRENAME
-
-

Copy the file to the path designed by Path and Transfer Information arguments.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    EXEC
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The file is not marked as moved.

-

 

-

The external command is supposed to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution
  • - -
  • exit 1, for a warned execution (but however correct)
  • - -
  • -
    other exit values for a failed execution
-
    -
  • -
    EXECMOVE
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The last line returned by the external command is interpreted as the new full file path. The external command is responsible to really move the previous file to the new one.

-

 

-

The file is marked as moved.

-

 

-

The external command is supposed to to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution

  • - -
  • exit 1, for a warned execution (but however correct)

  • - -
  • -

    other exit values for a failed execution

-
    -
  • -
    EXECOUTPUT
-
-

Execute an external command given by Path and Transfer Information arguments.

-

 

-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

All lines returned by the external command (normal output) is interpreted as the possible error message in case of error.

-

 

-

The file is not marked as moved.

-

 

-

The external command is supposed to to behave as the following for its exiting value:

-
    -
  • exit 0, for a correct execution

  • - -
  • exit 1, for a warned execution (but however correct)

  • - -
  • -

    other exit values for a failed execution, for which the output (stdout) lines are used as error message, bring back to the remote host as #ERRORMSG# and #ERRORCODE# / #ERRORSTRCODE#

-
    -
  • -
    EXECJAVA
-
-

Execute an external Java class given by Path and Transfer Information arguments.

-
-

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

-

 

-

The class name (which must implement R66Runnable) is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)). The first argument is this full classname. The allocation must be of the form new MyClass(), so an empty constructor.

-

 

-

The file is not marked as moved.

-
    -
  • -
    TRANSFER
-
-

Submit a new transfer based on the Path and Transfer Information arguments.

-

 

-

The transfer arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The result should be as r66send command except "-info" must be the last field:

-

"-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] -info transferInformation"

-

where each field is separated by blank character. Last field (transferInformation) may contain however blank character.

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-
    -
  • -
    VALIDFILEPATH
-
-

Test if the current file is under one of the paths based on the Path and Transfer Information arguments.

-

 

-

The paths arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

The result should be as: "path1 path2 ..." where each path is separated by blank character.

-

 

-

If Delay is not 0, a log is printed out.

-

 

-

The file is not marked as moved.

-
    -
  • -
    DELETE
-
-

This task deletes the current file.

-

 

-

The current file is no more valid.

-

 

-

No arguments are taken into account.

-
    -
  • -
    LINKRENAME
-
-

Create a link of the current file and make the file pointing to it.

-

 

-

The link first tries to be a hard link, then a soft link, and if it is really not possible (not supported by the filesystem), it does a copy and rename task.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay is ignored.

-

 

-

The file is not marked as moved.

-

 

-
    -
  • -
    RESCHEDULE
-
-

Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error code is one of the specified codes and the optional intervals of date are compatible with the new time schedule

Result of arguments will be as following options (the two first are mandatory):

-
    -
  • -
      -
    • "-delay ms" where ms is the added number of ms on current time before retry on schedule
    • - -
    • "-case errorCode,errorCode,..." where errorCode is one of the following error of the current transfer (either literal or code in 1 character):
      ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
    • - -
    • "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can be not set) and where start and stop are in the following format:
      Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
      Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, while X=n or Xn means setting exact value
      If one time specification is not set, it is based on the current date.

      If "-notbetween" is specified, the planned date must not be in the area.
      If "-between" is specified, the planned date must be found in any such specified areas (could be in any of the occurrence). If not specified, it only depends on "-notbetween".
      If none is specified, the planned date is always valid.
    • - -
    • -
      "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule as "#CPTLIMIT#newlimit#CPTLIMIT#".
-
-
-

Each time this function is called, the limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".

-

To ensure correctness, the value must be in the "info of transfer" since this value will be changed statically in the "info of transfer". If taken from the rule, it will be wrong since the value will never decrease. However, a value must be setup in the rule in order to reset the value when the count reach 0.
So in the rule, "-count resetlimit" must be present, where resetlimit will be the new value set when the limit reach 0, and in the "info on transfer", "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied.

-



-
-

Note that if a previous called to a reschedule was done for this attempt and was successful, the following calls will be ignored.

-
-

Important note: any subsequent task will be ignored and not executed once the reschedule is accepted. On the contrary, if the reschedule is not accepted, the following tasks will be executed normally.

In case start > end, end will be +1 day

-
-

In case start and end < current planned date, both will have +1 day.

-
-


Example:

-
-

"-delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0 -count 1"
And in the “file information”:

-
-

"#CPTLIMIT#3#CPTLIMIT#”

-
-

means retry in case of error during initialization of connection in 1 hour if not between 7AM to 7PM and not between 1AM to 3AM and with a limit of 3 retries (retry will be reset to 1 in case of 3 attempts).

-
    -
  • -
    TAR
-
-

Create a TAR from the argument as source and destination or UNTAR files from a TAR file.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay of 1 = UNTAR PATH="sourceFile targetDirectory"

-

 

-

Delay of 2 = TAR PATH="targetFile sourceDirectory"

-

 

-

Delay of 3 = TAR PATH="targetFile sourceFile1 sourceFile2..."

-

 

-

The current file is not touched.

-
    -
  • -
    ZIP
-
-

Create a ZIP from the argument as source and destination or UNZIP files from a ZIP file.

-

 

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-

 

-

Delay of 1 = UNZIP PATH="sourceFile targetDirectory"

-

 

-

Delay of 2 = ZIP PATH="targetFile sourceDirectory"

-

 

-

Delay of 3 = ZIP PATH="targetFile sourceFile1 sourceFile2..."

-

 

-

The current file is not touched.

-
    -
  • -

    TRANSCODE

-
-

Allow to transcode a file from a Charset to another one.

-

-

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

-
    -
  • "-from fromCharset"
  • - -
  • "-to toCharset"
  • - -
  • "-newfile filename" optional argument ; if not used, will be current filename.extension ; if used, extension is ignored
  • - -
  • -
    "-extension extension" optional argument ; if not used, will be filename.transcode
-

-

fromCharset and toCharset are string representations of the official charsets in Java.

-

 

-

A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) all the supported Charsets from your JVM. To use it, run the following command:

-

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]

-

 

-

-

-

It could also be used as a test of transcode outside R66:

-

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset

-

 

-

The current file is not touched and is not marked as moved.

-
-

 

-

 

-

 

-

Example:

-

 

-

      <tasks>

-

     <task>

-

        <type>MOVE</type>

-

        <path>/pathout/</path>

-

        <comment>move the file to /pathout/#TRUEFILENAME#</comment>

-

        <delay>0</delay>

-

     </task>

-

     <task>

-

        <type>EXEC</type>

-

        <path>#HOMEPATH#/pathexec/monscript #TRUEFULLPATH# #ORIGINALFILENAME# #FILESIZE# #RULE# %s %d #REMOTEHOST#</path>

-

        <comment>information passed by transfer is "a_string_without_blank a_number" and replaced respectively in %s and %d</comment>

-

        <delay>30000</delay>

-

        <comment>maximum 30 seconds to execute this script</comment>

-

     </task>

-

   </tasks>

-
-
-
-
-

 

- - + + + + + + + +Waarp - Waarp R66-TaskOptions + + +

Waarp R66-TaskOptions

+

We focus here on the several tasks that are possible to run before a transfer starts (pre action), after a transfer is finished correctly (post action) or after an error occurs (either in pre or post action or during transfer: error action).

+

 

+

Those actions are defined in one rule. Each rule contains 2 parts:

+
    +
  1. Sender actions: A host is a Sender if it is the requester on a SEND rule or if it is the requested on a RECV rule.
  2. + +
  3. +
    Receiver actions: A host is a Sender if it is the requester on a RECV rule or if it is the requested on a SEND rule.
+

Each action could be on pre, post or error step, each step can have several actions.

+

 

+

It is defined with a unified form of XML:

+

 

+

        <tasks>

+

          <task>

+

             <type>NAME</type>

+

             <path>path</path>

+

             <delay>x</delay>

+

          </task>

+

          <task>

+

             <type>NAME</type>

+

             <path>path</path>

+

             <delay>x</delay>

+

          </task>

+

      </tasks>

+
    +
  • Type is the type of task to execute (see below the supported types)
  • + +
  • Path is a fixed argument for the task to execute. On this argument, string replacements are done when the following patterns are found:
      +
    • #TRUEFULLPATH# : Current full path of current FILENAME
    • + +
    • #TRUEFILENAME# : Current FILENAME (basename) (change in retrieval part)
    • + +
    • #ORIGINALFULLPATH# : Original full path FILENAME (before changing in retrieval part)
    • + +
    • #ORIGINALFILENAME# : Original FILENAME (basename) (before changing in retrieval part)
    • + +
    • #FILESIZE# : File size if it exists
    • + +
    • #INPATH# : In (Receive) path 
    • + +
    • #OUTPATH# : Out (Send) path 
    • + +
    • #WORKPATH# : Working (while receiving) path 
    • + +
    • #ARCHPATH# : Archive path (for export Log)
    • + +
    • #HOMEPATH# : Home path (to enable for instance relative path commands) 
    • + +
    • #RULE# : Rule used during transfer 
    • + +
    • #DATE# : Current Date in yyyyMMdd format
    • + +
    • #HOUR# : Current Hour in HHmmss format
    • + +
    • #REMOTEHOST# : Remote host id (if not the initiator of the call)
    • + +
    • #REMOTEHOSTIP# : Remote host IP (if not the initiator of the call)
    • + +
    • #LOCALHOST# : Local host Id
    • + +
    • #LOCALHOSTIP# : Local host IP
    • + +
    • #TRANSFERID# : Transfer Id
    • + +
    • #REQUESTERHOST# : Requester host Id 
    • + +
    • #REQUESTEDHOST# : Requested host Id
    • + +
    • #FULLTRANSFERID# : Full Transfer Id as TRANSFERID_REQUESTERHOST_REQUESTEDHOST 
    • + +
    • #RANKTRANSFER# : Current or final RANK of block
    • + +
    • #BLOCKSIZE# : Block size used
    • + +
    • #ERRORMSG# : The current error message or NoError if no error occurs until this call
    • + +
    • #ERRORCODE# : The current error code or '-' (Unknown) if no error occurs until this call
    • + +
    • #ERRORSTRCODE# : The current error code message or "Unknown" if no error occurs until this call
    • + +
    • #NOWAIT# : Used by Exec type task to specify that the command will be executed in asynchronous mode, without waiting any result from it
    • + +
    • +
      #LOCALEXEC# : Used by Exec type task to specify that the command will be executed not locally (within the JVM) but outside using a LocalExec Daemon (specified in the global configuration)
  • + + +
  • Delay is generally the delay (if any) for execution before the execution becomes out of time.
  • + +
  • +
    Additionnaly, a task will use also the argument from the transfer itself (Transfer Information).
+

Each action is of one of the following items:

+
    +
  • +
    LOG
+
+

This task logs or writes to an external file some info:

+
    +
  • if delay is 0, no echo at all will be done
  • + +
  • if delay is 1, will echo some information in the normal log
  • + +
  • if delay is 2, will echo some information in the file (last deduced argument will be the full path for the file output)
  • + +
  • if delay is 3, will echo both in the normal log and in the file (last deduced argument will be the full path for the file output)
  • + +
  • +
    If first word of the log is one of debug, info, warn or error, this word will be used as the log level
+
    +
  • +
    MOVE
+
+

Move the file to the path designed by Path and Transfer Information arguments without renaming the filename (same basename).

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is marked as moved.

+
    +
  • +
    MOVERENAME
+
+

Move the file to the path designed by Path and Transfer Information arguments.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored. 

+

 

+

The file is marked as moved.

+
    +
  • +
    COPY
+
+

Copy the file to the path designed by Path argument without renaming the filename (same basename).

+

 

+

Delay and Transfer Information are ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    COPYRENAME
+
+

Copy the file to the path designed by Path and Transfer Information arguments.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    EXEC
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The file is not marked as moved.

+

 

+

The external command is supposed to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution
  • + +
  • exit 1, for a warned execution (but however correct)
  • + +
  • +
    other exit values for a failed execution
+
    +
  • +
    EXECMOVE
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The last line returned by the external command is interpreted as the new full file path. The external command is responsible to really move the previous file to the new one.

+

 

+

The file is marked as moved.

+

 

+

The external command is supposed to to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution

  • + +
  • exit 1, for a warned execution (but however correct)

  • + +
  • +

    other exit values for a failed execution

+
    +
  • +
    EXECOUTPUT
+
+

Execute an external command given by Path and Transfer Information arguments.

+

 

+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The command path is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

All lines returned by the external command (normal output) is interpreted as the possible error message in case of error.

+

 

+

The file is not marked as moved.

+

 

+

The external command is supposed to to behave as the following for its exiting value:

+
    +
  • exit 0, for a correct execution

  • + +
  • exit 1, for a warned execution (but however correct)

  • + +
  • +

    other exit values for a failed execution, for which the output (stdout) lines are used as error message, bring back to the remote host as #ERRORMSG# and #ERRORCODE# / #ERRORSTRCODE#

+
    +
  • +
    EXECJAVA
+
+

Execute an external Java class given by Path and Transfer Information arguments.

+
+

The Delay is the maximum amount of time in milliseconds before the task should be considered as over time and so in error.

+

 

+

The class name (which must implement R66Runnable) is obtained from Path transformed according to above dynamic replacements, and after a String Format where Transfer Information is used as input (String.format(Path,Info)). The first argument is this full classname. The allocation must be of the form new MyClass(), so an empty constructor.

+

 

+

The file is not marked as moved.

+
    +
  • +
    TRANSFER
+
+

Submit a new transfer based on the Path and Transfer Information arguments.

+

 

+

The transfer arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The result should be as r66send command except "-info" must be the last field:

+

"-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] -info transferInformation"

+

where each field is separated by blank character. Last field (transferInformation) may contain however blank character.

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+
    +
  • +
    VALIDFILEPATH
+
+

Test if the current file is under one of the paths based on the Path and Transfer Information arguments.

+

 

+

The paths arguments are obtained from Path transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

The result should be as: "path1 path2 ..." where each path is separated by blank character.

+

 

+

If Delay is not 0, a log is printed out.

+

 

+

The file is not marked as moved.

+
    +
  • +
    DELETE
+
+

This task deletes the current file.

+

 

+

The current file is no more valid.

+

 

+

No arguments are taken into account.

+
    +
  • +
    LINKRENAME
+
+

Create a link of the current file and make the file pointing to it.

+

 

+

The link first tries to be a hard link, then a soft link, and if it is really not possible (not supported by the filesystem), it does a copy and rename task.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay is ignored.

+

 

+

The file is not marked as moved.

+

 

+
    +
  • +
    RESCHEDULE
+
+

Reschedule Transfer task to a time delayed by the specified number of milliseconds, if the error code is one of the specified codes and the optional intervals of date are compatible with the new time schedule

Result of arguments will be as following options (the two first are mandatory):

+
    +
  • +
      +
    • "-delay ms" where ms is the added number of ms on current time before retry on schedule
    • + +
    • "-case errorCode,errorCode,..." where errorCode is one of the following error of the current transfer (either literal or code in 1 character):
      ConnectionImpossible(C), ServerOverloaded(l), BadAuthent(A), ExternalOp(E), TransferError(T), MD5Error(M), Disconnection(D), RemoteShutdown(r), FinalOp(F), Unimplemented(U), Shutdown(S), RemoteError(R), Internal(I), StoppedTransfer(H), CanceledTransfer(K), Warning(W), Unknown(-), QueryAlreadyFinished(Q), QueryStillRunning(s), NotKnownHost(N), QueryRemotelyUnknown(u), FileNotFound(f), CommandNotFound(c), PassThroughMode(p)
    • + +
    • "-between start;end" and/or "-notbetween start;end" (multiple times are allowed, start or end can be not set) and where start and stop are in the following format:
      Yn:Mn:Dn:Hn:mn:Sn where n is a number for each time specification, each specification is optional, as Y=Year, M=Month, D=Day, H=Hour, m=minute, s=second.
      Format can be X+n, X-n, X=n or Xn where X+-n means adding/subtracting n to current date value, while X=n or Xn means setting exact value
      If one time specification is not set, it is based on the current date.

      If "-notbetween" is specified, the planned date must not be in the area.
      If "-between" is specified, the planned date must be found in any such specified areas (could be in any of the occurrence). If not specified, it only depends on "-notbetween".
      If none is specified, the planned date is always valid.
    • + +
    • +
      "-count limit" will be the limit of retry. The value limit is taken from the "info on transfer" and not from the rule as "#CPTLIMIT#newlimit#CPTLIMIT#".
+
+
+

Each time this function is called, the limit value will be replaced as newlimit = limit - 1 in the "info of transfer" as "#CPTLIMIT#newlimit#CPTLIMIT#".

+

To ensure correctness, the value must be in the "info of transfer" since this value will be changed statically in the "info of transfer". If taken from the rule, it will be wrong since the value will never decrease. However, a value must be setup in the rule in order to reset the value when the count reach 0.
So in the rule, "-count resetlimit" must be present, where resetlimit will be the new value set when the limit reach 0, and in the "info on transfer", "#CPTLIMIT#limit#CPTLIMIT#" must be present. If one is missing, the condition is not applied.

+



+
+

Note that if a previous called to a reschedule was done for this attempt and was successful, the following calls will be ignored.

+
+

Important note: any subsequent task will be ignored and not executed once the reschedule is accepted. On the contrary, if the reschedule is not accepted, the following tasks will be executed normally.

In case start > end, end will be +1 day

+
+

In case start and end < current planned date, both will have +1 day.

+
+


Example:

+
+

"-delay 3600000 -case ConnectionImpossible,ServerOverloaded,Shutdown -notbetween H7:m0:S0;H19:m0:S0 -notbetween H1:m0:S0;H=3:m0:S0 -count 1"
And in the “file information”:

+
+

"#CPTLIMIT#3#CPTLIMIT#”

+
+

means retry in case of error during initialization of connection in 1 hour if not between 7AM to 7PM and not between 1AM to 3AM and with a limit of 3 retries (retry will be reset to 1 in case of 3 attempts).

+
    +
  • +
    TAR
+
+

Create a TAR from the argument as source and destination or UNTAR files from a TAR file.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay of 1 = UNTAR PATH="sourceFile targetDirectory"

+

 

+

Delay of 2 = TAR PATH="targetFile sourceDirectory"

+

 

+

Delay of 3 = TAR PATH="targetFile sourceFile1 sourceFile2..."

+

 

+

The current file is not touched.

+
    +
  • +
    ZIP
+
+

Create a ZIP from the argument as source and destination or UNZIP files from a ZIP file.

+

 

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+

 

+

Delay of 1 = UNZIP PATH="sourceFile targetDirectory"

+

 

+

Delay of 2 = ZIP PATH="targetFile sourceDirectory"

+

 

+

Delay of 3 = ZIP PATH="targetFile sourceFile1 sourceFile2..."

+

 

+

The current file is not touched.

+
    +
  • +

    TRANSCODE

+
+

Allow to transcode a file from a Charset to another one.

+

+

After Path is transformed according to above dynamic replacements, it is then used as a String Format where Transfer Information is used as input (String.format(Path,Info)).

+
    +
  • "-from fromCharset"
  • + +
  • "-to toCharset"
  • + +
  • "-newfile filename" optional argument ; if not used, will be current filename.extension ; if used, extension is ignored
  • + +
  • +
    "-extension extension" optional argument ; if not used, will be filename.transcode
+

+

fromCharset and toCharset are string representations of the official charsets in Java.

+

 

+

A convenient method (from Waarp Common) allows to list in html (-html), csv (-csv) or text format (-text) all the supported Charsets from your JVM. To use it, run the following command:

+

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil [-csv | -html | -text ]

+

 

+

+

+

It could also be used as a test of transcode outside R66:

+

java -cp WaarpCommon-1.2.7.jar org.waarp.common.transcode.CharsetsUtil -from fromFilename fromCharset -to toFilename toCharset

+

 

+

The current file is not touched and is not marked as moved.

+
+

 

+

 

+

 

+

Example:

+

 

+

      <tasks>

+

     <task>

+

        <type>MOVE</type>

+

        <path>/pathout/</path>

+

        <comment>move the file to /pathout/#TRUEFILENAME#</comment>

+

        <delay>0</delay>

+

     </task>

+

     <task>

+

        <type>EXEC</type>

+

        <path>#HOMEPATH#/pathexec/monscript #TRUEFULLPATH# #ORIGINALFILENAME# #FILESIZE# #RULE# %s %d #REMOTEHOST#</path>

+

        <comment>information passed by transfer is "a_string_without_blank a_number" and replaced respectively in %s and %d</comment>

+

        <delay>30000</delay>

+

        <comment>maximum 30 seconds to execute this script</comment>

+

     </task>

+

   </tasks>

+
+
+
+
+

 

+ + diff --git a/src/main/admin2/res/fieldhelp.js b/src/main/admin2/res/fieldhelp.js index 114576245..bf3fe7c91 100644 --- a/src/main/admin2/res/fieldhelp.js +++ b/src/main/admin2/res/fieldhelp.js @@ -1,77 +1,77 @@ -/* start multiple load function - allows scripts to load/register gracefully - design by Simon Willison */ -function addLoadEvent(func) { - var oldonload = window.onload; - if (typeof window.onload != 'function') { - window.onload = func; - } else { - window.onload = function() { - if (oldonload) { - oldonload(); - } - func(); - } - } -} -addLoadEvent(init); -addLoadEvent(function() { -/* more code to run on page load */ -addLoadEvent(openClose); -}); -/* end multiple load function */ - - -/* start function init() - design by Gez Lemon */ -function init() -{ - var objImage = document.getElementsByTagName('img'); - var objHelp, objAnchor, objClone; - - for (var iCounter=0; iCounter - - ------------------------------------------------------------------------------------ - - Copyright(c) 2011 jbulb.org. - http://jbulb.org - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/* + marknote.js + + Minified copy of Marknote - for production use. + For debugging in a tool such as Firebug, use the unminified copy, marknote-debug.js, instead. + + marknote version 0.5.1 + XML DOM/Parser API + + Usage: + + + ------------------------------------------------------------------------------------ + + Copyright(c) 2011 jbulb.org. + http://jbulb.org + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ marknote=function(){};marknote.constants={DOCTYPE_START:"",COMMENT_START:"",TAG_OPEN:"<",TAG_CLOSE:">",TAG_CLOSE_SELF_TERMINATING:"/>",ENDTAG_OPEN:"",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",TOKENTYPE_BRACKET_OPEN:"bracketOpen",TOKENTYPE_TAG_OPEN:"tagOpen",TOKENTYPE_TAG_CLOSE:"tagClose",TOKENTYPE_ENDTAG_OPEN:"endTagOpen",TOKENTYPE_ENDTAG_CLOSE:"endTagClose",TOKENTYPE_SELF_TERMINATING:"closeTagSelfTerminating",TOKENTYPE_WHITESPACE:"whitespace",TOKENTYPE_ATTRIBUTE:"attribute",TOKENTYPE_QUOTE:"quote",TOKENTYPE_QUOTED:"quotedLiteral",TOKENTYPE_NORMAL:"normal",TOKENTYPE_COMMENT_START:"commentStart",TOKENTYPE_COMMENT_END:"commentEnd",TOKENTYPE_CDATA_START:"cdataStart",TOKENTYPE_CDATA_END:"cdataEnd",TOKENTYPE_PI_START:"piStart",TOKENTYPE_PI_END:"piEnd",TOKENTYPE_DOCTYPE_START:"docTypeStart",DATATYPE_ATTRIBUTE:"marknote.Attribute",DATATYPE_CDATA:"marknote.CDATA",DATATYPE_CLONER:"marknote.Cloner",DATATYPE_COMMENT:"marknote.Comment",DATATYPE_DOCTYPE:"marknote.DOCTYPE",DATATYPE_DOCUMENT:"marknote.Document",DATATYPE_ELEMENT:"marknote.Element",DATATYPE_ENTITYREF:"marknote.EntityRef",DATATYPE_XMLENTITYREFS:"marknote.XMLEntityRefs",DATATYPE_ENTITYREFS:"marknote.EntityRefs",DATATYPE_PARSER:"marknote.Parser",DATATYPE_PROCESSINGINSTRUCTION:"marknote.ProcessingInstruction",DATATYPE_QNAME:"marknote.QName",DATATYPE_TEXT:"marknote.Text",DATATYPE_TOKEN:"marknote.Token",DATATYPE_TOKENIZER:"marknote.Tokenizer",DATATYPE_WRITER:"marknote.Writer"};marknote.ajaxDoc=null;marknote.AJAX=function(){this.req=null;this.status=null;this.statusText=null;this.responseText=null};marknote.AJAX.prototype.genRequest=function(){var d=false;try{d=new XMLHttpRequest()}catch(c){try{d=new ActiveXObject("Msxml2.XMLHTTP")}catch(b){try{d=new ActiveXObject("Microsoft.XMLHTTP")}catch(a){d=false}}}this.req=d;return d};marknote.AJAX.prototype.getRequest=function(){return this.req};marknote.AJAX.prototype.getStatus=function(){return this.status};marknote.AJAX.prototype.getStatusText=function(){return this.statusText};marknote.AJAX.prototype.getResponseText=function(){return this.responseText};marknote.AJAX.prototype.constructQueryString=function(d){var c="";if(d&&typeof d=="object"){var a="";for(var b in d){c+=a+encodeURIComponent(b)+"="+encodeURIComponent(d[b]);a="&"}}else{if(d&&typeof d=="string"){c=d}}return c};marknote.AJAX.prototype.read=function(b,c,h,e,a){var f=this.genRequest();var i=this;var d=this.constructQueryString(c);var g;marknote.AJAXDoc=null;a=a&&a.toUpperCase()==="POST"?"POST":"GET";if(!f){return false}if(!h){h=marknote.AJAX.defaultCallback}if(!e){e=new Object()}f.open(a,b,true);f.setRequestHeader("Content-Type","application/x-www-form-urlencoded");f.onreadystatechange=function(){if(f.readyState==4){i.status=f.status;i.statusText=f.statusText;i.responseText=f.responseText;var j=new marknote.Parser();g=j.parse(f.responseText);h.call(i,g,e)}};f.send(d)};marknote.AJAX.prototype.defaultCallback=function(a,b){marknote.AJAXDoc=a};marknote.SJAX=function(){this.req=null;this.status=null;this.statusText=null;this.responseText=null};marknote.SJAX.prototype.getRequest=function(){return this.req};marknote.SJAX.prototype.getStatus=function(){return this.status};marknote.SJAX.prototype.getStatusText=function(){return this.statusText};marknote.SJAX.prototype.getResponseText=function(){return this.responseText};marknote.SJAX.prototype.read=function(a,e,g){var d=new marknote.AJAX();var b=d.genRequest();var c=d.constructQueryString(e);var f=new marknote.Parser();g=g&&g.toUpperCase()==="POST"?"POST":"GET";if(!b){return new marknote.Document()}b.open(g,a,false);b.setRequestHeader("Content-Type","application/x-www-form-urlencoded");b.send(c);this.req=b;this.status=b.status;this.statusText=b.statusText;this.responseText=b.responseText;return f.parse(b.responseText)};marknote.Attribute=function(a,b){this.dataType=marknote.constants.DATATYPE_ATTRIBUTE;this.isSw8tXmlContent=false;this.name=a;this.value=marknote.Util.erefEncode(marknote.Util.nothingToBlank(b))};marknote.Attribute.prototype.getName=function(){return this.name};marknote.Attribute.prototype.setName=function(a){this.name=a};marknote.Attribute.prototype.getValue=function(){return marknote.Util.erefDecode(marknote.Util.nothingToBlank(this.value))};marknote.Attribute.prototype.setValue=function(a){this.value=marknote.Util.erefEncode(marknote.Util.nothingToBlank(a))};marknote.Attribute.prototype.toString=function(){return this.getName()+'="'+this.getValue()+'"'};marknote.Attribute.prototype.clone=function(){return new marknote.Attribute(this.getName(),this.getValue())};marknote.CDATA=function(a){this.dataType=marknote.constants.DATATYPE_CDATA;this.isSw8tXmlContent=true;this.text=marknote.Util.nothingToBlank(a)};marknote.CDATA.prototype.getText=function(){return marknote.Util.nothingToBlank(this.text)};marknote.CDATA.prototype.setText=function(a){this.text=marknote.Util.nothingToBlank(a)};marknote.CDATA.prototype.toString=function(){return this.getText()};marknote.CDATA.prototype.clone=function(){var a=new marknote.Cloner();return a.clone(this)};marknote.Cloner=function(){this.dataType=marknote.constants.DATATYPE_CLONER;this.isSw8tXmlContent=false};marknote.Cloner.prototype.cloneDocument=function(f){var d=new marknote.Document();var g=f.getProcessingInstructions();var a=f.getRootElement();var c;for(var e=0;e0)||typeof d=="object";if(!a){return d}var c=new Object();for(var b in d){c[b]=this.clone(d[b])}return c};marknote.Cloner.prototype.cloneArray=function(c){var b=new Array();var d;for(var a=0;a"};marknote.DOCTYPE.prototype.getTopElement=function(){return this.topElement};marknote.DOCTYPE.prototype.setTopElement=function(a){this.topElement=a};marknote.DOCTYPE.prototype.getAvailability=function(){return this.availability};marknote.DOCTYPE.prototype.setAvailability=function(a){this.availability=a};marknote.DOCTYPE.prototype.getFPI=function(){return this.FPI};marknote.DOCTYPE.prototype.setFPI=function(a){this.FPI=a};marknote.DOCTYPE.prototype.getURL=function(){return this.URL};marknote.DOCTYPE.prototype.setURL=function(a){var b=marknote.Util.trim(a);if(b===""){this.URL="";return}if(b.charAt(0)!='"'){b='"'+b}if(b.charAt(b.length-1)!='"'){b+='"'}this.URL=b};marknote.DOCTYPE.prototype.getInternalSubset=function(){return this.internalSubset};marknote.DOCTYPE.prototype.setInternalSubset=function(a){this.dataType=marknote.constants.DATATYPE_DOCTYPE;this.internalSubset=a};marknote.Document=function(){this.dataType=marknote.constants.DATATYPE_DOCUMENT;this.isSw8tXmlContent=false;this.processingInstructions=new Array();this.rootElement=new marknote.Element();this.contents=new Array()};marknote.Document.prototype.getProcessingInstructions=function(){return this.processingInstructions};marknote.Document.prototype.setProcessingInstructions=function(a){this.processingInstructions=a};marknote.Document.prototype.addProcessingInstruction=function(a){this.processingInstructions.push(a)};marknote.Document.prototype.removeProcessingInstruction=function(c){for(var b=0;b0};marknote.Element.prototype.getContents=function(){return this.contents};marknote.Element.prototype.getContentAt=function(a){return this.getContents()[a]};marknote.Element.prototype.addContent=function(a){if(a&&a.isSw8tXmlContent){this.getContents().push(a)}};marknote.Element.prototype.removeContent=function(a){marknote.Util.removeArrayItem(this.contents,a)};marknote.Element.prototype.setContents=function(a){this.contents=a};marknote.Element.prototype.getText=function(d){var e="";if(typeof d=="undefined"){d=true}for(var b=0;b=0;b--){var c=this.getContentAt(b);var a=marknote.Util.dataType(c);if(a==marknote.constants.DATATYPE_TEXT||a==marknote.constants.DATATYPE_CDATA){marknote.Util.removeArrayItem(this.contents,b)}}};marknote.Element.prototype.getCommentText=function(){var d="";for(var b=0;b=0;b--){var c=this.getContentAt(b);var a=marknote.Util.dataType(c);if(a==marknote.constants.DATATYPE_COMMENT){marknote.Util.removeArrayItem(this.contents,b)}}};marknote.Element.prototype.addChildElement=function(b){var a=marknote.Util.dataType(b);if(!a==marknote.constants.DATATYPE_ELEMENT){return}this.getContents().push(b)};marknote.Element.prototype.removeChildElements=function(f){var e=0;if(!f){e=this.contents.length;this.contents=new Array();return e}var c=f.dataType==marknote.constants.DATATYPE_QNAME?f.getName():f;var d=marknote.Cloner.cloneArray(this.contents);for(var b=d.length-1;b>=0;b--){var a=marknote.Util.dataType(d[b]);if(a!=marknote.constants.DATATYPE_ELEMENT){continue}if(this.clonedContents[b].getName()==c){marknote.Util.removeArrayItem(this.contents,b);e++}}return e};marknote.Element.prototype.getChildElements=function(e){var c=false;var f=new Array();if(e){c=e.dataType==marknote.constants.DATATYPE_QNAME?e.getName():e}for(var b=0;bg){var e=g>0?k.slice(0,g):"";var d=k.slice(c+1);return marknote.Util.trim(e+d)}else{return k}};marknote.Parser.prototype.parseProcessingInstructions=function(k,n){var p=new marknote.Tokenizer(k);var l=p.tokenize();var g=0,c=0;var b=false;var h,j,f,i,a,m,o;for(var q=0;qg){var e=g>0?k.slice(0,g):"";var d=k.slice(c+1);return marknote.Util.trim(e+d)}else{return k}};marknote.Parser.prototype.parseDOCTYPE=function(d,f){var h=new marknote.Tokenizer(d);var e=h.tokenize();var c=new marknote.DOCTYPE();var g,b;try{for(var i=0;i1){this.prefix=a[0];this.localPart=a[1]}else{this.prefix="";this.localPart=c}};marknote.QName.prototype.getPrefix=function(){return marknote.Util.nothingToBlank(this.prefix)};marknote.QName.prototype.setPrefix=function(a){this.prefix=marknote.Util.nothingToBlank(a)};marknote.QName.prototype.getLocalPart=function(){return marknote.Util.nothingToBlank(this.localPart)};marknote.QName.prototype.setLocalPart=function(a){this.localPart=marknote.Util.nothingToBlank(a)};marknote.QName.prototype.toString=function(){return this.getName()};marknote.QName.prototype.clone=function(){var a=new marknote.Cloner();return a.clone(this)};marknote.Text=function(a){this.dataType=marknote.constants.DATATYPE_TEXT;this.isSw8tXmlContent=true;this.text=marknote.Util.erefEncode(marknote.Util.nothingToBlank(a))};marknote.Text.prototype.getText=function(b){if(marknote.Util.isEmpty(b)){b=true}var a=marknote.Util.nothingToBlank(this.text);return b?marknote.Util.erefDecode(a):a};marknote.Text.prototype.setText=function(a){this.text=marknote.Util.erefEncode(marknote.Util.nothingToBlank(a))};marknote.Text.prototype.toString=function(){return this.getText()};marknote.Text.prototype.clone=function(){var a=new marknote.Cloner();return a.clone(this)};marknote.Token=function(b,a){this.dataType=marknote.constants.DATATYPE_TOKEN;this.isSwt8XmlContent=false;this.content=typeof(b)=="undefined"?new String():b;this.isLiteral=false;this.position=a?a:0};marknote.Token.prototype.getContent=function(){return this.content};marknote.Token.prototype.setContent=function(a){this.content=a};marknote.Token.prototype.getPosition=function(){return this.position};marknote.Token.prototype.setPosition=function(a){this.position=a};marknote.Token.prototype.hasValue=function(){try{return marknote.Util.hasValue(this.content)}catch(a){return false}};marknote.Token.prototype.isDOCTYPEStart=function(){return this.content==marknote.constants.DOCTYPE_START};marknote.Token.prototype.isPIStart=function(){return this.content==marknote.constants.PI_START};marknote.Token.prototype.isPIEnd=function(){return this.content==marknote.constants.PI_END};marknote.Token.prototype.isSelfTerminating=function(){return this.content==marknote.constants.TAG_CLOSE_SELF_TERMINATING};marknote.Token.prototype.isEndTag=function(){return this.content==marknote.constants.ENDTAG_OPEN};marknote.Token.prototype.isCommentStart=function(){return this.content==marknote.constants.COMMENT_START};marknote.Token.prototype.isCommentEnd=function(){return this.content==marknote.constants.COMMENT_END};marknote.Token.prototype.isAttribute=function(){return this.content==marknote.constants.EQUALS};marknote.Token.prototype.isCDATAStart=function(){return this.content==marknote.constants.CDATA_START};marknote.Token.prototype.isCDATAEnd=function(){return this.content==marknote.constants.CDATA_END};marknote.Token.prototype.isTagOpen=function(){return this.content==marknote.constants.TAG_OPEN};marknote.Token.prototype.isTagClose=function(){return this.content==marknote.constants.TAG_CLOSE};marknote.Token.prototype.isQuote=function(){return this.content==marknote.constants.SQUOTE||this.content==marknote.constants.DQUOTE};marknote.Token.prototype.isQuoted=function(){return this.content.charAt(0)=='"'&&this.content.charAt(this.content.length-1)=='"'};marknote.Token.prototype.getType=function(){if(this.isDOCTYPEStart()){return marknote.constants.TOKENTYPE_DOCTYPE_START}if(this.isPIStart()){return marknote.constants.TOKENTYPE_PI_START}if(this.isPIEnd()){return marknote.constants.TOKENTYPE_PI_END}if(this.isSelfTerminating()){return marknote.constants.TOKENTYPE_SELF_TERMINATING}if(this.isEndTag()){return marknote.constants.TOKENTYPE_ENDTAG_OPEN}if(this.isCommentStart()){return marknote.constants.TOKENTYPE_COMMENT_START}if(this.isCommentEnd()){return marknote.constants.TOKENTYPE_COMMENT_END}if(this.isAttribute()){return marknote.constants.TOKENTYPE_ATTRIBUTE}if(this.isCDATAStart()){return marknote.constants.TOKENTYPE_CDATA_START}if(this.isCDATAEnd()){return marknote.constants.TOKENTYPE_CDATA_END}if(this.isTagOpen()){return marknote.constants.TOKENTYPE_TAG_OPEN}if(this.isTagClose()){return marknote.constants.TOKENTYPE_TAG_CLOSE}if(this.isQuote()){return marknote.constants.TOKENTYPE_QUOTE}if(this.isQuoted()){return marknote.constants.TOKENTYPE_QUOTED}return marknote.constants.TOKENTYPE_NORMAL};marknote.Tokenizer=function(a){this.dataType=marknote.constants.DATATYPE_TOKENIZER;this.isSw8tXmlContent=false;this.setMarkup(a);this.tokens=new Array()};marknote.Tokenizer.prototype.getMarkup=function(){return this.markup};marknote.Tokenizer.prototype.setMarkup=function(a){this.markup=a?a:""};marknote.Tokenizer.prototype.determineTokenType=function(e,a){var b=this.markup.charAt(e);var d=e>0?this.markup.charAt(e-1):null;if(marknote.Util.hasWhitespace(b)){return marknote.constants.TOKENTYPE_WHITESPACE}if(this.markup.slice(e,e+9)==marknote.constants.DOCTYPE_START){return marknote.constants.TOKENTYPE_DOCTYPE_START}if(this.markup.slice(e,e+9)==marknote.constants.CDATA_START){return marknote.constants.TOKENTYPE_CDATA_START}if(this.markup.slice(e,e+4)==marknote.constants.COMMENT_START){return marknote.constants.TOKENTYPE_COMMENT_START}if(this.markup.slice(e,e+3)==marknote.constants.CDATA_END){return marknote.constants.TOKENTYPE_CDATA_END}if(this.markup.slice(e,e+2)==marknote.constants.PI_START){return marknote.constants.TOKENTYPE_PI_START}if(this.markup.slice(e,e+2)==marknote.constants.PI_END){return marknote.constants.TOKENTYPE_PI_END}if(this.markup.slice(e,e+2)==marknote.constants.TAG_CLOSE_SELF_TERMINATING){return marknote.constants.TOKENTYPE_SELF_TERMINATING}if(this.markup.slice(e,e+2)==marknote.constants.ENDTAG_OPEN){return marknote.constants.TOKENTYPE_ENDTAG_OPEN}if(b==marknote.constants.EQUALS&&a){return marknote.constants.TOKENTYPE_ATTRIBUTE}if(b==marknote.constants.TAG_OPEN){return marknote.constants.TOKENTYPE_TAG_OPEN}if(b==marknote.constants.TAG_CLOSE){return marknote.constants.TOKENTYPE_TAG_CLOSE}if(b==marknote.constants.SQUOTE){return marknote.constants.TOKENTYPE_QUOTE}if(b==marknote.constants.DQUOTE){if(d!==null||d!="\\"){return marknote.constants.TOKENTYPE_QUOTE}}if(b==marknote.constants.BRACKET_OPEN){return marknote.constants.TOKENTYPE_BRACKET_OPEN}return marknote.constants.TOKENTYPE_NORMAL};marknote.Tokenizer.prototype.isQuote=function(a){return a==marknote.constants.SQUOTE||a==marknote.constants.DQUOTE};marknote.Tokenizer.prototype.toString=function(){var b=this.tokens;var c=new String();for(var a=0;a0){c+=","}c+=b[a].content}return c};marknote.Tokenizer.prototype.tokenizeTagContent=function(f,h){var a=false;var e,b;for(var g=h+1;g9&&a.dataType.slice(0,9)=="marknote."?a.dataType:typeof a};marknote.Util.replaceAll=function(f,b,e){var a=f+"";var d=0;var c="";while(a.indexOf(b,d)!=-1){c+=a.substring(d,a.indexOf(b,d));c+=e;d=(a.indexOf(b,d)+b.length)}c+=f.substring(d,f.length);return c};marknote.Util.erefEncode=function(b){var a=b+"";return marknote.Util.erefTransform(a,true)};marknote.Util.erefXMLEncode=function(b){var a=b+"";return marknote.Util.erefTransform(a,true,true)};marknote.Util.erefDecode=function(b){var a=b+"";return marknote.Util.erefTransform(a,false)};marknote.Util.erefXMLDecode=function(b){var a=b+"";return marknote.Util.erefTransform(a,false,true)};marknote.Util.erefTransform=function(f,j,k){var g=k?new marknote.XMLEntityRefs().getRefs():new marknote.EntityRefs().getRefs();var c=new String();c+=f;for(var d=0;d0){c+="\n"}c+=marknote.constants.PI_START;var f=e[b];c+=f.getTarget();var i=f.getData();for(var k=0;k0&&this.hasStrictText(f)?"":this.calculateIndent(b,e);var c=i+marknote.constants.ENDTAG_OPEN+f.getName()+marknote.constants.TAG_CLOSE;return d+h+c};marknote.Writer.prototype.hasStrictText=function(e){var c=true;for(var b=0;b - LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE - - - ... - - */ - var typeTask = document.createElement("select"); - typeTask.id = "type" + j; - typeTask.setAttribute('name', 'type'); - var found = 0; - for (var k = 0; k < availableTasks.length ; k++) { - var option = document.createElement("option"); - option.setAttribute('value', availableTasks[k]); - var text = document.createTextNode(availableTasks[k]); - option.appendChild(text); - if (availableTasks[k] == arrayTasks[j][0]) { - found = k; - option.setAttribute("selected","selected"); - } - typeTask.appendChild(option); - } - typeTask.options[found].selected = true; - typeTask.setAttribute("onChange", "dialog_typeSelect(" + j + " )" ); - field.appendChild(typeTask); - rownext.appendChild(field); - field=document.createElement('td'); - // - var path = document.createElement("input"); - path.id = "path" + j; - path.setAttribute('type', 'text'); - path.setAttribute('name', 'path'); - path.setAttribute('size', '30'); - path.setAttribute('value', arrayTasks[j][1]); - path.setAttribute("onChange", "dialog_typeInput(" + j + "," + 1 + " )" ); - field.appendChild(path); - rownext.appendChild(field); - field=document.createElement('td'); - // - var delay = document.createElement("input"); - delay.id = "delay" + j; - delay.setAttribute('type', 'text'); - delay.setAttribute('name', 'delay'); - delay.setAttribute('size', '5'); - delay.setAttribute('value', arrayTasks[j][2]); - delay.setAttribute("onChange", "dialog_typeInput(" + j + "," + 2 + " )" ); - field.appendChild(delay); - rownext.appendChild(field); - field=document.createElement('td'); - // - var comment = document.createElement("input"); - comment.id = "comment" + j; - comment.setAttribute('type', 'text'); - comment.setAttribute('name', 'comment'); - comment.setAttribute('size', '20'); - if (arrayTasks[j].length > 3) { - comment.setAttribute('value', arrayTasks[j][3]); - } else { - comment.setAttribute('value', ''); - } - comment.setAttribute("onChange", "dialog_typeInput(" + j + "," + 3 + " )" ); - field.appendChild(comment); - rownext.appendChild(field); - field=document.createElement('td'); - // - var oTask = document.createElement("input"); - oTask.id = "add_" + j; - oTask.setAttribute('type', 'submit'); - oTask.setAttribute('name', 'ADD'); - oTask.setAttribute('value', 'ADD BEFORE'); - oTask.setAttribute("onClick", "dialog_add(" + j + " )" ); - field.appendChild(oTask); - rownext.appendChild(field); - field=document.createElement('td'); - // - oTask = document.createElement("input"); - oTask.id = "del_" + j; - oTask.setAttribute('type', 'submit'); - oTask.setAttribute('name', 'REMOVE'); - oTask.setAttribute('value', 'REMOVE'); - oTask.setAttribute("onClick", "dialog_delete(" + j + " )" ); - field.appendChild(oTask); - rownext.appendChild(field); - tab.appendChild(rownext); - } - dialog_content.appendChild(tab); - // - var oTask = document.createElement("input"); - oTask.id = "add_" + (arrayTasks.length); - oTask.setAttribute('type', 'submit'); - oTask.setAttribute('name', 'ADD'); - oTask.setAttribute('value', 'ADD AFTER'); - oTask.setAttribute("onClick", "dialog_add(" + arrayTasks.length + " )" ); - dialog_content.appendChild(oTask); - // - var oValid = document.createElement("input"); - oValid.id = "set"; - oValid.setAttribute('type', 'submit'); - oValid.setAttribute('name', 'SET'); - oValid.setAttribute('value', 'SET'); - oValid.onclick = function() {dialog_selectOk();}; - dialog_content.appendChild(oValid); - // - oValid = document.createElement("input"); - oValid.id = "cancel"; - oValid.setAttribute('type', 'submit'); - oValid.setAttribute('name', 'CANCEL'); - oValid.setAttribute('value', 'CANCEL'); - oValid.onclick = function() {dialog_cancel();}; - dialog_content.appendChild(oValid); - var br = document.createElement("br"); - dialog_content.appendChild(br); - var tt = document.createElement("tt"); - var text = document.createTextNode("Keywords: #TRUEFULLPATH# #TRUEFILENAME# #ORIGINALFULLPATH# " + - "#ORIGINALFILENAME# #FILESIZE# #RULE# #DATE# #HOUR# #REMOTEHOST# #REMOTEHOSTADDR# " + - "#LOCALHOST# #LOCALHOSTADDR# #TRANSFERID# #REQUESTERHOST# #REQUESTEDHOST# " + - "#FULLTRANSFERID# #RANKTRANSFER# #BLOCKSIZE# #INPATH# #OUTPATH# #WORKPATH# " + - "#ARCHPATH# #HOMEPATH# #ERRORMSG# #ERRORCODE# #ERRORSTRCODE# #NOWAIT# " + - "#LOCALEXEC# #CPTLIMIT#"); - tt.appendChild(text); - dialog_content.appendChild(tt); -} -// Select value from SELECT -function dialog_typeSelect(rank) { - var select = document.getElementById('type'+rank); - var chosenoption = select.options[select.selectedIndex]; - arrayTasks[rank][0] = chosenoption.value; -} -// Select value from INPUT -function dialog_typeInput(rank, field) { - var fieldname = ''; - if (field == 1) { - fieldname = "path"+rank; - } else if (field == 2) { - fieldname = "delay"+rank; - } else { - fieldname = "comment"+rank; - } - var input = document.getElementById(fieldname); - arrayTasks[rank][field] = input.value; -} -/******************************************************************************* - * inputName : field name that contains the value of rule tasks - ******************************************************************************/ -function dialog_open(inputName, title) { - // back zone unvalidated - var dialog_background = document.getElementById('dialog_background'); - dialog_background.style.display = "block"; - // Keeo original object - var obInput = document.getElementById(inputName); - dialog_input = obInput; - // dialog show - var dialog_box = document.getElementById('dialog_box'); - dialog_box.style.display = "block"; - var dialog_title = document.getElementById('dialog_title'); - var code = ''; - if (dialog_input.id.charAt(0) == 'r') { - code = " Recv "; - } else { - code = " Send "; - } - if (dialog_input.id.charAt(1) == 'e') { - code = code + " Error Tasks"; - } else if (dialog_input.id.charAt(2) == 'o') { - code = code + " Post Tasks"; - } else { - code = code + " Pre Tasks"; - } - dialog_title.innerHTML = title + code; - dialog_box.style.top = (document.body.scrollTop * 1) + 100; - // parser xml tasks - value1 = obInput.value; - var parser = new marknote.Parser(); - var xml = parser.parse(value1); - var root = xml.getRootElement(); - var tasks = root.getChildElements(); - arrayTasks = new Array(tasks.length); - for ( var i = 0; i < tasks.length; i++) { - var task = tasks[i]; - var type = task.getChildElement("type"); - var path = task.getChildElement("path"); - var delay = task.getChildElement("delay"); - var comment = task.getChildElement("comment"); - if (comment) { - arrayTasks[i] = new Array(type.getText(), path.getText(), delay.getText(), comment.getText()); - } else { - arrayTasks[i] = new Array(type.getText(), path.getText(), delay.getText(), ""); - } - } - dialog_load(); - // unallow bar box behind - document.body.style.overflow = 'hidden'; -} -// Add a new Task -function dialog_add(rank) { - var tempElt = new Array("LOG",'',0,''); - if (rank == 0) { - arrayTasks.unshift(tempElt); - } else if (rank < arrayTasks.length) { - var before = arrayTasks.slice(0, rank); - before.push(tempElt); - arrayTasks = before.concat(arrayTasks.slice(rank, arrayTasks.length)); - } else { - arrayTasks.push(tempElt); - } - dialog_load(); -} -// Delete a Task -function dialog_delete(rank) { - var max = arrayTasks.length-1; - if (rank == 0) { - arrayTasks.shift(); - } else if (rank < max) { - var before = arrayTasks.slice(0, rank); - arrayTasks = before.concat(arrayTasks.slice(rank+1, arrayTasks.length)); - } else if (rank == max) { - arrayTasks.pop(); - } - dialog_load(); -} -// Get value from SELECT -function getSelectValue(selectElmt) { - return selectElmt.options[selectElmt.selectedIndex].value; -} -// Ignore changes -function dialog_cancel() { - dialog_close(); -} -function dialog_close() { - // Mask dialog - dialog_win = document.getElementById('dialog_background'); - dialog_win.style.display = "none"; - var dialog_box = document.getElementById('dialog_box'); - dialog_box.style.display = "none"; - // scrollbar activated - document.body.style.overflow = 'scroll'; -} -// Update tasks -function dialog_selectOk() { - var root = new marknote.Element("tasks"); - for ( var j = 0; j < arrayTasks.length; j++) { - var task = new marknote.Element("task"); - var obj = document.getElementById("type" + j); - if (obj) { - var val = getSelectValue(obj); - if (val && val.length > 0) { - var sub = new marknote.Element("type"); - sub.setText(val); - task.addContent(sub); - obj = document.getElementById("path" + j); - if (obj && obj.value && obj.value.length > 0) { - sub = new marknote.Element("path"); - sub.setText(obj.value); - task.addContent(sub); - } else { - sub = new marknote.Element("path"); - task.addContent(sub); - } - obj = document.getElementById("delay" + j); - if (obj && obj.value && obj.value.length > 0) { - sub = new marknote.Element("delay"); - sub.setText(obj.value); - task.addContent(sub); - } else { - sub = new marknote.Element("delay"); - sub.setText(0); - task.addContent(sub); - } - obj = document.getElementById("comment" + j); - if (obj && obj.value && obj.value.length > 0) { - sub = new marknote.Element("comment"); - sub.setText(obj.value); - task.addContent(sub); - } - root.addContent(task); - } - } - } - var result = root.toString("\f"); - var regexp = new RegExp("^\n\r|^\r\n|^\n|^\r|\f", "g"); - result = result.replace(regexp, ""); - dialog_input.value = result; - dialog_close(); -} -// code from: http://www.geekdaily.net/2007/07/04/javascript-cross-browser-window-size-and-centering/ -window.size = function() { - var w = 0; - var h = 0; - //IE - if(!window.innerWidth) { - //strict mode - if(!(document.documentElement.clientWidth == 0)) { - w = document.documentElement.clientWidth; - h = document.documentElement.clientHeight; - } //quirks mode - else { - w = document.body.clientWidth; - h = document.body.clientHeight; - } - } //w3c - else { - w = window.innerWidth; - h = window.innerHeight; - } - return {width:w,height:h}; -} -window.center = function() { - var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0}; - var _x = 0; - var _y = 0; - var offsetX = 0; - var offsetY = 0; - //IE - if(!window.pageYOffset) { - //strict mode - if(!(document.documentElement.scrollTop == 0)) { - offsetY = document.documentElement.scrollTop; - offsetX = document.documentElement.scrollLeft; - } //quirks mode - else { - offsetY = document.body.scrollTop; - offsetX = document.body.scrollLeft; - } - } //w3c - else { - offsetX = window.pageXOffset; - offsetY = window.pageYOffset; - } - _x = ((this.size().width-hWnd.width)/2)+offsetX; - _y = ((this.size().height-hWnd.height)/2)+offsetY; - return{x:_x,y:_y}; -} +/** + * Rule Helper + */ +// Source Input field name +var dialog_inputName = ''; +// Current tasks array +var arrayTasks = new Array(); +// Available Task's types +var availableTasks = new Array("LOG", "MOVE", "MOVERENAME", "COPY", "COPYRENAME", "EXEC", "EXECMOVE", "EXECOUTPUT", "EXECJAVA", "TRANSFER", "VALIDFILEPATH", "DELETE", "LINKRENAME", "RESCHEDULE", "TAR", "ZIP", "TRANSCODE", "FTP"); +// Load dialog +function dialog_load() { + // get container + var dialog_box = document.getElementById('dialog_box'); + var pt = window.center({width:800,height:300}); + dialog_box.style.top = pt.y + "px"; + dialog_box.style.left = pt.x + "px"; + var dialog_content = document.getElementById('dialog_content'); + dialog_content.innerHTML = ''; + var tab=document.createElement('table'); + var row=document.createElement('tr'); + var header=document.createElement('th'); + header.textContent = "Task Type"; + row.appendChild(header); + header=document.createElement('th'); + header.textContent = "Path argument"; + row.appendChild(header); + header=document.createElement('th'); + header.textContent = "Delay"; + row.appendChild(header); + header=document.createElement('th'); + header.textContent = "Comment (optional)"; + row.appendChild(header); + tab.appendChild(row); + for ( var j = 0; j < arrayTasks.length; j++) { + var rownext=document.createElement('tr'); + var field=document.createElement('td'); + /* + + */ + var typeTask = document.createElement("select"); + typeTask.id = "type" + j; + typeTask.setAttribute('name', 'type'); + var found = 0; + for (var k = 0; k < availableTasks.length ; k++) { + var option = document.createElement("option"); + option.setAttribute('value', availableTasks[k]); + var text = document.createTextNode(availableTasks[k]); + option.appendChild(text); + if (availableTasks[k] == arrayTasks[j][0]) { + found = k; + option.setAttribute("selected","selected"); + } + typeTask.appendChild(option); + } + typeTask.options[found].selected = true; + typeTask.setAttribute("onChange", "dialog_typeSelect(" + j + " )" ); + field.appendChild(typeTask); + rownext.appendChild(field); + field=document.createElement('td'); + // + var path = document.createElement("input"); + path.id = "path" + j; + path.setAttribute('type', 'text'); + path.setAttribute('name', 'path'); + path.setAttribute('size', '30'); + path.setAttribute('value', arrayTasks[j][1]); + path.setAttribute("onChange", "dialog_typeInput(" + j + "," + 1 + " )" ); + field.appendChild(path); + rownext.appendChild(field); + field=document.createElement('td'); + // + var delay = document.createElement("input"); + delay.id = "delay" + j; + delay.setAttribute('type', 'text'); + delay.setAttribute('name', 'delay'); + delay.setAttribute('size', '5'); + delay.setAttribute('value', arrayTasks[j][2]); + delay.setAttribute("onChange", "dialog_typeInput(" + j + "," + 2 + " )" ); + field.appendChild(delay); + rownext.appendChild(field); + field=document.createElement('td'); + // + var comment = document.createElement("input"); + comment.id = "comment" + j; + comment.setAttribute('type', 'text'); + comment.setAttribute('name', 'comment'); + comment.setAttribute('size', '20'); + if (arrayTasks[j].length > 3) { + comment.setAttribute('value', arrayTasks[j][3]); + } else { + comment.setAttribute('value', ''); + } + comment.setAttribute("onChange", "dialog_typeInput(" + j + "," + 3 + " )" ); + field.appendChild(comment); + rownext.appendChild(field); + field=document.createElement('td'); + // + var oTask = document.createElement("input"); + oTask.id = "add_" + j; + oTask.setAttribute('type', 'submit'); + oTask.setAttribute('name', 'ADD'); + oTask.setAttribute('value', 'ADD BEFORE'); + oTask.setAttribute("onClick", "dialog_add(" + j + " )" ); + field.appendChild(oTask); + rownext.appendChild(field); + field=document.createElement('td'); + // + oTask = document.createElement("input"); + oTask.id = "del_" + j; + oTask.setAttribute('type', 'submit'); + oTask.setAttribute('name', 'REMOVE'); + oTask.setAttribute('value', 'REMOVE'); + oTask.setAttribute("onClick", "dialog_delete(" + j + " )" ); + field.appendChild(oTask); + rownext.appendChild(field); + tab.appendChild(rownext); + } + dialog_content.appendChild(tab); + // + var oTask = document.createElement("input"); + oTask.id = "add_" + (arrayTasks.length); + oTask.setAttribute('type', 'submit'); + oTask.setAttribute('name', 'ADD'); + oTask.setAttribute('value', 'ADD AFTER'); + oTask.setAttribute("onClick", "dialog_add(" + arrayTasks.length + " )" ); + dialog_content.appendChild(oTask); + // + var oValid = document.createElement("input"); + oValid.id = "set"; + oValid.setAttribute('type', 'submit'); + oValid.setAttribute('name', 'SET'); + oValid.setAttribute('value', 'SET'); + oValid.onclick = function() {dialog_selectOk();}; + dialog_content.appendChild(oValid); + // + oValid = document.createElement("input"); + oValid.id = "cancel"; + oValid.setAttribute('type', 'submit'); + oValid.setAttribute('name', 'CANCEL'); + oValid.setAttribute('value', 'CANCEL'); + oValid.onclick = function() {dialog_cancel();}; + dialog_content.appendChild(oValid); + var br = document.createElement("br"); + dialog_content.appendChild(br); + var tt = document.createElement("tt"); + var text = document.createTextNode("Keywords: #TRUEFULLPATH# #TRUEFILENAME# #ORIGINALFULLPATH# " + + "#ORIGINALFILENAME# #FILESIZE# #RULE# #DATE# #HOUR# #REMOTEHOST# #REMOTEHOSTADDR# " + + "#LOCALHOST# #LOCALHOSTADDR# #TRANSFERID# #REQUESTERHOST# #REQUESTEDHOST# " + + "#FULLTRANSFERID# #RANKTRANSFER# #BLOCKSIZE# #INPATH# #OUTPATH# #WORKPATH# " + + "#ARCHPATH# #HOMEPATH# #ERRORMSG# #ERRORCODE# #ERRORSTRCODE# #NOWAIT# " + + "#LOCALEXEC# #CPTLIMIT#"); + tt.appendChild(text); + dialog_content.appendChild(tt); +} +// Select value from SELECT +function dialog_typeSelect(rank) { + var select = document.getElementById('type'+rank); + var chosenoption = select.options[select.selectedIndex]; + arrayTasks[rank][0] = chosenoption.value; +} +// Select value from INPUT +function dialog_typeInput(rank, field) { + var fieldname = ''; + if (field == 1) { + fieldname = "path"+rank; + } else if (field == 2) { + fieldname = "delay"+rank; + } else { + fieldname = "comment"+rank; + } + var input = document.getElementById(fieldname); + arrayTasks[rank][field] = input.value; +} +/******************************************************************************* + * inputName : field name that contains the value of rule tasks + ******************************************************************************/ +function dialog_open(inputName, title) { + // back zone unvalidated + var dialog_background = document.getElementById('dialog_background'); + dialog_background.style.display = "block"; + // Keeo original object + var obInput = document.getElementById(inputName); + dialog_input = obInput; + // dialog show + var dialog_box = document.getElementById('dialog_box'); + dialog_box.style.display = "block"; + var dialog_title = document.getElementById('dialog_title'); + var code = ''; + if (dialog_input.id.charAt(0) == 'r') { + code = " Recv "; + } else { + code = " Send "; + } + if (dialog_input.id.charAt(1) == 'e') { + code = code + " Error Tasks"; + } else if (dialog_input.id.charAt(2) == 'o') { + code = code + " Post Tasks"; + } else { + code = code + " Pre Tasks"; + } + dialog_title.innerHTML = title + code; + dialog_box.style.top = (document.body.scrollTop * 1) + 100; + // parser xml tasks + value1 = obInput.value; + var parser = new marknote.Parser(); + var xml = parser.parse(value1); + var root = xml.getRootElement(); + var tasks = root.getChildElements(); + arrayTasks = new Array(tasks.length); + for ( var i = 0; i < tasks.length; i++) { + var task = tasks[i]; + var type = task.getChildElement("type"); + var path = task.getChildElement("path"); + var delay = task.getChildElement("delay"); + var comment = task.getChildElement("comment"); + if (comment) { + arrayTasks[i] = new Array(type.getText(), path.getText(), delay.getText(), comment.getText()); + } else { + arrayTasks[i] = new Array(type.getText(), path.getText(), delay.getText(), ""); + } + } + dialog_load(); + // unallow bar box behind + document.body.style.overflow = 'hidden'; +} +// Add a new Task +function dialog_add(rank) { + var tempElt = new Array("LOG",'',0,''); + if (rank == 0) { + arrayTasks.unshift(tempElt); + } else if (rank < arrayTasks.length) { + var before = arrayTasks.slice(0, rank); + before.push(tempElt); + arrayTasks = before.concat(arrayTasks.slice(rank, arrayTasks.length)); + } else { + arrayTasks.push(tempElt); + } + dialog_load(); +} +// Delete a Task +function dialog_delete(rank) { + var max = arrayTasks.length-1; + if (rank == 0) { + arrayTasks.shift(); + } else if (rank < max) { + var before = arrayTasks.slice(0, rank); + arrayTasks = before.concat(arrayTasks.slice(rank+1, arrayTasks.length)); + } else if (rank == max) { + arrayTasks.pop(); + } + dialog_load(); +} +// Get value from SELECT +function getSelectValue(selectElmt) { + return selectElmt.options[selectElmt.selectedIndex].value; +} +// Ignore changes +function dialog_cancel() { + dialog_close(); +} +function dialog_close() { + // Mask dialog + dialog_win = document.getElementById('dialog_background'); + dialog_win.style.display = "none"; + var dialog_box = document.getElementById('dialog_box'); + dialog_box.style.display = "none"; + // scrollbar activated + document.body.style.overflow = 'scroll'; +} +// Update tasks +function dialog_selectOk() { + var root = new marknote.Element("tasks"); + for ( var j = 0; j < arrayTasks.length; j++) { + var task = new marknote.Element("task"); + var obj = document.getElementById("type" + j); + if (obj) { + var val = getSelectValue(obj); + if (val && val.length > 0) { + var sub = new marknote.Element("type"); + sub.setText(val); + task.addContent(sub); + obj = document.getElementById("path" + j); + if (obj && obj.value && obj.value.length > 0) { + sub = new marknote.Element("path"); + sub.setText(obj.value); + task.addContent(sub); + } else { + sub = new marknote.Element("path"); + task.addContent(sub); + } + obj = document.getElementById("delay" + j); + if (obj && obj.value && obj.value.length > 0) { + sub = new marknote.Element("delay"); + sub.setText(obj.value); + task.addContent(sub); + } else { + sub = new marknote.Element("delay"); + sub.setText(0); + task.addContent(sub); + } + obj = document.getElementById("comment" + j); + if (obj && obj.value && obj.value.length > 0) { + sub = new marknote.Element("comment"); + sub.setText(obj.value); + task.addContent(sub); + } + root.addContent(task); + } + } + } + var result = root.toString("\f"); + var regexp = new RegExp("^\n\r|^\r\n|^\n|^\r|\f", "g"); + result = result.replace(regexp, ""); + dialog_input.value = result; + dialog_close(); +} +// code from: http://www.geekdaily.net/2007/07/04/javascript-cross-browser-window-size-and-centering/ +window.size = function() { + var w = 0; + var h = 0; + //IE + if(!window.innerWidth) { + //strict mode + if(!(document.documentElement.clientWidth == 0)) { + w = document.documentElement.clientWidth; + h = document.documentElement.clientHeight; + } //quirks mode + else { + w = document.body.clientWidth; + h = document.body.clientHeight; + } + } //w3c + else { + w = window.innerWidth; + h = window.innerHeight; + } + return {width:w,height:h}; +} +window.center = function() { + var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0}; + var _x = 0; + var _y = 0; + var offsetX = 0; + var offsetY = 0; + //IE + if(!window.pageYOffset) { + //strict mode + if(!(document.documentElement.scrollTop == 0)) { + offsetY = document.documentElement.scrollTop; + offsetX = document.documentElement.scrollLeft; + } //quirks mode + else { + offsetY = document.body.scrollTop; + offsetX = document.body.scrollLeft; + } + } //w3c + else { + offsetX = window.pageXOffset; + offsetY = window.pageYOffset; + } + _x = ((this.size().width-hWnd.width)/2)+offsetX; + _y = ((this.size().height-hWnd.height)/2)+offsetY; + return{x:_x,y:_y}; +} diff --git a/src/main/config/OPENR66-MIB b/src/main/config/OPENR66-MIB index 870e8b18c..77aac4082 100644 --- a/src/main/config/OPENR66-MIB +++ b/src/main/config/OPENR66-MIB @@ -1,867 +1,867 @@ -OPENR66-MIB DEFINITIONS ::= BEGIN - -IMPORTS - NOTIFICATION-GROUP, NOTIFICATION-TYPE, enterprises, OBJECT-TYPE, Counter32, Gauge32, Counter64, MODULE-IDENTITY, mib-2 - FROM SNMPv2-SMI - TimeStamp, TEXTUAL-CONVENTION - FROM SNMPv2-TC - SnmpAdminString - FROM SNMP-FRAMEWORK-MIB - system - FROM SNMPv2-MIB; - -openr66 MODULE-IDENTITY - LAST-UPDATED "201103050000Z" - ORGANIZATION "Waarp OpenR66" - CONTACT-INFO - " Frederic Bregier - - E-Mail: openr66@free.fr" - DESCRIPTION - "The MIB module describing OpenR66 Mib" - REVISION "201103050000Z" - DESCRIPTION - "This revision is the first setup of the OpenR66 MIB." --- 1.3.6.1.4.1.66666.66.1.1 -- -::= { enterprises 66666 66 1 1 } - --- root -waarp OBJECT IDENTIFIER ::= { enterprises 66666 } -r66 OBJECT IDENTIFIER ::= { waarp 66 } - --- Textual conventions - --- DistinguishedName is used to refer to objects in the --- directory. - -DistinguishedName ::= TEXTUAL-CONVENTION - DISPLAY-HINT "255a" - STATUS current - DESCRIPTION - "A Distinguished Name represented in accordance with - RFC 2253, presented in the UTF-8 charset defined in - RFC 2279." - SYNTAX OCTET STRING (SIZE (0..255)) - --- Uniform Resource Locators are stored in URLStrings. - -URLString ::= TEXTUAL-CONVENTION - DISPLAY-HINT "255a" - STATUS current - DESCRIPTION - "A Uniform Resource Locator represented in accordance - with RFCs 1738 and 2368, presented in the NVT ASCII - charset defined in RFC 854." - SYNTAX OCTET STRING (SIZE (0..255)) - - --- The basic applEntry contains the different elements. - -applDefinitions OBJECT IDENTIFIER ::= { r66 1 } -applGlobalValues OBJECT IDENTIFIER ::= { r66 2 } -applDetailedValues OBJECT IDENTIFIER ::= { r66 3 } -applErrorValues OBJECT IDENTIFIER ::= { r66 4 } -waarptraps OBJECT IDENTIFIER ::= { r66 5 } - - -applName OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The name the network service application chooses to be - known by." - ::= {applDefinitions 1} - -applServerName OBJECT-TYPE - SYNTAX DistinguishedName - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The Server Name of this particular instance." - ::= {applDefinitions 2} - -applVersion OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The version of network service application software. - This field is usually defined by the vendor of the - network service application software." - ::= {applDefinitions 3} - -applDescription OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "A text description of the application. This information - is intended to identify and briefly describe the - application in a status display." - ::= {applDefinitions 4} - -applURL OBJECT-TYPE - SYNTAX URLString - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "A URL pointing to a description of the application. - This information is intended to identify and describe - the application in a status display." - ::= {applDefinitions 5} - -assocApplicationProtocol OBJECT-TYPE - SYNTAX OBJECT IDENTIFIER - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "An identification of the protocol being used for the - application. For an OSI Application, this will be the - Application Context. For Internet applications, OID - values of the form {applTCPProtoID port} or {applUDPProtoID - port} are used for TCP-based and UDP-based protocols, - respectively. In either case 'port' corresponds to the - primary port number being used by the protocol. The - usual IANA procedures may be used to register ports for - new protocols." - ::= {applDefinitions 6} - - -applUptime OBJECT-TYPE - SYNTAX TimeStamp - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The value of sysUpTime at the time the network service - application was last initialized. If the application was - last initialized prior to the last initialization of the - network management subsystem, then this object contains - a zero value." - ::= {applGlobalValues 1} - -applOperStatus OBJECT-TYPE - SYNTAX INTEGER { - up(1), - down(2), - halted(3), - congested(4), - restarting(5), - quiescing(6) - } - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Indicates the operational status of the network service - application. 'down' indicates that the network service is - not available. 'up' indicates that the network service - is operational and available. 'halted' indicates that the - service is operational but not available. 'congested' - indicates that the service is operational but no additional - inbound associations can be accommodated. 'restarting' - indicates that the service is currently unavailable but is - in the process of restarting and will be available soon. - 'quiescing' indicates that service is currently operational - but is in the process of shutting down. Additional inbound - associations may be rejected by applications in the - 'quiescing' state." - ::= {applGlobalValues 2} - -applLastChange OBJECT-TYPE - SYNTAX TimeStamp - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The value of sysUpTime at the time the network service - application entered its current operational state. If - the current state was entered prior to the last - initialization of the local network management subsystem, - then this object contains a zero value." - ::= {applGlobalValues 3} - -applInboundAssociations OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The number of current associations to the network service - application, where it is the responder. An inbound - association occurs when another application successfully - connects to this one." - ::= {applGlobalValues 4} - -applOutboundAssociations OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The number of current associations to the network service - application, where it is the initiator. An outbound - association occurs when this application successfully - connects to another one." - ::= {applGlobalValues 5} - -applAccumInboundAssociations OBJECT-TYPE - SYNTAX Counter32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The total number of associations to the application entity - since application initialization, where it was the responder." - ::= {applGlobalValues 6} - -applAccumOutboundAssociations OBJECT-TYPE - SYNTAX Counter32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The total number of associations to the application entity - since application initialization, where it was the initiator." - ::= {applGlobalValues 7} - -applLastInboundActivity OBJECT-TYPE - SYNTAX TimeStamp - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The value of sysUpTime at the time this application last - had an inbound association. If the last association - occurred prior to the last initialization of the network - subsystem, then this object contains a zero value." - ::= {applGlobalValues 8} - -applLastOutboundActivity OBJECT-TYPE - SYNTAX TimeStamp - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The value of sysUpTime at the time this application last - had an outbound association. If the last association - occurred prior to the last initialization of the network - subsystem, then this object contains a zero value." - ::= {applGlobalValues 9} - -applRejectedInboundAssociations OBJECT-TYPE - SYNTAX Counter32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The total number of inbound associations the application - entity has rejected, since application initialization. - Rejected associations are not counted in the accumulated - association totals. Note that this only counts - associations the application entity has rejected itself; - it does not count rejections that occur at lower layers - of the network. Thus, this counter may not reflect the - true number of failed inbound associations." - ::= {applGlobalValues 10} - -applFailedOutboundAssociations OBJECT-TYPE - SYNTAX Counter32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The total number associations where the application entity - is initiator and association establishment has failed, - since application initialization. Failed associations are - not counted in the accumulated association totals." - ::= {applGlobalValues 11} - - -- Bandwidth -applInboundBandwidthKBS OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The Inbound bandwidth usage in KB/s." - ::= {applGlobalValues 12} - -applOutboundBandwidthKBS OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "The Outbound bandwidth usage in KB/s." - ::= {applGlobalValues 13} - - -- Overall status including past, future and current transfers -nbInfoUnknown OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as Unknown." - ::= {applGlobalValues 14} - -nbInfoNotUpdated OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as NotUpdated." - ::= {applGlobalValues 15} - -nbInfoInterrupted OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as Interrupted." - ::= {applGlobalValues 16} - -nbInfoToSubmit OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as ToSubmit." - ::= {applGlobalValues 17} - -nbInfoError OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as Error." - ::= {applGlobalValues 18} - -nbInfoRunning OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as Running." - ::= {applGlobalValues 19} - -nbInfoDone OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count with Info as Done." - ::= {applGlobalValues 20} - - - -- Current situation of all transfers, running or not -nbStepAllTransfer OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in total, running or not." - ::= {applGlobalValues 21} - -memoryTotal OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Total Allocated Memory in KiloBytes." - ::= {applGlobalValues 22} - -memoryFree OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Total Free Memory in KiloBytes." - ::= {applGlobalValues 23} - -memoryUsed OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Total Used Memory in KiloBytes." - ::= {applGlobalValues 24} - -nbThreads OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Total number of active threads." - ::= {applGlobalValues 25} - -nbNetworkConnection OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Total number of active network connections." - ::= {applGlobalValues 26} - --- detailed part - -nbStepNotask OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as NoTask." - ::= {applDetailedValues 1} - -nbStepPretask OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as PreTask." - ::= {applDetailedValues 2} - -nbStepTransfer OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as Transfer." - ::= {applDetailedValues 3} - -nbStepPosttask OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as PostTask." - ::= {applDetailedValues 4} - -nbStepAllDone OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as AllDone." - ::= {applDetailedValues 5} - -nbStepError OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Step is as Error." - ::= {applDetailedValues 6} - - - -- First on Running Transfers only -nbAllRunningStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count of all transfers currently in running." - ::= {applDetailedValues 7} - -nbRunningStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step Running." - ::= {applDetailedValues 8} - -nbInitOkStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step InitOk." - ::= {applDetailedValues 9} - -nbPreProcessingOkStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step PreProcessingOk." - ::= {applDetailedValues 10} - -nbTransferOkStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step TransferOk." - ::= {applDetailedValues 11} - -nbPostProcessingOkStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step PostProcessingOk." - ::= {applDetailedValues 12} - -nbCompleteOkStep OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count in Step CompleteOk." - ::= {applDetailedValues 13} - - - -- Error Status on all transfers -nbStatusConnectionImpossible OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is ConnectionImpossible." - ::= {applErrorValues 1} - -nbStatusServerOverloaded OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is ServerOverloaded." - ::= {applErrorValues 2} - -nbStatusBadAuthent OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is BadAuthent." - ::= {applErrorValues 3} - -nbStatusExternalOp OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is ExternalOp." - ::= {applErrorValues 4} - -nbStatusTransferError OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is TransferError." - ::= {applErrorValues 5} - -nbStatusMD5Error OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is MD5Error." - ::= {applErrorValues 6} - -nbStatusDisconnection OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Disconnection." - ::= {applErrorValues 7} - -nbStatusFinalOp OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is FinalOp." - ::= {applErrorValues 8} - -nbStatusUnimplemented OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Unimplemented." - ::= {applErrorValues 9} - -nbStatusInternal OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Internal." - ::= {applErrorValues 10} - -nbStatusWarning OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Warning." - ::= {applErrorValues 11} - -nbStatusQueryAlreadyFinished OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is QueryAlreadyFinished." - ::= {applErrorValues 12} - -nbStatusQueryStillRunning OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is QueryStillRunning." - ::= {applErrorValues 13} - -nbStatusNotKnownHost OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is NotKnownHost." - ::= {applErrorValues 14} - -nbStatusQueryRemotelyUnknown OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is QueryRemotelyUnknown." - ::= {applErrorValues 15} - -nbStatusCommandNotFound OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is CommandNotFound." - ::= {applErrorValues 16} - -nbStatusPassThroughMode OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is PassThroughMode." - ::= {applErrorValues 17} - -nbStatusRemoteShutdown OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is RemoteShutdown." - ::= {applErrorValues 18} - -nbStatusShutdown OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Shutdown." - ::= {applErrorValues 19} - -nbStatusRemoteError OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is RemoteError." - ::= {applErrorValues 20} - -nbStatusStopped OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Stopped." - ::= {applErrorValues 21} - -nbStatusCanceled OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Canceled." - ::= {applErrorValues 22} - -nbStatusFileNotFound OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is FileNotFound." - ::= {applErrorValues 23} - -nbStatusUnknown OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION - "Transfers count where Status is Unknown." - ::= {applErrorValues 24} - --- test notification - -startOrShutdownObject OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Start Or Shutdown Extra Information." -::= { startOrShutdownWaarp 1 } - -startOrShutdownWaarp NOTIFICATION-TYPE - OBJECTS { startOrShutdownObject } - STATUS current - DESCRIPTION "Start or Shutdown SMIv2 notification" - ::= { waarpgroup 1 } - -errorObject OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Nature of Error." -::= { errorWaarp 1 } - -errorWaarp NOTIFICATION-TYPE - OBJECTS { errorObject } - STATUS current - DESCRIPTION "Error SMIv2 notification" - ::= { waarpgroup 2 } - -warningObject OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Nature of Warning." -::= { warningWaarp 1 } - -warningWaarp NOTIFICATION-TYPE - OBJECTS { warningObject } - STATUS current - DESCRIPTION "Warning SMIv2 notification" - ::= { waarpgroup 3 } - -overloadedObject OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Overloaded Server extra information." -::= { overloadedWaarp 1 } - -overloadedWaarp NOTIFICATION-TYPE - OBJECTS { overloadedObject } - STATUS current - DESCRIPTION "Overloaded SMIv2 notification" - ::= { waarpgroup 4 } - -globalStepInfo OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "GlobalStep rank." -::= { infoWaarp 1 } -stepInfo OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Step in GlobalStep." -::= { infoWaarp 2 } -rankFileInfo OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "File Rank." -::= { infoWaarp 3 } -stepStatusInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Status of Step." -::= { infoWaarp 4 } -filenameInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Current Filename." -::= { infoWaarp 5 } -originalNameInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Original Filename." -::= { infoWaarp 6 } -idRuleInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "ID of Rule." -::= { infoWaarp 7 } -modeTransInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Mode of Transfer." -::= { infoWaarp 8 } -retrieveModeInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Retrieve Mode." -::= { infoWaarp 9 } -startTransInfo OBJECT-TYPE - SYNTAX TimeStamp - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Start Time of this transfer." -::= { infoWaarp 10 } -infoStatusInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Current Status." -::= { infoWaarp 11 } -requesterInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Requester Id for this transfer." -::= { infoWaarp 12 } -requestedInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Requested Id for this transfer." -::= { infoWaarp 13 } -specialIdInfo OBJECT-TYPE - SYNTAX SnmpAdminString - MAX-ACCESS accessible-for-notify - STATUS current - DESCRIPTION - "Unique Id for this Transfer." -::= { infoWaarp 14 } - -infoWaarp NOTIFICATION-TYPE - OBJECTS { globalStepInfo, stepInfo, rankFileInfo, stepStatusInfo, filenameInfo, - originalNameInfo, idRuleInfo, modeTransInfo, retrieveModeInfo, startTransInfo, - infoStatusInfo, requesterInfo, requestedInfo, specialIdInfo } - STATUS current - DESCRIPTION "Info SMIv2 notification" - ::= { waarpgroup 5 } - -waarpgroup NOTIFICATION-GROUP - NOTIFICATIONS { startOrShutdownWaarp,errorWaarp,warningWaarp,overloadedWaarp,infoWaarp } - STATUS current - DESCRIPTION "Group of Notification in Waarp" - ::= { waarptraps 1 } - -END +OPENR66-MIB DEFINITIONS ::= BEGIN + +IMPORTS + NOTIFICATION-GROUP, NOTIFICATION-TYPE, enterprises, OBJECT-TYPE, Counter32, Gauge32, Counter64, MODULE-IDENTITY, mib-2 + FROM SNMPv2-SMI + TimeStamp, TEXTUAL-CONVENTION + FROM SNMPv2-TC + SnmpAdminString + FROM SNMP-FRAMEWORK-MIB + system + FROM SNMPv2-MIB; + +openr66 MODULE-IDENTITY + LAST-UPDATED "201103050000Z" + ORGANIZATION "Waarp OpenR66" + CONTACT-INFO + " Frederic Bregier + + E-Mail: openr66@free.fr" + DESCRIPTION + "The MIB module describing OpenR66 Mib" + REVISION "201103050000Z" + DESCRIPTION + "This revision is the first setup of the OpenR66 MIB." +-- 1.3.6.1.4.1.66666.66.1.1 -- +::= { enterprises 66666 66 1 1 } + +-- root +waarp OBJECT IDENTIFIER ::= { enterprises 66666 } +r66 OBJECT IDENTIFIER ::= { waarp 66 } + +-- Textual conventions + +-- DistinguishedName is used to refer to objects in the +-- directory. + +DistinguishedName ::= TEXTUAL-CONVENTION + DISPLAY-HINT "255a" + STATUS current + DESCRIPTION + "A Distinguished Name represented in accordance with + RFC 2253, presented in the UTF-8 charset defined in + RFC 2279." + SYNTAX OCTET STRING (SIZE (0..255)) + +-- Uniform Resource Locators are stored in URLStrings. + +URLString ::= TEXTUAL-CONVENTION + DISPLAY-HINT "255a" + STATUS current + DESCRIPTION + "A Uniform Resource Locator represented in accordance + with RFCs 1738 and 2368, presented in the NVT ASCII + charset defined in RFC 854." + SYNTAX OCTET STRING (SIZE (0..255)) + + +-- The basic applEntry contains the different elements. + +applDefinitions OBJECT IDENTIFIER ::= { r66 1 } +applGlobalValues OBJECT IDENTIFIER ::= { r66 2 } +applDetailedValues OBJECT IDENTIFIER ::= { r66 3 } +applErrorValues OBJECT IDENTIFIER ::= { r66 4 } +waarptraps OBJECT IDENTIFIER ::= { r66 5 } + + +applName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The name the network service application chooses to be + known by." + ::= {applDefinitions 1} + +applServerName OBJECT-TYPE + SYNTAX DistinguishedName + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Server Name of this particular instance." + ::= {applDefinitions 2} + +applVersion OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The version of network service application software. + This field is usually defined by the vendor of the + network service application software." + ::= {applDefinitions 3} + +applDescription OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "A text description of the application. This information + is intended to identify and briefly describe the + application in a status display." + ::= {applDefinitions 4} + +applURL OBJECT-TYPE + SYNTAX URLString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "A URL pointing to a description of the application. + This information is intended to identify and describe + the application in a status display." + ::= {applDefinitions 5} + +assocApplicationProtocol OBJECT-TYPE + SYNTAX OBJECT IDENTIFIER + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "An identification of the protocol being used for the + application. For an OSI Application, this will be the + Application Context. For Internet applications, OID + values of the form {applTCPProtoID port} or {applUDPProtoID + port} are used for TCP-based and UDP-based protocols, + respectively. In either case 'port' corresponds to the + primary port number being used by the protocol. The + usual IANA procedures may be used to register ports for + new protocols." + ::= {applDefinitions 6} + + +applUptime OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time the network service + application was last initialized. If the application was + last initialized prior to the last initialization of the + network management subsystem, then this object contains + a zero value." + ::= {applGlobalValues 1} + +applOperStatus OBJECT-TYPE + SYNTAX INTEGER { + up(1), + down(2), + halted(3), + congested(4), + restarting(5), + quiescing(6) + } + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Indicates the operational status of the network service + application. 'down' indicates that the network service is + not available. 'up' indicates that the network service + is operational and available. 'halted' indicates that the + service is operational but not available. 'congested' + indicates that the service is operational but no additional + inbound associations can be accommodated. 'restarting' + indicates that the service is currently unavailable but is + in the process of restarting and will be available soon. + 'quiescing' indicates that service is currently operational + but is in the process of shutting down. Additional inbound + associations may be rejected by applications in the + 'quiescing' state." + ::= {applGlobalValues 2} + +applLastChange OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time the network service + application entered its current operational state. If + the current state was entered prior to the last + initialization of the local network management subsystem, + then this object contains a zero value." + ::= {applGlobalValues 3} + +applInboundAssociations OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The number of current associations to the network service + application, where it is the responder. An inbound + association occurs when another application successfully + connects to this one." + ::= {applGlobalValues 4} + +applOutboundAssociations OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The number of current associations to the network service + application, where it is the initiator. An outbound + association occurs when this application successfully + connects to another one." + ::= {applGlobalValues 5} + +applAccumInboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of associations to the application entity + since application initialization, where it was the responder." + ::= {applGlobalValues 6} + +applAccumOutboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of associations to the application entity + since application initialization, where it was the initiator." + ::= {applGlobalValues 7} + +applLastInboundActivity OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time this application last + had an inbound association. If the last association + occurred prior to the last initialization of the network + subsystem, then this object contains a zero value." + ::= {applGlobalValues 8} + +applLastOutboundActivity OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time this application last + had an outbound association. If the last association + occurred prior to the last initialization of the network + subsystem, then this object contains a zero value." + ::= {applGlobalValues 9} + +applRejectedInboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of inbound associations the application + entity has rejected, since application initialization. + Rejected associations are not counted in the accumulated + association totals. Note that this only counts + associations the application entity has rejected itself; + it does not count rejections that occur at lower layers + of the network. Thus, this counter may not reflect the + true number of failed inbound associations." + ::= {applGlobalValues 10} + +applFailedOutboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number associations where the application entity + is initiator and association establishment has failed, + since application initialization. Failed associations are + not counted in the accumulated association totals." + ::= {applGlobalValues 11} + + -- Bandwidth +applInboundBandwidthKBS OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Inbound bandwidth usage in KB/s." + ::= {applGlobalValues 12} + +applOutboundBandwidthKBS OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Outbound bandwidth usage in KB/s." + ::= {applGlobalValues 13} + + -- Overall status including past, future and current transfers +nbInfoUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Unknown." + ::= {applGlobalValues 14} + +nbInfoNotUpdated OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as NotUpdated." + ::= {applGlobalValues 15} + +nbInfoInterrupted OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Interrupted." + ::= {applGlobalValues 16} + +nbInfoToSubmit OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as ToSubmit." + ::= {applGlobalValues 17} + +nbInfoError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Error." + ::= {applGlobalValues 18} + +nbInfoRunning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Running." + ::= {applGlobalValues 19} + +nbInfoDone OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Done." + ::= {applGlobalValues 20} + + + -- Current situation of all transfers, running or not +nbStepAllTransfer OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in total, running or not." + ::= {applGlobalValues 21} + +memoryTotal OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Allocated Memory in KiloBytes." + ::= {applGlobalValues 22} + +memoryFree OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Free Memory in KiloBytes." + ::= {applGlobalValues 23} + +memoryUsed OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Used Memory in KiloBytes." + ::= {applGlobalValues 24} + +nbThreads OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total number of active threads." + ::= {applGlobalValues 25} + +nbNetworkConnection OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total number of active network connections." + ::= {applGlobalValues 26} + +-- detailed part + +nbStepNotask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as NoTask." + ::= {applDetailedValues 1} + +nbStepPretask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as PreTask." + ::= {applDetailedValues 2} + +nbStepTransfer OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as Transfer." + ::= {applDetailedValues 3} + +nbStepPosttask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as PostTask." + ::= {applDetailedValues 4} + +nbStepAllDone OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as AllDone." + ::= {applDetailedValues 5} + +nbStepError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as Error." + ::= {applDetailedValues 6} + + + -- First on Running Transfers only +nbAllRunningStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count of all transfers currently in running." + ::= {applDetailedValues 7} + +nbRunningStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step Running." + ::= {applDetailedValues 8} + +nbInitOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step InitOk." + ::= {applDetailedValues 9} + +nbPreProcessingOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step PreProcessingOk." + ::= {applDetailedValues 10} + +nbTransferOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step TransferOk." + ::= {applDetailedValues 11} + +nbPostProcessingOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step PostProcessingOk." + ::= {applDetailedValues 12} + +nbCompleteOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step CompleteOk." + ::= {applDetailedValues 13} + + + -- Error Status on all transfers +nbStatusConnectionImpossible OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ConnectionImpossible." + ::= {applErrorValues 1} + +nbStatusServerOverloaded OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ServerOverloaded." + ::= {applErrorValues 2} + +nbStatusBadAuthent OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is BadAuthent." + ::= {applErrorValues 3} + +nbStatusExternalOp OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ExternalOp." + ::= {applErrorValues 4} + +nbStatusTransferError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is TransferError." + ::= {applErrorValues 5} + +nbStatusMD5Error OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is MD5Error." + ::= {applErrorValues 6} + +nbStatusDisconnection OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Disconnection." + ::= {applErrorValues 7} + +nbStatusFinalOp OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is FinalOp." + ::= {applErrorValues 8} + +nbStatusUnimplemented OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Unimplemented." + ::= {applErrorValues 9} + +nbStatusInternal OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Internal." + ::= {applErrorValues 10} + +nbStatusWarning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Warning." + ::= {applErrorValues 11} + +nbStatusQueryAlreadyFinished OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryAlreadyFinished." + ::= {applErrorValues 12} + +nbStatusQueryStillRunning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryStillRunning." + ::= {applErrorValues 13} + +nbStatusNotKnownHost OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is NotKnownHost." + ::= {applErrorValues 14} + +nbStatusQueryRemotelyUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryRemotelyUnknown." + ::= {applErrorValues 15} + +nbStatusCommandNotFound OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is CommandNotFound." + ::= {applErrorValues 16} + +nbStatusPassThroughMode OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is PassThroughMode." + ::= {applErrorValues 17} + +nbStatusRemoteShutdown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is RemoteShutdown." + ::= {applErrorValues 18} + +nbStatusShutdown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Shutdown." + ::= {applErrorValues 19} + +nbStatusRemoteError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is RemoteError." + ::= {applErrorValues 20} + +nbStatusStopped OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Stopped." + ::= {applErrorValues 21} + +nbStatusCanceled OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Canceled." + ::= {applErrorValues 22} + +nbStatusFileNotFound OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is FileNotFound." + ::= {applErrorValues 23} + +nbStatusUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Unknown." + ::= {applErrorValues 24} + +-- test notification + +startOrShutdownObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Start Or Shutdown Extra Information." +::= { startOrShutdownWaarp 1 } + +startOrShutdownWaarp NOTIFICATION-TYPE + OBJECTS { startOrShutdownObject } + STATUS current + DESCRIPTION "Start or Shutdown SMIv2 notification" + ::= { waarpgroup 1 } + +errorObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Nature of Error." +::= { errorWaarp 1 } + +errorWaarp NOTIFICATION-TYPE + OBJECTS { errorObject } + STATUS current + DESCRIPTION "Error SMIv2 notification" + ::= { waarpgroup 2 } + +warningObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Nature of Warning." +::= { warningWaarp 1 } + +warningWaarp NOTIFICATION-TYPE + OBJECTS { warningObject } + STATUS current + DESCRIPTION "Warning SMIv2 notification" + ::= { waarpgroup 3 } + +overloadedObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Overloaded Server extra information." +::= { overloadedWaarp 1 } + +overloadedWaarp NOTIFICATION-TYPE + OBJECTS { overloadedObject } + STATUS current + DESCRIPTION "Overloaded SMIv2 notification" + ::= { waarpgroup 4 } + +globalStepInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "GlobalStep rank." +::= { infoWaarp 1 } +stepInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Step in GlobalStep." +::= { infoWaarp 2 } +rankFileInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "File Rank." +::= { infoWaarp 3 } +stepStatusInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Status of Step." +::= { infoWaarp 4 } +filenameInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Current Filename." +::= { infoWaarp 5 } +originalNameInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Original Filename." +::= { infoWaarp 6 } +idRuleInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "ID of Rule." +::= { infoWaarp 7 } +modeTransInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Mode of Transfer." +::= { infoWaarp 8 } +retrieveModeInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Retrieve Mode." +::= { infoWaarp 9 } +startTransInfo OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Start Time of this transfer." +::= { infoWaarp 10 } +infoStatusInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Current Status." +::= { infoWaarp 11 } +requesterInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Requester Id for this transfer." +::= { infoWaarp 12 } +requestedInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Requested Id for this transfer." +::= { infoWaarp 13 } +specialIdInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Unique Id for this Transfer." +::= { infoWaarp 14 } + +infoWaarp NOTIFICATION-TYPE + OBJECTS { globalStepInfo, stepInfo, rankFileInfo, stepStatusInfo, filenameInfo, + originalNameInfo, idRuleInfo, modeTransInfo, retrieveModeInfo, startTransInfo, + infoStatusInfo, requesterInfo, requestedInfo, specialIdInfo } + STATUS current + DESCRIPTION "Info SMIv2 notification" + ::= { waarpgroup 5 } + +waarpgroup NOTIFICATION-GROUP + NOTIFICATIONS { startOrShutdownWaarp,errorWaarp,warningWaarp,overloadedWaarp,infoWaarp } + STATUS current + DESCRIPTION "Group of Notification in Waarp" + ::= { waarptraps 1 } + +END diff --git a/src/main/config/OpenR66-authent-A.xml b/src/main/config/OpenR66-authent-A.xml index f6db4075f..8d65a7988 100644 --- a/src/main/config/OpenR66-authent-A.xml +++ b/src/main/config/OpenR66-authent-A.xml @@ -1,52 +1,52 @@ - - - example for ServerA - - hosta -
127.0.0.1
- 6666 - False - D:\GG\R66\certs\test-passwd.ggp -
- - hostas -
127.0.0.1
- 6667 - True - True - D:\GG\R66\certs\test-passwd.ggp -
- - hostb -
127.0.0.1
- 6676 - False - False - D:\GG\R66\certs\test-passwd2.ggp -
- - hostbs -
127.0.0.1
- 6677 - True - True - a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 -
- - test -
127.0.0.1
- 6670 - False - True - D:\GG\R66\certs\test-passwd3.ggp -
- - tests -
127.0.0.1
- 6670 - True - True - True - D:\GG\R66\certs\test-passwd3.ggp -
-
+ + + example for ServerA + + hosta +
127.0.0.1
+ 6666 + False + D:\GG\R66\certs\test-passwd.ggp +
+ + hostas +
127.0.0.1
+ 6667 + True + True + D:\GG\R66\certs\test-passwd.ggp +
+ + hostb +
127.0.0.1
+ 6676 + False + False + D:\GG\R66\certs\test-passwd2.ggp +
+ + hostbs +
127.0.0.1
+ 6677 + True + True + a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 +
+ + test +
127.0.0.1
+ 6670 + False + True + D:\GG\R66\certs\test-passwd3.ggp +
+ + tests +
127.0.0.1
+ 6670 + True + True + True + D:\GG\R66\certs\test-passwd3.ggp +
+
diff --git a/src/main/config/config-clientA.xml b/src/main/config/config-clientA.xml index 6364cddb6..9d32a4979 100644 --- a/src/main/config/config-clientA.xml +++ b/src/main/config/config-clientA.xml @@ -1,40 +1,40 @@ - - - Example of config file: change its as your need. - - hosta - hostas - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - False - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - - - h2 - jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + Example of config file: change its as your need. + + hosta + hostas + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + False + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/config-clientB.xml b/src/main/config/config-clientB.xml index 12a76addf..96ff88be6 100644 --- a/src/main/config/config-clientB.xml +++ b/src/main/config/config-clientB.xml @@ -1,40 +1,40 @@ - - - Example of config file: change its as your need. - - hostb - hostbs - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - False - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - - - h2 - jdbc:h2:D:/GG/R66/data/openr66b;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + Example of config file: change its as your need. + + hostb + hostbs + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + False + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66b;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/config-clientNoDB.xml b/src/main/config/config-clientNoDB.xml index bf8de2585..1ff7ccc9c 100644 --- a/src/main/config/config-clientNoDB.xml +++ b/src/main/config/config-clientNoDB.xml @@ -1,35 +1,35 @@ - - - Example of config file: change its as your need. - - test - tests - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - True - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - False - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - - + + + Example of config file: change its as your need. + + test + tests + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + True + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + False + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + + diff --git a/src/main/config/config-clientSubmitA.xml b/src/main/config/config-clientSubmitA.xml index 9a55ee206..ef48ed3dd 100644 --- a/src/main/config/config-clientSubmitA.xml +++ b/src/main/config/config-clientSubmitA.xml @@ -1,18 +1,18 @@ - - - - hosta - hostas - D:\GG\R66\certs\test-key.des - - - D:\GG\R66 - - - - h2 - jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + + hosta + hostas + D:\GG\R66\certs\test-key.des + + + D:\GG\R66 + + + + h2 + jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/config-clienttest.xml b/src/main/config/config-clienttest.xml index 63bc2421f..e943fa495 100644 --- a/src/main/config/config-clienttest.xml +++ b/src/main/config/config-clienttest.xml @@ -1,32 +1,32 @@ - - - Example of config file: change its as your need. - - test - tests - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - False - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - - + + + Example of config file: change its as your need. + + test + tests + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + False + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + + diff --git a/src/main/config/config-serverA.xml b/src/main/config/config-serverA.xml index b1f28e363..c6eb9091a 100644 --- a/src/main/config/config-serverA.xml +++ b/src/main/config/config-serverA.xml @@ -1,81 +1,81 @@ - - - Example of config file: change its as your need. - - hosta - hostas - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - monadmin - c5f4876737cf351a - True - True - False - False - D:\NEWSOURCE\GoldenGateR66\src\main\admin - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - False - False - 86400000 - 5000 - D:/GG/R66/conf/snmpconfig.xml - - - 6666 - 6667 - 8066 - 8067 - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - True - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - 8 - 80 - 4000000000 - 8388608 - 67108864 - 10000 - 10000 - 5000 - 65536 - 30 - False - False - False - 0.9 - 0 - 0.5 - 0.9 - 0.25 - 1000 - 4096 - - - h2 - jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + Example of config file: change its as your need. + + hosta + hostas + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + True + True + False + False + D:\NEWSOURCE\GoldenGateR66\src\main\admin + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + False + False + 86400000 + 5000 + D:/GG/R66/conf/snmpconfig.xml + + + 6666 + 6667 + 8066 + 8067 + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + True + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + 8 + 80 + 4000000000 + 8388608 + 67108864 + 10000 + 10000 + 5000 + 65536 + 30 + False + False + False + 0.9 + 0 + 0.5 + 0.9 + 0.25 + 1000 + 4096 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/config-serverB.xml b/src/main/config/config-serverB.xml index fd1ae29b8..d4a8957b9 100644 --- a/src/main/config/config-serverB.xml +++ b/src/main/config/config-serverB.xml @@ -1,56 +1,56 @@ - - - Example of config file: change its as your need. - - hostb - hostbs - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - monadmin - c5f4876737cf351a - True - False - False - False - D:\NEWSOURCE\GoldenGateR66\src\main\admin - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - - - 6676 - 6677 - 8076 - 8077 - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - True - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - - - h2 - jdbc:h2:D:/GG/R66/data/openr66b;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + Example of config file: change its as your need. + + hostb + hostbs + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + True + False + False + False + D:\NEWSOURCE\GoldenGateR66\src\main\admin + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + + + 6676 + 6677 + 8076 + 8077 + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + True + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66b;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/config-serverInitA.xml b/src/main/config/config-serverInitA.xml index a94ba6180..48781c900 100644 --- a/src/main/config/config-serverInitA.xml +++ b/src/main/config/config-serverInitA.xml @@ -1,56 +1,56 @@ - - - Example of config file: change its as your need. - - hosta - hostas - D:\GG\R66\certs\test-key.des - D:\GG\R66\conf\OpenR66-authent-A.xml - - - True - True - True - False - monadmin - c5f4876737cf351a - D:/NEWSOURCE/GoldenGateR66/src/main/admin/ - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - - - 6666 - 6667 - 8066 - 8067 - - - D:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - D:\GG\R66\certs\testcert.jks - testcert - True - - - d:/GG/R66 - in - out - arch - work - conf - - - True - D:\NEWJARS\gglib\win32\MD5.dll - 10000 - 10000 - - - h2 - jdbc:h2:D:/GG/R66/data/openr66;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - + + + Example of config file: change its as your need. + + hosta + hostas + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + True + True + True + False + monadmin + c5f4876737cf351a + D:/NEWSOURCE/GoldenGateR66/src/main/admin/ + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + + + 6666 + 6667 + 8066 + 8067 + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + True + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/main/config/limitConfiga.xml b/src/main/config/limitConfiga.xml index f3097aa74..c449e44f2 100644 --- a/src/main/config/limitConfiga.xml +++ b/src/main/config/limitConfiga.xml @@ -1,15 +1,15 @@ - - - Example of config file: change its as your need. - - hosta - - - 0 - 0 - 10000 - 10000 - 5000 - 30000 - - + + + Example of config file: change its as your need. + + hosta + + + 0 + 0 + 10000 + 10000 + 5000 + 30000 + + diff --git a/src/main/config/logback-client.xml b/src/main/config/logback-client.xml index 48826fa5d..d2aefd802 100644 --- a/src/main/config/logback-client.xml +++ b/src/main/config/logback-client.xml @@ -1,35 +1,35 @@ - - - - GG/R66/log/R66Client.log - true - - /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - - + + + + GG/R66/log/R66Client.log + true + + /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/main/config/logback-service.xml b/src/main/config/logback-service.xml index 567c52a4d..465821864 100644 --- a/src/main/config/logback-service.xml +++ b/src/main/config/logback-service.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/config/logback.xml b/src/main/config/logback.xml index 567c52a4d..465821864 100644 --- a/src/main/config/logback.xml +++ b/src/main/config/logback.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/config/rulerecv-any.rule.xml b/src/main/config/rulerecv-any.rule.xml index 033ada5f1..99682b4e3 100644 --- a/src/main/config/rulerecv-any.rule.xml +++ b/src/main/config/rulerecv-any.rule.xml @@ -1,86 +1,86 @@ - - rule4 - 2 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - test - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - mon info - 0 - 0 - - - - - - - LOG - test - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule4 + 2 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + test + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + mon info + 0 + 0 + + + + + + + LOG + test + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/rulerecv.rule.xml b/src/main/config/rulerecv.rule.xml index d033fdd89..3346bc1c8 100644 --- a/src/main/config/rulerecv.rule.xml +++ b/src/main/config/rulerecv.rule.xml @@ -1,70 +1,70 @@ - - rule2 - - hosta - hostb - - 2 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - test - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule2 + + hosta + hostb + + 2 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + test + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/rulerecvthrough-any.rule.xml b/src/main/config/rulerecvthrough-any.rule.xml index 747722478..170f3c9f0 100644 --- a/src/main/config/rulerecvthrough-any.rule.xml +++ b/src/main/config/rulerecvthrough-any.rule.xml @@ -1,66 +1,66 @@ - - rule6 - 6 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - petittest - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule6 + 6 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/rulesend-any.rule.xml b/src/main/config/rulesend-any.rule.xml index 0f17ec865..5952a0977 100644 --- a/src/main/config/rulesend-any.rule.xml +++ b/src/main/config/rulesend-any.rule.xml @@ -1,66 +1,66 @@ - - rule3 - 1 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - petittest - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule3 + 1 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/rulesend.rule.xml b/src/main/config/rulesend.rule.xml index 6060f75ce..f7f21cbfc 100644 --- a/src/main/config/rulesend.rule.xml +++ b/src/main/config/rulesend.rule.xml @@ -1,70 +1,70 @@ - - rule1 - - hosta - hostb - - 1 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - petittest - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule1 + + hosta + hostb + + 1 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/rulesendthrough-any.rule.xml b/src/main/config/rulesendthrough-any.rule.xml index f7a243b90..001a8c358 100644 --- a/src/main/config/rulesendthrough-any.rule.xml +++ b/src/main/config/rulesendthrough-any.rule.xml @@ -1,66 +1,66 @@ - - rule5 - 5 - - - - - - - - LOG - mon info - 0 - 0 - - - LOG - une autre info - 0 - 1 - - - - - - - LOG - petittest - 0 - 0 - - - EXECRENAME - D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# - 20000 - 0 - - - COPYRENAME - D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s - 0 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - - - - - LOG - erreur - 1 - 0 - - - + + rule5 + 5 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + \ No newline at end of file diff --git a/src/main/config/snmpconfig.xml b/src/main/config/snmpconfig.xml index 808da1545..52c3d732a 100644 --- a/src/main/config/snmpconfig.xml +++ b/src/main/config/snmpconfig.xml @@ -1,99 +1,99 @@ - - - - udp:0.0.0.0/2001 - tcp:0.0.0.0/2002 - 4 - False - True - 4 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - -
+ + + + udp:0.0.0.0/2001 + tcp:0.0.0.0/2002 + 4 + False + True + 4 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + + +
diff --git a/src/main/example/Linux/conf/logback-client.xml b/src/main/example/Linux/conf/logback-client.xml index 48826fa5d..d2aefd802 100644 --- a/src/main/example/Linux/conf/logback-client.xml +++ b/src/main/example/Linux/conf/logback-client.xml @@ -1,35 +1,35 @@ - - - - GG/R66/log/R66Client.log - true - - /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - - + + + + GG/R66/log/R66Client.log + true + + /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/main/example/Linux/conf/logback-service.xml b/src/main/example/Linux/conf/logback-service.xml index 567c52a4d..465821864 100644 --- a/src/main/example/Linux/conf/logback-service.xml +++ b/src/main/example/Linux/conf/logback-service.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Linux/conf/logback.xml b/src/main/example/Linux/conf/logback.xml index 567c52a4d..465821864 100644 --- a/src/main/example/Linux/conf/logback.xml +++ b/src/main/example/Linux/conf/logback.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Linux/conf/snmpconfig-proxy.xml b/src/main/example/Linux/conf/snmpconfig-proxy.xml index f6427b407..84812d9ec 100644 --- a/src/main/example/Linux/conf/snmpconfig-proxy.xml +++ b/src/main/example/Linux/conf/snmpconfig-proxy.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2011 - tcp:0.0.0.0/2012 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2011 + tcp:0.0.0.0/2012 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Linux/conf/snmpconfig.xml b/src/main/example/Linux/conf/snmpconfig.xml index 914036e45..ceca3690f 100644 --- a/src/main/example/Linux/conf/snmpconfig.xml +++ b/src/main/example/Linux/conf/snmpconfig.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2001 - tcp:0.0.0.0/2002 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2001 + tcp:0.0.0.0/2002 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Unix/AIX/conf/logback-client.xml b/src/main/example/Unix/AIX/conf/logback-client.xml index 48826fa5d..d2aefd802 100644 --- a/src/main/example/Unix/AIX/conf/logback-client.xml +++ b/src/main/example/Unix/AIX/conf/logback-client.xml @@ -1,35 +1,35 @@ - - - - GG/R66/log/R66Client.log - true - - /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - - + + + + GG/R66/log/R66Client.log + true + + /GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/main/example/Unix/AIX/conf/logback-service.xml b/src/main/example/Unix/AIX/conf/logback-service.xml index 567c52a4d..465821864 100644 --- a/src/main/example/Unix/AIX/conf/logback-service.xml +++ b/src/main/example/Unix/AIX/conf/logback-service.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Unix/AIX/conf/logback.xml b/src/main/example/Unix/AIX/conf/logback.xml index 567c52a4d..465821864 100644 --- a/src/main/example/Unix/AIX/conf/logback.xml +++ b/src/main/example/Unix/AIX/conf/logback.xml @@ -1,34 +1,34 @@ - - - - /GG/R66/log/R66Server.log - true - - /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + /GG/R66/log/R66Server.log + true + + /GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Unix/AIX/conf/snmpconfig-proxy.xml b/src/main/example/Unix/AIX/conf/snmpconfig-proxy.xml index f6427b407..84812d9ec 100644 --- a/src/main/example/Unix/AIX/conf/snmpconfig-proxy.xml +++ b/src/main/example/Unix/AIX/conf/snmpconfig-proxy.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2011 - tcp:0.0.0.0/2012 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2011 + tcp:0.0.0.0/2012 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Unix/AIX/conf/snmpconfig.xml b/src/main/example/Unix/AIX/conf/snmpconfig.xml index 914036e45..ceca3690f 100644 --- a/src/main/example/Unix/AIX/conf/snmpconfig.xml +++ b/src/main/example/Unix/AIX/conf/snmpconfig.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2001 - tcp:0.0.0.0/2002 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2001 + tcp:0.0.0.0/2002 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Windows/bin/R66ClGUI.bat b/src/main/example/Windows/bin/R66ClGUI.bat index 07534fe66..a8ec23ebd 100644 --- a/src/main/example/Windows/bin/R66ClGUI.bat +++ b/src/main/example/Windows/bin/R66ClGUI.bat @@ -1,6 +1,6 @@ -echo Start R66 Client GUI -call setvari.bat -echo %R66GUI% -%R66GUI% -echo R66 Client GUI stopped +echo Start R66 Client GUI +call setvari.bat +echo %R66GUI% +%R66GUI% +echo R66 Client GUI stopped rem pause \ No newline at end of file diff --git a/src/main/example/Windows/bin/R66SYNCSEND.bat b/src/main/example/Windows/bin/R66SYNCSEND.bat index e4df477df..bbf0c1459 100644 --- a/src/main/example/Windows/bin/R66SYNCSEND.bat +++ b/src/main/example/Windows/bin/R66SYNCSEND.bat @@ -1,5 +1,5 @@ -echo Start R66 Sync Send -call setvari.bat -%R66SYNCSEND% %* -echo R66 Sync Send stopped -REM pause +echo Start R66 Sync Send +call setvari.bat +%R66SYNCSEND% %* +echo R66 Sync Send stopped +REM pause diff --git a/src/main/example/Windows/bin/server.bat b/src/main/example/Windows/bin/server.bat index 21a261aa1..021dba1df 100644 --- a/src/main/example/Windows/bin/server.bat +++ b/src/main/example/Windows/bin/server.bat @@ -1,4 +1,4 @@ -echo Start R66Server -call setvari.bat -%JAVARUNSERVER% -echo R66Server stopped +echo Start R66Server +call setvari.bat +%JAVARUNSERVER% +echo R66Server stopped diff --git a/src/main/example/Windows/bin/setvari.bat b/src/main/example/Windows/bin/setvari.bat index c02b46db8..7f6e63c29 100644 --- a/src/main/example/Windows/bin/setvari.bat +++ b/src/main/example/Windows/bin/setvari.bat @@ -1,97 +1,97 @@ -@echo off -REM JDK SUN -SET JAVA_OPTS1=-server -SET JAVA_OPTS2=-Xms256m -Xmx4096m -SET JAVA_RUN="C:\Program Files\Java\jdk1.6.0_14\jre\bin\java" %JAVA_OPTS1% %JAVA_OPTS2% - -SET R66HOME=D:\GG\R66Client\ -SET R66BIN=%R66HOME%\lib - -REM command for Client - -REM Logger -SET LOGSERVER=" -Dlogback.configurationFile=${R66HOME}\conf\logback.xml " -SET LOGCLIENT=" -Dlogback.configurationFile=${R66HOME}\conf\logback-client.xml " - -SET R66_CLASSPATH=" ${R66BIN}\WaarpR66-2.4.11.jar;${R66BIN}\* " - -SET JAVARUNCLIENT=%JAVA_RUN% -cp %R66_CLASSPATH% %LOGCLIENT% -SET JAVARUNSERVER=%JAVA_RUN% -cp %R66_CLASSPATH% %LOGSERVER% - -SET SERVER_CONFIG="${R66HOME}/conf/config-serverA.xml" -SET CLIENT_CONFIG="${R66HOME}/conf/config-clientA.xml" - -REM ################ -REM # R66 COMMANDS # -REM ################ - -REM # SERVER SIDE # -REM ############### - -REM # start the OpenR66 server -REM # no option -set R66SERVER=%JAVARUNSERVER% openr66.server.R66Server %SERVER_CONFIG% - -REM # init database from argument -REM # [ -initdb ] [ -dir rulesDirectory ] [ -limit xmlFileLimit ] [ -auth xmlFileAuthent ] -set R66INIT=%JAVARUNCLIENT% openr66.server.ServerInitDatabase %SERVER_CONFIG% - -REM # export configuration into directory -REM # directory -set R66CNFEXP=%JAVARUNCLIENT% org.waarp.openr66.server.ServerExportConfiguration %SERVER_CONFIG% - -REM # export configuration as arguments -REM # [-hosts] [-rules] -set R66CONFEXP=%JAVARUNCLIENT% org.waarp.openr66.server.ConfigExport %SERVER_CONFIG% - -REM # import configuration as arguments -REM # [-hosts host-configuration-file] [-purgehosts] [-rules rule-configuration-file] [-purgerules] -set R66CONFIMP=%JAVARUNCLIENT% org.waarp.openr66.server.ConfigImport %SERVER_CONFIG% - -REM # shutdown locally the server -REM # PID optional PID of the server process -set R66SIGNAL="taskkill /T /PID " - -REM # shutdown by network the server -REM # [-nossl|-ssl] default = -ssl -set R66SHUTD=%JAVARUNCLIENT% org.waarp.openr66.server.ServerShutdown %SERVER_CONFIG% - -REM # export the log -REM # [ -purge ] [ -clean ] [ -start timestamp ] [ -stop timestamp ] where timestamp are in yyyyMMddHHmmssSSS format eventually truncated and with possible ':- ' as separators -set R66EXPORT=%JAVARUNCLIENT% org.waarp.openr66.server.LogExport %SERVER_CONFIG% - -REM # change limits of bandwidth -REM # "[ -wglob x ] [ -rglob w ] [ -wsess x ] [ -rsess x ]" -set R66LIMIT=%JAVARUNCLIENT% org.waarp.openr66.server.ChangeBandwidthLimits %SERVER_CONFIG% - -REM # Administrator Gui -REM # no argument -set R66ADMIN=%JAVARUNCLIENT% org.waarp.administrator.AdminGui %SERVER_CONFIG% - -REM # CLIENT SIDE # -REM ############### - -REM # asynchronous transfer -REM # (-to hostId -file filepath -rule ruleId) | (-to hostId -id transferId) [ -md5 ] [ -block size ] [ -nolog ] [-start yyyyMMddHHmmssSSS | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds] [ -info "information" ] -set R66SEND=%JAVARUNCLIENT% org.waarp.openr66.client.SubmitTransfer %CLIENT_CONFIG% - -REM # synchronous transfer -REM # (-to hostId -file filepath -rule ruleId) | (-to hostId -id transferId) [ -md5 ] [ -block size ] [ -nolog ] [-start yyyyMMddHHmmssSSS | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds] [ -info "information" ] -set R66SYNCSEND=%JAVARUNCLIENT% org.waarp.openr66.client.DirectTransfer %CLIENT_CONFIG% - -REM # get information on transfers -REM # (-id transferId -to hostId as requested | -id transferId -from hostId as requester) -REM # follow by one of: (-cancel | -stop | -restart [ -start yyyyMMddHHmmss | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds ] -set R66REQ=%JAVARUNCLIENT% org.waarp.openr66.client.RequestTransfer %CLIENT_CONFIG% - -REM # get information on remote files or directory -REM # "-to host -rule rule [ -file file ] [ -exist | -detail | -list | -mlsx ] -set R66INFO=%JAVARUNCLIENT% org.waarp.openr66.client.RequestInformation %CLIENT_CONFIG% - -REM # test the connectivity -REM # -to host -msg "message" -set R66MESG=%JAVARUNCLIENT% org.waarp.openr66.client.Message %CLIENT_CONFIG% - -REM # Gui interface -REM # no argument -set R66GUI=%JAVARUNCLIENT% org.waarp.openr66.r66gui.R66ClientGui %CLIENT_CONFIG% +@echo off +REM JDK SUN +SET JAVA_OPTS1=-server +SET JAVA_OPTS2=-Xms256m -Xmx4096m +SET JAVA_RUN="C:\Program Files\Java\jdk1.6.0_14\jre\bin\java" %JAVA_OPTS1% %JAVA_OPTS2% + +SET R66HOME=D:\GG\R66Client\ +SET R66BIN=%R66HOME%\lib + +REM command for Client + +REM Logger +SET LOGSERVER=" -Dlogback.configurationFile=${R66HOME}\conf\logback.xml " +SET LOGCLIENT=" -Dlogback.configurationFile=${R66HOME}\conf\logback-client.xml " + +SET R66_CLASSPATH=" ${R66BIN}\WaarpR66-2.4.11.jar;${R66BIN}\* " + +SET JAVARUNCLIENT=%JAVA_RUN% -cp %R66_CLASSPATH% %LOGCLIENT% +SET JAVARUNSERVER=%JAVA_RUN% -cp %R66_CLASSPATH% %LOGSERVER% + +SET SERVER_CONFIG="${R66HOME}/conf/config-serverA.xml" +SET CLIENT_CONFIG="${R66HOME}/conf/config-clientA.xml" + +REM ################ +REM # R66 COMMANDS # +REM ################ + +REM # SERVER SIDE # +REM ############### + +REM # start the OpenR66 server +REM # no option +set R66SERVER=%JAVARUNSERVER% openr66.server.R66Server %SERVER_CONFIG% + +REM # init database from argument +REM # [ -initdb ] [ -dir rulesDirectory ] [ -limit xmlFileLimit ] [ -auth xmlFileAuthent ] +set R66INIT=%JAVARUNCLIENT% openr66.server.ServerInitDatabase %SERVER_CONFIG% + +REM # export configuration into directory +REM # directory +set R66CNFEXP=%JAVARUNCLIENT% org.waarp.openr66.server.ServerExportConfiguration %SERVER_CONFIG% + +REM # export configuration as arguments +REM # [-hosts] [-rules] +set R66CONFEXP=%JAVARUNCLIENT% org.waarp.openr66.server.ConfigExport %SERVER_CONFIG% + +REM # import configuration as arguments +REM # [-hosts host-configuration-file] [-purgehosts] [-rules rule-configuration-file] [-purgerules] +set R66CONFIMP=%JAVARUNCLIENT% org.waarp.openr66.server.ConfigImport %SERVER_CONFIG% + +REM # shutdown locally the server +REM # PID optional PID of the server process +set R66SIGNAL="taskkill /T /PID " + +REM # shutdown by network the server +REM # [-nossl|-ssl] default = -ssl +set R66SHUTD=%JAVARUNCLIENT% org.waarp.openr66.server.ServerShutdown %SERVER_CONFIG% + +REM # export the log +REM # [ -purge ] [ -clean ] [ -start timestamp ] [ -stop timestamp ] where timestamp are in yyyyMMddHHmmssSSS format eventually truncated and with possible ':- ' as separators +set R66EXPORT=%JAVARUNCLIENT% org.waarp.openr66.server.LogExport %SERVER_CONFIG% + +REM # change limits of bandwidth +REM # "[ -wglob x ] [ -rglob w ] [ -wsess x ] [ -rsess x ]" +set R66LIMIT=%JAVARUNCLIENT% org.waarp.openr66.server.ChangeBandwidthLimits %SERVER_CONFIG% + +REM # Administrator Gui +REM # no argument +set R66ADMIN=%JAVARUNCLIENT% org.waarp.administrator.AdminGui %SERVER_CONFIG% + +REM # CLIENT SIDE # +REM ############### + +REM # asynchronous transfer +REM # (-to hostId -file filepath -rule ruleId) | (-to hostId -id transferId) [ -md5 ] [ -block size ] [ -nolog ] [-start yyyyMMddHHmmssSSS | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds] [ -info "information" ] +set R66SEND=%JAVARUNCLIENT% org.waarp.openr66.client.SubmitTransfer %CLIENT_CONFIG% + +REM # synchronous transfer +REM # (-to hostId -file filepath -rule ruleId) | (-to hostId -id transferId) [ -md5 ] [ -block size ] [ -nolog ] [-start yyyyMMddHHmmssSSS | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds] [ -info "information" ] +set R66SYNCSEND=%JAVARUNCLIENT% org.waarp.openr66.client.DirectTransfer %CLIENT_CONFIG% + +REM # get information on transfers +REM # (-id transferId -to hostId as requested | -id transferId -from hostId as requester) +REM # follow by one of: (-cancel | -stop | -restart [ -start yyyyMMddHHmmss | -delay +durationInMilliseconds | -delay preciseTimeInMilliseconds ] +set R66REQ=%JAVARUNCLIENT% org.waarp.openr66.client.RequestTransfer %CLIENT_CONFIG% + +REM # get information on remote files or directory +REM # "-to host -rule rule [ -file file ] [ -exist | -detail | -list | -mlsx ] +set R66INFO=%JAVARUNCLIENT% org.waarp.openr66.client.RequestInformation %CLIENT_CONFIG% + +REM # test the connectivity +REM # -to host -msg "message" +set R66MESG=%JAVARUNCLIENT% org.waarp.openr66.client.Message %CLIENT_CONFIG% + +REM # Gui interface +REM # no argument +set R66GUI=%JAVARUNCLIENT% org.waarp.openr66.r66gui.R66ClientGui %CLIENT_CONFIG% diff --git a/src/main/example/Windows/conf/OpenR66-authent-A-2.xml b/src/main/example/Windows/conf/OpenR66-authent-A-2.xml index a4641e23a..9fab411ec 100644 --- a/src/main/example/Windows/conf/OpenR66-authent-A-2.xml +++ b/src/main/example/Windows/conf/OpenR66-authent-A-2.xml @@ -1,94 +1,94 @@ - - - example for ServerA - - hosta -
127.0.0.1
- 6686 - False - J:\GG\R66\certs\test-passwd.ggp -
- - hostas -
127.0.0.1
- 6687 - True - True - J:\GG\R66\certs\test-passwd.ggp -
- - hostasalias -
127.0.0.1
- 6687 - True - True - J:\GG\R66\certs\test-passwd.ggp -
- - hostb -
127.0.0.1
- 6676 - False - False - J:\GG\R66\certs\test-passwd2.ggp -
- - hostbs -
127.0.0.1
- 6677 - True - True - a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 -
- - test -
127.0.0.1
- 6670 - False - True - J:\GG\R66\certs\test-passwd3.ggp -
- - tests -
127.0.0.1
- 6670 - True - True - True - J:\GG\R66\certs\test-passwd3.ggp -
- - proxy - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9986 - false -
- - proxy2 - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9988 - false -
- - proxys - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9987 - true -
- - hostas - proxys2 - J:\GG\R66\certs\test-passwd.ggp - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9989 - true -
-
+ + + example for ServerA + + hosta +
127.0.0.1
+ 6686 + False + J:\GG\R66\certs\test-passwd.ggp +
+ + hostas +
127.0.0.1
+ 6687 + True + True + J:\GG\R66\certs\test-passwd.ggp +
+ + hostasalias +
127.0.0.1
+ 6687 + True + True + J:\GG\R66\certs\test-passwd.ggp +
+ + hostb +
127.0.0.1
+ 6676 + False + False + J:\GG\R66\certs\test-passwd2.ggp +
+ + hostbs +
127.0.0.1
+ 6677 + True + True + a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 +
+ + test +
127.0.0.1
+ 6670 + False + True + J:\GG\R66\certs\test-passwd3.ggp +
+ + tests +
127.0.0.1
+ 6670 + True + True + True + J:\GG\R66\certs\test-passwd3.ggp +
+ + proxy + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9986 + false +
+ + proxy2 + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9988 + false +
+ + proxys + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9987 + true +
+ + hostas + proxys2 + J:\GG\R66\certs\test-passwd.ggp + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9989 + true +
+
diff --git a/src/main/example/Windows/conf/config-clientNoDb.xml b/src/main/example/Windows/conf/config-clientNoDb.xml index b4a1478e8..4dd4a1eb2 100644 --- a/src/main/example/Windows/conf/config-clientNoDb.xml +++ b/src/main/example/Windows/conf/config-clientNoDb.xml @@ -1,52 +1,52 @@ - - - Example of config file: change its as your need. - - hosta - hostas - J:\GG\R66\certs\test-key.des - J:\GG\R66\conf\OpenR66-authent-A-2.xml - - - - - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - J:\GG\R66\certs\testcert.jks - testcert - False - - - J:/GG/R66 - in - out - arch - work - conf - - - 4 - True - 4096 - 10000 - 0 - 0 - 10000 - True - - - hosta - hostas - - - - hosta - CONFIGADMIN|SYSTEM - - - hostas - FULLADMIN - - - + + + Example of config file: change its as your need. + + hosta + hostas + J:\GG\R66\certs\test-key.des + J:\GG\R66\conf\OpenR66-authent-A-2.xml + + + + + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + J:\GG\R66\certs\testcert.jks + testcert + False + + + J:/GG/R66 + in + out + arch + work + conf + + + 4 + True + 4096 + 10000 + 0 + 0 + 10000 + True + + + hosta + hostas + + + + hosta + CONFIGADMIN|SYSTEM + + + hostas + FULLADMIN + + + diff --git a/src/main/example/Windows/conf/config-clienttest2.xml b/src/main/example/Windows/conf/config-clienttest2.xml index dc4112813..c9d4dc983 100644 --- a/src/main/example/Windows/conf/config-clienttest2.xml +++ b/src/main/example/Windows/conf/config-clienttest2.xml @@ -1,39 +1,39 @@ - - - Example of config file: change its as your need. - - test - tests - J:\GG\R66\certs\test-key.des - J:\GG\R66\conf\OpenR66-authent-A-2.xml - - - - - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - J:\GG\R66\certs\testcert.jks - testcert - False - - - J:/GG/R66 - in - out - arch - work - conf - - - 4 - True - J:\NEWJARS\gglib\win32\MD5.dll - 4096 - 10000 - 0 - 0 - 10000 - True - - + + + Example of config file: change its as your need. + + test + tests + J:\GG\R66\certs\test-key.des + J:\GG\R66\conf\OpenR66-authent-A-2.xml + + + + + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + J:\GG\R66\certs\testcert.jks + testcert + False + + + J:/GG/R66 + in + out + arch + work + conf + + + 4 + True + J:\NEWJARS\gglib\win32\MD5.dll + 4096 + 10000 + 0 + 0 + 10000 + True + + diff --git a/src/main/example/Windows/conf/config-proxy.xml b/src/main/example/Windows/conf/config-proxy.xml index 305eca5d5..5a457325c 100644 --- a/src/main/example/Windows/conf/config-proxy.xml +++ b/src/main/example/Windows/conf/config-proxy.xml @@ -1,94 +1,94 @@ - - - Example of config file: change its as your need. - - hostproxy - hostproxys - J:\GG\R66\certs\test-key.des - J:\GG\R66\conf\OpenR66-authent-A.xml - - - monadmin - c5f4876737cf351a - J:\GG\R66\certs\test-passwd-http.ggp - True - True - False - False - J:\GG\R66\adminproxy - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - 86400000 - 5000 - J:\GG\R66\conf\snmpconfig-proxy.xml - - - - 127.0.0.1 - 9986 - false - 127.0.0.1 - 6686 - false - - - 127.0.0.1 - 9987 - true - 127.0.0.1 - 6686 - false - - - 127.0.0.1 - 9988 - false - 127.0.0.1 - 6687 - true - - - 127.0.0.1 - 9989 - true - 127.0.0.1 - 6687 - true - - 10086 - 10087 - - - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - J:\GG\R66\certs\testcert.jks - testcert - True - - - J:/GG/R66 - arch - conf - - - 10000 - 2 - 4 - 4000000000 - 0 - 0 - 10000 - False - False - 0.9 - 0 - 0.5 - 0.9 - 0.25 - 1000 - 4096 - True - - + + + Example of config file: change its as your need. + + hostproxy + hostproxys + J:\GG\R66\certs\test-key.des + J:\GG\R66\conf\OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + J:\GG\R66\certs\test-passwd-http.ggp + True + True + False + False + J:\GG\R66\adminproxy + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + 86400000 + 5000 + J:\GG\R66\conf\snmpconfig-proxy.xml + + + + 127.0.0.1 + 9986 + false + 127.0.0.1 + 6686 + false + + + 127.0.0.1 + 9987 + true + 127.0.0.1 + 6686 + false + + + 127.0.0.1 + 9988 + false + 127.0.0.1 + 6687 + true + + + 127.0.0.1 + 9989 + true + 127.0.0.1 + 6687 + true + + 10086 + 10087 + + + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + J:\GG\R66\certs\testcert.jks + testcert + True + + + J:/GG/R66 + arch + conf + + + 10000 + 2 + 4 + 4000000000 + 0 + 0 + 10000 + False + False + 0.9 + 0 + 0.5 + 0.9 + 0.25 + 1000 + 4096 + True + + diff --git a/src/main/example/Windows/conf/config-serverA.xml b/src/main/example/Windows/conf/config-serverA.xml index 1a52c6037..e3c1f06c4 100644 --- a/src/main/example/Windows/conf/config-serverA.xml +++ b/src/main/example/Windows/conf/config-serverA.xml @@ -1,103 +1,103 @@ - - - Example of config file: change its as your need. - - hosta - hostas - J:\GG\R66\certs\test-key.des - J:\GG\R66\conf\OpenR66-authent-A.xml - - - monadmin - c5f4876737cf351a - J:\GG\R66\certs\test-passwd-http.ggp - True - True - False - False - J:\GG\R66\admin2 - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - False - False - 86400000 - 5000 - J:\GG\R66\conf\snmpconfig.xml - 2 - - - 6686 - 6687 - 8086 - 8087 - - - J:\GG\R66\certs\testsslnocert.jks - testsslnocert - testalias - J:\GG\R66\certs\testcert.jks - testcert - True - - - J:/GG/R66 - in - out - arch - work - conf - - - 4 - True - 10000 - 10000 - 10 - 50 - 4000000000 - 0 - 0 - 10000 - 10000 - 5000 - 65536 - 30 - False - False - False - 0.9 - 0 - 0.5 - 0.9 - 0.25 - 1000 - 4096 - 4266 - True - - - h2 - jdbc:h2:J:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE - openr66 - openr66 - - - hosta - hostas - - - - hosta - CONFIGADMIN|SYSTEM - - - hostas - FULLADMIN - - - tests - FULLADMIN - - - + + + Example of config file: change its as your need. + + hosta + hostas + J:\GG\R66\certs\test-key.des + J:\GG\R66\conf\OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + J:\GG\R66\certs\test-passwd-http.ggp + True + True + False + False + J:\GG\R66\admin2 + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + False + False + 86400000 + 5000 + J:\GG\R66\conf\snmpconfig.xml + 2 + + + 6686 + 6687 + 8086 + 8087 + + + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + J:\GG\R66\certs\testcert.jks + testcert + True + + + J:/GG/R66 + in + out + arch + work + conf + + + 4 + True + 10000 + 10000 + 10 + 50 + 4000000000 + 0 + 0 + 10000 + 10000 + 5000 + 65536 + 30 + False + False + False + 0.9 + 0 + 0.5 + 0.9 + 0.25 + 1000 + 4096 + 4266 + True + + + h2 + jdbc:h2:J:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + + hosta + hostas + + + + hosta + CONFIGADMIN|SYSTEM + + + hostas + FULLADMIN + + + tests + FULLADMIN + + + diff --git a/src/main/example/Windows/conf/hosta.rules.xml b/src/main/example/Windows/conf/hosta.rules.xml index 6fc689211..99adfe630 100644 --- a/src/main/example/Windows/conf/hosta.rules.xml +++ b/src/main/example/Windows/conf/hosta.rules.xml @@ -1,150 +1,150 @@ - - - - - rule4 - - 2 - in - out - arch - work - - - - LOG - mon info pre recv - 0 - - - LOG - une autre info - 0 - - - - - - - LOG - mon info pre recv - 0 - - - LOG - une autre info - 0 - - - - - - - LOG - erreur recv ##ERRORMSG## - 1 - - - - - - - LOG - mon info pre send - 0 - - - - - - - LOG - test post send - 0 - - - - - - - LOG - erreur send ##ERRORMSG## - 1 - - - - - - rule3 - - 1 - in - out - arch - work - - - - LOG - mon info pre recv - 0 - - - LOG - une autre info - 0 - - - - - - - LOG - mon info pre recv - 0 - - - LOG - -file #TRUEFULLPATH# -to 127.0.0.1 -port 21 -user fred -pwd fred2 -account a -digest sha1 -command put - 0 - - - - - - - LOG - erreur RECV ##ERRORMSG## - 1 - - - - - - - LOG - mon info pre send - 0 - - - - - - - LOG - test post send - 0 - - - - - - - LOG - erreur SEND ##ERRORMSG## - 1 - - - - - + + + + + rule4 + + 2 + in + out + arch + work + + + + LOG + mon info pre recv + 0 + + + LOG + une autre info + 0 + + + + + + + LOG + mon info pre recv + 0 + + + LOG + une autre info + 0 + + + + + + + LOG + erreur recv ##ERRORMSG## + 1 + + + + + + + LOG + mon info pre send + 0 + + + + + + + LOG + test post send + 0 + + + + + + + LOG + erreur send ##ERRORMSG## + 1 + + + + + + rule3 + + 1 + in + out + arch + work + + + + LOG + mon info pre recv + 0 + + + LOG + une autre info + 0 + + + + + + + LOG + mon info pre recv + 0 + + + LOG + -file #TRUEFULLPATH# -to 127.0.0.1 -port 21 -user fred -pwd fred2 -account a -digest sha1 -command put + 0 + + + + + + + LOG + erreur RECV ##ERRORMSG## + 1 + + + + + + + LOG + mon info pre send + 0 + + + + + + + LOG + test post send + 0 + + + + + + + LOG + erreur SEND ##ERRORMSG## + 1 + + + + + diff --git a/src/main/example/Windows/conf/hosta_Authentications.xml b/src/main/example/Windows/conf/hosta_Authentications.xml index fe22b2d9c..eea63b819 100644 --- a/src/main/example/Windows/conf/hosta_Authentications.xml +++ b/src/main/example/Windows/conf/hosta_Authentications.xml @@ -1,92 +1,92 @@ - - - - - hostbs - a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 - true -
127.0.0.1
- 6677 - true -
- - tests - a5847a6ebb2eb5230554eb160326e7b1b59da443feab31e5 - true -
127.0.0.1
- 6670 - true -
- - hostb - a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 - false -
127.0.0.1
- 6676 - false -
- - test - a5847a6ebb2eb5230554eb160326e7b1b59da443feab31e5 - false -
127.0.0.1
- 6670 - false -
- - hostas - a5847a6ebb2eb5230554eb160326e7b1893eecb714f52fc6 - true -
127.0.0.1
- 6687 - true -
- - hosta - a5847a6ebb2eb5230554eb160326e7b1893eecb714f52fc6 - false -
127.0.0.1
- 6686 - false -
- - proxy - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9986 - false -
- - proxy2 - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9988 - false -
- - proxys - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9987 - true -
- - proxys2 - 90d61c4a9a55e7d0 - false -
127.0.0.1
- 9989 - true -
- - hostbsalias - f867b20c2aa2c0163ba1fe457fc6e2bc893eecb714f52fc6 - false -
127.0.0.1
- 6677 - true -
-
+ + + + + hostbs + a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 + true +
127.0.0.1
+ 6677 + true +
+ + tests + a5847a6ebb2eb5230554eb160326e7b1b59da443feab31e5 + true +
127.0.0.1
+ 6670 + true +
+ + hostb + a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 + false +
127.0.0.1
+ 6676 + false +
+ + test + a5847a6ebb2eb5230554eb160326e7b1b59da443feab31e5 + false +
127.0.0.1
+ 6670 + false +
+ + hostas + a5847a6ebb2eb5230554eb160326e7b1893eecb714f52fc6 + true +
127.0.0.1
+ 6687 + true +
+ + hosta + a5847a6ebb2eb5230554eb160326e7b1893eecb714f52fc6 + false +
127.0.0.1
+ 6686 + false +
+ + proxy + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9986 + false +
+ + proxy2 + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9988 + false +
+ + proxys + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9987 + true +
+ + proxys2 + 90d61c4a9a55e7d0 + false +
127.0.0.1
+ 9989 + true +
+ + hostbsalias + f867b20c2aa2c0163ba1fe457fc6e2bc893eecb714f52fc6 + false +
127.0.0.1
+ 6677 + true +
+
diff --git a/src/main/example/Windows/conf/limitConfiga.xml b/src/main/example/Windows/conf/limitConfiga.xml index f3097aa74..c449e44f2 100644 --- a/src/main/example/Windows/conf/limitConfiga.xml +++ b/src/main/example/Windows/conf/limitConfiga.xml @@ -1,15 +1,15 @@ - - - Example of config file: change its as your need. - - hosta - - - 0 - 0 - 10000 - 10000 - 5000 - 30000 - - + + + Example of config file: change its as your need. + + hosta + + + 0 + 0 + 10000 + 10000 + 5000 + 30000 + + diff --git a/src/main/example/Windows/conf/logback-client.xml b/src/main/example/Windows/conf/logback-client.xml index 353d6cf15..c9fcd863f 100644 --- a/src/main/example/Windows/conf/logback-client.xml +++ b/src/main/example/Windows/conf/logback-client.xml @@ -1,35 +1,35 @@ - - - - J:/GG/R66/log/R66Client.log - true - - J:/GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - - + + + + J:/GG/R66/log/R66Client.log + true + + J:/GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/main/example/Windows/conf/logback-service.xml b/src/main/example/Windows/conf/logback-service.xml index 5f379ec5a..6878bf268 100644 --- a/src/main/example/Windows/conf/logback-service.xml +++ b/src/main/example/Windows/conf/logback-service.xml @@ -1,34 +1,34 @@ - - - - J:/GG/R66/log/R66Server.log - true - - J:/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + J:/GG/R66/log/R66Server.log + true + + J:/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Windows/conf/logback.xml b/src/main/example/Windows/conf/logback.xml index 5f379ec5a..6878bf268 100644 --- a/src/main/example/Windows/conf/logback.xml +++ b/src/main/example/Windows/conf/logback.xml @@ -1,34 +1,34 @@ - - - - J:/GG/R66/log/R66Server.log - true - - J:/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip - 30 - - 10MB - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n - - - - - - - - - + + + + J:/GG/R66/log/R66Server.log + true + + J:/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/main/example/Windows/conf/snmpconfig-proxy.xml b/src/main/example/Windows/conf/snmpconfig-proxy.xml index f6427b407..84812d9ec 100644 --- a/src/main/example/Windows/conf/snmpconfig-proxy.xml +++ b/src/main/example/Windows/conf/snmpconfig-proxy.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2011 - tcp:0.0.0.0/2012 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2011 + tcp:0.0.0.0/2012 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Windows/conf/snmpconfig.xml b/src/main/example/Windows/conf/snmpconfig.xml index 914036e45..ceca3690f 100644 --- a/src/main/example/Windows/conf/snmpconfig.xml +++ b/src/main/example/Windows/conf/snmpconfig.xml @@ -1,98 +1,98 @@ - - - udp:0.0.0.0/2001 - tcp:0.0.0.0/2002 - 4 - False - True - 5 - - - - notificationV2c - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - True -
- - notificationV3 - UdpIpv4 -
127.0.0.1/162
- 200 - 1 - False -
-
- - - SHADES - SHA - SHADESAuthPassword - PDES - SHADESPrivPassword - - - TEST - SHA - maplesyrup - PDES - maplesyrup - - - SHA - SHA - SHAAuthPassword - - - MD5DES - MD5 - MD5DESAuthPassword - PDES - MD5DESPrivPassword - - - SHAAES128 - SHA - SHAAES128AuthPassword - PAES128 - SHAAES128PrivPassword - - - SHAAES192 - SHA - SHAAES192AuthPassword - PAES192 - SHAAES192PrivPassword - - - SHAAES256 - SHA - SHAAES256AuthPassword - PAES256 - SHAAES256PrivPassword - - - MD5AES128 - MD5 - MD5AES128AuthPassword - PAES128 - MD5AES128PrivPassword - - - MD5AES192 - MD5 - MD5AES192AuthPassword - PAES192 - MD5AES192PrivPassword - - - MD5AES256 - MD5 - MD5AES256AuthPassword - PAES256 - MD5AES256PrivPassword - - + + + udp:0.0.0.0/2001 + tcp:0.0.0.0/2002 + 4 + False + True + 5 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + +
\ No newline at end of file diff --git a/src/main/example/Windows/service/readme.txt b/src/main/example/Windows/service/readme.txt index 3a4d3bd10..20d7c729a 100644 --- a/src/main/example/Windows/service/readme.txt +++ b/src/main/example/Windows/service/readme.txt @@ -1,6 +1,6 @@ - -Install prunmgr.exe and prunsrv.exe in the sub directory windows to be able to run Waarp R66 as a service under Windows. -Fix the service.bat file to fit your installation. - -See: + +Install prunmgr.exe and prunsrv.exe in the sub directory windows to be able to run Waarp R66 as a service under Windows. +Fix the service.bat file to fit your installation. + +See: http://commons.apache.org/proper/commons-daemon/binaries.html \ No newline at end of file diff --git a/src/main/example/Windows/service/service.bat b/src/main/example/Windows/service/service.bat index 2f1d2b0da..d2e2104f5 100644 --- a/src/main/example/Windows/service/service.bat +++ b/src/main/example/Windows/service/service.bat @@ -1,143 +1,143 @@ -@echo off - -rem -- DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) - -rem -- INSTALL prunmgr.exe and prunsrv.exe from Daemon Apache project in the directory windows under EXEC_PATH - -rem -- Organization: -rem -- EXEC_PATH is root (pid will be there) -rem -- EXEC_PATH\..\logs\ will be the log place -rem -- EXEC_PATH\windows\ is where prunsrv.exe is placed -rem -- DAEMON_ROOT is where all you jars are (even commons-daemon) -rem -- DAEMON_NAME will be the service name -rem -- SERVICE_DESCRIPTION will be the service description -rem -- MAIN_DAEMON_CLASS will be the start/stop class used - -rem inspired from: http://algorithmique.net/Dev/2011/04/11/crer-un-dmon-ou-un-service-pour-uix-et-windows-en-java-avec-commons-deamon.html -rem and http://tanakanbb.blogspot.fr/2012/04/commons-daemon-2.html -rem and http://commons.apache.org/daemon/procrun.html and associated wiki - -rem -- Root path where the executables are -set EXEC_PATH=J:\GG\R66\bin - -rem -- Change this by the path where all jars are -set DAEMON_ROOT=J:\GG\R66\bin\AllJarsWaarpR66-2.4.11 - -rem -- Service description -set SERVICE_DESCRIPTION="Waarp R66 Server" - -rem -- Service name -set SERVICE_NAME=WaarpR66 - -rem -- Service CLASSPATH -set SERVICE_CLASSPATH=%DAEMON_ROOT%/lib/WaarpR66-2.4.11.jar;%DAEMON_ROOT%/lib/libthrift-0.8.0.jar;%DAEMON_ROOT%/lib/* - -rem -- Service main class -set MAIN_SERVICE_CLASS=org.waarp.openr66.service.R66ServiceLauncher - -rem -- Path for log files -set LOG_PATH=%EXEC_PATH%\..\log - -rem -- STDERR log file -set ERR_LOG_FILE=%LOG_PATH%\stderr.txt - -rem -- STDOUT log file: IMPORTANT SINCE LOG will be there -set OUT_LOG_FILE=%LOG_PATH%\stdout.txt - -rem -- Startup mode (manual or auto) -set SERVICE_STARTUP=auto -set SERVICE_STARTUP=manual - -rem -- JVM option (auto or full path to jvm.dll, if possible pointing to server version) -rem example: "C:\Program Files\Java\jdk1.7.0_05\jre\bin\server\jvm.dll" -rem set JVMMODE=--Jvm=auto -set JVMMODE=--Jvm=C:\Outils\Java\jdk1.7.0_05\jre\bin\server\jvm.dll - -rem -- Java memory options -set JAVAxMS=64m -set JAVAxMX=512m - -rem -- Logback configuration file -set LOGBACK_CONF=%EXEC_PATH%\..\conf\logback-service.xml - -rem -- prunsrv.exe location -set PRUNSRVEXEC=%EXEC_PATH%\windows\prunsrv.exe - -rem -- R66 configuration file -set R66_CONF=%EXEC_PATH%\..\conf\config-server.xml - -rem -- Loglevel of Daemon between debug, info, warn, error -set LOGLEVEL=info - -rem --------------------------------------------------------------------------- -rem -- Various Java options -set JAVA_OPTS=%JVMMODE% --JvmMs=%JAVAxMS% --JvmMx=%JAVAxMX% ++JvmOptions=-Dlogback.configurationFile=%LOGBACK_CONF% ++JvmOptions=-Dorg.waarp.r66.config.file=%R66_CONF% - -set SERVICE_OPTIONS=%JAVA_OPTS% --Description=%SERVICE_DESCRIPTION% --Classpath=%SERVICE_CLASSPATH% --StartMode=jvm --StartClass=%MAIN_SERVICE_CLASS% --StartMethod=windowsStart --StopMode=jvm --StopClass=%MAIN_SERVICE_CLASS% --StopMethod=windowsStop --LogPath=%LOG_PATH% --StdOutput=%OUT_LOG_FILE% --StdError=%ERR_LOG_FILE% --Startup=%SERVICE_STARTUP% --PidFile=service.pid --LogLevel=%LOGLEVEL% - -set RESTART=0 - -:GETOPTS -if /I "%1" == "start" ( goto START ) -if /I "%1" == "stop" ( goto STOP ) -if /I "%1" == "console" ( goto CONSOLE ) -if /I "%1" == "restart" ( goto RESTART ) -if /I "%1" == "install" ( goto INSTALL ) -if /I "%1" == "remove" ( goto REMOVE ) - -goto HELP - -rem -- START ------------------------------------------------------------------ -:START - -echo Start service %SERVICE_NAME% -%PRUNSRVEXEC% //RS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- INSTALL ---------------------------------------------------------------- -:INSTALL - -echo Install service %SERVICE_NAME% -%PRUNSRVEXEC% //IS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- STOP ------------------------------------------------------------------- -:STOP - -echo Stop service %SERVICE_NAME% -%PRUNSRVEXEC% //SS/%SERVICE_NAME% %SERVICE_OPTIONS% - -if "%RESTART%" == "1" ( goto START ) -goto FIN - -rem -- REMOVE ----------------------------------------------------------------- -:REMOVE - -echo Remove service %SERVICE_NAME% -%PRUNSRVEXEC% //DS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- CONSOLE ---------------------------------------------------------------- -:CONSOLE - -%PRUNSRVEXEC% //TS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- RESTART ---------------------------------------------------------------- -:RESTART - -set RESTART=1 - -goto STOP - -rem -- HELP ------------------------------------------------------------------- -:HELP - -echo "service.bat install|remove|start|stop|restart" -goto FIN - -:FIN +@echo off + +rem -- DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) + +rem -- INSTALL prunmgr.exe and prunsrv.exe from Daemon Apache project in the directory windows under EXEC_PATH + +rem -- Organization: +rem -- EXEC_PATH is root (pid will be there) +rem -- EXEC_PATH\..\logs\ will be the log place +rem -- EXEC_PATH\windows\ is where prunsrv.exe is placed +rem -- DAEMON_ROOT is where all you jars are (even commons-daemon) +rem -- DAEMON_NAME will be the service name +rem -- SERVICE_DESCRIPTION will be the service description +rem -- MAIN_DAEMON_CLASS will be the start/stop class used + +rem inspired from: http://algorithmique.net/Dev/2011/04/11/crer-un-dmon-ou-un-service-pour-uix-et-windows-en-java-avec-commons-deamon.html +rem and http://tanakanbb.blogspot.fr/2012/04/commons-daemon-2.html +rem and http://commons.apache.org/daemon/procrun.html and associated wiki + +rem -- Root path where the executables are +set EXEC_PATH=J:\GG\R66\bin + +rem -- Change this by the path where all jars are +set DAEMON_ROOT=J:\GG\R66\bin\AllJarsWaarpR66-2.4.11 + +rem -- Service description +set SERVICE_DESCRIPTION="Waarp R66 Server" + +rem -- Service name +set SERVICE_NAME=WaarpR66 + +rem -- Service CLASSPATH +set SERVICE_CLASSPATH=%DAEMON_ROOT%/lib/WaarpR66-2.4.11.jar;%DAEMON_ROOT%/lib/libthrift-0.8.0.jar;%DAEMON_ROOT%/lib/* + +rem -- Service main class +set MAIN_SERVICE_CLASS=org.waarp.openr66.service.R66ServiceLauncher + +rem -- Path for log files +set LOG_PATH=%EXEC_PATH%\..\log + +rem -- STDERR log file +set ERR_LOG_FILE=%LOG_PATH%\stderr.txt + +rem -- STDOUT log file: IMPORTANT SINCE LOG will be there +set OUT_LOG_FILE=%LOG_PATH%\stdout.txt + +rem -- Startup mode (manual or auto) +set SERVICE_STARTUP=auto +set SERVICE_STARTUP=manual + +rem -- JVM option (auto or full path to jvm.dll, if possible pointing to server version) +rem example: "C:\Program Files\Java\jdk1.7.0_05\jre\bin\server\jvm.dll" +rem set JVMMODE=--Jvm=auto +set JVMMODE=--Jvm=C:\Outils\Java\jdk1.7.0_05\jre\bin\server\jvm.dll + +rem -- Java memory options +set JAVAxMS=64m +set JAVAxMX=512m + +rem -- Logback configuration file +set LOGBACK_CONF=%EXEC_PATH%\..\conf\logback-service.xml + +rem -- prunsrv.exe location +set PRUNSRVEXEC=%EXEC_PATH%\windows\prunsrv.exe + +rem -- R66 configuration file +set R66_CONF=%EXEC_PATH%\..\conf\config-server.xml + +rem -- Loglevel of Daemon between debug, info, warn, error +set LOGLEVEL=info + +rem --------------------------------------------------------------------------- +rem -- Various Java options +set JAVA_OPTS=%JVMMODE% --JvmMs=%JAVAxMS% --JvmMx=%JAVAxMX% ++JvmOptions=-Dlogback.configurationFile=%LOGBACK_CONF% ++JvmOptions=-Dorg.waarp.r66.config.file=%R66_CONF% + +set SERVICE_OPTIONS=%JAVA_OPTS% --Description=%SERVICE_DESCRIPTION% --Classpath=%SERVICE_CLASSPATH% --StartMode=jvm --StartClass=%MAIN_SERVICE_CLASS% --StartMethod=windowsStart --StopMode=jvm --StopClass=%MAIN_SERVICE_CLASS% --StopMethod=windowsStop --LogPath=%LOG_PATH% --StdOutput=%OUT_LOG_FILE% --StdError=%ERR_LOG_FILE% --Startup=%SERVICE_STARTUP% --PidFile=service.pid --LogLevel=%LOGLEVEL% + +set RESTART=0 + +:GETOPTS +if /I "%1" == "start" ( goto START ) +if /I "%1" == "stop" ( goto STOP ) +if /I "%1" == "console" ( goto CONSOLE ) +if /I "%1" == "restart" ( goto RESTART ) +if /I "%1" == "install" ( goto INSTALL ) +if /I "%1" == "remove" ( goto REMOVE ) + +goto HELP + +rem -- START ------------------------------------------------------------------ +:START + +echo Start service %SERVICE_NAME% +%PRUNSRVEXEC% //RS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- INSTALL ---------------------------------------------------------------- +:INSTALL + +echo Install service %SERVICE_NAME% +%PRUNSRVEXEC% //IS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- STOP ------------------------------------------------------------------- +:STOP + +echo Stop service %SERVICE_NAME% +%PRUNSRVEXEC% //SS/%SERVICE_NAME% %SERVICE_OPTIONS% + +if "%RESTART%" == "1" ( goto START ) +goto FIN + +rem -- REMOVE ----------------------------------------------------------------- +:REMOVE + +echo Remove service %SERVICE_NAME% +%PRUNSRVEXEC% //DS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- CONSOLE ---------------------------------------------------------------- +:CONSOLE + +%PRUNSRVEXEC% //TS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- RESTART ---------------------------------------------------------------- +:RESTART + +set RESTART=1 + +goto STOP + +rem -- HELP ------------------------------------------------------------------- +:HELP + +echo "service.bat install|remove|start|stop|restart" +goto FIN + +:FIN diff --git a/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java b/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java index a754298eb..3c0156417 100644 --- a/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java +++ b/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java @@ -1,224 +1,224 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Abstract class for internal Business Request - * - * @author Frederic Bregier - * - */ -public abstract class AbstractBusinessRequest implements Runnable { - /** - * Internal Logger - */ - static protected volatile WaarpInternalLogger logger; - - public static final String BUSINESSREQUEST = "BusinessRequest"; - - protected final R66Future future; - - protected final String remoteHost; - - protected final NetworkTransaction networkTransaction; - - private final BusinessRequestPacket businessPacket; - - private LocalChannelReference localChannelReference; - - public AbstractBusinessRequest(Class clasz, - R66Future future, - String remoteHost, - NetworkTransaction networkTransaction, - BusinessRequestPacket packet) { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(clasz); - } - this.future = future; - this.remoteHost = remoteHost; - this.networkTransaction = networkTransaction; - this.businessPacket = packet; - } - - public void run() { - try { - initRequest(); - sendRequest(); - } catch (OpenR66ProtocolNoConnectionException e) { - } - } - - public void initRequest() throws OpenR66ProtocolNoConnectionException { - DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, - remoteHost); - final SocketAddress socketServerAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - localChannelReference = networkTransaction - .createConnectionWithRetry(socketServerAddress, isSSL, future); - if (localChannelReference == null) { - future.setResult(null); - OpenR66ProtocolNoConnectionException e = - new OpenR66ProtocolNoConnectionException( - "Cannot connect to server " + host.toString()); - future.setFailure(e); - throw e; - } - localChannelReference.sessionNewState(R66FiniteDualStates.BUSINESSR); - } - - public void sendRequest() { - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, businessPacket, false); - } catch (OpenR66ProtocolPacketException e) { - future.setResult(null); - future.setFailure(e); - Channels.close(localChannelReference.getLocalChannel()); - return; - } - - } - - /** - * Dummy Main method - * - * @param args - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(AbstractBusinessRequest.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(2); - } - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - R66Future future = new R66Future(true); - - logger.info("Start Test of Transaction"); - long time1 = System.currentTimeMillis(); - - @SuppressWarnings("unused") - BusinessRequestPacket packet = - new BusinessRequestPacket(classname + " " + classarg, 0); - // XXX FIXME this has to be adapted - /* - * AbstractBusinessRequest transaction = new AbstractBusinessRequest( - * AbstractBusinessRequest.class, future, rhost, networkTransaction, packet); - * transaction.run(); future.awaitUninterruptibly(); - */ - long time2 = System.currentTimeMillis(); - logger.debug("Finish Business Request: " + future.isSuccess()); - long delay = time2 - time1; - if (future.isSuccess()) { - logger.info("Business Request in status:\nSUCCESS" + - "\n " + rhost + "" + - "\n delay: " + delay); - } else { - logger.info("Business Request in status:\nFAILURE" + - "\n " + rhost + "" + - "\n " + future.getCause() + "" + - "\n delay: " + delay); - networkTransaction.closeAll(); - System.exit(ErrorCode.Unknown.ordinal()); - } - networkTransaction.closeAll(); - } - - static protected String rhost = null; - static protected String classname = null; - static protected String classarg = null; - static protected boolean nolog = false; - - /** - * Parse the parameter and set current values - * - * @param args - * @return True if all parameters were found and correct - */ - protected static boolean getParams(String[] args) { - if (args.length < 5) { - logger - .error("Needs at least 3 or 4 arguments:\n" + - " the XML client configuration file,\n" + - " '-to' the remoteHost Id,\n" + - " '-class' the Business full class name,\n" + - " '-arg' the argument to pass (optional)\n" + - "Other options:\n" + - " '-nolog' to not log locally this action\n"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - // Now set default values from configuration - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-to")) { - i++; - rhost = args[i]; - } else if (args[i].equalsIgnoreCase("-class")) { - i++; - classname = args[i]; - } else if (args[i].equalsIgnoreCase("-arg")) { - i++; - classarg = args[i]; - } else if (args[i].equalsIgnoreCase("-nolog")) { - nolog = true; - i++; - } - } - if (rhost != null && classname != null) { - return true; - } - logger.error("All params are not set! Need at least (-to -class)"); - return false; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Abstract class for internal Business Request + * + * @author Frederic Bregier + * + */ +public abstract class AbstractBusinessRequest implements Runnable { + /** + * Internal Logger + */ + static protected volatile WaarpInternalLogger logger; + + public static final String BUSINESSREQUEST = "BusinessRequest"; + + protected final R66Future future; + + protected final String remoteHost; + + protected final NetworkTransaction networkTransaction; + + private final BusinessRequestPacket businessPacket; + + private LocalChannelReference localChannelReference; + + public AbstractBusinessRequest(Class clasz, + R66Future future, + String remoteHost, + NetworkTransaction networkTransaction, + BusinessRequestPacket packet) { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(clasz); + } + this.future = future; + this.remoteHost = remoteHost; + this.networkTransaction = networkTransaction; + this.businessPacket = packet; + } + + public void run() { + try { + initRequest(); + sendRequest(); + } catch (OpenR66ProtocolNoConnectionException e) { + } + } + + public void initRequest() throws OpenR66ProtocolNoConnectionException { + DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, + remoteHost); + final SocketAddress socketServerAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + localChannelReference = networkTransaction + .createConnectionWithRetry(socketServerAddress, isSSL, future); + if (localChannelReference == null) { + future.setResult(null); + OpenR66ProtocolNoConnectionException e = + new OpenR66ProtocolNoConnectionException( + "Cannot connect to server " + host.toString()); + future.setFailure(e); + throw e; + } + localChannelReference.sessionNewState(R66FiniteDualStates.BUSINESSR); + } + + public void sendRequest() { + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, businessPacket, false); + } catch (OpenR66ProtocolPacketException e) { + future.setResult(null); + future.setFailure(e); + Channels.close(localChannelReference.getLocalChannel()); + return; + } + + } + + /** + * Dummy Main method + * + * @param args + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(AbstractBusinessRequest.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(2); + } + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + R66Future future = new R66Future(true); + + logger.info("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + + @SuppressWarnings("unused") + BusinessRequestPacket packet = + new BusinessRequestPacket(classname + " " + classarg, 0); + // XXX FIXME this has to be adapted + /* + * AbstractBusinessRequest transaction = new AbstractBusinessRequest( + * AbstractBusinessRequest.class, future, rhost, networkTransaction, packet); + * transaction.run(); future.awaitUninterruptibly(); + */ + long time2 = System.currentTimeMillis(); + logger.debug("Finish Business Request: " + future.isSuccess()); + long delay = time2 - time1; + if (future.isSuccess()) { + logger.info("Business Request in status:\nSUCCESS" + + "\n " + rhost + "" + + "\n delay: " + delay); + } else { + logger.info("Business Request in status:\nFAILURE" + + "\n " + rhost + "" + + "\n " + future.getCause() + "" + + "\n delay: " + delay); + networkTransaction.closeAll(); + System.exit(ErrorCode.Unknown.ordinal()); + } + networkTransaction.closeAll(); + } + + static protected String rhost = null; + static protected String classname = null; + static protected String classarg = null; + static protected boolean nolog = false; + + /** + * Parse the parameter and set current values + * + * @param args + * @return True if all parameters were found and correct + */ + protected static boolean getParams(String[] args) { + if (args.length < 5) { + logger + .error("Needs at least 3 or 4 arguments:\n" + + " the XML client configuration file,\n" + + " '-to' the remoteHost Id,\n" + + " '-class' the Business full class name,\n" + + " '-arg' the argument to pass (optional)\n" + + "Other options:\n" + + " '-nolog' to not log locally this action\n"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + // Now set default values from configuration + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-to")) { + i++; + rhost = args[i]; + } else if (args[i].equalsIgnoreCase("-class")) { + i++; + classname = args[i]; + } else if (args[i].equalsIgnoreCase("-arg")) { + i++; + classarg = args[i]; + } else if (args[i].equalsIgnoreCase("-nolog")) { + nolog = true; + i++; + } + } + if (rhost != null && classname != null) { + return true; + } + logger.error("All params are not set! Need at least (-to -class)"); + return false; + } + +} diff --git a/src/main/java/org/waarp/openr66/client/AbstractTransfer.java b/src/main/java/org/waarp/openr66/client/AbstractTransfer.java index 665cfc8fb..c0240f30e 100644 --- a/src/main/java/org/waarp/openr66/client/AbstractTransfer.java +++ b/src/main/java/org/waarp/openr66/client/AbstractTransfer.java @@ -1,321 +1,321 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.io.File; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Abstract class for Transfer operation - * - * @author Frederic Bregier - * - */ -public abstract class AbstractTransfer implements Runnable { - /** - * Internal Logger - */ - static protected volatile WaarpInternalLogger logger; - - protected static final String NOINFO = "noinfo"; - - protected final R66Future future; - - protected final String filename; - - protected final String rulename; - - protected final String fileinfo; - - protected final boolean isMD5; - - protected final String remoteHost; - - protected final int blocksize; - - protected final long id; - - protected final Timestamp startTime; - - /** - * @param clasz - * Class of Client Transfer - * @param future - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param remoteHost - * @param blocksize - * @param id - */ - public AbstractTransfer(Class clasz, R66Future future, String filename, - String rulename, String fileinfo, - boolean isMD5, String remoteHost, int blocksize, long id, Timestamp timestart) { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(clasz); - } - this.future = future; - this.filename = filename; - this.rulename = rulename; - this.fileinfo = fileinfo; - this.isMD5 = isMD5; - if (Configuration.configuration.aliases.containsKey(remoteHost)) { - this.remoteHost = Configuration.configuration.aliases.get(remoteHost); - } else { - this.remoteHost = remoteHost; - } - this.blocksize = blocksize; - this.id = id; - this.startTime = timestart; - } - - /** - * Initiate the Request and return a potential DbTaskRunner - * - * @return null if an error occurs or a DbTaskRunner - */ - protected DbTaskRunner initRequest() { - DbRule rule; - try { - rule = new DbRule(DbConstant.admin.session, rulename); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Rule: " + rulename, e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return null; - } - int mode = rule.mode; - if (isMD5) { - mode = RequestPacket.getModeMD5(mode); - } - DbTaskRunner taskRunner = null; - if (id != DbConstant.ILLEGALVALUE) { - try { - taskRunner = new DbTaskRunner(DbConstant.admin.session, id, - remoteHost); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get task", e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.QueryRemotelyUnknown, null)); - future.setFailure(e); - return null; - } - // requested - taskRunner.setSenderByRequestToValidate(true); - if (fileinfo != null && !fileinfo.equals(NOINFO)) { - taskRunner.setFileInformation(fileinfo); - } - if (startTime != null) { - taskRunner.setStart(startTime); - } - } else { - long originalSize = -1; - if (RequestPacket.isSendMode(mode) && ! RequestPacket.isThroughMode(mode)) { - File file = new File(filename); - if (file.canRead()) { - originalSize = file.length(); - } - } - RequestPacket request = new RequestPacket(rulename, - mode, filename, blocksize, 0, - id, fileinfo, originalSize); - // Not isRecv since it is the requester, so send => isRetrieve is true - boolean isRetrieve = !RequestPacket.isRecvMode(request.getMode()); - try { - taskRunner = - new DbTaskRunner(DbConstant.admin.session, rule, isRetrieve, request, - remoteHost, startTime); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get task", e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return null; - } - } - return taskRunner; - } - - static protected String rhost = null; - static protected String localFilename = null; - static protected String rule = null; - static protected String fileInfo = null; - static protected boolean ismd5 = false; - static protected int block = 0x10000; // 64K - // as - // default - static protected boolean nolog = false; - static protected long idt = DbConstant.ILLEGALVALUE; - static protected Timestamp ttimestart = null; - static protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - - /** - * Parse the parameter and set current values - * - * @param args - * @param submitOnly - * True if the client is only a submitter (through database) - * @return True if all parameters were found and correct - */ - protected static boolean getParams(String[] args, boolean submitOnly) { - if (args.length < 2) { - logger - .error("Needs at least 3 or 4 arguments:\n" - + - " the XML client configuration file,\n" - + - " '-to' the remoteHost Id,\n" - + - " '-file' the file to transfer,\n" - + - " '-rule' the rule\n" - + - "Or\n" - + - " '-to' the remoteHost Id,\n" - + - " '-id' \"Id of a previous transfer\",\n" - + - "Other options:\n" - + - " '-info' \"information to send\",\n" - + - " '-md5' to force MD5 by packet control,\n" - + - " '-block' size of packet > 1K (prefered is 64K),\n" - + - " '-nolog' to not log locally this action\n" - + - " '-start' \"time start\" as yyyyMMddHHmmss (override previous -delay options)\n" - + - " '-delay' \"+delay in ms\" as delay in ms from current time(override previous -start options)\n" - + - " '-delay' \"delay in ms\" as time in ms (override previous -start options)"); - return false; - } - if (submitOnly) { - if (!FileBasedConfiguration - .setSubmitClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - } else if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - // Now set default values from configuration - block = Configuration.configuration.BLOCKSIZE; - int i = 1; - try { - for (i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-to")) { - i++; - rhost = args[i]; - } else if (args[i].equalsIgnoreCase("-file")) { - i++; - localFilename = args[i]; - } else if (args[i].equalsIgnoreCase("-rule")) { - i++; - rule = args[i]; - } else if (args[i].equalsIgnoreCase("-info")) { - i++; - fileInfo = args[i]; - } else if (args[i].equalsIgnoreCase("-md5")) { - ismd5 = true; - } else if (args[i].equalsIgnoreCase("-block")) { - i++; - block = Integer.parseInt(args[i]); - if (block < 100) { - logger.error("Block size is too small: " + block); - return false; - } - } else if (args[i].equalsIgnoreCase("-nolog")) { - nolog = true; - i++; - } else if (args[i].equalsIgnoreCase("-id")) { - i++; - idt = Long.parseLong(args[i]); - } else if (args[i].equalsIgnoreCase("-start")) { - i++; - Date date; - try { - date = dateFormat.parse(args[i]); - ttimestart = new Timestamp(date.getTime()); - } catch (ParseException e) { - } - } else if (args[i].equalsIgnoreCase("-delay")) { - i++; - if (args[i].charAt(0) == '+') { - ttimestart = new Timestamp(System.currentTimeMillis() + - Long.parseLong(args[i].substring(1))); - } else { - ttimestart = new Timestamp(Long.parseLong(args[i])); - } - } - } - } catch (NumberFormatException e) { - logger.error("Number Format exception at Rank "+i); - return false; - } - if (fileInfo == null) { - fileInfo = NOINFO; - } - if (rhost != null && rule != null && localFilename != null) { - return true; - } else if (idt != DbConstant.ILLEGALVALUE && rhost != null) { - try { - DbTaskRunner runner = new DbTaskRunner(DbConstant.admin.session, idt, - rhost); - rule = runner.getRuleId(); - localFilename = runner.getOriginalFilename(); - return true; - } catch (WaarpDatabaseException e) { - logger.error( - "All params are not correctly set! Need at least (-to -rule and -file)" + - " or (-to and -id) params", e); - return false; - } - - } - logger.error("All params are not set! Need at least (-to -rule and -file)" + - " or (-to and -id) params"); - return false; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.io.File; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Abstract class for Transfer operation + * + * @author Frederic Bregier + * + */ +public abstract class AbstractTransfer implements Runnable { + /** + * Internal Logger + */ + static protected volatile WaarpInternalLogger logger; + + protected static final String NOINFO = "noinfo"; + + protected final R66Future future; + + protected final String filename; + + protected final String rulename; + + protected final String fileinfo; + + protected final boolean isMD5; + + protected final String remoteHost; + + protected final int blocksize; + + protected final long id; + + protected final Timestamp startTime; + + /** + * @param clasz + * Class of Client Transfer + * @param future + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param remoteHost + * @param blocksize + * @param id + */ + public AbstractTransfer(Class clasz, R66Future future, String filename, + String rulename, String fileinfo, + boolean isMD5, String remoteHost, int blocksize, long id, Timestamp timestart) { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(clasz); + } + this.future = future; + this.filename = filename; + this.rulename = rulename; + this.fileinfo = fileinfo; + this.isMD5 = isMD5; + if (Configuration.configuration.aliases.containsKey(remoteHost)) { + this.remoteHost = Configuration.configuration.aliases.get(remoteHost); + } else { + this.remoteHost = remoteHost; + } + this.blocksize = blocksize; + this.id = id; + this.startTime = timestart; + } + + /** + * Initiate the Request and return a potential DbTaskRunner + * + * @return null if an error occurs or a DbTaskRunner + */ + protected DbTaskRunner initRequest() { + DbRule rule; + try { + rule = new DbRule(DbConstant.admin.session, rulename); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Rule: " + rulename, e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return null; + } + int mode = rule.mode; + if (isMD5) { + mode = RequestPacket.getModeMD5(mode); + } + DbTaskRunner taskRunner = null; + if (id != DbConstant.ILLEGALVALUE) { + try { + taskRunner = new DbTaskRunner(DbConstant.admin.session, id, + remoteHost); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get task", e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.QueryRemotelyUnknown, null)); + future.setFailure(e); + return null; + } + // requested + taskRunner.setSenderByRequestToValidate(true); + if (fileinfo != null && !fileinfo.equals(NOINFO)) { + taskRunner.setFileInformation(fileinfo); + } + if (startTime != null) { + taskRunner.setStart(startTime); + } + } else { + long originalSize = -1; + if (RequestPacket.isSendMode(mode) && ! RequestPacket.isThroughMode(mode)) { + File file = new File(filename); + if (file.canRead()) { + originalSize = file.length(); + } + } + RequestPacket request = new RequestPacket(rulename, + mode, filename, blocksize, 0, + id, fileinfo, originalSize); + // Not isRecv since it is the requester, so send => isRetrieve is true + boolean isRetrieve = !RequestPacket.isRecvMode(request.getMode()); + try { + taskRunner = + new DbTaskRunner(DbConstant.admin.session, rule, isRetrieve, request, + remoteHost, startTime); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get task", e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return null; + } + } + return taskRunner; + } + + static protected String rhost = null; + static protected String localFilename = null; + static protected String rule = null; + static protected String fileInfo = null; + static protected boolean ismd5 = false; + static protected int block = 0x10000; // 64K + // as + // default + static protected boolean nolog = false; + static protected long idt = DbConstant.ILLEGALVALUE; + static protected Timestamp ttimestart = null; + static protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + + /** + * Parse the parameter and set current values + * + * @param args + * @param submitOnly + * True if the client is only a submitter (through database) + * @return True if all parameters were found and correct + */ + protected static boolean getParams(String[] args, boolean submitOnly) { + if (args.length < 2) { + logger + .error("Needs at least 3 or 4 arguments:\n" + + + " the XML client configuration file,\n" + + + " '-to' the remoteHost Id,\n" + + + " '-file' the file to transfer,\n" + + + " '-rule' the rule\n" + + + "Or\n" + + + " '-to' the remoteHost Id,\n" + + + " '-id' \"Id of a previous transfer\",\n" + + + "Other options:\n" + + + " '-info' \"information to send\",\n" + + + " '-md5' to force MD5 by packet control,\n" + + + " '-block' size of packet > 1K (prefered is 64K),\n" + + + " '-nolog' to not log locally this action\n" + + + " '-start' \"time start\" as yyyyMMddHHmmss (override previous -delay options)\n" + + + " '-delay' \"+delay in ms\" as delay in ms from current time(override previous -start options)\n" + + + " '-delay' \"delay in ms\" as time in ms (override previous -start options)"); + return false; + } + if (submitOnly) { + if (!FileBasedConfiguration + .setSubmitClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + } else if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + // Now set default values from configuration + block = Configuration.configuration.BLOCKSIZE; + int i = 1; + try { + for (i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-to")) { + i++; + rhost = args[i]; + } else if (args[i].equalsIgnoreCase("-file")) { + i++; + localFilename = args[i]; + } else if (args[i].equalsIgnoreCase("-rule")) { + i++; + rule = args[i]; + } else if (args[i].equalsIgnoreCase("-info")) { + i++; + fileInfo = args[i]; + } else if (args[i].equalsIgnoreCase("-md5")) { + ismd5 = true; + } else if (args[i].equalsIgnoreCase("-block")) { + i++; + block = Integer.parseInt(args[i]); + if (block < 100) { + logger.error("Block size is too small: " + block); + return false; + } + } else if (args[i].equalsIgnoreCase("-nolog")) { + nolog = true; + i++; + } else if (args[i].equalsIgnoreCase("-id")) { + i++; + idt = Long.parseLong(args[i]); + } else if (args[i].equalsIgnoreCase("-start")) { + i++; + Date date; + try { + date = dateFormat.parse(args[i]); + ttimestart = new Timestamp(date.getTime()); + } catch (ParseException e) { + } + } else if (args[i].equalsIgnoreCase("-delay")) { + i++; + if (args[i].charAt(0) == '+') { + ttimestart = new Timestamp(System.currentTimeMillis() + + Long.parseLong(args[i].substring(1))); + } else { + ttimestart = new Timestamp(Long.parseLong(args[i])); + } + } + } + } catch (NumberFormatException e) { + logger.error("Number Format exception at Rank "+i); + return false; + } + if (fileInfo == null) { + fileInfo = NOINFO; + } + if (rhost != null && rule != null && localFilename != null) { + return true; + } else if (idt != DbConstant.ILLEGALVALUE && rhost != null) { + try { + DbTaskRunner runner = new DbTaskRunner(DbConstant.admin.session, idt, + rhost); + rule = runner.getRuleId(); + localFilename = runner.getOriginalFilename(); + return true; + } catch (WaarpDatabaseException e) { + logger.error( + "All params are not correctly set! Need at least (-to -rule and -file)" + + " or (-to and -id) params", e); + return false; + } + + } + logger.error("All params are not set! Need at least (-to -rule and -file)" + + " or (-to and -id) params"); + return false; + } +} diff --git a/src/main/java/org/waarp/openr66/client/DirectTransfer.java b/src/main/java/org/waarp/openr66/client/DirectTransfer.java index 21e77ca98..be1da06ee 100644 --- a/src/main/java/org/waarp/openr66/client/DirectTransfer.java +++ b/src/main/java/org/waarp/openr66/client/DirectTransfer.java @@ -1,220 +1,220 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Direct Transfer from a client with or without database connection - * - * @author Frederic Bregier - * - */ -public class DirectTransfer extends AbstractTransfer { - protected final NetworkTransaction networkTransaction; - - public DirectTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - long id, - NetworkTransaction networkTransaction) { - // no starttime since it is direct (blocking request, no delay) - super(DirectTransfer.class, - future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); - this.networkTransaction = networkTransaction; - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); - } - DbTaskRunner taskRunner = this.initRequest(); - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - runner.runTransfer(); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.debug("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.debug("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - // since no connection : just forget it - if (nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e1) { - } - } - future.setFailure(e); - return; - } catch (OpenR66ProtocolPacketException e) { - logger.debug("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - return; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.debug("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - // since no connection : just forget it - if (nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e1) { - } - } - future.setFailure(exc); - return; - } - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(2); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - DirectTransfer transaction = new DirectTransfer(future, - rhost, localFilename, rule, fileInfo, ismd5, block, idt, - networkTransaction); - logger.warn("rhost: "+rhost+":"+transaction.remoteHost); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - logger.debug("finish transfer: " + future.isSuccess()); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in status:\nWARNED\n " - + result.runner.toShortString() - + - "\n " - + rhost - + "" - + - "\n " - + - (result.file != null ? result.file.toString() + "" - : "no file") - + "\n delay: " + delay); - } else { - logger.info("Transfer in status:\nSUCCESS\n " - + result.runner.toShortString() - + - "\n " - + rhost - + "" - + - "\n " - + - (result.file != null ? result.file.toString() + "" - : "no file") - + "\n delay: " + delay); - } - if (nolog) { - // In case of success, delete the runner - try { - result.runner.delete(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot apply nolog to\n " + result.runner.toShortString(), - e); - } - } - } else { - if (result == null || result.runner == null) { - logger.error("Transfer in\n FAILURE with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(ErrorCode.Unknown.ordinal()); - } - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer is\n WARNED\n " + result.runner.toShortString() + - "\n " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in\n FAILURE\n " + result.runner.toShortString() + - "\n " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } catch (Exception e) { - logger.debug("exc", e); - } finally { - logger.debug("finish transfer: " + future.isDone() + ":" + future.isSuccess()); - networkTransaction.closeAll(); - // In case something wrong append - if (future.isDone() && future.isSuccess()) { - System.exit(0); - } else { - System.exit(66); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Direct Transfer from a client with or without database connection + * + * @author Frederic Bregier + * + */ +public class DirectTransfer extends AbstractTransfer { + protected final NetworkTransaction networkTransaction; + + public DirectTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, + long id, + NetworkTransaction networkTransaction) { + // no starttime since it is direct (blocking request, no delay) + super(DirectTransfer.class, + future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); + this.networkTransaction = networkTransaction; + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); + } + DbTaskRunner taskRunner = this.initRequest(); + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + runner.runTransfer(); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.debug("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.debug("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + // since no connection : just forget it + if (nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e1) { + } + } + future.setFailure(e); + return; + } catch (OpenR66ProtocolPacketException e) { + logger.debug("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + return; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; + } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.debug("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + // since no connection : just forget it + if (nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e1) { + } + } + future.setFailure(exc); + return; + } + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(2); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + DirectTransfer transaction = new DirectTransfer(future, + rhost, localFilename, rule, fileInfo, ismd5, block, idt, + networkTransaction); + logger.warn("rhost: "+rhost+":"+transaction.remoteHost); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + logger.debug("finish transfer: " + future.isSuccess()); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in status:\nWARNED\n " + + result.runner.toShortString() + + + "\n " + + rhost + + "" + + + "\n " + + + (result.file != null ? result.file.toString() + "" + : "no file") + + "\n delay: " + delay); + } else { + logger.info("Transfer in status:\nSUCCESS\n " + + result.runner.toShortString() + + + "\n " + + rhost + + "" + + + "\n " + + + (result.file != null ? result.file.toString() + "" + : "no file") + + "\n delay: " + delay); + } + if (nolog) { + // In case of success, delete the runner + try { + result.runner.delete(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot apply nolog to\n " + result.runner.toShortString(), + e); + } + } + } else { + if (result == null || result.runner == null) { + logger.error("Transfer in\n FAILURE with no Id", future.getCause()); + networkTransaction.closeAll(); + System.exit(ErrorCode.Unknown.ordinal()); + } + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer is\n WARNED\n " + result.runner.toShortString() + + "\n " + rhost + "", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in\n FAILURE\n " + result.runner.toShortString() + + "\n " + rhost + "", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } catch (Exception e) { + logger.debug("exc", e); + } finally { + logger.debug("finish transfer: " + future.isDone() + ":" + future.isSuccess()); + networkTransaction.closeAll(); + // In case something wrong append + if (future.isDone() && future.isSuccess()) { + System.exit(0); + } else { + System.exit(66); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/client/Message.java b/src/main/java/org/waarp/openr66/client/Message.java index c4a21dd17..6da9a9b08 100644 --- a/src/main/java/org/waarp/openr66/client/Message.java +++ b/src/main/java/org/waarp/openr66/client/Message.java @@ -1,234 +1,234 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.TestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Message testing between two hosts - * - * @author Frederic Bregier - * - */ -public class Message implements Runnable { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger; - - final private NetworkTransaction networkTransaction; - - final private R66Future future; - - private final String requested; - - private final DbHostAuth hostAuth; - - final private TestPacket testPacket; - - static String srequested = null; - static String smessage = "MESSAGE"; - - /** - * Parse the parameter and set current values - * - * @param args - * @return True if all parameters were found and correct - */ - protected static boolean getParams(String[] args) { - if (args.length < 5) { - logger - .error("Needs 5 arguments:\n" + - " the XML client configuration file,\n" + - " '-to' the remoteHost Id,\n" + - " '-msg' the message\n"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-to")) { - i++; - srequested = args[i]; - } else if (args[i].equalsIgnoreCase("-msg")) { - i++; - smessage = args[i]; - } - } - if (srequested == null) { - logger.error("Requested HostId must be set"); - return false; - } - return true; - } - - public Message(NetworkTransaction networkTransaction, - R66Future future, String requested, TestPacket packet) { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(Message.class); - } - this.networkTransaction = networkTransaction; - this.future = future; - this.requested = requested; - testPacket = packet; - this.hostAuth = null; - } - - public Message(NetworkTransaction networkTransaction, - R66Future future, DbHostAuth hostAuth, TestPacket packet) { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(Message.class); - } - this.networkTransaction = networkTransaction; - this.future = future; - this.requested = null; - testPacket = packet; - this.hostAuth = hostAuth; - } - - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger( - Message.class); - } - // Connection - DbHostAuth host = null; - if (hostAuth == null) { - host = R66Auth.getServerAuth(DbConstant.admin.session, - requested); - } else { - host = hostAuth; - } - if (host == null) { - logger.debug("Requested host cannot be found: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - if (host.isClient()) { - logger.error("Requested host is a client and cannot be requested: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - LocalChannelReference localChannelReference = null; - localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - logger.debug("Cannot connect to server: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.TEST); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, testPacket, false); - } catch (OpenR66ProtocolPacketException e) { - future.setResult(null); - future.setFailure(e); - Channels.close(localChannelReference.getLocalChannel()); - return; - } - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(Message.class); - } - if (args.length < 5) { - logger - .error("Needs 5 arguments:\n" + - " the XML client configuration file,\n" + - " '-to' the remoteHost Id,\n" + - " '-msg' the message\n"); - System.exit(1); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - } - NetworkTransaction networkTransaction = null; - int value = 3; - try { - Configuration.configuration.pipelineInit(); - networkTransaction = new NetworkTransaction(); - R66Future result = new R66Future(true); - TestPacket packet = new TestPacket("MSG", smessage, 100); - Message transaction = new Message( - networkTransaction, result, srequested, - packet); - transaction.run(); - result.awaitUninterruptibly(); - if (result.isSuccess()) { - value = 0; - R66Result r66result = result.getResult(); - ValidPacket info = (ValidPacket) r66result.other; - logger.warn("Test Message\n SUCCESS\n " + info.getSheader()); - } else { - value = 2; - logger.error("Test Message\n FAILURE\n " + - result.getResult().toString()); - } - } finally { - if (networkTransaction != null) { - networkTransaction.closeAll(); - } - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - System.exit(value); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.TestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Message testing between two hosts + * + * @author Frederic Bregier + * + */ +public class Message implements Runnable { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger; + + final private NetworkTransaction networkTransaction; + + final private R66Future future; + + private final String requested; + + private final DbHostAuth hostAuth; + + final private TestPacket testPacket; + + static String srequested = null; + static String smessage = "MESSAGE"; + + /** + * Parse the parameter and set current values + * + * @param args + * @return True if all parameters were found and correct + */ + protected static boolean getParams(String[] args) { + if (args.length < 5) { + logger + .error("Needs 5 arguments:\n" + + " the XML client configuration file,\n" + + " '-to' the remoteHost Id,\n" + + " '-msg' the message\n"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-to")) { + i++; + srequested = args[i]; + } else if (args[i].equalsIgnoreCase("-msg")) { + i++; + smessage = args[i]; + } + } + if (srequested == null) { + logger.error("Requested HostId must be set"); + return false; + } + return true; + } + + public Message(NetworkTransaction networkTransaction, + R66Future future, String requested, TestPacket packet) { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(Message.class); + } + this.networkTransaction = networkTransaction; + this.future = future; + this.requested = requested; + testPacket = packet; + this.hostAuth = null; + } + + public Message(NetworkTransaction networkTransaction, + R66Future future, DbHostAuth hostAuth, TestPacket packet) { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(Message.class); + } + this.networkTransaction = networkTransaction; + this.future = future; + this.requested = null; + testPacket = packet; + this.hostAuth = hostAuth; + } + + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger( + Message.class); + } + // Connection + DbHostAuth host = null; + if (hostAuth == null) { + host = R66Auth.getServerAuth(DbConstant.admin.session, + requested); + } else { + host = hostAuth; + } + if (host == null) { + logger.debug("Requested host cannot be found: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + if (host.isClient()) { + logger.error("Requested host is a client and cannot be requested: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + LocalChannelReference localChannelReference = null; + localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + logger.debug("Cannot connect to server: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.TEST); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, testPacket, false); + } catch (OpenR66ProtocolPacketException e) { + future.setResult(null); + future.setFailure(e); + Channels.close(localChannelReference.getLocalChannel()); + return; + } + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(Message.class); + } + if (args.length < 5) { + logger + .error("Needs 5 arguments:\n" + + " the XML client configuration file,\n" + + " '-to' the remoteHost Id,\n" + + " '-msg' the message\n"); + System.exit(1); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + } + NetworkTransaction networkTransaction = null; + int value = 3; + try { + Configuration.configuration.pipelineInit(); + networkTransaction = new NetworkTransaction(); + R66Future result = new R66Future(true); + TestPacket packet = new TestPacket("MSG", smessage, 100); + Message transaction = new Message( + networkTransaction, result, srequested, + packet); + transaction.run(); + result.awaitUninterruptibly(); + if (result.isSuccess()) { + value = 0; + R66Result r66result = result.getResult(); + ValidPacket info = (ValidPacket) r66result.other; + logger.warn("Test Message\n SUCCESS\n " + info.getSheader()); + } else { + value = 2; + logger.error("Test Message\n FAILURE\n " + + result.getResult().toString()); + } + } finally { + if (networkTransaction != null) { + networkTransaction.closeAll(); + } + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + System.exit(value); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/client/ProgressBarTransfer.java b/src/main/java/org/waarp/openr66/client/ProgressBarTransfer.java index 1b5c9a410..18b9b1b46 100644 --- a/src/main/java/org/waarp/openr66/client/ProgressBarTransfer.java +++ b/src/main/java/org/waarp/openr66/client/ProgressBarTransfer.java @@ -1,187 +1,187 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Through API Transfer from a client with or without database connection, and enabling access to - * statistic of the transfer (unblocking transfer) - * - * @author Frederic Bregier - * - */ -public abstract class ProgressBarTransfer extends AbstractTransfer { - protected final NetworkTransaction networkTransaction; - protected long INTERVALCALLBACK = 100; - protected long filesize = 0; - - public ProgressBarTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - long id, - NetworkTransaction networkTransaction, long callbackdelay) { - // no delay so starttime = null - super(ProgressBarTransfer.class, - future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); - this.networkTransaction = networkTransaction; - this.INTERVALCALLBACK = callbackdelay; - } - - /** - * This function will be called every 100ms (or other fixed value in INTERVALCALLBACK). Note - * that final rank is unknown. - * - * @param currentBlock - * the current block rank (from 0 to n-1) - * @param blocksize - * blocksize of 1 block - */ - abstract public void callBack(int currentBlock, int blocksize); - - /** - * This function will be called only once when the transfer is over - * - * @param success - * True if the transfer is successful - * @param currentBlock - * @param blocksize - */ - abstract public void lastCallBack(boolean success, int currentBlock, int blocksize); - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ProgressBarTransfer.class); - } - DbTaskRunner taskRunner = this.initRequest(); - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - LocalChannelReference localChannelReference = runner.initRequest(); - try { - localChannelReference.getFutureValidRequest().await(); - } catch (InterruptedException e) { - } - if ((!localChannelReference.getFutureValidRequest().isSuccess()) && - (localChannelReference.getFutureValidRequest().getResult().code == - ErrorCode.ServerOverloaded)) { - switch (taskRunner.getUpdatedInfo()) { - case DONE: - case INERROR: - case INTERRUPTED: - break; - default: - runner.changeUpdatedInfo(UpdatedInfo.INERROR, - ErrorCode.ServerOverloaded, true); - } - // redo if possible - if (runner.incrementTaskRunerTry(taskRunner, Configuration.RETRYNB)) { - try { - Thread.sleep(Configuration.configuration.constraintLimitHandler - .getSleepTime()); - } catch (InterruptedException e) { - } - i--; - continue; - } else { - throw new OpenR66ProtocolNotYetConnectionException( - "End of retry on ServerOverloaded"); - } - } - this.filesize = future.filesize; - while (!future.awaitUninterruptibly(INTERVALCALLBACK)) { - if (future.isDone()) { - break; - } - callBack(future.runner.getRank(), future.runner.getBlocksize()); - } - runner.finishTransfer(false, localChannelReference); - lastCallBack(future.isSuccess(), - future.runner.getRank(), future.runner.getBlocksize()); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); - return; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - // since no connection : just forget it - if (nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e1) { - } - } - future.setFailure(e); - lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); - return; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); - return; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.error("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); - // since no connection : just forget it - if (nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e1) { - } - } - future.setFailure(exc); - return; - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Through API Transfer from a client with or without database connection, and enabling access to + * statistic of the transfer (unblocking transfer) + * + * @author Frederic Bregier + * + */ +public abstract class ProgressBarTransfer extends AbstractTransfer { + protected final NetworkTransaction networkTransaction; + protected long INTERVALCALLBACK = 100; + protected long filesize = 0; + + public ProgressBarTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, + long id, + NetworkTransaction networkTransaction, long callbackdelay) { + // no delay so starttime = null + super(ProgressBarTransfer.class, + future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); + this.networkTransaction = networkTransaction; + this.INTERVALCALLBACK = callbackdelay; + } + + /** + * This function will be called every 100ms (or other fixed value in INTERVALCALLBACK). Note + * that final rank is unknown. + * + * @param currentBlock + * the current block rank (from 0 to n-1) + * @param blocksize + * blocksize of 1 block + */ + abstract public void callBack(int currentBlock, int blocksize); + + /** + * This function will be called only once when the transfer is over + * + * @param success + * True if the transfer is successful + * @param currentBlock + * @param blocksize + */ + abstract public void lastCallBack(boolean success, int currentBlock, int blocksize); + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ProgressBarTransfer.class); + } + DbTaskRunner taskRunner = this.initRequest(); + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + LocalChannelReference localChannelReference = runner.initRequest(); + try { + localChannelReference.getFutureValidRequest().await(); + } catch (InterruptedException e) { + } + if ((!localChannelReference.getFutureValidRequest().isSuccess()) && + (localChannelReference.getFutureValidRequest().getResult().code == + ErrorCode.ServerOverloaded)) { + switch (taskRunner.getUpdatedInfo()) { + case DONE: + case INERROR: + case INTERRUPTED: + break; + default: + runner.changeUpdatedInfo(UpdatedInfo.INERROR, + ErrorCode.ServerOverloaded, true); + } + // redo if possible + if (runner.incrementTaskRunerTry(taskRunner, Configuration.RETRYNB)) { + try { + Thread.sleep(Configuration.configuration.constraintLimitHandler + .getSleepTime()); + } catch (InterruptedException e) { + } + i--; + continue; + } else { + throw new OpenR66ProtocolNotYetConnectionException( + "End of retry on ServerOverloaded"); + } + } + this.filesize = future.filesize; + while (!future.awaitUninterruptibly(INTERVALCALLBACK)) { + if (future.isDone()) { + break; + } + callBack(future.runner.getRank(), future.runner.getBlocksize()); + } + runner.finishTransfer(false, localChannelReference); + lastCallBack(future.isSuccess(), + future.runner.getRank(), future.runner.getBlocksize()); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); + return; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + // since no connection : just forget it + if (nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e1) { + } + } + future.setFailure(e); + lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); + return; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); + return; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; + } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.error("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + lastCallBack(false, taskRunner.getRank(), taskRunner.getBlocksize()); + // since no connection : just forget it + if (nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e1) { + } + } + future.setFailure(exc); + return; + } + } +} diff --git a/src/main/java/org/waarp/openr66/client/RecvThroughClient.java b/src/main/java/org/waarp/openr66/client/RecvThroughClient.java index 86a142e2c..928e6443f 100644 --- a/src/main/java/org/waarp/openr66/client/RecvThroughClient.java +++ b/src/main/java/org/waarp/openr66/client/RecvThroughClient.java @@ -1,157 +1,157 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Class for Recv Through client - * - * This class does not included the real file transfer since it is up to the business project to - * implement how to write new data received from the remote host. If an error occurs, no transfer - * log is kept. - * - * 1) Configuration must have been loaded
- *
- * 2) Pipeline and NetworkTransaction must have been initiated:
- * Configuration.configuration.pipelineInit();
- * NetworkTransaction networkTransaction = new NetworkTransaction();
- *
- * 3) Prepare the request of transfer:
- * R66Future futureReq = new R66Future(true);
- * RecvThroughHandler rth = new RecvThroughHandler(...);
- * RecvThroughClient transaction = new RecvThroughClient(futureReq, rth, ...);
- * transaction.run();
- *
- * 4) If everything is in success, wait for the transfer to finish:
- * futureReq.awaitUninterruptibly();
- * R66Result result = futureReq.getResult();
- *
- * 5) If there is the need to re-do, just re-execute the steps from 3 to 4.
- * Don't forget at the very end to finish the global structure (steps 3 to 4 no more executed):
- * networkTransaction.closeAll();
- *
- *
- * - * @see TestRecvThroughClient Class as example of usage in test part - * - * @author Frederic Bregier - * - */ -public class RecvThroughClient extends AbstractTransfer { - protected final NetworkTransaction networkTransaction; - protected LocalChannelReference localChannelReference; - protected final RecvThroughHandler handler; - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param id - * @param networkTransaction - */ - public RecvThroughClient(R66Future future, RecvThroughHandler handler, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, long id, NetworkTransaction networkTransaction) { - // timestart since immediate - super(RecvThroughClient.class, - future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); - this.networkTransaction = networkTransaction; - this.handler = handler; - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(RecvThroughClient.class); - } - DbTaskRunner taskRunner = this.initRequest(); - try { - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - runner.setRecvThroughHandler(handler); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - runner.runTransfer(); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(e); - return; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - return; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.error("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(exc); - return; - } - } finally { - if (taskRunner != null) { - if (future.isFailed() || nolog) { - try { - taskRunner.delete(); - } catch (WaarpDatabaseException e) { - } - } - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Class for Recv Through client + * + * This class does not included the real file transfer since it is up to the business project to + * implement how to write new data received from the remote host. If an error occurs, no transfer + * log is kept. + * + * 1) Configuration must have been loaded
+ *
+ * 2) Pipeline and NetworkTransaction must have been initiated:
+ * Configuration.configuration.pipelineInit();
+ * NetworkTransaction networkTransaction = new NetworkTransaction();
+ *
+ * 3) Prepare the request of transfer:
+ * R66Future futureReq = new R66Future(true);
+ * RecvThroughHandler rth = new RecvThroughHandler(...);
+ * RecvThroughClient transaction = new RecvThroughClient(futureReq, rth, ...);
+ * transaction.run();
+ *
+ * 4) If everything is in success, wait for the transfer to finish:
+ * futureReq.awaitUninterruptibly();
+ * R66Result result = futureReq.getResult();
+ *
+ * 5) If there is the need to re-do, just re-execute the steps from 3 to 4.
+ * Don't forget at the very end to finish the global structure (steps 3 to 4 no more executed):
+ * networkTransaction.closeAll();
+ *
+ *
+ * + * @see TestRecvThroughClient Class as example of usage in test part + * + * @author Frederic Bregier + * + */ +public class RecvThroughClient extends AbstractTransfer { + protected final NetworkTransaction networkTransaction; + protected LocalChannelReference localChannelReference; + protected final RecvThroughHandler handler; + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param id + * @param networkTransaction + */ + public RecvThroughClient(R66Future future, RecvThroughHandler handler, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, long id, NetworkTransaction networkTransaction) { + // timestart since immediate + super(RecvThroughClient.class, + future, filename, rulename, fileinfo, isMD5, remoteHost, blocksize, id, null); + this.networkTransaction = networkTransaction; + this.handler = handler; + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(RecvThroughClient.class); + } + DbTaskRunner taskRunner = this.initRequest(); + try { + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); + runner.setRecvThroughHandler(handler); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + runner.runTransfer(); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(e); + return; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + return; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; + } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.error("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(exc); + return; + } + } finally { + if (taskRunner != null) { + if (future.isFailed() || nolog) { + try { + taskRunner.delete(); + } catch (WaarpDatabaseException e) { + } + } + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/client/RecvThroughHandler.java b/src/main/java/org/waarp/openr66/client/RecvThroughHandler.java index 22997d789..135e01859 100644 --- a/src/main/java/org/waarp/openr66/client/RecvThroughHandler.java +++ b/src/main/java/org/waarp/openr66/client/RecvThroughHandler.java @@ -1,52 +1,52 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; - -/** - * Class to be implemented for {@link RecvThroughClient} - * - * @author Frederic Bregier - * - */ -public abstract class RecvThroughHandler { - /** - * This method will be called for each valid packet received to be written - * - * @param buffer - * @exception OpenR66ProtocolBusinessException - * This exception has to be throw if any error occurs during write in business - * process. - */ - abstract public void writeChannelBuffer(ChannelBuffer buffer) - throws OpenR66ProtocolBusinessException; - - /** - * Facility function to read from buffer and transfer to an array of bytes - * - * @param buffer - * @return the array of bytes - */ - protected byte[] getByte(ChannelBuffer buffer) { - byte[] dst = new byte[buffer.readableBytes()]; - buffer.readBytes(dst, 0, dst.length); - return dst; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; + +/** + * Class to be implemented for {@link RecvThroughClient} + * + * @author Frederic Bregier + * + */ +public abstract class RecvThroughHandler { + /** + * This method will be called for each valid packet received to be written + * + * @param buffer + * @exception OpenR66ProtocolBusinessException + * This exception has to be throw if any error occurs during write in business + * process. + */ + abstract public void writeChannelBuffer(ChannelBuffer buffer) + throws OpenR66ProtocolBusinessException; + + /** + * Facility function to read from buffer and transfer to an array of bytes + * + * @param buffer + * @return the array of bytes + */ + protected byte[] getByte(ChannelBuffer buffer) { + byte[] dst = new byte[buffer.readableBytes()]; + buffer.readBytes(dst, 0, dst.length); + return dst; + } +} diff --git a/src/main/java/org/waarp/openr66/client/RequestInformation.java b/src/main/java/org/waarp/openr66/client/RequestInformation.java index 1abf4d903..90956ad02 100644 --- a/src/main/java/org/waarp/openr66/client/RequestInformation.java +++ b/src/main/java/org/waarp/openr66/client/RequestInformation.java @@ -1,240 +1,240 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.net.SocketAddress; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Class to request information on remote files - * - * @author Frederic Bregier - * - */ -public class RequestInformation implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final NetworkTransaction networkTransaction; - final R66Future future; - String requested = null; - String filename = null; - String rulename = null; - byte code; - - static String srequested = null; - static String sfilename = null; - static String srulename = null; - static byte scode = 0; - - /** - * Parse the parameter and set current values - * - * @param args - * @return True if all parameters were found and correct - */ - protected static boolean getParams(String[] args) { - if (args.length < 5) { - logger - .error("Needs at least 3 arguments:\n" + - " the XML client configuration file,\n" + - " '-to' the remoteHost Id,\n" + - " '-rule' the rule\n" + - "Other options:\n" + - " '-file' the optional file for which to get info,\n" + - " '-exist' to test the existence\n" + - " '-detail' to get the detail on file\n" + - " '-list' to get the list of files\n" + - " '-mlsx' to get the list and details of files"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-to")) { - i++; - srequested = args[i]; - } else if (args[i].equalsIgnoreCase("-file")) { - i++; - sfilename = args[i]; - } else if (args[i].equalsIgnoreCase("-rule")) { - i++; - srulename = args[i]; - } else if (args[i].equalsIgnoreCase("-exist")) { - scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal(); - } else if (args[i].equalsIgnoreCase("-detail")) { - scode = (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(); - } else if (args[i].equalsIgnoreCase("-list")) { - scode = (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(); - } else if (args[i].equalsIgnoreCase("-mlsx")) { - scode = (byte) InformationPacket.ASKENUM.ASKMLSLIST.ordinal(); - } - } - if (srulename == null || srequested == null) { - logger.error("Rulename and Requested HostId must be set"); - return false; - } - - return true; - } - - /** - * @param future - * @param requested - * @param rulename - * @param filename - * @param request - * @param networkTransaction - */ - public RequestInformation(R66Future future, String requested, String rulename, - String filename, byte request, - NetworkTransaction networkTransaction) { - this.future = future; - this.rulename = rulename; - this.requested = requested; - this.filename = filename; - this.code = request; - this.networkTransaction = networkTransaction; - } - - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(RequestInformation.class); - } - InformationPacket request = new InformationPacket(rulename, code, - filename); - - // Connection - DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, - requested); - if (host == null) { - logger.error("Requested host cannot be found: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - if (host.isClient()) { - logger.error("Requested host is a client and cannot be requested: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - logger.error("Cannot connect to server: " + requested); - R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.INFORMATION); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, request, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Cannot write request"); - R66Result result = new R66Result(null, true, ErrorCode.TransferError, null); - this.future.setResult(result); - this.future.cancel(); - return; - } - localChannelReference.getFutureRequest().awaitUninterruptibly(); - } - - /** - * @param args - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(RequestInformation.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - } - NetworkTransaction networkTransaction = null; - int value = 3; - try { - Configuration.configuration.pipelineInit(); - networkTransaction = new NetworkTransaction(); - R66Future result = new R66Future(true); - RequestInformation requestInformation = - new RequestInformation(result, srequested, srulename, - sfilename, scode, - networkTransaction); - requestInformation.run(); - result.awaitUninterruptibly(); - if (result.isSuccess()) { - value = 0; - R66Result r66result = result.getResult(); - ValidPacket info = (ValidPacket) r66result.other; - logger.warn("SUCCESS\n " + info.getSmiddle() + "\n " + info.getSheader()); - } else { - value = 2; - logger.error("FAILURE\n " + - result.getResult().toString()); - } - - } finally { - if (networkTransaction != null) { - networkTransaction.closeAll(); - } - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - System.exit(value); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.net.SocketAddress; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Class to request information on remote files + * + * @author Frederic Bregier + * + */ +public class RequestInformation implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final NetworkTransaction networkTransaction; + final R66Future future; + String requested = null; + String filename = null; + String rulename = null; + byte code; + + static String srequested = null; + static String sfilename = null; + static String srulename = null; + static byte scode = 0; + + /** + * Parse the parameter and set current values + * + * @param args + * @return True if all parameters were found and correct + */ + protected static boolean getParams(String[] args) { + if (args.length < 5) { + logger + .error("Needs at least 3 arguments:\n" + + " the XML client configuration file,\n" + + " '-to' the remoteHost Id,\n" + + " '-rule' the rule\n" + + "Other options:\n" + + " '-file' the optional file for which to get info,\n" + + " '-exist' to test the existence\n" + + " '-detail' to get the detail on file\n" + + " '-list' to get the list of files\n" + + " '-mlsx' to get the list and details of files"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-to")) { + i++; + srequested = args[i]; + } else if (args[i].equalsIgnoreCase("-file")) { + i++; + sfilename = args[i]; + } else if (args[i].equalsIgnoreCase("-rule")) { + i++; + srulename = args[i]; + } else if (args[i].equalsIgnoreCase("-exist")) { + scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal(); + } else if (args[i].equalsIgnoreCase("-detail")) { + scode = (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(); + } else if (args[i].equalsIgnoreCase("-list")) { + scode = (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(); + } else if (args[i].equalsIgnoreCase("-mlsx")) { + scode = (byte) InformationPacket.ASKENUM.ASKMLSLIST.ordinal(); + } + } + if (srulename == null || srequested == null) { + logger.error("Rulename and Requested HostId must be set"); + return false; + } + + return true; + } + + /** + * @param future + * @param requested + * @param rulename + * @param filename + * @param request + * @param networkTransaction + */ + public RequestInformation(R66Future future, String requested, String rulename, + String filename, byte request, + NetworkTransaction networkTransaction) { + this.future = future; + this.rulename = rulename; + this.requested = requested; + this.filename = filename; + this.code = request; + this.networkTransaction = networkTransaction; + } + + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(RequestInformation.class); + } + InformationPacket request = new InformationPacket(rulename, code, + filename); + + // Connection + DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, + requested); + if (host == null) { + logger.error("Requested host cannot be found: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + if (host.isClient()) { + logger.error("Requested host is a client and cannot be requested: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + logger.error("Cannot connect to server: " + requested); + R66Result result = new R66Result(null, true, ErrorCode.ConnectionImpossible, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.INFORMATION); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, request, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Cannot write request"); + R66Result result = new R66Result(null, true, ErrorCode.TransferError, null); + this.future.setResult(result); + this.future.cancel(); + return; + } + localChannelReference.getFutureRequest().awaitUninterruptibly(); + } + + /** + * @param args + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(RequestInformation.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + } + NetworkTransaction networkTransaction = null; + int value = 3; + try { + Configuration.configuration.pipelineInit(); + networkTransaction = new NetworkTransaction(); + R66Future result = new R66Future(true); + RequestInformation requestInformation = + new RequestInformation(result, srequested, srulename, + sfilename, scode, + networkTransaction); + requestInformation.run(); + result.awaitUninterruptibly(); + if (result.isSuccess()) { + value = 0; + R66Result r66result = result.getResult(); + ValidPacket info = (ValidPacket) r66result.other; + logger.warn("SUCCESS\n " + info.getSmiddle() + "\n " + info.getSheader()); + } else { + value = 2; + logger.error("FAILURE\n " + + result.getResult().toString()); + } + + } finally { + if (networkTransaction != null) { + networkTransaction.closeAll(); + } + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + System.exit(value); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/client/RequestTransfer.java b/src/main/java/org/waarp/openr66/client/RequestTransfer.java index 5f142bc59..f30ebe692 100644 --- a/src/main/java/org/waarp/openr66/client/RequestTransfer.java +++ b/src/main/java/org/waarp/openr66/client/RequestTransfer.java @@ -1,530 +1,530 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import java.net.SocketAddress; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Class to request information or request cancellation or restart - * - * @author Frederic Bregier - * - */ -public class RequestTransfer implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final NetworkTransaction networkTransaction; - final R66Future future; - final long specialId; - String requested = null; - String requester = null; - boolean cancel = false; - boolean stop = false; - boolean restart = false; - String restarttime = null; - - static long sspecialId; - static String srequested = null; - static String srequester = null; - static boolean scancel = false; - static boolean sstop = false; - static boolean srestart = false; - static String srestarttime = null; - - /** - * Parse the parameter and set current values - * - * @param args - * @return True if all parameters were found and correct - */ - protected static boolean getParams(String[] args) { - if (args.length < 5) { - logger - .error("Needs at least 5 arguments:\n" + - " the XML client configuration file,\n" + - " '-id' the transfer Id,\n" + - " '-to' the requested host Id or '-from' the requester host Id " + - "(localhost will be the opposite),\n" + - "Other options (only one):\n" + - " '-cancel' to cancel completely the transfer,\n" + - " '-stop' to stop the transfer (maybe restarted),\n" + - " '-restart' to restart if possible a transfer and optionnally the following arguments may be specified for a restart:\n"+ - " '-start' \"time start\" as yyyyMMddHHmmss (override previous -delay options)\n" - + - " '-delay' \"+delay in ms\" as delay in ms from current time(override previous -start options)\n" - + - " '-delay' \"delay in ms\" as time in ms (override previous -start options)"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-id")) { - i++; - try { - sspecialId = Long.parseLong(args[i]); - } catch (NumberFormatException e) { - logger.error("Cannot value Id: "+args[i],e); - return false; - } - } else if (args[i].equalsIgnoreCase("-to")) { - i++; - srequested = args[i]; - try { - srequester = Configuration.configuration.getHostId(DbConstant.admin.session, - srequested); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Host Id: " + srequester, e); - return false; - } - } else if (args[i].equalsIgnoreCase("-from")) { - i++; - srequester = args[i]; - try { - srequested = Configuration.configuration.getHostId(DbConstant.admin.session, - srequester); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Host Id: " + srequested, e); - return false; - } - } else if (args[i].equalsIgnoreCase("-cancel")) { - scancel = true; - } else if (args[i].equalsIgnoreCase("-stop")) { - sstop = true; - } else if (args[i].equalsIgnoreCase("-restart")) { - srestart = true; - } else if (args[i].equalsIgnoreCase("-start")) { - i++; - srestarttime = args[i]; - } else if (args[i].equalsIgnoreCase("-delay")) { - i++; - if (args[i].charAt(0) == '+') { - Date date = new Date(System.currentTimeMillis() + - Long.parseLong(args[i].substring(1))); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - srestarttime = dateFormat.format(date); - } else { - Date date = new Date(Long.parseLong(args[i])); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - srestarttime = dateFormat.format(date); - } - } - } - if ((scancel && srestart) || (scancel && sstop) || (srestart && sstop)) { - logger.error("Cannot cancel or restart or stop at the same time"); - return false; - } - if (sspecialId == DbConstant.ILLEGALVALUE || srequested == null) { - logger.error("TransferId and Requested/Requester HostId must be set"); - return false; - } - - return true; - } - - /** - * @param future - * @param specialId - * @param requested - * @param requester - * @param cancel - * @param stop - * @param restart - * @param networkTransaction - */ - public RequestTransfer(R66Future future, long specialId, String requested, String requester, - boolean cancel, boolean stop, boolean restart, - NetworkTransaction networkTransaction) { - this(future, specialId, requested, requester, cancel, stop, restart, null, networkTransaction); - } - - /** - * @param future - * @param specialId - * @param requested - * @param requester - * @param cancel - * @param stop - * @param restart - * @param restarttime in yyyyMMddHHmmss format - * @param networkTransaction - */ - public RequestTransfer(R66Future future, long specialId, String requested, String requester, - boolean cancel, boolean stop, boolean restart, String restarttime, - NetworkTransaction networkTransaction) { - this.future = future; - this.specialId = specialId; - this.requested = requested; - this.requester = requester; - this.cancel = cancel; - this.stop = stop; - this.restart = restart; - this.restarttime = restarttime; - this.networkTransaction = networkTransaction; - } - - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class); - } - DbTaskRunner runner = null; - try { - runner = new DbTaskRunner(DbConstant.admin.session, null, null, - specialId, requester, requested); - } catch (WaarpDatabaseException e) { - logger.error("Cannot find the transfer"); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return; - } - if (cancel || stop || restart) { - if (cancel) { - // Cancel the task and delete any file if in retrieve - if (runner.isAllDone()) { - // nothing to do since already finished - setDone(runner); - logger.info("Transfer already finished: " + runner.toString()); - future.setResult(new R66Result(null, true, ErrorCode.TransferOk, runner)); - future.getResult().runner = runner; - future.setSuccess(); - return; - } else { - // Send a request of cancel - ErrorCode code = sendValid(LocalPacketFactory.CANCELPACKET); - switch (code) { - case CompleteOk: - logger.info("Transfer cancel requested and done: {}", - runner); - break; - case TransferOk: - logger.info("Transfer cancel requested but already finished: {}", - runner); - break; - default: - logger.info("Transfer cancel requested but internal error: {}", - runner); - break; - } - } - } else if (stop) { - // Just stop the task - // Send a request - ErrorCode code = sendValid(LocalPacketFactory.STOPPACKET); - switch (code) { - case CompleteOk: - logger.info("Transfer stop requested and done: {}", runner); - break; - case TransferOk: - logger.info("Transfer stop requested but already finished: {}", - runner); - break; - default: - logger.info("Transfer stop requested but internal error: {}", - runner); - break; - } - } else if (restart) { - // Restart if already stopped and not finished - ErrorCode code = sendValid(LocalPacketFactory.VALIDPACKET); - switch (code) { - case QueryStillRunning: - logger.info( - "Transfer restart requested but already active and running: {}", - runner); - break; - case Running: - logger.info("Transfer restart requested but already running: {}", - runner); - break; - case PreProcessingOk: - logger.info("Transfer restart requested and restarted: {}", - runner); - break; - case CompleteOk: - logger.info("Transfer restart requested but already finished: {}", - runner); - break; - case RemoteError: - logger.info("Transfer restart requested but remote error: {}", - runner); - break; - case PassThroughMode: - logger.info("Transfer not restarted since it is in PassThrough mode: {}", - runner); - break; - default: - logger.info("Transfer restart requested but internal error: {}", - runner); - break; - } - } - } else { - // Only request - logger.info("Transfer information:\n " + runner.toShortString()); - future.setResult(new R66Result(null, true, runner.getErrorInfo(), runner)); - future.setSuccess(); - } - } - - /** - * Set the runner to DONE - * - * @param runner - */ - private void setDone(DbTaskRunner runner) { - if (runner.getUpdatedInfo() != UpdatedInfo.DONE) { - runner.changeUpdatedInfo(UpdatedInfo.DONE); - runner.forceSaveStatus(); - } - } - - private ErrorCode sendValid(byte code) { - DbHostAuth host; - host = R66Auth.getServerAuth(DbConstant.admin.session, - this.requester); - if (host == null) { - logger.error("Requested host cannot be found: " + this.requester); - OpenR66Exception e = - new OpenR66RunnerErrorException("Requested host cannot be found"); - future.setResult(new R66Result( - e, - null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return ErrorCode.Internal; - } - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - logger.debug("Cannot connect to " + host.toString()); - host = null; - future.setResult(new R66Result(null, true, - ErrorCode.ConnectionImpossible, null)); - future.cancel(); - return ErrorCode.Internal; - } - ValidPacket packet = null; - if (restarttime != null && code == LocalPacketFactory.VALIDPACKET) { - // restart time set - logger.debug("Restart with time: "+restarttime); - packet = new ValidPacket("Request on Transfer", - this.requested + " " + this.requester + " " + this.specialId+" "+restarttime, - code); - } else { - packet = new ValidPacket("Request on Transfer", - this.requested + " " + this.requester + " " + this.specialId, - code); - } - localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Cannot transfer request to " + host.toString()); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - host = null; - packet = null; - logger.debug("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return ErrorCode.Internal; - } - packet = null; - host = null; - future.awaitUninterruptibly(); - logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); - - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - R66Result result = future.getResult(); - if (result != null) { - return result.code; - } - return ErrorCode.Internal; - } - - /** - * @param args - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - } - int value = 99; - try { - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - R66Future result = new R66Future(true); - RequestTransfer requestTransfer = - new RequestTransfer(result, sspecialId, srequested, srequester, - scancel, sstop, srestart, srestarttime, - networkTransaction); - requestTransfer.run(); - result.awaitUninterruptibly(); - R66Result finalValue = result.getResult(); - if (scancel || sstop || srestart) { - if (scancel) { - if (result.isSuccess()) { - value = 0; - logger.warn("Transfer already finished:\n " + - finalValue.runner.toShortString()); - } else { - switch (finalValue.code) { - case CompleteOk: - value = 0; - logger.warn("Transfer cancel requested and done:\n " + - finalValue.runner.toShortString()); - break; - case TransferOk: - value = 3; - logger.warn("Transfer cancel requested but already finished:\n " - + - finalValue.runner.toShortString()); - break; - default: - value = 4; - logger.error("Transfer cancel requested but internal error:\n " + - finalValue.runner.toShortString()); - break; - } - } - } else if (sstop) { - switch (finalValue.code) { - case CompleteOk: - value = 0; - logger.warn("Transfer stop requested and done:\n " + - finalValue.runner.toShortString()); - break; - case TransferOk: - value = 0; - logger.warn("Transfer stop requested but already finished:\n " + - finalValue.runner.toShortString()); - break; - default: - value = 3; - logger.error("Transfer stop requested but internal error:\n " + - finalValue.runner.toShortString()); - break; - } - } else if (srestart) { - switch (finalValue.code) { - case QueryStillRunning: - value = 0; - logger.warn("Transfer restart requested but already active and running:\n " - + - finalValue.runner.toShortString()); - break; - case Running: - value = 0; - logger.warn("Transfer restart requested but already running:\n " + - finalValue.runner.toShortString()); - break; - case PreProcessingOk: - value = 0; - logger.warn("Transfer restart requested and restarted:\n " + - finalValue.runner.toShortString()); - break; - case CompleteOk: - value = 4; - logger.warn("Transfer restart requested but already finished:\n " + - finalValue.runner.toShortString()); - break; - case RemoteError: - value = 5; - logger.error("Transfer restart requested but remote error:\n " + - finalValue.runner.toShortString()); - break; - case PassThroughMode: - value = 6; - logger.warn("Transfer not restarted since it is in PassThrough mode:\n " - + - finalValue.runner.toShortString()); - break; - default: - value = 3; - logger.error("Transfer restart requested but internal error:\n " + - finalValue.runner.toShortString()); - break; - } - } - } else { - value = 0; - // Only request - logger.warn("Transfer information:\n " + - finalValue.runner.toShortString()); - } - } finally { - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - System.exit(value); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.client; + +import java.net.SocketAddress; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Class to request information or request cancellation or restart + * + * @author Frederic Bregier + * + */ +public class RequestTransfer implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final NetworkTransaction networkTransaction; + final R66Future future; + final long specialId; + String requested = null; + String requester = null; + boolean cancel = false; + boolean stop = false; + boolean restart = false; + String restarttime = null; + + static long sspecialId; + static String srequested = null; + static String srequester = null; + static boolean scancel = false; + static boolean sstop = false; + static boolean srestart = false; + static String srestarttime = null; + + /** + * Parse the parameter and set current values + * + * @param args + * @return True if all parameters were found and correct + */ + protected static boolean getParams(String[] args) { + if (args.length < 5) { + logger + .error("Needs at least 5 arguments:\n" + + " the XML client configuration file,\n" + + " '-id' the transfer Id,\n" + + " '-to' the requested host Id or '-from' the requester host Id " + + "(localhost will be the opposite),\n" + + "Other options (only one):\n" + + " '-cancel' to cancel completely the transfer,\n" + + " '-stop' to stop the transfer (maybe restarted),\n" + + " '-restart' to restart if possible a transfer and optionnally the following arguments may be specified for a restart:\n"+ + " '-start' \"time start\" as yyyyMMddHHmmss (override previous -delay options)\n" + + + " '-delay' \"+delay in ms\" as delay in ms from current time(override previous -start options)\n" + + + " '-delay' \"delay in ms\" as time in ms (override previous -start options)"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-id")) { + i++; + try { + sspecialId = Long.parseLong(args[i]); + } catch (NumberFormatException e) { + logger.error("Cannot value Id: "+args[i],e); + return false; + } + } else if (args[i].equalsIgnoreCase("-to")) { + i++; + srequested = args[i]; + try { + srequester = Configuration.configuration.getHostId(DbConstant.admin.session, + srequested); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Host Id: " + srequester, e); + return false; + } + } else if (args[i].equalsIgnoreCase("-from")) { + i++; + srequester = args[i]; + try { + srequested = Configuration.configuration.getHostId(DbConstant.admin.session, + srequester); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Host Id: " + srequested, e); + return false; + } + } else if (args[i].equalsIgnoreCase("-cancel")) { + scancel = true; + } else if (args[i].equalsIgnoreCase("-stop")) { + sstop = true; + } else if (args[i].equalsIgnoreCase("-restart")) { + srestart = true; + } else if (args[i].equalsIgnoreCase("-start")) { + i++; + srestarttime = args[i]; + } else if (args[i].equalsIgnoreCase("-delay")) { + i++; + if (args[i].charAt(0) == '+') { + Date date = new Date(System.currentTimeMillis() + + Long.parseLong(args[i].substring(1))); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + srestarttime = dateFormat.format(date); + } else { + Date date = new Date(Long.parseLong(args[i])); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + srestarttime = dateFormat.format(date); + } + } + } + if ((scancel && srestart) || (scancel && sstop) || (srestart && sstop)) { + logger.error("Cannot cancel or restart or stop at the same time"); + return false; + } + if (sspecialId == DbConstant.ILLEGALVALUE || srequested == null) { + logger.error("TransferId and Requested/Requester HostId must be set"); + return false; + } + + return true; + } + + /** + * @param future + * @param specialId + * @param requested + * @param requester + * @param cancel + * @param stop + * @param restart + * @param networkTransaction + */ + public RequestTransfer(R66Future future, long specialId, String requested, String requester, + boolean cancel, boolean stop, boolean restart, + NetworkTransaction networkTransaction) { + this(future, specialId, requested, requester, cancel, stop, restart, null, networkTransaction); + } + + /** + * @param future + * @param specialId + * @param requested + * @param requester + * @param cancel + * @param stop + * @param restart + * @param restarttime in yyyyMMddHHmmss format + * @param networkTransaction + */ + public RequestTransfer(R66Future future, long specialId, String requested, String requester, + boolean cancel, boolean stop, boolean restart, String restarttime, + NetworkTransaction networkTransaction) { + this.future = future; + this.specialId = specialId; + this.requested = requested; + this.requester = requester; + this.cancel = cancel; + this.stop = stop; + this.restart = restart; + this.restarttime = restarttime; + this.networkTransaction = networkTransaction; + } + + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class); + } + DbTaskRunner runner = null; + try { + runner = new DbTaskRunner(DbConstant.admin.session, null, null, + specialId, requester, requested); + } catch (WaarpDatabaseException e) { + logger.error("Cannot find the transfer"); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return; + } + if (cancel || stop || restart) { + if (cancel) { + // Cancel the task and delete any file if in retrieve + if (runner.isAllDone()) { + // nothing to do since already finished + setDone(runner); + logger.info("Transfer already finished: " + runner.toString()); + future.setResult(new R66Result(null, true, ErrorCode.TransferOk, runner)); + future.getResult().runner = runner; + future.setSuccess(); + return; + } else { + // Send a request of cancel + ErrorCode code = sendValid(LocalPacketFactory.CANCELPACKET); + switch (code) { + case CompleteOk: + logger.info("Transfer cancel requested and done: {}", + runner); + break; + case TransferOk: + logger.info("Transfer cancel requested but already finished: {}", + runner); + break; + default: + logger.info("Transfer cancel requested but internal error: {}", + runner); + break; + } + } + } else if (stop) { + // Just stop the task + // Send a request + ErrorCode code = sendValid(LocalPacketFactory.STOPPACKET); + switch (code) { + case CompleteOk: + logger.info("Transfer stop requested and done: {}", runner); + break; + case TransferOk: + logger.info("Transfer stop requested but already finished: {}", + runner); + break; + default: + logger.info("Transfer stop requested but internal error: {}", + runner); + break; + } + } else if (restart) { + // Restart if already stopped and not finished + ErrorCode code = sendValid(LocalPacketFactory.VALIDPACKET); + switch (code) { + case QueryStillRunning: + logger.info( + "Transfer restart requested but already active and running: {}", + runner); + break; + case Running: + logger.info("Transfer restart requested but already running: {}", + runner); + break; + case PreProcessingOk: + logger.info("Transfer restart requested and restarted: {}", + runner); + break; + case CompleteOk: + logger.info("Transfer restart requested but already finished: {}", + runner); + break; + case RemoteError: + logger.info("Transfer restart requested but remote error: {}", + runner); + break; + case PassThroughMode: + logger.info("Transfer not restarted since it is in PassThrough mode: {}", + runner); + break; + default: + logger.info("Transfer restart requested but internal error: {}", + runner); + break; + } + } + } else { + // Only request + logger.info("Transfer information:\n " + runner.toShortString()); + future.setResult(new R66Result(null, true, runner.getErrorInfo(), runner)); + future.setSuccess(); + } + } + + /** + * Set the runner to DONE + * + * @param runner + */ + private void setDone(DbTaskRunner runner) { + if (runner.getUpdatedInfo() != UpdatedInfo.DONE) { + runner.changeUpdatedInfo(UpdatedInfo.DONE); + runner.forceSaveStatus(); + } + } + + private ErrorCode sendValid(byte code) { + DbHostAuth host; + host = R66Auth.getServerAuth(DbConstant.admin.session, + this.requester); + if (host == null) { + logger.error("Requested host cannot be found: " + this.requester); + OpenR66Exception e = + new OpenR66RunnerErrorException("Requested host cannot be found"); + future.setResult(new R66Result( + e, + null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return ErrorCode.Internal; + } + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + logger.debug("Cannot connect to " + host.toString()); + host = null; + future.setResult(new R66Result(null, true, + ErrorCode.ConnectionImpossible, null)); + future.cancel(); + return ErrorCode.Internal; + } + ValidPacket packet = null; + if (restarttime != null && code == LocalPacketFactory.VALIDPACKET) { + // restart time set + logger.debug("Restart with time: "+restarttime); + packet = new ValidPacket("Request on Transfer", + this.requested + " " + this.requester + " " + this.specialId+" "+restarttime, + code); + } else { + packet = new ValidPacket("Request on Transfer", + this.requested + " " + this.requester + " " + this.specialId, + code); + } + localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Cannot transfer request to " + host.toString()); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + host = null; + packet = null; + logger.debug("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return ErrorCode.Internal; + } + packet = null; + host = null; + future.awaitUninterruptibly(); + logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); + + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + R66Result result = future.getResult(); + if (result != null) { + return result.code; + } + return ErrorCode.Internal; + } + + /** + * @param args + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(RequestTransfer.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + } + int value = 99; + try { + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + R66Future result = new R66Future(true); + RequestTransfer requestTransfer = + new RequestTransfer(result, sspecialId, srequested, srequester, + scancel, sstop, srestart, srestarttime, + networkTransaction); + requestTransfer.run(); + result.awaitUninterruptibly(); + R66Result finalValue = result.getResult(); + if (scancel || sstop || srestart) { + if (scancel) { + if (result.isSuccess()) { + value = 0; + logger.warn("Transfer already finished:\n " + + finalValue.runner.toShortString()); + } else { + switch (finalValue.code) { + case CompleteOk: + value = 0; + logger.warn("Transfer cancel requested and done:\n " + + finalValue.runner.toShortString()); + break; + case TransferOk: + value = 3; + logger.warn("Transfer cancel requested but already finished:\n " + + + finalValue.runner.toShortString()); + break; + default: + value = 4; + logger.error("Transfer cancel requested but internal error:\n " + + finalValue.runner.toShortString()); + break; + } + } + } else if (sstop) { + switch (finalValue.code) { + case CompleteOk: + value = 0; + logger.warn("Transfer stop requested and done:\n " + + finalValue.runner.toShortString()); + break; + case TransferOk: + value = 0; + logger.warn("Transfer stop requested but already finished:\n " + + finalValue.runner.toShortString()); + break; + default: + value = 3; + logger.error("Transfer stop requested but internal error:\n " + + finalValue.runner.toShortString()); + break; + } + } else if (srestart) { + switch (finalValue.code) { + case QueryStillRunning: + value = 0; + logger.warn("Transfer restart requested but already active and running:\n " + + + finalValue.runner.toShortString()); + break; + case Running: + value = 0; + logger.warn("Transfer restart requested but already running:\n " + + finalValue.runner.toShortString()); + break; + case PreProcessingOk: + value = 0; + logger.warn("Transfer restart requested and restarted:\n " + + finalValue.runner.toShortString()); + break; + case CompleteOk: + value = 4; + logger.warn("Transfer restart requested but already finished:\n " + + finalValue.runner.toShortString()); + break; + case RemoteError: + value = 5; + logger.error("Transfer restart requested but remote error:\n " + + finalValue.runner.toShortString()); + break; + case PassThroughMode: + value = 6; + logger.warn("Transfer not restarted since it is in PassThrough mode:\n " + + + finalValue.runner.toShortString()); + break; + default: + value = 3; + logger.error("Transfer restart requested but internal error:\n " + + finalValue.runner.toShortString()); + break; + } + } + } else { + value = 0; + // Only request + logger.warn("Transfer information:\n " + + finalValue.runner.toShortString()); + } + } finally { + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + System.exit(value); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/client/SendThroughClient.java b/src/main/java/org/waarp/openr66/client/SendThroughClient.java index 9f6254e2d..0fa66aa2e 100644 --- a/src/main/java/org/waarp/openr66/client/SendThroughClient.java +++ b/src/main/java/org/waarp/openr66/client/SendThroughClient.java @@ -1,361 +1,361 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.client; - -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.ChannelFuture; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.RetrieveRunner; -import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Class for Send Through client - * - * This class does not included the real file transfer since it is up to the business project to - * implement how to read new data to be sent to the remote host. If an error occurs, no transfer log - * is kept. - * - * 1) Configuration must have been loaded
- *
- * 2) Pipeline and NetworkTransaction must have been initiated:
- * Configuration.configuration.pipelineInit();
- * NetworkTransaction networkTransaction = new NetworkTransaction();
- *
- * 3) Prepare the request of transfer:
- * R66Future futureReq = new R66Future(true);
- * SendThroughClient transaction = new SendThroughClient(futureReq,...);
- * if (! transaction.initiateRequest()) { error }
- *
- * 4) Once initiateRequest() gives true, you are ready to send the data in through mode like:
- * byte[] data = readOrGetInSomeWayData();
- * DataBlock block = transaction.transformToDataBlock(data);
- * futureWrite = transaction.writeWhenPossible(block);
- *
- * 5) Once you have finished, so this is the last block, you have to do the following:
- * If the last block is not empty:
- * DataBlock block = transaction.transformToDataBlock(data);
- * block.setEOF(true);
- * Or if the last block is empty:
- * DataBlock block = transaction.transformToDataBlock(null);
- * Then
- * futureWrite = transaction.writeWhenPossible(block);
- * futureWrite.awaitUninterruptibly();
- *
- * 6) If everything is in success:
- * transaction.finalizeRequest();
- *
- * And now wait for the transfer to finish:
- * futureReq.awaitUninterruptibly();
- * R66Result result = futureReq.getResult();
- *
- * 7) If there is the need to re-do, just re-execute the steps from 3 to 6.
- * Don't forget at the very end to finish the global structure (steps 3 to 6 no more executed):
- * networkTransaction.closeAll();
- *
- * 8) In case of errors during steps 4 or 5 (and only those), call the following:
- *
SpecialIdRuleFilenameInfo" - + "Step (LastStep)ActionStatus" - + "InternalTransfer RankBlockSizeisMoved" - + "RequesterRequested" - + "StartStopBandwidth (Mbits)Free Space(MB)" + - specialId + - "" + - (rule != null ? rule.toShortString() : ruleId) + - "" + - filename + - "" + fileInformation + - "" + - TASKSTEP.values()[globalstep] + - " (" + - TASKSTEP.values()[globallaststep] + - ")" + - step + - "" + - status.mesg + " " + running + - "" + - UpdatedInfo.values()[updatedInfo].name() + " : " + infostatus.mesg + - "" + - rank + - "" + - blocksize + - "" + - isFileMoved + - "" + - requesterHostId + - "" + - requestedHostId + - "" + - start + - "" + - stop + - "" + - bandwidth() + "" + - freespace + "SpecialIdRuleFilenameInfo" + + "Step (LastStep)ActionStatus" + + "InternalTransfer RankBlockSizeisMoved" + + "RequesterRequested" + + "StartStopBandwidth (Mbits)Free Space(MB)" + + specialId + + "" + + (rule != null ? rule.toShortString() : ruleId) + + "" + + filename + + "" + fileInformation + + "" + + TASKSTEP.values()[globalstep] + + " (" + + TASKSTEP.values()[globallaststep] + + ")" + + step + + "" + + status.mesg + " " + running + + "" + + UpdatedInfo.values()[updatedInfo].name() + " : " + infostatus.mesg + + "" + + rank + + "" + + blocksize + + "" + + isFileMoved + + "" + + requesterHostId + + "" + + requestedHostId + + "" + + start + + "" + + stop + + "" + + bandwidth() + "" + + freespace + "
"); - responseContent.append(""); - responseContent.append(DbTaskRunner.headerHtml()); - responseContent.append("\r\n"); - int i = 0; - while (preparedStatement.getNext()) { - DbTaskRunner taskRunner = DbTaskRunner - .getFromStatement(preparedStatement); - responseContent.append(""); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - responseContent.append(taskRunner.toHtml(authentHttp, - lcr != null ? "Active" : "NotActive")); - responseContent.append("\r\n"); - if (nb > 0) { - i++; - if (i >= nb) { - break; - } - } - } - responseContent.append("
"); - responseContent.append(type); - responseContent.append("
"); - responseContent.append(taskRunner.isSender() ? "S" : "R"); - responseContent.append("

\r\n"); - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - } - - /** - * print all active transfers - * - * @param ctx - * @param nb - */ - private void active(ChannelHandlerContext ctx, int nb) { - responseContent.append(REQUEST.active.readHeader(this)); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.Running, nb); - addRunners(preparedStatement, ErrorCode.Running.mesg, nb); - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.INTERRUPTED, true, nb); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - addRunners(preparedStatement, UpdatedInfo.INTERRUPTED.name(), nb); - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.TOSUBMIT, true, nb); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - addRunners(preparedStatement, UpdatedInfo.TOSUBMIT.name(), nb); - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.InitOk, nb); - addRunners(preparedStatement, ErrorCode.InitOk.mesg, nb); - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.PreProcessingOk, nb); - addRunners(preparedStatement, ErrorCode.PreProcessingOk.mesg, nb); - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.TransferOk, nb); - addRunners(preparedStatement, ErrorCode.TransferOk.mesg, nb); - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.PostProcessingOk, nb); - addRunners(preparedStatement, ErrorCode.PostProcessingOk.mesg, nb); - preparedStatement = null; - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); - return; - } - responseContent.append(REQUEST.active.readEnd()); - } - - /** - * print all transfers in error - * - * @param ctx - * @param nb - */ - private void error(ChannelHandlerContext ctx, int nb) { - responseContent.append(REQUEST.error.readHeader(this)); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.INERROR, true, nb / 2); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - addRunners(preparedStatement, UpdatedInfo.INERROR.name(), nb / 2); - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.INTERRUPTED, true, nb / 2); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - addRunners(preparedStatement, UpdatedInfo.INTERRUPTED.name(), - nb / 2); - preparedStatement = DbTaskRunner.getStepPrepareStatement(dbSession, - TASKSTEP.ERRORTASK, nb / 4); - addRunners(preparedStatement, TASKSTEP.ERRORTASK.name(), nb / 4); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); - return; - } - responseContent.append(REQUEST.error.readEnd()); - } - - /** - * Print all done transfers - * - * @param ctx - * @param nb - */ - private void done(ChannelHandlerContext ctx, int nb) { - responseContent.append(REQUEST.done.readHeader(this)); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - ErrorCode.CompleteOk, nb); - addRunners(preparedStatement, ErrorCode.CompleteOk.mesg, nb); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); - return; - } - responseContent.append(REQUEST.done.readEnd()); - } - - /** - * Print all nb last transfers - * - * @param ctx - * @param nb - */ - private void all(ChannelHandlerContext ctx, int nb) { - responseContent.append(REQUEST.all.readHeader(this)); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, - null, nb);// means all - addRunners(preparedStatement, "ALL RUNNERS: " + nb, nb); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); - return; - } - responseContent.append(REQUEST.all.readEnd()); - } - - /** - * print only status - * - * @param ctx - * @param nb - */ - private void status(ChannelHandlerContext ctx, int nb) { - responseContent.append(REQUEST.status.readHeader(this)); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.INERROR, true, 1); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - try { - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - responseContent.append("

Some Transfers are in ERROR


"); - status = HttpResponseStatus.INTERNAL_SERVER_ERROR; - } - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( - dbSession, UpdatedInfo.INTERRUPTED, true, 1); - DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); - try { - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - responseContent.append("

Some Transfers are INTERRUPTED


"); - status = HttpResponseStatus.INTERNAL_SERVER_ERROR; - } - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - preparedStatement = DbTaskRunner.getStepPrepareStatement(dbSession, - TASKSTEP.ERRORTASK, 1); - try { - preparedStatement.executeQuery(); - if (preparedStatement.getNext()) { - responseContent.append("

Some Transfers are in ERRORTASK


"); - status = HttpResponseStatus.INTERNAL_SERVER_ERROR; - } - } finally { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - } - if (status != HttpResponseStatus.INTERNAL_SERVER_ERROR) { - responseContent.append("

No problem is found in Transfers


"); - } - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); - return; - } - responseContent.append(REQUEST.status.readEnd()); - } - - /** - * print only status - * - * @param ctx - * @param nb - */ - private void statusxml(ChannelHandlerContext ctx, long nb, boolean detail) { - Configuration.configuration.monitoring.run(nb, detail); - responseContent.append(Configuration.configuration.monitoring.exportXml(detail)); - } - - /** - * Write the response - * - * @param e - */ - private void writeResponse(MessageEvent e) { - // Convert the response content to a ChannelBuffer. - ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent - .toString(), WaarpStringUtils.UTF8); - responseContent.setLength(0); - // Decide whether to close the connection or not. - boolean keepAlive = HttpHeaders.isKeepAlive(request); - boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request - .getHeader(HttpHeaders.Names.CONNECTION)) || - (!keepAlive); - - // Build the response object. - HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - status); - response.setContent(buf); - if (isCurrentRequestXml) { - response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); - } else { - response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); - } - if (keepAlive) { - response.setHeader(HttpHeaders.Names.CONNECTION, - HttpHeaders.Values.KEEP_ALIVE); - } - if (!close) { - // There's no need to add 'Content-Length' header - // if this is the last response. - response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String - .valueOf(buf.readableBytes())); - } - - String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); - if (cookieString != null) { - CookieDecoder cookieDecoder = new CookieDecoder(); - Set cookies = cookieDecoder.decode(cookieString); - if (!cookies.isEmpty()) { - // Reset the cookies if necessary. - CookieEncoder cookieEncoder = new CookieEncoder(true); - for (Cookie cookie : cookies) { - cookieEncoder.addCookie(cookie); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - cookieEncoder = new CookieEncoder(true); - } - } - } - - // Write the response. - ChannelFuture future = e.getChannel().write(response); - - // Close the connection after the write operation is done if necessary. - if (close) { - future.addListener(ChannelFutureListener.CLOSE); - } - if (this.isPrivateDbSession && dbSession != null) { - dbSession.disconnect(); - DbAdmin.nbHttpSession--; - dbSession = null; - } - } - - /** - * Send an error and close - * - * @param ctx - * @param status - */ - private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { - HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - status); - response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); - responseContent.setLength(0); - responseContent.append(REQUEST.error.readHeader(this)); - responseContent.append("OpenR66 Web Failure: "); - responseContent.append(status.toString()); - responseContent.append(REQUEST.error.readEnd()); - response.setContent(ChannelBuffers.copiedBuffer(responseContent - .toString(), WaarpStringUtils.UTF8)); - // Close the connection as soon as the error message is sent. - ctx.getChannel().write(response).addListener( - ChannelFutureListener.CLOSE); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { - OpenR66Exception exception = OpenR66ExceptionTrappedFactory - .getExceptionFromTrappedException(e.getChannel(), e); - if (exception != null) { - if (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) { - if (e.getCause() instanceof IOException) { - if (this.isPrivateDbSession && dbSession != null) { - dbSession.disconnect(); - DbAdmin.nbHttpSession--; - dbSession = null; - } - // Nothing to do - return; - } - logger.warn("Exception in HttpHandler {}", exception.getMessage()); - } - if (e.getChannel().isConnected()) { - sendError(ctx, HttpResponseStatus.BAD_REQUEST); - } - } else { - if (this.isPrivateDbSession && dbSession != null) { - dbSession.disconnect(); - dbSession = null; - } - // Nothing to do - return; - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelClosed(org - * .jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - logger.debug("Closed"); - super.channelClosed(ctx, e); - if (this.isPrivateDbSession && dbSession != null) { - dbSession.disconnect(); - DbAdmin.nbHttpSession--; - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelConnected - * (org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - logger.debug("Connected"); - authentHttp.getAuth().specialNoSessionAuth(false, Configuration.configuration.HOST_ID); - super.channelConnected(ctx, e); - ChannelGroup group = Configuration.configuration.getHttpChannelGroup(); - if (group != null) { - group.add(e.getChannel()); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.http; + +import java.io.IOException; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelFutureListener; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import org.jboss.netty.channel.group.ChannelGroup; +import org.jboss.netty.handler.codec.http.Cookie; +import org.jboss.netty.handler.codec.http.CookieDecoder; +import org.jboss.netty.handler.codec.http.CookieEncoder; +import org.jboss.netty.handler.codec.http.DefaultHttpResponse; +import org.jboss.netty.handler.codec.http.HttpHeaders; +import org.jboss.netty.handler.codec.http.HttpMethod; +import org.jboss.netty.handler.codec.http.HttpRequest; +import org.jboss.netty.handler.codec.http.HttpResponse; +import org.jboss.netty.handler.codec.http.HttpResponseStatus; +import org.jboss.netty.handler.codec.http.HttpVersion; +import org.jboss.netty.handler.codec.http.QueryStringDecoder; +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.exception.FileTransferException; +import org.waarp.common.exception.InvalidArgumentException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; + +/** + * Handler for HTTP information support + * + * @author Frederic Bregier + * + */ +public class HttpFormattedHandler extends SimpleChannelUpstreamHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(HttpFormattedHandler.class); + + private static enum REQUEST { + index("index.html"), + active("monitoring_header.html", "monitoring_end.html"), + error("monitoring_header.html", "monitoring_end.html"), + done("monitoring_header.html", "monitoring_end.html"), + all("monitoring_header.html", "monitoring_end.html"), + status("monitoring_header.html", "monitoring_end.html"), + statusxml(""); + + private String header; + private String end; + + /** + * Constructor for a unique file + * + * @param uniquefile + */ + private REQUEST(String uniquefile) { + this.header = uniquefile; + this.end = uniquefile; + } + + /** + * @param header + * @param end + */ + private REQUEST(String header, String end) { + this.header = header; + this.end = end; + } + + /** + * Reader for a unique file + * + * @return the content of the unique file + */ + public String readFileUnique(HttpFormattedHandler handler) { + return handler.readFileHeader(Configuration.configuration.httpBasePath + "monitor/" + + this.header); + } + + public String readHeader(HttpFormattedHandler handler) { + return handler.readFileHeader(Configuration.configuration.httpBasePath + "monitor/" + + this.header); + } + + public String readEnd() { + return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + "monitor/" + + this.end); + } + } + + private static enum REPLACEMENT { + XXXHOSTIDXXX, XXXLOCACTIVEXXX, XXXNETACTIVEXXX, XXXBANDWIDTHXXX, XXXDATEXXX; + } + + public static final int LIMITROW = 60; // better + // if + // it + // can + // be + // divided + // by + // 4 + + public final R66Session authentHttp = new R66Session(); + + private volatile HttpRequest request; + + private final StringBuilder responseContent = new StringBuilder(); + + private volatile HttpResponseStatus status; + + private volatile String uriRequest; + + private static final String sINFO = "INFO", + sNB = "NB", sDETAIL = "DETAIL"; + + /** + * The Database connection attached to this NetworkChannel shared among all associated + * LocalChannels + */ + private DbSession dbSession; + + /** + * Does this dbSession is private and so should be closed + */ + private boolean isPrivateDbSession = false; + private boolean isCurrentRequestXml = false; + + private Map> params = null; + + private String readFileHeader(String filename) { + String value; + try { + value = WaarpStringUtils.readFileException(filename); + } catch (InvalidArgumentException e) { + logger.error("Error while trying to open: " + filename, e); + return ""; + } catch (FileTransferException e) { + logger.error("Error while trying to read: " + filename, e); + return ""; + } + StringBuilder builder = new StringBuilder(value); + + WaarpStringUtils.replace(builder, REPLACEMENT.XXXDATEXXX.toString(), + (new Date()).toString()); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXLOCACTIVEXXX.toString(), + Integer.toString( + Configuration.configuration.getLocalTransaction(). + getNumberLocalChannel())); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXNETACTIVEXXX.toString(), + Integer.toString( + DbAdmin.getNbConnection())); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), + Configuration.configuration.HOST_ID); + TrafficCounter trafficCounter = + Configuration.configuration.getGlobalTrafficShapingHandler().getTrafficCounter(); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXBANDWIDTHXXX.toString(), + "IN:" + (trafficCounter.getLastReadThroughput() / 131072) + + "Mbits  OUT:" + + (trafficCounter.getLastWriteThroughput() / 131072) + "Mbits"); + return builder.toString(); + } + + private String getTrimValue(String varname) { + String value = null; + try { + value = params.get(varname).get(0).trim(); + } catch (NullPointerException e) { + return null; + } + if (value.length() == 0) { + value = null; + } + return value; + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) + throws Exception { + isCurrentRequestXml = false; + status = HttpResponseStatus.OK; + try { + if (DbConstant.admin.isConnected) { + this.dbSession = new DbSession(DbConstant.admin, false); + DbAdmin.nbHttpSession++; + this.isPrivateDbSession = true; + } + } catch (WaarpDatabaseNoConnectionException e1) { + // Cannot connect so use default connection + logger.warn("Use default database connection"); + this.dbSession = DbConstant.admin.session; + } + HttpRequest request = this.request = (HttpRequest) e.getMessage(); + QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request + .getUri()); + uriRequest = queryStringDecoder.getPath(); + logger.debug("Msg: " + uriRequest); + if (uriRequest.contains("gre/") || uriRequest.contains("img/") || + uriRequest.contains("res/")) { + HttpWriteCacheEnable.writeFile(request, + e.getChannel(), Configuration.configuration.httpBasePath + uriRequest, + "XYZR66NOSESSION"); + return; + } + char cval = 'z'; + long nb = LIMITROW; + // check the URI + if (uriRequest.equalsIgnoreCase("/active")) { + cval = '0'; + } else if (uriRequest.equalsIgnoreCase("/error")) { + cval = '1'; + } else if (uriRequest.equalsIgnoreCase("/done")) { + cval = '2'; + } else if (uriRequest.equalsIgnoreCase("/all")) { + cval = '3'; + } else if (uriRequest.equalsIgnoreCase("/status")) { + cval = '4'; + } else if (uriRequest.equalsIgnoreCase("/statusxml")) { + cval = '5'; + nb = 0; // since it could be the default or setup by request + isCurrentRequestXml = true; + } + // Get the params according to get or post + if (request.getMethod() == HttpMethod.GET) { + params = queryStringDecoder.getParameters(); + } else if (request.getMethod() == HttpMethod.POST) { + ChannelBuffer content = request.getContent(); + if (content.readable()) { + String param = content.toString(WaarpStringUtils.UTF8); + queryStringDecoder = new QueryStringDecoder("/?" + param); + } else { + responseContent.append(REQUEST.index.readFileUnique(this)); + writeResponse(e); + return; + } + params = queryStringDecoder.getParameters(); + } + boolean getMenu = (cval == 'z'); + boolean extraBoolean = false; + if (!params.isEmpty()) { + // if not uri, from get or post + if (getMenu) { + String info = getTrimValue(sINFO); + if (info != null) { + getMenu = false; + cval = info.charAt(0); + } else { + getMenu = true; + } + } + // search the nb param + String snb = getTrimValue(sNB); + if (snb != null) { + try { + nb = Long.parseLong(snb); + } catch (Exception e1) { + } + } + // search the detail param + String sdetail = getTrimValue(sDETAIL); + if (sdetail != null) { + try { + if (Integer.parseInt(sdetail) > 0) + extraBoolean = true; + } catch (Exception e1) { + } + } + } + if (getMenu) { + responseContent.append(REQUEST.index.readFileUnique(this)); + } else { + // Use value 0=Active 1=Error 2=Done 3=All + switch (cval) { + case '0': + active(ctx, (int) nb); + break; + case '1': + error(ctx, (int) nb); + break; + case '2': + done(ctx, (int) nb); + break; + case '3': + all(ctx, (int) nb); + break; + case '4': + status(ctx, (int) nb); + break; + case '5': + statusxml(ctx, nb, extraBoolean); + break; + default: + responseContent.append(REQUEST.index.readFileUnique(this)); + } + } + writeResponse(e); + } + + /** + * Add all runners from preparedStatement for type + * + * @param preparedStatement + * @param type + * @param nb + * @throws WaarpDatabaseNoConnectionException + * @throws WaarpDatabaseSqlException + */ + private void addRunners(DbPreparedStatement preparedStatement, String type, + int nb) throws WaarpDatabaseNoConnectionException, + WaarpDatabaseSqlException { + try { + preparedStatement.executeQuery(); + responseContent + .append(""); + responseContent.append(""); + responseContent.append(DbTaskRunner.headerHtml()); + responseContent.append("\r\n"); + int i = 0; + while (preparedStatement.getNext()) { + DbTaskRunner taskRunner = DbTaskRunner + .getFromStatement(preparedStatement); + responseContent.append(""); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + responseContent.append(taskRunner.toHtml(authentHttp, + lcr != null ? "Active" : "NotActive")); + responseContent.append("\r\n"); + if (nb > 0) { + i++; + if (i >= nb) { + break; + } + } + } + responseContent.append("
"); + responseContent.append(type); + responseContent.append("
"); + responseContent.append(taskRunner.isSender() ? "S" : "R"); + responseContent.append("

\r\n"); + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + } + + /** + * print all active transfers + * + * @param ctx + * @param nb + */ + private void active(ChannelHandlerContext ctx, int nb) { + responseContent.append(REQUEST.active.readHeader(this)); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.Running, nb); + addRunners(preparedStatement, ErrorCode.Running.mesg, nb); + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.INTERRUPTED, true, nb); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + addRunners(preparedStatement, UpdatedInfo.INTERRUPTED.name(), nb); + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.TOSUBMIT, true, nb); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + addRunners(preparedStatement, UpdatedInfo.TOSUBMIT.name(), nb); + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.InitOk, nb); + addRunners(preparedStatement, ErrorCode.InitOk.mesg, nb); + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.PreProcessingOk, nb); + addRunners(preparedStatement, ErrorCode.PreProcessingOk.mesg, nb); + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.TransferOk, nb); + addRunners(preparedStatement, ErrorCode.TransferOk.mesg, nb); + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.PostProcessingOk, nb); + addRunners(preparedStatement, ErrorCode.PostProcessingOk.mesg, nb); + preparedStatement = null; + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); + return; + } + responseContent.append(REQUEST.active.readEnd()); + } + + /** + * print all transfers in error + * + * @param ctx + * @param nb + */ + private void error(ChannelHandlerContext ctx, int nb) { + responseContent.append(REQUEST.error.readHeader(this)); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.INERROR, true, nb / 2); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + addRunners(preparedStatement, UpdatedInfo.INERROR.name(), nb / 2); + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.INTERRUPTED, true, nb / 2); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + addRunners(preparedStatement, UpdatedInfo.INTERRUPTED.name(), + nb / 2); + preparedStatement = DbTaskRunner.getStepPrepareStatement(dbSession, + TASKSTEP.ERRORTASK, nb / 4); + addRunners(preparedStatement, TASKSTEP.ERRORTASK.name(), nb / 4); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); + return; + } + responseContent.append(REQUEST.error.readEnd()); + } + + /** + * Print all done transfers + * + * @param ctx + * @param nb + */ + private void done(ChannelHandlerContext ctx, int nb) { + responseContent.append(REQUEST.done.readHeader(this)); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + ErrorCode.CompleteOk, nb); + addRunners(preparedStatement, ErrorCode.CompleteOk.mesg, nb); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); + return; + } + responseContent.append(REQUEST.done.readEnd()); + } + + /** + * Print all nb last transfers + * + * @param ctx + * @param nb + */ + private void all(ChannelHandlerContext ctx, int nb) { + responseContent.append(REQUEST.all.readHeader(this)); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = DbTaskRunner.getStatusPrepareStatement(dbSession, + null, nb);// means all + addRunners(preparedStatement, "ALL RUNNERS: " + nb, nb); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); + return; + } + responseContent.append(REQUEST.all.readEnd()); + } + + /** + * print only status + * + * @param ctx + * @param nb + */ + private void status(ChannelHandlerContext ctx, int nb) { + responseContent.append(REQUEST.status.readHeader(this)); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.INERROR, true, 1); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + try { + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + responseContent.append("

Some Transfers are in ERROR


"); + status = HttpResponseStatus.INTERNAL_SERVER_ERROR; + } + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + preparedStatement = DbTaskRunner.getSelectFromInfoPrepareStatement( + dbSession, UpdatedInfo.INTERRUPTED, true, 1); + DbTaskRunner.finishSelectOrCountPrepareStatement(preparedStatement); + try { + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + responseContent.append("

Some Transfers are INTERRUPTED


"); + status = HttpResponseStatus.INTERNAL_SERVER_ERROR; + } + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + preparedStatement = DbTaskRunner.getStepPrepareStatement(dbSession, + TASKSTEP.ERRORTASK, 1); + try { + preparedStatement.executeQuery(); + if (preparedStatement.getNext()) { + responseContent.append("

Some Transfers are in ERRORTASK


"); + status = HttpResponseStatus.INTERNAL_SERVER_ERROR; + } + } finally { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + } + if (status != HttpResponseStatus.INTERNAL_SERVER_ERROR) { + responseContent.append("

No problem is found in Transfers


"); + } + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); + return; + } + responseContent.append(REQUEST.status.readEnd()); + } + + /** + * print only status + * + * @param ctx + * @param nb + */ + private void statusxml(ChannelHandlerContext ctx, long nb, boolean detail) { + Configuration.configuration.monitoring.run(nb, detail); + responseContent.append(Configuration.configuration.monitoring.exportXml(detail)); + } + + /** + * Write the response + * + * @param e + */ + private void writeResponse(MessageEvent e) { + // Convert the response content to a ChannelBuffer. + ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent + .toString(), WaarpStringUtils.UTF8); + responseContent.setLength(0); + // Decide whether to close the connection or not. + boolean keepAlive = HttpHeaders.isKeepAlive(request); + boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request + .getHeader(HttpHeaders.Names.CONNECTION)) || + (!keepAlive); + + // Build the response object. + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + status); + response.setContent(buf); + if (isCurrentRequestXml) { + response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); + } else { + response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); + } + if (keepAlive) { + response.setHeader(HttpHeaders.Names.CONNECTION, + HttpHeaders.Values.KEEP_ALIVE); + } + if (!close) { + // There's no need to add 'Content-Length' header + // if this is the last response. + response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String + .valueOf(buf.readableBytes())); + } + + String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); + if (cookieString != null) { + CookieDecoder cookieDecoder = new CookieDecoder(); + Set cookies = cookieDecoder.decode(cookieString); + if (!cookies.isEmpty()) { + // Reset the cookies if necessary. + CookieEncoder cookieEncoder = new CookieEncoder(true); + for (Cookie cookie : cookies) { + cookieEncoder.addCookie(cookie); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + cookieEncoder = new CookieEncoder(true); + } + } + } + + // Write the response. + ChannelFuture future = e.getChannel().write(response); + + // Close the connection after the write operation is done if necessary. + if (close) { + future.addListener(ChannelFutureListener.CLOSE); + } + if (this.isPrivateDbSession && dbSession != null) { + dbSession.disconnect(); + DbAdmin.nbHttpSession--; + dbSession = null; + } + } + + /** + * Send an error and close + * + * @param ctx + * @param status + */ + private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + status); + response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); + responseContent.setLength(0); + responseContent.append(REQUEST.error.readHeader(this)); + responseContent.append("OpenR66 Web Failure: "); + responseContent.append(status.toString()); + responseContent.append(REQUEST.error.readEnd()); + response.setContent(ChannelBuffers.copiedBuffer(responseContent + .toString(), WaarpStringUtils.UTF8)); + // Close the connection as soon as the error message is sent. + ctx.getChannel().write(response).addListener( + ChannelFutureListener.CLOSE); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) + throws Exception { + OpenR66Exception exception = OpenR66ExceptionTrappedFactory + .getExceptionFromTrappedException(e.getChannel(), e); + if (exception != null) { + if (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) { + if (e.getCause() instanceof IOException) { + if (this.isPrivateDbSession && dbSession != null) { + dbSession.disconnect(); + DbAdmin.nbHttpSession--; + dbSession = null; + } + // Nothing to do + return; + } + logger.warn("Exception in HttpHandler {}", exception.getMessage()); + } + if (e.getChannel().isConnected()) { + sendError(ctx, HttpResponseStatus.BAD_REQUEST); + } + } else { + if (this.isPrivateDbSession && dbSession != null) { + dbSession.disconnect(); + dbSession = null; + } + // Nothing to do + return; + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelClosed(org + * .jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + logger.debug("Closed"); + super.channelClosed(ctx, e); + if (this.isPrivateDbSession && dbSession != null) { + dbSession.disconnect(); + DbAdmin.nbHttpSession--; + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelConnected + * (org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + logger.debug("Connected"); + authentHttp.getAuth().specialNoSessionAuth(false, Configuration.configuration.HOST_ID); + super.channelConnected(ctx, e); + ChannelGroup group = Configuration.configuration.getHttpChannelGroup(); + if (group != null) { + group.add(e.getChannel()); + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/http/HttpPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/http/HttpPipelineFactory.java index 7c16c659a..122222ff9 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/HttpPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/http/HttpPipelineFactory.java @@ -1,61 +1,61 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.http; - -import static org.jboss.netty.channel.Channels.pipeline; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.handler.codec.http.HttpChunkAggregator; -import org.jboss.netty.handler.codec.http.HttpContentCompressor; -import org.jboss.netty.handler.codec.http.HttpRequestDecoder; -import org.jboss.netty.handler.codec.http.HttpResponseEncoder; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.jboss.netty.handler.stream.ChunkedWriteHandler; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * Pipeline Factory for HTTP support - * - * @author Frederic Bregier - * - */ -public class HttpPipelineFactory implements ChannelPipelineFactory { - public boolean useHttpCompression = false; - - public HttpPipelineFactory(boolean useHttpCompression) { - this.useHttpCompression = useHttpCompression; - } - - public ChannelPipeline getPipeline() throws Exception { - // Create a default pipeline implementation. - ChannelPipeline pipeline = pipeline(); - - pipeline.addLast("decoder", new HttpRequestDecoder()); - pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); - pipeline.addLast("encoder", new HttpResponseEncoder()); - pipeline.addLast("pipelineExecutor", new ExecutionHandler( - Configuration.configuration.getHttpPipelineExecutor())); - pipeline.addLast("streamer", new ChunkedWriteHandler()); - if (useHttpCompression) { - pipeline.addLast("deflater", new HttpContentCompressor()); - } - pipeline.addLast("handler", new HttpFormattedHandler()); - return pipeline; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.http; + +import static org.jboss.netty.channel.Channels.pipeline; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.handler.codec.http.HttpChunkAggregator; +import org.jboss.netty.handler.codec.http.HttpContentCompressor; +import org.jboss.netty.handler.codec.http.HttpRequestDecoder; +import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.jboss.netty.handler.stream.ChunkedWriteHandler; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * Pipeline Factory for HTTP support + * + * @author Frederic Bregier + * + */ +public class HttpPipelineFactory implements ChannelPipelineFactory { + public boolean useHttpCompression = false; + + public HttpPipelineFactory(boolean useHttpCompression) { + this.useHttpCompression = useHttpCompression; + } + + public ChannelPipeline getPipeline() throws Exception { + // Create a default pipeline implementation. + ChannelPipeline pipeline = pipeline(); + + pipeline.addLast("decoder", new HttpRequestDecoder()); + pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); + pipeline.addLast("encoder", new HttpResponseEncoder()); + pipeline.addLast("pipelineExecutor", new ExecutionHandler( + Configuration.configuration.getHttpPipelineExecutor())); + pipeline.addLast("streamer", new ChunkedWriteHandler()); + if (useHttpCompression) { + pipeline.addLast("deflater", new HttpContentCompressor()); + } + pipeline.addLast("handler", new HttpFormattedHandler()); + return pipeline; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/http/HttpWriteCacheEnable.java b/src/main/java/org/waarp/openr66/protocol/http/HttpWriteCacheEnable.java index 27d95c0c8..d0131ed97 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/HttpWriteCacheEnable.java +++ b/src/main/java/org/waarp/openr66/protocol/http/HttpWriteCacheEnable.java @@ -1,129 +1,129 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.http; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Set; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.handler.codec.http.Cookie; -import org.jboss.netty.handler.codec.http.CookieDecoder; -import org.jboss.netty.handler.codec.http.CookieEncoder; -import org.jboss.netty.handler.codec.http.DefaultHttpResponse; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.handler.codec.http.HttpRequest; -import org.jboss.netty.handler.codec.http.HttpResponse; -import org.jboss.netty.handler.codec.http.HttpResponseStatus; -import org.jboss.netty.handler.codec.http.HttpVersion; -import org.jboss.netty.handler.stream.ChunkedNioFile; - -/** - * - * Utility class to write external file with cache enable properties - * - * @author Frederic Bregier - * - */ -public class HttpWriteCacheEnable { - - /** - * Write a file, taking into account cache enabled and removing session cookie - * - * @param request - * @param channel - * @param filename - * @param cookieNameToRemove - */ - public static void writeFile(HttpRequest request, Channel channel, String filename, - String cookieNameToRemove) { - // Convert the response content to a ChannelBuffer. - HttpResponse response; - if (request.containsHeader(HttpHeaders.Names.IF_MODIFIED_SINCE)) { - response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.NOT_MODIFIED); - handleCookies(request, response, cookieNameToRemove); - channel.write(response); - return; - } - File file = new File(filename); - if (!file.isFile() || !file.canRead()) { - response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.NOT_FOUND); - handleCookies(request, response, cookieNameToRemove); - channel.write(response); - return; - } - long size = file.length(); - ChunkedNioFile nioFile; - try { - nioFile = new ChunkedNioFile(file); - } catch (IOException e) { - response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.NOT_FOUND); - handleCookies(request, response, cookieNameToRemove); - channel.write(response); - return; - } - response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.OK); - response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, - String.valueOf(size)); - ArrayList cache_control = new ArrayList(2); - cache_control.add(HttpHeaders.Values.PUBLIC); - cache_control.add(HttpHeaders.Values.MAX_AGE + "=" + 31536000);// 1 year - response.setHeader(HttpHeaders.Names.CACHE_CONTROL, cache_control); - response.setHeader(HttpHeaders.Names.LAST_MODIFIED, - "Tue, 15 Nov 1994 12:45:26 GMT"); - handleCookies(request, response, cookieNameToRemove); - // Write the response. - channel.write(response); - channel.write(nioFile); - } - - /** - * Remove the given named cookie - * - * @param request - * @param response - * @param cookieNameToRemove - */ - public static void handleCookies(HttpRequest request, HttpResponse response, - String cookieNameToRemove) { - String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); - if (cookieString != null) { - CookieDecoder cookieDecoder = new CookieDecoder(); - Set cookies = cookieDecoder.decode(cookieString); - if (!cookies.isEmpty()) { - // Reset the sessions if necessary. - CookieEncoder cookieEncoder = new CookieEncoder(true); - // Remove all Session for images - for (Cookie cookie : cookies) { - if (cookie.getName().equalsIgnoreCase(cookieNameToRemove)) { - } else { - cookieEncoder.addCookie(cookie); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - cookieEncoder = new CookieEncoder(true); - } - } - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.http; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Set; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.handler.codec.http.Cookie; +import org.jboss.netty.handler.codec.http.CookieDecoder; +import org.jboss.netty.handler.codec.http.CookieEncoder; +import org.jboss.netty.handler.codec.http.DefaultHttpResponse; +import org.jboss.netty.handler.codec.http.HttpHeaders; +import org.jboss.netty.handler.codec.http.HttpRequest; +import org.jboss.netty.handler.codec.http.HttpResponse; +import org.jboss.netty.handler.codec.http.HttpResponseStatus; +import org.jboss.netty.handler.codec.http.HttpVersion; +import org.jboss.netty.handler.stream.ChunkedNioFile; + +/** + * + * Utility class to write external file with cache enable properties + * + * @author Frederic Bregier + * + */ +public class HttpWriteCacheEnable { + + /** + * Write a file, taking into account cache enabled and removing session cookie + * + * @param request + * @param channel + * @param filename + * @param cookieNameToRemove + */ + public static void writeFile(HttpRequest request, Channel channel, String filename, + String cookieNameToRemove) { + // Convert the response content to a ChannelBuffer. + HttpResponse response; + if (request.containsHeader(HttpHeaders.Names.IF_MODIFIED_SINCE)) { + response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + HttpResponseStatus.NOT_MODIFIED); + handleCookies(request, response, cookieNameToRemove); + channel.write(response); + return; + } + File file = new File(filename); + if (!file.isFile() || !file.canRead()) { + response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + HttpResponseStatus.NOT_FOUND); + handleCookies(request, response, cookieNameToRemove); + channel.write(response); + return; + } + long size = file.length(); + ChunkedNioFile nioFile; + try { + nioFile = new ChunkedNioFile(file); + } catch (IOException e) { + response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + HttpResponseStatus.NOT_FOUND); + handleCookies(request, response, cookieNameToRemove); + channel.write(response); + return; + } + response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, + HttpResponseStatus.OK); + response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, + String.valueOf(size)); + ArrayList cache_control = new ArrayList(2); + cache_control.add(HttpHeaders.Values.PUBLIC); + cache_control.add(HttpHeaders.Values.MAX_AGE + "=" + 31536000);// 1 year + response.setHeader(HttpHeaders.Names.CACHE_CONTROL, cache_control); + response.setHeader(HttpHeaders.Names.LAST_MODIFIED, + "Tue, 15 Nov 1994 12:45:26 GMT"); + handleCookies(request, response, cookieNameToRemove); + // Write the response. + channel.write(response); + channel.write(nioFile); + } + + /** + * Remove the given named cookie + * + * @param request + * @param response + * @param cookieNameToRemove + */ + public static void handleCookies(HttpRequest request, HttpResponse response, + String cookieNameToRemove) { + String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); + if (cookieString != null) { + CookieDecoder cookieDecoder = new CookieDecoder(); + Set cookies = cookieDecoder.decode(cookieString); + if (!cookies.isEmpty()) { + // Reset the sessions if necessary. + CookieEncoder cookieEncoder = new CookieEncoder(true); + // Remove all Session for images + for (Cookie cookie : cookies) { + if (cookie.getName().equalsIgnoreCase(cookieNameToRemove)) { + } else { + cookieEncoder.addCookie(cookie); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + cookieEncoder = new CookieEncoder(true); + } + } + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslHandler.java b/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslHandler.java index e7f895f93..309b0be3c 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslHandler.java @@ -1,1977 +1,1977 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.http.adminssl; - -import java.io.IOException; -import java.net.SocketAddress; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelUpstreamHandler; -import org.jboss.netty.handler.codec.http.Cookie; -import org.jboss.netty.handler.codec.http.CookieDecoder; -import org.jboss.netty.handler.codec.http.CookieEncoder; -import org.jboss.netty.handler.codec.http.DefaultCookie; -import org.jboss.netty.handler.codec.http.DefaultHttpResponse; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.handler.codec.http.HttpMethod; -import org.jboss.netty.handler.codec.http.HttpRequest; -import org.jboss.netty.handler.codec.http.HttpResponse; -import org.jboss.netty.handler.codec.http.HttpResponseStatus; -import org.jboss.netty.handler.codec.http.HttpVersion; -import org.jboss.netty.handler.codec.http.QueryStringDecoder; -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.exception.FileTransferException; -import org.waarp.common.exception.InvalidArgumentException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.utility.WaarpStringUtils; -import org.waarp.openr66.client.Message; -import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; -import org.waarp.openr66.configuration.RuleFileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.http.HttpWriteCacheEnable; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; -import org.waarp.openr66.protocol.localhandler.packet.TestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.NbAndSpecialId; -import org.waarp.openr66.protocol.utils.R66Future; -import org.waarp.openr66.protocol.utils.TransferUtils; -import org.waarp.openr66.protocol.utils.Version; - -/** - * @author Frederic Bregier - * - */ -public class HttpSslHandler extends SimpleChannelUpstreamHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(HttpSslHandler.class); - /** - * Session Management - */ - private static final ConcurrentHashMap sessions = new ConcurrentHashMap(); - private static final ConcurrentHashMap dbSessions = new ConcurrentHashMap(); - private volatile R66Session authentHttp = new R66Session(); - - private volatile HttpRequest request; - private volatile boolean newSession = false; - private volatile Cookie admin = null; - private final StringBuilder responseContent = new StringBuilder(); - private volatile String uriRequest; - private volatile Map> params; - private volatile QueryStringDecoder queryStringDecoder; - private volatile boolean forceClose = false; - private volatile boolean shutdown = false; - - private static final String R66SESSION = "R66SESSION"; - - private static enum REQUEST { - Logon("Logon.html"), - index("index.html"), - error("error.html"), - Transfers("Transfers.html"), - Listing("Listing_head.html", "Listing_body0.html", "Listing_body.html", - "Listing_body1.html", "Listing_end.html"), - CancelRestart("CancelRestart_head.html", "CancelRestart_body0.html", - "CancelRestart_body.html", "CancelRestart_body1.html", "CancelRestart_end.html"), - Export("Export.html"), - Hosts("Hosts_head.html", "Hosts_body0.html", "Hosts_body.html", "Hosts_body1.html", - "Hosts_end.html"), - Rules("Rules_head.html", "Rules_body0.html", "Rules_body.html", "Rules_body1.html", - "Rules_end.html"), - System("System.html"); - - private String header; - private String headerBody; - private String body; - private String endBody; - private String end; - - /** - * Constructor for a unique file - * - * @param uniquefile - */ - private REQUEST(String uniquefile) { - this.header = uniquefile; - this.headerBody = null; - this.body = null; - this.endBody = null; - this.end = null; - } - - /** - * @param header - * @param headerBody - * @param body - * @param endBody - * @param end - */ - private REQUEST(String header, String headerBody, String body, - String endBody, String end) { - this.header = header; - this.headerBody = headerBody; - this.body = body; - this.endBody = endBody; - this.end = end; - } - - /** - * Reader for a unique file - * - * @return the content of the unique file - */ - public String readFileUnique(HttpSslHandler handler) { - return handler.readFileHeader(Configuration.configuration.httpBasePath + this.header); - } - - public String readHeader(HttpSslHandler handler) { - return handler.readFileHeader(Configuration.configuration.httpBasePath + this.header); - } - - public String readBodyHeader() { - return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath - + this.headerBody); - } - - public String readBody() { - return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + this.body); - } - - public String readBodyEnd() { - return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath - + this.endBody); - } - - public String readEnd() { - return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + this.end); - } - } - - private static enum REPLACEMENT { - XXXHOSTIDXXX, XXXADMINXXX, XXXVERSIONXXX, XXXBANDWIDTHXXX, - XXXXSESSIONLIMITRXXX, XXXXSESSIONLIMITWXXX, - XXXXCHANNELLIMITRXXX, XXXXCHANNELLIMITWXXX, - XXXXDELAYCOMMDXXX, XXXXDELAYRETRYXXX, - XXXLOCALXXX, XXXNETWORKXXX, - XXXERRORMESGXXX; - } - - public static final int LIMITROW = 48; // better if it can - // be divided by 4 - - /** - * The Database connection attached to this NetworkChannel shared among all associated - * LocalChannels in the session - */ - private volatile DbSession dbSession = null; - /** - * Does this dbSession is private and so should be closed - */ - private volatile boolean isPrivateDbSession = false; - - private String readFileHeader(String filename) { - String value; - try { - value = WaarpStringUtils.readFileException(filename); - } catch (InvalidArgumentException e) { - logger.error("Error while trying to open: " + filename, e); - return ""; - } catch (FileTransferException e) { - logger.error("Error while trying to read: " + filename, e); - return ""; - } - StringBuilder builder = new StringBuilder(value); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXLOCALXXX.toString(), - Integer.toString( - Configuration.configuration.getLocalTransaction(). - getNumberLocalChannel()) + " " + Thread.activeCount()); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXNETWORKXXX.toString(), - Integer.toString( - DbAdmin.getNbConnection())); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), - Configuration.configuration.HOST_ID); - if (authentHttp.isAuthenticated()) { - WaarpStringUtils.replace(builder, REPLACEMENT.XXXADMINXXX.toString(), - "Connected"); - } else { - WaarpStringUtils.replace(builder, REPLACEMENT.XXXADMINXXX.toString(), - "Not authenticated"); - } - TrafficCounter trafficCounter = - Configuration.configuration.getGlobalTrafficShapingHandler().getTrafficCounter(); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXBANDWIDTHXXX.toString(), - "IN:" + (trafficCounter.getLastReadThroughput() >> 17) + - "Mbits 
 OUT:" + - (trafficCounter.getLastWriteThroughput() >> 17) + "Mbits"); - return builder.toString(); - } - - private String getTrimValue(String varname) { - String value = params.get(varname).get(0).trim(); - if (value.length() == 0) { - value = null; - } - return value; - } - - private String getValue(String varname) { - return params.get(varname).get(0); - } - - private String index() { - String index = REQUEST.index.readFileUnique(this); - StringBuilder builder = new StringBuilder(index); - WaarpStringUtils.replaceAll(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), - Configuration.configuration.HOST_ID); - WaarpStringUtils.replaceAll(builder, REPLACEMENT.XXXADMINXXX.toString(), - "Administrator Connected"); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXVERSIONXXX.toString(), - Version.ID); - return builder.toString(); - } - - private String error(String mesg) { - String index = REQUEST.error.readFileUnique(this); - return index.replaceAll(REPLACEMENT.XXXERRORMESGXXX.toString(), - mesg); - } - - private String Logon() { - return REQUEST.Logon.readFileUnique(this); - } - - private String Transfers() { - return REQUEST.Transfers.readFileUnique(this); - } - - private String resetOptionTransfer(String header, String startid, String stopid, - String start, String stop, String rule, String req, - boolean pending, boolean transfer, boolean error, boolean done, boolean all) { - StringBuilder builder = new StringBuilder(header); - WaarpStringUtils.replace(builder, "XXXSTARTIDXXX", startid); - WaarpStringUtils.replace(builder, "XXXSTOPIDXXX", stopid); - WaarpStringUtils.replace(builder, "XXXSTARTXXX", start); - WaarpStringUtils.replace(builder, "XXXSTOPXXX", stop); - WaarpStringUtils.replace(builder, "XXXRULEXXX", rule); - WaarpStringUtils.replace(builder, "XXXREQXXX", req); - WaarpStringUtils.replace(builder, "XXXPENDXXX", pending ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXTRANSXXX", transfer ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXERRXXX", error ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXDONEXXX", done ? "checked" : ""); - WaarpStringUtils.replace(builder, "XXXALLXXX", all ? "checked" : ""); - return builder.toString(); - } - - private String Listing() { - getParams(); - if (params == null) { - String head = REQUEST.Listing.readHeader(this); - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - String end = REQUEST.Listing.readEnd(); - return head + end; - } - String head = REQUEST.Listing.readHeader(this); - String body0, body, body1; - body0 = body1 = body = ""; - List parms = params.get("ACTION"); - if (parms != null) { - body0 = REQUEST.Listing.readBodyHeader(); - String parm = parms.get(0); - if ("Filter".equalsIgnoreCase(parm)) { - String startid = getTrimValue("startid"); - String stopid = getTrimValue("stopid"); - if (startid != null && stopid == null) { - try { - stopid = Long.toString(Long.parseLong(startid)+(LIMITROW/2)); - } catch (NumberFormatException e) { - stopid = null; - startid = null; - } - } - if (stopid != null && startid == null) { - try { - startid = Long.toString(Long.parseLong(stopid) - (LIMITROW / 2)); - } catch (NumberFormatException e) { - stopid = null; - startid = null; - } - } - String start = getValue("start"); - String stop = getValue("stop"); - String rule = getTrimValue("rule"); - String req = getTrimValue("req"); - boolean pending, transfer, error, done, all; - pending = params.containsKey("pending"); - transfer = params.containsKey("transfer"); - error = params.containsKey("error"); - done = params.containsKey("done"); - all = params.containsKey("all"); - if (pending && transfer && error && done) { - all = true; - } else if (!(pending || transfer || error || done)) { - all = true; - } - Timestamp tstart = WaarpStringUtils.fixDate(start); - if (tstart != null) { - start = tstart.toString(); - } - Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); - if (tstop != null) { - stop = tstop.toString(); - } - head = resetOptionTransfer(head, startid == null ? "" : startid, - stopid == null ? "" : stopid, start, stop, - rule == null ? "" : rule, req == null ? "" : req, - pending, transfer, error, done, all); - body = REQUEST.Listing.readBody(); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, - startid, stopid, tstart, tstop, rule, req, - pending, transfer, error, done, all); - preparedStatement.executeQuery(); - StringBuilder builder = new StringBuilder(); - int i = 0; - while (preparedStatement.getNext()) { - try { - i++; - DbTaskRunner taskRunner = DbTaskRunner - .getFromStatement(preparedStatement); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - builder.append(taskRunner.toSpecializedHtml(authentHttp, body, - lcr != null ? "Active" : "NotActive")); - if (i > LIMITROW) { - break; - } - } catch (WaarpDatabaseException e) { - // try to continue if possible - logger.warn("An error occurs while accessing a Runner: {}", - e.getMessage()); - continue; - } - } - preparedStatement.realClose(); - body = builder.toString(); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - } - } else { - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - } - body1 = REQUEST.Listing.readBodyEnd(); - } else { - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - } - String end; - end = REQUEST.Listing.readEnd(); - return head + body0 + body + body1 + end; - } - - private String CancelRestart() { - getParams(); - if (params == null) { - String head = REQUEST.CancelRestart.readHeader(this); - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - String end; - end = REQUEST.CancelRestart.readEnd(); - return head + end; - } - String head = REQUEST.CancelRestart.readHeader(this); - String body0, body, body1; - body0 = body1 = body = ""; - List parms = params.get("ACTION"); - if (parms != null) { - body0 = REQUEST.CancelRestart.readBodyHeader(); - String parm = parms.get(0); - if ("Filter".equalsIgnoreCase(parm)) { - String startid = getTrimValue("startid"); - String stopid = getTrimValue("stopid"); - if (startid != null && stopid == null) { - try { - stopid = Long.toString(Long.parseLong(startid)+(LIMITROW/2)); - } catch (NumberFormatException e) { - stopid = null; - startid = null; - } - } - if (stopid != null && startid == null) { - try { - startid = Long.toString(Long.parseLong(stopid) - (LIMITROW / 2)); - } catch (NumberFormatException e) { - stopid = null; - startid = null; - } - } - String start = getValue("start"); - String stop = getValue("stop"); - String rule = getTrimValue("rule"); - String req = getTrimValue("req"); - boolean pending, transfer, error, done, all; - pending = params.containsKey("pending"); - transfer = params.containsKey("transfer"); - error = params.containsKey("error"); - done = params.containsKey("done"); - all = params.containsKey("all"); - if (pending && transfer && error && done) { - all = true; - } else if (!(pending || transfer || error || done)) { - all = true; - } - Timestamp tstart = WaarpStringUtils.fixDate(start); - if (tstart != null) { - start = tstart.toString(); - } - Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); - if (tstop != null) { - stop = tstop.toString(); - } - head = resetOptionTransfer(head, startid == null ? "" : startid, - stopid == null ? "" : stopid, start, stop, - rule == null ? "" : rule, req == null ? "" : req, - pending, transfer, error, done, all); - body = REQUEST.CancelRestart.readBody(); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, - startid, stopid, tstart, tstop, rule, req, - pending, transfer, error, done, all); - preparedStatement.executeQuery(); - StringBuilder builder = new StringBuilder(); - int i = 0; - while (preparedStatement.getNext()) { - try { - i++; - DbTaskRunner taskRunner = DbTaskRunner - .getFromStatement(preparedStatement); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - builder.append(taskRunner.toSpecializedHtml(authentHttp, body, - lcr != null ? "Active" : "NotActive")); - if (i > LIMITROW) { - break; - } - } catch (WaarpDatabaseException e) { - // try to continue if possible - logger.warn("An error occurs while accessing a Runner: {}", - e.getMessage()); - continue; - } - } - preparedStatement.realClose(); - body = builder.toString(); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - } - body1 = REQUEST.CancelRestart.readBodyEnd(); - } else if ("RestartAll".equalsIgnoreCase(parm) || - "StopAll".equalsIgnoreCase(parm)) { - boolean stopcommand = "StopAll".equalsIgnoreCase(parm); - String startid = getTrimValue("startid"); - String stopid = getTrimValue("stopid"); - String start = getValue("start"); - String stop = getValue("stop"); - String rule = getTrimValue("rule"); - String req = getTrimValue("req"); - boolean pending, transfer, error, done, all; - pending = params.containsKey("pending"); - transfer = params.containsKey("transfer"); - error = params.containsKey("error"); - done = false; - all = false; - if (pending && transfer && error && done) { - all = true; - } else if (!(pending || transfer || error || done)) { - all = true; - pending = true; - transfer = true; - error = true; - } - Timestamp tstart = WaarpStringUtils.fixDate(start); - if (tstart != null) { - start = tstart.toString(); - } - Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); - if (tstop != null) { - stop = tstop.toString(); - } - head = resetOptionTransfer(head, startid == null ? "" : startid, - stopid == null ? "" : stopid, start, stop, - rule == null ? "" : rule, req == null ? "" : req, - pending, transfer, error, done, all); - body = REQUEST.CancelRestart.readBody(); - StringBuilder builder = new StringBuilder(); - if (stopcommand) { - builder = TransferUtils.stopSelectedTransfers(dbSession, LIMITROW, builder, - authentHttp, body, startid, stopid, tstart, tstop, rule, req, - pending, transfer, error); - } else { - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, - startid, stopid, tstart, tstop, rule, req, - pending, transfer, error, done, all); - preparedStatement.executeQuery(); - int i = 0; - while (preparedStatement.getNext()) { - try { - i++; - DbTaskRunner taskRunner = DbTaskRunner - .getFromStatement(preparedStatement); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - R66Result finalResult = TransferUtils.restartTransfer(taskRunner, - lcr); - ErrorCode result = finalResult.code; - ErrorCode last = taskRunner.getErrorInfo(); - taskRunner.setErrorExecutionStatus(result); - builder.append(taskRunner.toSpecializedHtml(authentHttp, body, - lcr != null ? "Active" : "NotActive")); - taskRunner.setErrorExecutionStatus(last); - if (i > LIMITROW) { - break; - } - } catch (WaarpDatabaseException e) { - // try to continue if possible - logger.warn("An error occurs while accessing a Runner: {}", - e.getMessage()); - continue; - } - } - preparedStatement.realClose(); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - } - } - if (builder != null) { - body = builder.toString(); - } else { - body = ""; - } - body1 = REQUEST.CancelRestart.readBodyEnd(); - } else if ("Cancel".equalsIgnoreCase(parm) || "Stop".equalsIgnoreCase(parm)) { - // Cancel or Stop - boolean stop = "Stop".equalsIgnoreCase(parm); - String specid = getValue("specid"); - String reqd = getValue("reqd"); - String reqr = getValue("reqr"); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(reqd + " " + reqr + " " + specid); - // stop the current transfer - ErrorCode result; - long lspecid; - try { - lspecid = Long.parseLong(specid); - } catch (NumberFormatException e) { - body = ""; - body1 = REQUEST.CancelRestart.readBodyEnd(); - body1 += "
"+parm+" aborted since Transfer is not found"; - String end; - end = REQUEST.CancelRestart.readEnd(); - return head+body0+body+body1+end; - } - DbTaskRunner taskRunner = null; - try { - taskRunner = new DbTaskRunner(dbSession, authentHttp, null, - lspecid, reqr, reqd); - } catch (WaarpDatabaseException e) { - } - if (taskRunner == null) { - body = ""; - body1 = REQUEST.CancelRestart.readBodyEnd(); - body1 += "
" + parm + " aborted since Transfer is not found"; - String end; - end = REQUEST.CancelRestart.readEnd(); - return head + body0 + body + body1 + end; - } - ErrorCode code = (stop) ? - ErrorCode.StoppedTransfer : ErrorCode.CanceledTransfer; - if (lcr != null) { - int rank = taskRunner.getRank(); - lcr.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket("Transfer " + parm + " " + rank, - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - // XXX ChannelUtils.writeAbstractLocalPacket(lcr, error); - // inform local instead of remote - ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); - } catch (Exception e) { - } - result = ErrorCode.CompleteOk; - } else { - // Transfer is not running - // But is the database saying the contrary - result = ErrorCode.TransferOk; - if (taskRunner != null) { - if (taskRunner.stopOrCancelRunner(code)) { - result = ErrorCode.CompleteOk; - } - } - } - if (taskRunner != null) { - body = REQUEST.CancelRestart.readBody(); - body = taskRunner.toSpecializedHtml(authentHttp, body, - lcr != null ? "Active" : "NotActive"); - String tstart = taskRunner.getStart().toString(); - tstart = tstart.substring(0, tstart.length()); - String tstop = taskRunner.getStop().toString(); - tstop = tstop.substring(0, tstop.length()); - head = resetOptionTransfer(head, (taskRunner.getSpecialId() - 1) + "", - (taskRunner.getSpecialId() + 1) + "", tstart, tstop, - taskRunner.getRuleId(), taskRunner.getRequested(), - false, false, false, false, true); - } - body1 = REQUEST.CancelRestart.readBodyEnd(); - body1 += "
" + (result == ErrorCode.CompleteOk ? parm + " transmitted" : - parm + " aborted since Transfer is not running") + ""; - } else if ("Restart".equalsIgnoreCase(parm)) { - // Restart - String specid = getValue("specid"); - String reqd = getValue("reqd"); - String reqr = getValue("reqr"); - long lspecid; - try { - lspecid = Long.parseLong(specid); - } catch (NumberFormatException e) { - body = ""; - body1 = REQUEST.CancelRestart.readBodyEnd(); - body1 += "
"+parm+" aborted since Transfer is not found"; - String end; - end = REQUEST.CancelRestart.readEnd(); - return head+body0+body+body1+end; - } - DbTaskRunner taskRunner; - String comment; - try { - taskRunner = new DbTaskRunner(dbSession, authentHttp, null, - lspecid, reqr, reqd); - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - R66Result finalResult = TransferUtils.restartTransfer(taskRunner, lcr); - comment = (String) finalResult.other; - body = REQUEST.CancelRestart.readBody(); - body = taskRunner.toSpecializedHtml(authentHttp, body, - lcr != null ? "Active" : "NotActive"); - String tstart = taskRunner.getStart().toString(); - tstart = tstart.substring(0, tstart.length()); - String tstop = taskRunner.getStop().toString(); - tstop = tstop.substring(0, tstop.length()); - head = resetOptionTransfer(head, (taskRunner.getSpecialId() - 1) + "", - (taskRunner.getSpecialId() + 1) + "", tstart, tstop, - taskRunner.getRuleId(), taskRunner.getRequested(), - false, false, false, false, true); - } catch (WaarpDatabaseException e) { - body = ""; - comment = "Internal error"; - } - body1 = REQUEST.CancelRestart.readBodyEnd(); - body1 += "
" + comment + ""; - } else { - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - } - } else { - head = resetOptionTransfer(head, "", "", "", "", "", "", - false, false, false, false, true); - } - String end; - end = REQUEST.CancelRestart.readEnd(); - return head + body0 + body + body1 + end; - } - - private String Export() { - getParams(); - if (params == null) { - String body = REQUEST.Export.readFileUnique(this); - body = resetOptionTransfer(body, "", "", "", "", "", "", - false, false, false, true, false); - return body.replace("XXXRESULTXXX", ""); - } - String body = REQUEST.Export.readFileUnique(this); - String start = getValue("start"); - String stop = getValue("stop"); - String rule = getTrimValue("rule"); - String req = getTrimValue("req"); - boolean pending, transfer, error, done, all; - pending = params.containsKey("pending"); - transfer = params.containsKey("transfer"); - error = params.containsKey("error"); - done = params.containsKey("done"); - all = params.containsKey("all"); - boolean toPurge = params.containsKey("purge"); - if (toPurge) { - transfer = false; - } - if (pending && transfer && error && done) { - all = true; - } else if (!(pending || transfer || error || done)) { - all = true; - } - Timestamp tstart = WaarpStringUtils.fixDate(start); - if (tstart != null) { - start = tstart.toString(); - } - Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); - if (tstop != null) { - stop = tstop.toString(); - } - body = resetOptionTransfer(body, "", "", start, stop, - rule == null ? "" : rule, req == null ? "" : req, - pending, transfer, error, done, all); - boolean isexported = true; - // clean a bit the database before exporting - try { - DbTaskRunner.changeFinishedToDone(dbSession); - } catch (WaarpDatabaseNoConnectionException e2) { - // should not be - } - // create export of log and optionally purge them from database - DbPreparedStatement getValid = null; - NbAndSpecialId nbAndSpecialId = null; - String filename = Configuration.configuration.baseDirectory + - Configuration.configuration.archivePath + R66Dir.SEPARATOR + - Configuration.configuration.HOST_ID + "_" + System.currentTimeMillis() + - "_runners.xml"; - try { - getValid = - DbTaskRunner.getFilterPrepareStatement(dbSession, 0,// 0 means no limit - true, null, null, tstart, tstop, rule, req, - pending, transfer, error, done, all); - nbAndSpecialId = DbTaskRunner.writeXMLWriter(getValid, filename); - } catch (WaarpDatabaseNoConnectionException e1) { - isexported = false; - toPurge = false; - } catch (WaarpDatabaseSqlException e1) { - isexported = false; - toPurge = false; - } catch (OpenR66ProtocolBusinessException e) { - isexported = false; - toPurge = false; - } finally { - if (getValid != null) { - getValid.realClose(); - } - } - int purge = 0; - if (isexported && nbAndSpecialId != null) { - if (nbAndSpecialId.nb <= 0) { - return body.replace("XXXRESULTXXX", - "Export unsuccessful since no records were found"); - } - // in case of purge - if (isexported && toPurge) { - // purge with same filter all runners where globallasttep - // is ALLDONE or ERROR - // but getting the higher Special first - String stopId = Long.toString(nbAndSpecialId.higherSpecialId); - try { - purge = - DbTaskRunner.purgeLogPrepareStatement(dbSession, - null, stopId, tstart, tstop, rule, req, - pending, transfer, error, done, all); - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } - } - } - return body.replace("XXXRESULTXXX", "Export " - + (isexported ? "successful into " + - filename + " with " + nbAndSpecialId.nb + " exported and " + purge - + " purged records" : - "in error")); - } - - private String resetOptionHosts(String header, - String host, String addr, boolean ssl) { - StringBuilder builder = new StringBuilder(header); - WaarpStringUtils.replace(builder, "XXXFHOSTXXX", host); - WaarpStringUtils.replace(builder, "XXXFADDRXXX", addr); - WaarpStringUtils.replace(builder, "XXXFSSLXXX", ssl ? "checked" : ""); - return builder.toString(); - } - - private String Hosts() { - getParams(); - String head = REQUEST.Hosts.readHeader(this); - String end; - end = REQUEST.Hosts.readEnd(); - if (params == null) { - head = resetOptionHosts(head, "", "", false); - return head + end; - } - String body0, body, body1; - body0 = body1 = body = ""; - List parms = params.get("ACTION"); - if (parms != null) { - body0 = REQUEST.Hosts.readBodyHeader(); - String parm = parms.get(0); - if ("Create".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - String addr = getTrimValue("address"); - String port = getTrimValue("port"); - String key = getTrimValue("hostkey"); - boolean ssl, admin, isclient; - ssl = params.containsKey("ssl"); - admin = params.containsKey("admin"); - isclient = params.containsKey("isclient"); - if (host == null || addr == null || port == null || key == null) { - body0 = body1 = body = ""; - body = "

Not enough data to create a Host

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - head = resetOptionHosts(head, host, addr, ssl); - int iport; - try { - iport = Integer.parseInt(port); - } catch (NumberFormatException e1) { - body0 = body1 = body = ""; - body = "

Cannot create a Host: "+e1.getMessage()+"

"; - head = resetOptionHosts(head, "", "", false); - return head+body0+body+body1+end; - } - DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, - ssl, key.getBytes(), admin, isclient); - try { - dbhost.insert(); - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot create a Host: " + e.getMessage() - + "

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - body = REQUEST.Hosts.readBody(); - body = dbhost.toSpecializedHtml(authentHttp, body, false); - } else if ("Filter".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - String addr = getTrimValue("address"); - boolean ssl = params.containsKey("ssl"); - head = resetOptionHosts(head, host == null ? "" : host, - addr == null ? "" : addr, ssl); - body = REQUEST.Hosts.readBody(); - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbHostAuth.getFilterPrepareStament(dbSession, - host, addr, ssl); - preparedStatement.executeQuery(); - StringBuilder builder = new StringBuilder(); - int i = 0; - while (preparedStatement.getNext()) { - i++; - DbHostAuth dbhost = DbHostAuth.getFromStatement(preparedStatement); - builder.append(dbhost.toSpecializedHtml(authentHttp, body, false)); - if (i > LIMITROW) { - break; - } - } - preparedStatement.realClose(); - body = builder.toString(); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - } - body1 = REQUEST.Hosts.readBodyEnd(); - } else if ("Update".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - String addr = getTrimValue("address"); - String port = getTrimValue("port"); - String key = getTrimValue("hostkey"); - boolean ssl, admin, isclient; - ssl = params.containsKey("ssl"); - admin = params.containsKey("admin"); - isclient = params.containsKey("isclient"); - if (host == null || addr == null || port == null || key == null) { - body0 = body1 = body = ""; - body = "

Not enough data to update a Host

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - head = resetOptionHosts(head, host, addr, ssl); - int iport; - try { - iport = Integer.parseInt(port); - } catch (NumberFormatException e1) { - body0 = body1 = body = ""; - body = "

Cannot Update a Host: "+e1.getMessage()+"

"; - head = resetOptionHosts(head, "", "", false); - return head+body0+body+body1+end; - } - DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, - ssl, key.getBytes(), admin, isclient); - try { - if (dbhost.exist()) { - dbhost.update(); - } else { - dbhost.insert(); - } - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot update a Host: " + e.getMessage() - + "

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - body = REQUEST.Hosts.readBody(); - body = dbhost.toSpecializedHtml(authentHttp, body, false); - } else if ("TestConn".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - String addr = getTrimValue("address"); - String port = getTrimValue("port"); - String key = getTrimValue("hostkey"); - boolean ssl, admin, isclient; - ssl = params.containsKey("ssl"); - admin = params.containsKey("admin"); - isclient = params.containsKey("isclient"); - head = resetOptionHosts(head, host, addr, ssl); - int iport; - try { - iport = Integer.parseInt(port); - } catch (NumberFormatException e1) { - body0 = body1 = body = ""; - body = "

Cannot find a Host: "+e1.getMessage()+"

"; - head = resetOptionHosts(head, "", "", false); - return head+body0+body+body1+end; - } - DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, - ssl, key.getBytes(), admin, isclient); - R66Future result = new R66Future(true); - TestPacket packet = new TestPacket("MSG", "CheckConnection", 100); - Message transaction = new Message( - Configuration.configuration.getInternalRunner().getNetworkTransaction(), - result, dbhost, packet); - transaction.run(); - result.awaitUninterruptibly(Configuration.configuration.TIMEOUTCON); - body = REQUEST.Hosts.readBody(); - if (result.isSuccess()) { - body = dbhost.toSpecializedHtml(authentHttp, body, false); - body += "

Connection SUCCESSFUL

"; - } else { - boolean resultShutDown = false; - if (!dbhost.isClient()) { - SocketAddress socketAddress = dbhost.getSocketAddress(); - resultShutDown = - NetworkTransaction.shuttingdownNetworkChannel(socketAddress, null); - } - resultShutDown = resultShutDown || - NetworkTransaction.shuttingdownNetworkChannels(host); - if (resultShutDown) { - body = dbhost.toSpecializedHtml(authentHttp, body, false); - body += "

Connection FAILURE: Disconnection is on going due to " - + - result.getResult().code.mesg + "

"; - } else { - body = dbhost.toSpecializedHtml(authentHttp, body, false); - body += "

Connection FAILURE: " + - result.getResult().code.mesg + "

"; - } - } - } else if ("CloseConn".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - String addr = getTrimValue("address"); - String port = getTrimValue("port"); - String key = getTrimValue("hostkey"); - boolean ssl, admin, isclient; - ssl = params.containsKey("ssl"); - admin = params.containsKey("admin"); - isclient = params.containsKey("isclient"); - head = resetOptionHosts(head, host, addr, ssl); - int iport; - try { - iport = Integer.parseInt(port); - } catch (NumberFormatException e1) { - body0 = body1 = body = ""; - body = "

Cannot find a Host: "+e1.getMessage()+"

"; - head = resetOptionHosts(head, "", "", false); - return head+body0+body+body1+end; - } - DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, - ssl, key.getBytes(), admin, isclient); - body = REQUEST.Hosts.readBody(); - boolean resultShutDown = false; - if (!dbhost.isClient()) { - SocketAddress socketAddress = dbhost.getSocketAddress(); - resultShutDown = - NetworkTransaction.shuttingdownNetworkChannel(socketAddress, null); - } - resultShutDown = resultShutDown || - NetworkTransaction.shuttingdownNetworkChannels(host); - if (resultShutDown) { - body = dbhost.toSpecializedHtml(authentHttp, body, false); - body += "

Disconnection on going SUCCESSFUL

"; - } else { - body = dbhost.toSpecializedHtml(authentHttp, body, false); - body += "

Disconnection cannot be done

"; - } - } else if ("Delete".equalsIgnoreCase(parm)) { - String host = getTrimValue("host"); - if (host == null || host.length() == 0) { - body0 = body1 = body = ""; - body = "

Not enough data to delete a Host

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - DbHostAuth dbhost; - try { - dbhost = new DbHostAuth(dbSession, host); - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot delete a Host: " + e.getMessage() - + "

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - try { - dbhost.delete(); - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot delete a Host: " + e.getMessage() - + "

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } - body0 = body1 = body = ""; - body = "

Deleted Host: " + host + "

"; - head = resetOptionHosts(head, "", "", false); - return head + body0 + body + body1 + end; - } else { - head = resetOptionHosts(head, "", "", false); - } - body1 = REQUEST.Hosts.readBodyEnd(); - } else { - head = resetOptionHosts(head, "", "", false); - } - return head + body0 + body + body1 + end; - } - - private void createExport(String body, StringBuilder builder, String rule, int mode, int limit, int start) { - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbRule.getFilterPrepareStament(dbSession, - rule, mode); - preparedStatement.executeQuery(); - int i = 0; - while (preparedStatement.getNext()) { - DbRule dbrule = DbRule.getFromStatement(preparedStatement); - String temp = dbrule.toSpecializedHtml(authentHttp, body); - temp = temp.replaceAll("XXXRANKXXX", ""+(start+i)); - builder.append(temp); - i++; - if (i > limit) { - break; - } - } - preparedStatement.realClose(); - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.warn("OpenR66 Web Error {}", e.getMessage()); - } - } - - private String resetOptionRules(String header, - String rule, RequestPacket.TRANSFERMODE mode, int gmode) { - StringBuilder builder = new StringBuilder(header); - WaarpStringUtils.replace(builder, "XXXRULEXXX", rule); - if (mode != null) { - switch (mode) { - case RECVMODE: - WaarpStringUtils.replace(builder, "XXXRECVXXX", "checked"); - break; - case SENDMODE: - WaarpStringUtils.replace(builder, "XXXSENDXXX", "checked"); - break; - case RECVMD5MODE: - WaarpStringUtils.replace(builder, "XXXRECVMXXX", "checked"); - break; - case SENDMD5MODE: - WaarpStringUtils.replace(builder, "XXXSENDMXXX", "checked"); - break; - case RECVTHROUGHMODE: - WaarpStringUtils.replace(builder, "XXXRECVTXXX", "checked"); - break; - case SENDTHROUGHMODE: - WaarpStringUtils.replace(builder, "XXXSENDTXXX", "checked"); - break; - case RECVMD5THROUGHMODE: - WaarpStringUtils.replace(builder, "XXXRECVMTXXX", "checked"); - break; - case SENDMD5THROUGHMODE: - WaarpStringUtils.replace(builder, "XXXSENDMTXXX", "checked"); - break; - case UNKNOWNMODE: - break; - default: - break; - } - } - if (gmode == -1) {// All Recv - WaarpStringUtils.replace(builder, "XXXARECVXXX", "checked"); - } else if (gmode == -2) {// All Send - WaarpStringUtils.replace(builder, "XXXASENDXXX", "checked"); - } else if (gmode == -3) {// All - WaarpStringUtils.replace(builder, "XXXALLXXX", "checked"); - } - return builder.toString(); - } - - private String Rules() { - getParams(); - String head = REQUEST.Rules.readHeader(this); - String end; - end = REQUEST.Rules.readEnd(); - if (params == null) { - head = resetOptionRules(head, "", null, -3); - return head + end; - } - String body0, body, body1; - body0 = body1 = body = ""; - List parms = params.get("ACTION"); - if (parms != null) { - body0 = REQUEST.Rules.readBodyHeader(); - String parm = parms.get(0); - if ("Create".equalsIgnoreCase(parm) || "Update".equalsIgnoreCase(parm)) { - String rule = getTrimValue("rule"); - String hostids = getTrimValue("hostids"); - String recvp = getTrimValue("recvp"); - String sendp = getTrimValue("sendp"); - String archp = getTrimValue("archp"); - String workp = getTrimValue("workp"); - String rpre = getTrimValue("rpre"); - String rpost = getTrimValue("rpost"); - String rerr = getTrimValue("rerr"); - String spre = getTrimValue("spre"); - String spost = getTrimValue("spost"); - String serr = getTrimValue("serr"); - String mode = getTrimValue("mode"); - if (rule == null || mode == null) { - body0 = body1 = body = ""; - body = "

Not enough data to " + parm + " a Rule

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } - int gmode = 0; - - TRANSFERMODE tmode = null; - if (mode.equals("send")) { - tmode = RequestPacket.TRANSFERMODE.SENDMODE; - gmode = -2; - } else if (mode.equals("recv")) { - tmode = RequestPacket.TRANSFERMODE.RECVMODE; - gmode = -1; - } else if (mode.equals("sendmd5")) { - tmode = RequestPacket.TRANSFERMODE.SENDMD5MODE; - gmode = -2; - } else if (mode.equals("recvmd5")) { - tmode = RequestPacket.TRANSFERMODE.RECVMD5MODE; - gmode = -1; - } else if (mode.equals("sendth")) { - tmode = RequestPacket.TRANSFERMODE.SENDTHROUGHMODE; - gmode = -2; - } else if (mode.equals("recvth")) { - tmode = RequestPacket.TRANSFERMODE.RECVTHROUGHMODE; - gmode = -1; - } else if (mode.equals("sendthmd5")) { - tmode = RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE; - gmode = -2; - } else if (mode.equals("recvthmd5")) { - tmode = RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE; - gmode = -1; - } - head = resetOptionRules(head, rule, tmode, gmode); - DbRule dbrule = new DbRule(dbSession, rule, hostids, tmode.ordinal(), - recvp, sendp, archp, workp, rpre, rpost, rerr, spre, spost, serr); - try { - if ("Create".equalsIgnoreCase(parm)) { - dbrule.insert(); - } else { - if (dbrule.exist()) { - dbrule.update(); - } else { - dbrule.insert(); - } - } - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot create a Rule: " + e.getMessage() - + "

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } - body = REQUEST.Rules.readBody(); - body = dbrule.toSpecializedHtml(authentHttp, body); - } else if ("Filter".equalsIgnoreCase(parm)) { - String rule = getTrimValue("rule"); - String mode = getTrimValue("mode"); - TRANSFERMODE tmode; - int gmode = 0; - if (mode.equals("all")) { - gmode = -3; - } else if (mode.equals("send")) { - gmode = -2; - } else if (mode.equals("recv")) { - gmode = -1; - } - head = resetOptionRules(head, rule == null ? "" : rule, - null, gmode); - body = REQUEST.Rules.readBody(); - StringBuilder builder = new StringBuilder(); - boolean specific = false; - int start = 1; - if (params.containsKey("send")) { - tmode = RequestPacket.TRANSFERMODE.SENDMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("recv")) { - tmode = RequestPacket.TRANSFERMODE.RECVMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("sendmd5")) { - tmode = RequestPacket.TRANSFERMODE.SENDMD5MODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("recvmd5")) { - tmode = RequestPacket.TRANSFERMODE.RECVMD5MODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("sendth")) { - tmode = RequestPacket.TRANSFERMODE.SENDTHROUGHMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("recvth")) { - tmode = RequestPacket.TRANSFERMODE.RECVTHROUGHMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("sendthmd5")) { - tmode = RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (params.containsKey("recvthmd5")) { - tmode = RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE; - head = resetOptionRules(head, rule == null ? "" : rule, - tmode, gmode); - specific = true; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } - if (!specific) { - if (gmode == -1) { - // recv - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(), - LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } else if (gmode == -2) { - // send - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal(), LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - createExport(body, builder, rule, - RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal(), - LIMITROW / 4, start); - start += LIMITROW / 4 + 1; - } else { - // all - createExport(body, builder, rule, - -1, LIMITROW, start); - start += LIMITROW + 1; - } - } - body = builder.toString(); - body1 = REQUEST.Rules.readBodyEnd(); - } else if ("Delete".equalsIgnoreCase(parm)) { - String rule = getTrimValue("rule"); - if (rule == null || rule.length() == 0) { - body0 = body1 = body = ""; - body = "

Not enough data to delete a Rule

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } - DbRule dbrule; - try { - dbrule = new DbRule(dbSession, rule); - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot delete a Rule: " + e.getMessage() - + "

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } - try { - dbrule.delete(); - } catch (WaarpDatabaseException e) { - body0 = body1 = body = ""; - body = "

Cannot delete a Rule: " + e.getMessage() - + "

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } - body0 = body1 = body = ""; - body = "

Deleted Rule: " + rule + "

"; - head = resetOptionRules(head, "", null, -3); - return head + body0 + body + body1 + end; - } else { - head = resetOptionRules(head, "", null, -3); - } - body1 = REQUEST.Rules.readBodyEnd(); - } else { - head = resetOptionRules(head, "", null, -3); - } - return head + body0 + body + body1 + end; - } - - private String System() { - getParams(); - if (params == null) { - String system = REQUEST.System.readFileUnique(this); - StringBuilder builder = new StringBuilder(system); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITWXXX.toString(), - Long.toString(Configuration.configuration.serverChannelWriteLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITRXXX.toString(), - Long.toString(Configuration.configuration.serverChannelReadLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYCOMMDXXX.toString(), - Long.toString(Configuration.configuration.delayCommander)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYRETRYXXX.toString(), - Long.toString(Configuration.configuration.delayRetry)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITWXXX.toString(), - Long.toString(Configuration.configuration.serverGlobalWriteLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITRXXX.toString(), - Long.toString(Configuration.configuration.serverGlobalReadLimit)); - return builder.toString(); - } - String extraInformation = null; - if (params.containsKey("ACTION")) { - List action = params.get("ACTION"); - for (String act : action) { - if (act.equalsIgnoreCase("ExportConfig")) { - String directory = Configuration.configuration.baseDirectory + - R66Dir.SEPARATOR + Configuration.configuration.archivePath; - extraInformation = "Export Directory: " + directory + "
"; - try { - RuleFileBasedConfiguration.writeXml(directory, - Configuration.configuration.HOST_ID); - extraInformation += "-Rule are exported.
"; - } catch (WaarpDatabaseNoConnectionException e1) { - } catch (WaarpDatabaseSqlException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - String filename = - directory + R66Dir.SEPARATOR + Configuration.configuration.HOST_ID + - "_Authentications.xml"; - try { - AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, - filename); - extraInformation += "-Authent are exported.
"; - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } catch (OpenR66ProtocolSystemException e) { - } - } else if (act.equalsIgnoreCase("Disconnect")) { - String logon = Logon(); - newSession = true; - clearSession(); - forceClose = true; - return logon; - } else if (act.equalsIgnoreCase("Shutdown")) { - String error; - if (Configuration.configuration.shutdownConfiguration.serviceFuture != null) { - error = error("Shutdown in progress but WARNING: R66 started as a service might not be correctly shown as stopped under Windows Services"); - } else { - error = error("Shutdown in progress"); - } - newSession = true; - clearSession(); - forceClose = true; - shutdown = true; - return error; - } else if (act.equalsIgnoreCase("Validate")) { - String bsessionr = getTrimValue("BSESSR"); - long lsessionr = Configuration.configuration.serverChannelReadLimit; - long lglobalr; - long lsessionw; - long lglobalw; - try { - if (bsessionr != null) { - lsessionr = (Long.parseLong(bsessionr) / 10) * 10; - } - String bglobalr = getTrimValue("BGLOBR"); - lglobalr = Configuration.configuration.serverGlobalReadLimit; - if (bglobalr != null) { - lglobalr = (Long.parseLong(bglobalr) / 10) * 10; - } - String bsessionw = getTrimValue("BSESSW"); - lsessionw = Configuration.configuration.serverChannelWriteLimit; - if (bsessionw != null) { - lsessionw = (Long.parseLong(bsessionw) / 10) * 10; - } - String bglobalw = getTrimValue("BGLOBW"); - lglobalw = Configuration.configuration.serverGlobalWriteLimit; - if (bglobalw != null) { - lglobalw = (Long.parseLong(bglobalw) / 10) * 10; - } - Configuration.configuration.changeNetworkLimit( - lglobalw, lglobalr, lsessionw, lsessionr, - Configuration.configuration.delayLimit); - String dcomm = getTrimValue("DCOM"); - if (dcomm != null) { - Configuration.configuration.delayCommander = Long.parseLong(dcomm); - if (Configuration.configuration.delayCommander <= 100) { - Configuration.configuration.delayCommander = 100; - } - Configuration.configuration.reloadCommanderDelay(); - } - String dret = getTrimValue("DRET"); - if (dret != null) { - Configuration.configuration.delayRetry = Long.parseLong(dret); - if (Configuration.configuration.delayRetry <= 1000) { - Configuration.configuration.delayRetry = 1000; - } - } - extraInformation = "Configuration Saved"; - } catch (NumberFormatException e) { - extraInformation = "Configuration cannot be Saved due to Format error"; - } - } - } - } - String system = REQUEST.System.readFileUnique(this); - StringBuilder builder = new StringBuilder(system); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITWXXX.toString(), - Long.toString(Configuration.configuration.serverChannelWriteLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITRXXX.toString(), - Long.toString(Configuration.configuration.serverChannelReadLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYCOMMDXXX.toString(), - Long.toString(Configuration.configuration.delayCommander)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYRETRYXXX.toString(), - Long.toString(Configuration.configuration.delayRetry)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITWXXX.toString(), - Long.toString(Configuration.configuration.serverGlobalWriteLimit)); - WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITRXXX.toString(), - Long.toString(Configuration.configuration.serverGlobalReadLimit)); - if (extraInformation != null) { - builder.append(extraInformation); - } - return builder.toString(); - } - - private void getParams() { - if (request.getMethod() == HttpMethod.GET) { - params = null; - } else if (request.getMethod() == HttpMethod.POST) { - ChannelBuffer content = request.getContent(); - if (content.readable()) { - String param = content.toString(WaarpStringUtils.UTF8); - QueryStringDecoder queryStringDecoder2 = new QueryStringDecoder("/?" + param); - params = queryStringDecoder2.getParameters(); - } else { - params = null; - } - } - } - - private void clearSession() { - if (admin != null) { - R66Session lsession = sessions.remove(admin.getValue()); - DbSession ldbsession = dbSessions.remove(admin.getValue()); - admin = null; - if (lsession != null) { - lsession.setStatus(75); - lsession.clear(); - } - if (ldbsession != null) { - ldbsession.disconnect(); - DbAdmin.nbHttpSession--; - } - } - } - - private void checkAuthent(MessageEvent e) { - newSession = true; - if (request.getMethod() == HttpMethod.GET) { - String logon = Logon(); - responseContent.append(logon); - clearSession(); - writeResponse(e.getChannel()); - return; - } else if (request.getMethod() == HttpMethod.POST) { - getParams(); - if (params == null) { - String logon = Logon(); - responseContent.append(logon); - clearSession(); - writeResponse(e.getChannel()); - return; - } - } - boolean getMenu = false; - if (params.containsKey("Logon")) { - String name = null, password = null; - List values = null; - if (!params.isEmpty()) { - // get values - if (params.containsKey("name")) { - values = params.get("name"); - if (values != null) { - name = values.get(0); - if (name == null || name.length() == 0) { - getMenu = true; - } - } - } else { - getMenu = true; - } - // search the nb param - if ((!getMenu) && params.containsKey("passwd")) { - values = params.get("passwd"); - if (values != null) { - password = values.get(0); - if (password == null || password.length() == 0) { - getMenu = true; - } else { - getMenu = false; - } - } else { - getMenu = true; - } - } else { - getMenu = true; - } - } else { - getMenu = true; - } - if (!getMenu) { - logger.debug("Name? " - + name.equals(Configuration.configuration.ADMINNAME) + - " Passwd? " + Arrays.equals(password.getBytes(), - Configuration.configuration.getSERVERADMINKEY())); - if (name.equals(Configuration.configuration.ADMINNAME) && - Arrays.equals(password.getBytes(), - Configuration.configuration.getSERVERADMINKEY())) { - authentHttp.getAuth().specialNoSessionAuth(true, - Configuration.configuration.HOST_ID); - authentHttp.setStatus(70); - } else { - getMenu = true; - } - if (!authentHttp.isAuthenticated()) { - authentHttp.setStatus(71); - logger.debug("Still not authenticated: {}", authentHttp); - getMenu = true; - } - logger.debug("Identified: "+authentHttp.getAuth().isIdentified()+":"+authentHttp.isAuthenticated()); - // load DbSession - if (this.dbSession == null) { - try { - if (DbConstant.admin.isConnected) { - this.dbSession = new DbSession(DbConstant.admin, false); - DbAdmin.nbHttpSession++; - this.isPrivateDbSession = true; - } - } catch (WaarpDatabaseNoConnectionException e1) { - // Cannot connect so use default connection - logger.warn("Use default database connection"); - this.dbSession = DbConstant.admin.session; - } - } - } - } else { - getMenu = true; - } - if (getMenu) { - String logon = Logon(); - responseContent.append(logon); - clearSession(); - writeResponse(e.getChannel()); - } else { - String index = index(); - responseContent.append(index); - clearSession(); - admin = new DefaultCookie(R66SESSION, Configuration.configuration.HOST_ID + - Long.toHexString(new Random().nextLong())); - sessions.put(admin.getValue(), this.authentHttp); - authentHttp.setStatus(72); - if (this.isPrivateDbSession) { - dbSessions.put(admin.getValue(), dbSession); - } - logger.debug("CreateSession: " + uriRequest + ":{}", admin); - writeResponse(e.getChannel()); - } - } - - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { - HttpRequest request = this.request = (HttpRequest) e.getMessage(); - queryStringDecoder = new QueryStringDecoder(request.getUri()); - uriRequest = queryStringDecoder.getPath(); - logger.debug("Msg: " + uriRequest); - if (uriRequest.contains("gre/") || uriRequest.contains("img/") || - uriRequest.contains("res/")) { - HttpWriteCacheEnable.writeFile(request, - e.getChannel(), Configuration.configuration.httpBasePath + uriRequest, - R66SESSION); - return; - } - checkSession(e.getChannel()); - if (!authentHttp.isAuthenticated()) { - logger.debug("Not Authent: " + uriRequest + ":{}", authentHttp); - checkAuthent(e); - return; - } - String find = uriRequest; - if (uriRequest.charAt(0) == '/') { - find = uriRequest.substring(1); - } - find = find.substring(0, find.indexOf(".")); - REQUEST req = REQUEST.index; - try { - req = REQUEST.valueOf(find); - } catch (IllegalArgumentException e1) { - req = REQUEST.index; - logger.debug("NotFound: " + find + ":" + uriRequest); - } - switch (req) { - case CancelRestart: - responseContent.append(CancelRestart()); - break; - case Export: - responseContent.append(Export()); - break; - case Hosts: - responseContent.append(Hosts()); - break; - case index: - responseContent.append(index()); - break; - case Listing: - responseContent.append(Listing()); - break; - case Logon: - responseContent.append(index()); - break; - case Rules: - responseContent.append(Rules()); - break; - case System: - responseContent.append(System()); - break; - case Transfers: - responseContent.append(Transfers()); - break; - default: - responseContent.append(index()); - break; - } - writeResponse(e.getChannel()); - } - - private void checkSession(Channel channel) { - String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); - if (cookieString != null) { - CookieDecoder cookieDecoder = new CookieDecoder(); - Set cookies = cookieDecoder.decode(cookieString); - if (!cookies.isEmpty()) { - for (Cookie elt : cookies) { - if (elt.getName().equalsIgnoreCase(R66SESSION)) { - logger.debug("Found session: "+elt); - admin = elt; - R66Session session = sessions.get(admin.getValue()); - if (session != null) { - authentHttp = session; - authentHttp.setStatus(73); - } else { - admin = null; - continue; - } - DbSession dbSession = dbSessions.get(admin.getValue()); - if (dbSession != null) { - this.dbSession = dbSession; - } else { - admin = null; - continue; - } - break; - } - } - } - } - if (admin == null) { - logger.debug("NoSession: " + uriRequest + ":{}", admin); - } - } - - private void handleCookies(HttpResponse response) { - String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); - if (cookieString != null) { - CookieDecoder cookieDecoder = new CookieDecoder(); - Set cookies = cookieDecoder.decode(cookieString); - if (!cookies.isEmpty()) { - // Reset the sessions if necessary. - CookieEncoder cookieEncoder = new CookieEncoder(true); - boolean findSession = false; - for (Cookie cookie : cookies) { - if (cookie.getName().equalsIgnoreCase(R66SESSION)) { - if (newSession) { - findSession = false; - } else { - findSession = true; - cookieEncoder.addCookie(cookie); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - cookieEncoder = new CookieEncoder(true); - } - } else { - cookieEncoder.addCookie(cookie); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - cookieEncoder = new CookieEncoder(true); - } - } - newSession = false; - if (!findSession) { - if (admin != null) { - cookieEncoder.addCookie(admin); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - logger.debug("AddSession: " + uriRequest + ":{}", admin); - } - } - } - } else if (admin != null) { - CookieEncoder cookieEncoder = new CookieEncoder(true); - cookieEncoder.addCookie(admin); - logger.debug("AddSession: " + uriRequest + ":{}", admin); - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); - } - } - - /** - * Write the response - * - * @param e - */ - private void writeResponse(Channel channel) { - // Convert the response content to a ChannelBuffer. - ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), - WaarpStringUtils.UTF8); - responseContent.setLength(0); - - // Decide whether to close the connection or not. - boolean keepAlive = HttpHeaders.isKeepAlive(request); - boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request - .getHeader(HttpHeaders.Names.CONNECTION)) || - (!keepAlive) || forceClose; - - // Build the response object. - HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); - response.setContent(buf); - response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); - if (keepAlive) { - response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); - } - if (!close) { - // There's no need to add 'Content-Length' header - // if this is the last response. - response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, - String.valueOf(buf.readableBytes())); - } - - handleCookies(response); - - // Write the response. - ChannelFuture future = channel.write(response); - // Close the connection after the write operation is done if necessary. - if (close) { - future.addListener(WaarpSslUtility.SSLCLOSE); - } - if (shutdown) { - ChannelUtils.startShutdown(); - } - } - - /** - * Send an error and close - * - * @param ctx - * @param status - */ - private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { - HttpResponse response = new DefaultHttpResponse( - HttpVersion.HTTP_1_1, status); - response.setHeader( - HttpHeaders.Names.CONTENT_TYPE, "text/html"); - responseContent.setLength(0); - responseContent.append(error(status.toString())); - response.setContent(ChannelBuffers.copiedBuffer(responseContent.toString(), - WaarpStringUtils.UTF8)); - clearSession(); - // Close the connection as soon as the error message is sent. - ctx.getChannel().write(response).addListener(WaarpSslUtility.SSLCLOSE); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { - OpenR66Exception exception = OpenR66ExceptionTrappedFactory - .getExceptionFromTrappedException(e.getChannel(), e); - if (exception != null) { - if (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) { - if (e.getCause() instanceof IOException) { - // Nothing to do - return; - } - logger.warn("Exception in HttpSslHandler {}", exception.getMessage()); - } - if (e.getChannel().isConnected()) { - sendError(ctx, HttpResponseStatus.BAD_REQUEST); - } - } else { - // Nothing to do - return; - } - } - - /* - * (non-Javadoc) - * @see - * org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelOpen(org.jboss.netty.channel. - * ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - Channel channel = e.getChannel(); - Configuration.configuration.getHttpChannelGroup().add(channel); - super.channelOpen(ctx, e); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.http.adminssl; + +import java.io.IOException; +import java.net.SocketAddress; +import java.sql.Timestamp; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import org.jboss.netty.handler.codec.http.Cookie; +import org.jboss.netty.handler.codec.http.CookieDecoder; +import org.jboss.netty.handler.codec.http.CookieEncoder; +import org.jboss.netty.handler.codec.http.DefaultCookie; +import org.jboss.netty.handler.codec.http.DefaultHttpResponse; +import org.jboss.netty.handler.codec.http.HttpHeaders; +import org.jboss.netty.handler.codec.http.HttpMethod; +import org.jboss.netty.handler.codec.http.HttpRequest; +import org.jboss.netty.handler.codec.http.HttpResponse; +import org.jboss.netty.handler.codec.http.HttpResponseStatus; +import org.jboss.netty.handler.codec.http.HttpVersion; +import org.jboss.netty.handler.codec.http.QueryStringDecoder; +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.exception.FileTransferException; +import org.waarp.common.exception.InvalidArgumentException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.utility.WaarpStringUtils; +import org.waarp.openr66.client.Message; +import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; +import org.waarp.openr66.configuration.RuleFileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.http.HttpWriteCacheEnable; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; +import org.waarp.openr66.protocol.localhandler.packet.TestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.NbAndSpecialId; +import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.openr66.protocol.utils.TransferUtils; +import org.waarp.openr66.protocol.utils.Version; + +/** + * @author Frederic Bregier + * + */ +public class HttpSslHandler extends SimpleChannelUpstreamHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(HttpSslHandler.class); + /** + * Session Management + */ + private static final ConcurrentHashMap sessions = new ConcurrentHashMap(); + private static final ConcurrentHashMap dbSessions = new ConcurrentHashMap(); + private volatile R66Session authentHttp = new R66Session(); + + private volatile HttpRequest request; + private volatile boolean newSession = false; + private volatile Cookie admin = null; + private final StringBuilder responseContent = new StringBuilder(); + private volatile String uriRequest; + private volatile Map> params; + private volatile QueryStringDecoder queryStringDecoder; + private volatile boolean forceClose = false; + private volatile boolean shutdown = false; + + private static final String R66SESSION = "R66SESSION"; + + private static enum REQUEST { + Logon("Logon.html"), + index("index.html"), + error("error.html"), + Transfers("Transfers.html"), + Listing("Listing_head.html", "Listing_body0.html", "Listing_body.html", + "Listing_body1.html", "Listing_end.html"), + CancelRestart("CancelRestart_head.html", "CancelRestart_body0.html", + "CancelRestart_body.html", "CancelRestart_body1.html", "CancelRestart_end.html"), + Export("Export.html"), + Hosts("Hosts_head.html", "Hosts_body0.html", "Hosts_body.html", "Hosts_body1.html", + "Hosts_end.html"), + Rules("Rules_head.html", "Rules_body0.html", "Rules_body.html", "Rules_body1.html", + "Rules_end.html"), + System("System.html"); + + private String header; + private String headerBody; + private String body; + private String endBody; + private String end; + + /** + * Constructor for a unique file + * + * @param uniquefile + */ + private REQUEST(String uniquefile) { + this.header = uniquefile; + this.headerBody = null; + this.body = null; + this.endBody = null; + this.end = null; + } + + /** + * @param header + * @param headerBody + * @param body + * @param endBody + * @param end + */ + private REQUEST(String header, String headerBody, String body, + String endBody, String end) { + this.header = header; + this.headerBody = headerBody; + this.body = body; + this.endBody = endBody; + this.end = end; + } + + /** + * Reader for a unique file + * + * @return the content of the unique file + */ + public String readFileUnique(HttpSslHandler handler) { + return handler.readFileHeader(Configuration.configuration.httpBasePath + this.header); + } + + public String readHeader(HttpSslHandler handler) { + return handler.readFileHeader(Configuration.configuration.httpBasePath + this.header); + } + + public String readBodyHeader() { + return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + + this.headerBody); + } + + public String readBody() { + return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + this.body); + } + + public String readBodyEnd() { + return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + + this.endBody); + } + + public String readEnd() { + return WaarpStringUtils.readFile(Configuration.configuration.httpBasePath + this.end); + } + } + + private static enum REPLACEMENT { + XXXHOSTIDXXX, XXXADMINXXX, XXXVERSIONXXX, XXXBANDWIDTHXXX, + XXXXSESSIONLIMITRXXX, XXXXSESSIONLIMITWXXX, + XXXXCHANNELLIMITRXXX, XXXXCHANNELLIMITWXXX, + XXXXDELAYCOMMDXXX, XXXXDELAYRETRYXXX, + XXXLOCALXXX, XXXNETWORKXXX, + XXXERRORMESGXXX; + } + + public static final int LIMITROW = 48; // better if it can + // be divided by 4 + + /** + * The Database connection attached to this NetworkChannel shared among all associated + * LocalChannels in the session + */ + private volatile DbSession dbSession = null; + /** + * Does this dbSession is private and so should be closed + */ + private volatile boolean isPrivateDbSession = false; + + private String readFileHeader(String filename) { + String value; + try { + value = WaarpStringUtils.readFileException(filename); + } catch (InvalidArgumentException e) { + logger.error("Error while trying to open: " + filename, e); + return ""; + } catch (FileTransferException e) { + logger.error("Error while trying to read: " + filename, e); + return ""; + } + StringBuilder builder = new StringBuilder(value); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXLOCALXXX.toString(), + Integer.toString( + Configuration.configuration.getLocalTransaction(). + getNumberLocalChannel()) + " " + Thread.activeCount()); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXNETWORKXXX.toString(), + Integer.toString( + DbAdmin.getNbConnection())); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), + Configuration.configuration.HOST_ID); + if (authentHttp.isAuthenticated()) { + WaarpStringUtils.replace(builder, REPLACEMENT.XXXADMINXXX.toString(), + "Connected"); + } else { + WaarpStringUtils.replace(builder, REPLACEMENT.XXXADMINXXX.toString(), + "Not authenticated"); + } + TrafficCounter trafficCounter = + Configuration.configuration.getGlobalTrafficShapingHandler().getTrafficCounter(); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXBANDWIDTHXXX.toString(), + "IN:" + (trafficCounter.getLastReadThroughput() >> 17) + + "Mbits 
 OUT:" + + (trafficCounter.getLastWriteThroughput() >> 17) + "Mbits"); + return builder.toString(); + } + + private String getTrimValue(String varname) { + String value = params.get(varname).get(0).trim(); + if (value.length() == 0) { + value = null; + } + return value; + } + + private String getValue(String varname) { + return params.get(varname).get(0); + } + + private String index() { + String index = REQUEST.index.readFileUnique(this); + StringBuilder builder = new StringBuilder(index); + WaarpStringUtils.replaceAll(builder, REPLACEMENT.XXXHOSTIDXXX.toString(), + Configuration.configuration.HOST_ID); + WaarpStringUtils.replaceAll(builder, REPLACEMENT.XXXADMINXXX.toString(), + "Administrator Connected"); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXVERSIONXXX.toString(), + Version.ID); + return builder.toString(); + } + + private String error(String mesg) { + String index = REQUEST.error.readFileUnique(this); + return index.replaceAll(REPLACEMENT.XXXERRORMESGXXX.toString(), + mesg); + } + + private String Logon() { + return REQUEST.Logon.readFileUnique(this); + } + + private String Transfers() { + return REQUEST.Transfers.readFileUnique(this); + } + + private String resetOptionTransfer(String header, String startid, String stopid, + String start, String stop, String rule, String req, + boolean pending, boolean transfer, boolean error, boolean done, boolean all) { + StringBuilder builder = new StringBuilder(header); + WaarpStringUtils.replace(builder, "XXXSTARTIDXXX", startid); + WaarpStringUtils.replace(builder, "XXXSTOPIDXXX", stopid); + WaarpStringUtils.replace(builder, "XXXSTARTXXX", start); + WaarpStringUtils.replace(builder, "XXXSTOPXXX", stop); + WaarpStringUtils.replace(builder, "XXXRULEXXX", rule); + WaarpStringUtils.replace(builder, "XXXREQXXX", req); + WaarpStringUtils.replace(builder, "XXXPENDXXX", pending ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXTRANSXXX", transfer ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXERRXXX", error ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXDONEXXX", done ? "checked" : ""); + WaarpStringUtils.replace(builder, "XXXALLXXX", all ? "checked" : ""); + return builder.toString(); + } + + private String Listing() { + getParams(); + if (params == null) { + String head = REQUEST.Listing.readHeader(this); + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + String end = REQUEST.Listing.readEnd(); + return head + end; + } + String head = REQUEST.Listing.readHeader(this); + String body0, body, body1; + body0 = body1 = body = ""; + List parms = params.get("ACTION"); + if (parms != null) { + body0 = REQUEST.Listing.readBodyHeader(); + String parm = parms.get(0); + if ("Filter".equalsIgnoreCase(parm)) { + String startid = getTrimValue("startid"); + String stopid = getTrimValue("stopid"); + if (startid != null && stopid == null) { + try { + stopid = Long.toString(Long.parseLong(startid)+(LIMITROW/2)); + } catch (NumberFormatException e) { + stopid = null; + startid = null; + } + } + if (stopid != null && startid == null) { + try { + startid = Long.toString(Long.parseLong(stopid) - (LIMITROW / 2)); + } catch (NumberFormatException e) { + stopid = null; + startid = null; + } + } + String start = getValue("start"); + String stop = getValue("stop"); + String rule = getTrimValue("rule"); + String req = getTrimValue("req"); + boolean pending, transfer, error, done, all; + pending = params.containsKey("pending"); + transfer = params.containsKey("transfer"); + error = params.containsKey("error"); + done = params.containsKey("done"); + all = params.containsKey("all"); + if (pending && transfer && error && done) { + all = true; + } else if (!(pending || transfer || error || done)) { + all = true; + } + Timestamp tstart = WaarpStringUtils.fixDate(start); + if (tstart != null) { + start = tstart.toString(); + } + Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); + if (tstop != null) { + stop = tstop.toString(); + } + head = resetOptionTransfer(head, startid == null ? "" : startid, + stopid == null ? "" : stopid, start, stop, + rule == null ? "" : rule, req == null ? "" : req, + pending, transfer, error, done, all); + body = REQUEST.Listing.readBody(); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, + startid, stopid, tstart, tstop, rule, req, + pending, transfer, error, done, all); + preparedStatement.executeQuery(); + StringBuilder builder = new StringBuilder(); + int i = 0; + while (preparedStatement.getNext()) { + try { + i++; + DbTaskRunner taskRunner = DbTaskRunner + .getFromStatement(preparedStatement); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + builder.append(taskRunner.toSpecializedHtml(authentHttp, body, + lcr != null ? "Active" : "NotActive")); + if (i > LIMITROW) { + break; + } + } catch (WaarpDatabaseException e) { + // try to continue if possible + logger.warn("An error occurs while accessing a Runner: {}", + e.getMessage()); + continue; + } + } + preparedStatement.realClose(); + body = builder.toString(); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + } + } else { + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + } + body1 = REQUEST.Listing.readBodyEnd(); + } else { + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + } + String end; + end = REQUEST.Listing.readEnd(); + return head + body0 + body + body1 + end; + } + + private String CancelRestart() { + getParams(); + if (params == null) { + String head = REQUEST.CancelRestart.readHeader(this); + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + String end; + end = REQUEST.CancelRestart.readEnd(); + return head + end; + } + String head = REQUEST.CancelRestart.readHeader(this); + String body0, body, body1; + body0 = body1 = body = ""; + List parms = params.get("ACTION"); + if (parms != null) { + body0 = REQUEST.CancelRestart.readBodyHeader(); + String parm = parms.get(0); + if ("Filter".equalsIgnoreCase(parm)) { + String startid = getTrimValue("startid"); + String stopid = getTrimValue("stopid"); + if (startid != null && stopid == null) { + try { + stopid = Long.toString(Long.parseLong(startid)+(LIMITROW/2)); + } catch (NumberFormatException e) { + stopid = null; + startid = null; + } + } + if (stopid != null && startid == null) { + try { + startid = Long.toString(Long.parseLong(stopid) - (LIMITROW / 2)); + } catch (NumberFormatException e) { + stopid = null; + startid = null; + } + } + String start = getValue("start"); + String stop = getValue("stop"); + String rule = getTrimValue("rule"); + String req = getTrimValue("req"); + boolean pending, transfer, error, done, all; + pending = params.containsKey("pending"); + transfer = params.containsKey("transfer"); + error = params.containsKey("error"); + done = params.containsKey("done"); + all = params.containsKey("all"); + if (pending && transfer && error && done) { + all = true; + } else if (!(pending || transfer || error || done)) { + all = true; + } + Timestamp tstart = WaarpStringUtils.fixDate(start); + if (tstart != null) { + start = tstart.toString(); + } + Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); + if (tstop != null) { + stop = tstop.toString(); + } + head = resetOptionTransfer(head, startid == null ? "" : startid, + stopid == null ? "" : stopid, start, stop, + rule == null ? "" : rule, req == null ? "" : req, + pending, transfer, error, done, all); + body = REQUEST.CancelRestart.readBody(); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, + startid, stopid, tstart, tstop, rule, req, + pending, transfer, error, done, all); + preparedStatement.executeQuery(); + StringBuilder builder = new StringBuilder(); + int i = 0; + while (preparedStatement.getNext()) { + try { + i++; + DbTaskRunner taskRunner = DbTaskRunner + .getFromStatement(preparedStatement); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + builder.append(taskRunner.toSpecializedHtml(authentHttp, body, + lcr != null ? "Active" : "NotActive")); + if (i > LIMITROW) { + break; + } + } catch (WaarpDatabaseException e) { + // try to continue if possible + logger.warn("An error occurs while accessing a Runner: {}", + e.getMessage()); + continue; + } + } + preparedStatement.realClose(); + body = builder.toString(); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + } + body1 = REQUEST.CancelRestart.readBodyEnd(); + } else if ("RestartAll".equalsIgnoreCase(parm) || + "StopAll".equalsIgnoreCase(parm)) { + boolean stopcommand = "StopAll".equalsIgnoreCase(parm); + String startid = getTrimValue("startid"); + String stopid = getTrimValue("stopid"); + String start = getValue("start"); + String stop = getValue("stop"); + String rule = getTrimValue("rule"); + String req = getTrimValue("req"); + boolean pending, transfer, error, done, all; + pending = params.containsKey("pending"); + transfer = params.containsKey("transfer"); + error = params.containsKey("error"); + done = false; + all = false; + if (pending && transfer && error && done) { + all = true; + } else if (!(pending || transfer || error || done)) { + all = true; + pending = true; + transfer = true; + error = true; + } + Timestamp tstart = WaarpStringUtils.fixDate(start); + if (tstart != null) { + start = tstart.toString(); + } + Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); + if (tstop != null) { + stop = tstop.toString(); + } + head = resetOptionTransfer(head, startid == null ? "" : startid, + stopid == null ? "" : stopid, start, stop, + rule == null ? "" : rule, req == null ? "" : req, + pending, transfer, error, done, all); + body = REQUEST.CancelRestart.readBody(); + StringBuilder builder = new StringBuilder(); + if (stopcommand) { + builder = TransferUtils.stopSelectedTransfers(dbSession, LIMITROW, builder, + authentHttp, body, startid, stopid, tstart, tstop, rule, req, + pending, transfer, error); + } else { + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbTaskRunner.getFilterPrepareStatement(dbSession, LIMITROW, false, + startid, stopid, tstart, tstop, rule, req, + pending, transfer, error, done, all); + preparedStatement.executeQuery(); + int i = 0; + while (preparedStatement.getNext()) { + try { + i++; + DbTaskRunner taskRunner = DbTaskRunner + .getFromStatement(preparedStatement); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + R66Result finalResult = TransferUtils.restartTransfer(taskRunner, + lcr); + ErrorCode result = finalResult.code; + ErrorCode last = taskRunner.getErrorInfo(); + taskRunner.setErrorExecutionStatus(result); + builder.append(taskRunner.toSpecializedHtml(authentHttp, body, + lcr != null ? "Active" : "NotActive")); + taskRunner.setErrorExecutionStatus(last); + if (i > LIMITROW) { + break; + } + } catch (WaarpDatabaseException e) { + // try to continue if possible + logger.warn("An error occurs while accessing a Runner: {}", + e.getMessage()); + continue; + } + } + preparedStatement.realClose(); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + } + } + if (builder != null) { + body = builder.toString(); + } else { + body = ""; + } + body1 = REQUEST.CancelRestart.readBodyEnd(); + } else if ("Cancel".equalsIgnoreCase(parm) || "Stop".equalsIgnoreCase(parm)) { + // Cancel or Stop + boolean stop = "Stop".equalsIgnoreCase(parm); + String specid = getValue("specid"); + String reqd = getValue("reqd"); + String reqr = getValue("reqr"); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(reqd + " " + reqr + " " + specid); + // stop the current transfer + ErrorCode result; + long lspecid; + try { + lspecid = Long.parseLong(specid); + } catch (NumberFormatException e) { + body = ""; + body1 = REQUEST.CancelRestart.readBodyEnd(); + body1 += "
"+parm+" aborted since Transfer is not found"; + String end; + end = REQUEST.CancelRestart.readEnd(); + return head+body0+body+body1+end; + } + DbTaskRunner taskRunner = null; + try { + taskRunner = new DbTaskRunner(dbSession, authentHttp, null, + lspecid, reqr, reqd); + } catch (WaarpDatabaseException e) { + } + if (taskRunner == null) { + body = ""; + body1 = REQUEST.CancelRestart.readBodyEnd(); + body1 += "
" + parm + " aborted since Transfer is not found"; + String end; + end = REQUEST.CancelRestart.readEnd(); + return head + body0 + body + body1 + end; + } + ErrorCode code = (stop) ? + ErrorCode.StoppedTransfer : ErrorCode.CanceledTransfer; + if (lcr != null) { + int rank = taskRunner.getRank(); + lcr.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket("Transfer " + parm + " " + rank, + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + // XXX ChannelUtils.writeAbstractLocalPacket(lcr, error); + // inform local instead of remote + ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); + } catch (Exception e) { + } + result = ErrorCode.CompleteOk; + } else { + // Transfer is not running + // But is the database saying the contrary + result = ErrorCode.TransferOk; + if (taskRunner != null) { + if (taskRunner.stopOrCancelRunner(code)) { + result = ErrorCode.CompleteOk; + } + } + } + if (taskRunner != null) { + body = REQUEST.CancelRestart.readBody(); + body = taskRunner.toSpecializedHtml(authentHttp, body, + lcr != null ? "Active" : "NotActive"); + String tstart = taskRunner.getStart().toString(); + tstart = tstart.substring(0, tstart.length()); + String tstop = taskRunner.getStop().toString(); + tstop = tstop.substring(0, tstop.length()); + head = resetOptionTransfer(head, (taskRunner.getSpecialId() - 1) + "", + (taskRunner.getSpecialId() + 1) + "", tstart, tstop, + taskRunner.getRuleId(), taskRunner.getRequested(), + false, false, false, false, true); + } + body1 = REQUEST.CancelRestart.readBodyEnd(); + body1 += "
" + (result == ErrorCode.CompleteOk ? parm + " transmitted" : + parm + " aborted since Transfer is not running") + ""; + } else if ("Restart".equalsIgnoreCase(parm)) { + // Restart + String specid = getValue("specid"); + String reqd = getValue("reqd"); + String reqr = getValue("reqr"); + long lspecid; + try { + lspecid = Long.parseLong(specid); + } catch (NumberFormatException e) { + body = ""; + body1 = REQUEST.CancelRestart.readBodyEnd(); + body1 += "
"+parm+" aborted since Transfer is not found"; + String end; + end = REQUEST.CancelRestart.readEnd(); + return head+body0+body+body1+end; + } + DbTaskRunner taskRunner; + String comment; + try { + taskRunner = new DbTaskRunner(dbSession, authentHttp, null, + lspecid, reqr, reqd); + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + R66Result finalResult = TransferUtils.restartTransfer(taskRunner, lcr); + comment = (String) finalResult.other; + body = REQUEST.CancelRestart.readBody(); + body = taskRunner.toSpecializedHtml(authentHttp, body, + lcr != null ? "Active" : "NotActive"); + String tstart = taskRunner.getStart().toString(); + tstart = tstart.substring(0, tstart.length()); + String tstop = taskRunner.getStop().toString(); + tstop = tstop.substring(0, tstop.length()); + head = resetOptionTransfer(head, (taskRunner.getSpecialId() - 1) + "", + (taskRunner.getSpecialId() + 1) + "", tstart, tstop, + taskRunner.getRuleId(), taskRunner.getRequested(), + false, false, false, false, true); + } catch (WaarpDatabaseException e) { + body = ""; + comment = "Internal error"; + } + body1 = REQUEST.CancelRestart.readBodyEnd(); + body1 += "
" + comment + ""; + } else { + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + } + } else { + head = resetOptionTransfer(head, "", "", "", "", "", "", + false, false, false, false, true); + } + String end; + end = REQUEST.CancelRestart.readEnd(); + return head + body0 + body + body1 + end; + } + + private String Export() { + getParams(); + if (params == null) { + String body = REQUEST.Export.readFileUnique(this); + body = resetOptionTransfer(body, "", "", "", "", "", "", + false, false, false, true, false); + return body.replace("XXXRESULTXXX", ""); + } + String body = REQUEST.Export.readFileUnique(this); + String start = getValue("start"); + String stop = getValue("stop"); + String rule = getTrimValue("rule"); + String req = getTrimValue("req"); + boolean pending, transfer, error, done, all; + pending = params.containsKey("pending"); + transfer = params.containsKey("transfer"); + error = params.containsKey("error"); + done = params.containsKey("done"); + all = params.containsKey("all"); + boolean toPurge = params.containsKey("purge"); + if (toPurge) { + transfer = false; + } + if (pending && transfer && error && done) { + all = true; + } else if (!(pending || transfer || error || done)) { + all = true; + } + Timestamp tstart = WaarpStringUtils.fixDate(start); + if (tstart != null) { + start = tstart.toString(); + } + Timestamp tstop = WaarpStringUtils.fixDate(stop, tstart); + if (tstop != null) { + stop = tstop.toString(); + } + body = resetOptionTransfer(body, "", "", start, stop, + rule == null ? "" : rule, req == null ? "" : req, + pending, transfer, error, done, all); + boolean isexported = true; + // clean a bit the database before exporting + try { + DbTaskRunner.changeFinishedToDone(dbSession); + } catch (WaarpDatabaseNoConnectionException e2) { + // should not be + } + // create export of log and optionally purge them from database + DbPreparedStatement getValid = null; + NbAndSpecialId nbAndSpecialId = null; + String filename = Configuration.configuration.baseDirectory + + Configuration.configuration.archivePath + R66Dir.SEPARATOR + + Configuration.configuration.HOST_ID + "_" + System.currentTimeMillis() + + "_runners.xml"; + try { + getValid = + DbTaskRunner.getFilterPrepareStatement(dbSession, 0,// 0 means no limit + true, null, null, tstart, tstop, rule, req, + pending, transfer, error, done, all); + nbAndSpecialId = DbTaskRunner.writeXMLWriter(getValid, filename); + } catch (WaarpDatabaseNoConnectionException e1) { + isexported = false; + toPurge = false; + } catch (WaarpDatabaseSqlException e1) { + isexported = false; + toPurge = false; + } catch (OpenR66ProtocolBusinessException e) { + isexported = false; + toPurge = false; + } finally { + if (getValid != null) { + getValid.realClose(); + } + } + int purge = 0; + if (isexported && nbAndSpecialId != null) { + if (nbAndSpecialId.nb <= 0) { + return body.replace("XXXRESULTXXX", + "Export unsuccessful since no records were found"); + } + // in case of purge + if (isexported && toPurge) { + // purge with same filter all runners where globallasttep + // is ALLDONE or ERROR + // but getting the higher Special first + String stopId = Long.toString(nbAndSpecialId.higherSpecialId); + try { + purge = + DbTaskRunner.purgeLogPrepareStatement(dbSession, + null, stopId, tstart, tstop, rule, req, + pending, transfer, error, done, all); + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } + } + } + return body.replace("XXXRESULTXXX", "Export " + + (isexported ? "successful into " + + filename + " with " + nbAndSpecialId.nb + " exported and " + purge + + " purged records" : + "in error")); + } + + private String resetOptionHosts(String header, + String host, String addr, boolean ssl) { + StringBuilder builder = new StringBuilder(header); + WaarpStringUtils.replace(builder, "XXXFHOSTXXX", host); + WaarpStringUtils.replace(builder, "XXXFADDRXXX", addr); + WaarpStringUtils.replace(builder, "XXXFSSLXXX", ssl ? "checked" : ""); + return builder.toString(); + } + + private String Hosts() { + getParams(); + String head = REQUEST.Hosts.readHeader(this); + String end; + end = REQUEST.Hosts.readEnd(); + if (params == null) { + head = resetOptionHosts(head, "", "", false); + return head + end; + } + String body0, body, body1; + body0 = body1 = body = ""; + List parms = params.get("ACTION"); + if (parms != null) { + body0 = REQUEST.Hosts.readBodyHeader(); + String parm = parms.get(0); + if ("Create".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + String addr = getTrimValue("address"); + String port = getTrimValue("port"); + String key = getTrimValue("hostkey"); + boolean ssl, admin, isclient; + ssl = params.containsKey("ssl"); + admin = params.containsKey("admin"); + isclient = params.containsKey("isclient"); + if (host == null || addr == null || port == null || key == null) { + body0 = body1 = body = ""; + body = "

Not enough data to create a Host

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + head = resetOptionHosts(head, host, addr, ssl); + int iport; + try { + iport = Integer.parseInt(port); + } catch (NumberFormatException e1) { + body0 = body1 = body = ""; + body = "

Cannot create a Host: "+e1.getMessage()+"

"; + head = resetOptionHosts(head, "", "", false); + return head+body0+body+body1+end; + } + DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, + ssl, key.getBytes(), admin, isclient); + try { + dbhost.insert(); + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot create a Host: " + e.getMessage() + + "

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + body = REQUEST.Hosts.readBody(); + body = dbhost.toSpecializedHtml(authentHttp, body, false); + } else if ("Filter".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + String addr = getTrimValue("address"); + boolean ssl = params.containsKey("ssl"); + head = resetOptionHosts(head, host == null ? "" : host, + addr == null ? "" : addr, ssl); + body = REQUEST.Hosts.readBody(); + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbHostAuth.getFilterPrepareStament(dbSession, + host, addr, ssl); + preparedStatement.executeQuery(); + StringBuilder builder = new StringBuilder(); + int i = 0; + while (preparedStatement.getNext()) { + i++; + DbHostAuth dbhost = DbHostAuth.getFromStatement(preparedStatement); + builder.append(dbhost.toSpecializedHtml(authentHttp, body, false)); + if (i > LIMITROW) { + break; + } + } + preparedStatement.realClose(); + body = builder.toString(); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + } + body1 = REQUEST.Hosts.readBodyEnd(); + } else if ("Update".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + String addr = getTrimValue("address"); + String port = getTrimValue("port"); + String key = getTrimValue("hostkey"); + boolean ssl, admin, isclient; + ssl = params.containsKey("ssl"); + admin = params.containsKey("admin"); + isclient = params.containsKey("isclient"); + if (host == null || addr == null || port == null || key == null) { + body0 = body1 = body = ""; + body = "

Not enough data to update a Host

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + head = resetOptionHosts(head, host, addr, ssl); + int iport; + try { + iport = Integer.parseInt(port); + } catch (NumberFormatException e1) { + body0 = body1 = body = ""; + body = "

Cannot Update a Host: "+e1.getMessage()+"

"; + head = resetOptionHosts(head, "", "", false); + return head+body0+body+body1+end; + } + DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, + ssl, key.getBytes(), admin, isclient); + try { + if (dbhost.exist()) { + dbhost.update(); + } else { + dbhost.insert(); + } + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot update a Host: " + e.getMessage() + + "

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + body = REQUEST.Hosts.readBody(); + body = dbhost.toSpecializedHtml(authentHttp, body, false); + } else if ("TestConn".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + String addr = getTrimValue("address"); + String port = getTrimValue("port"); + String key = getTrimValue("hostkey"); + boolean ssl, admin, isclient; + ssl = params.containsKey("ssl"); + admin = params.containsKey("admin"); + isclient = params.containsKey("isclient"); + head = resetOptionHosts(head, host, addr, ssl); + int iport; + try { + iport = Integer.parseInt(port); + } catch (NumberFormatException e1) { + body0 = body1 = body = ""; + body = "

Cannot find a Host: "+e1.getMessage()+"

"; + head = resetOptionHosts(head, "", "", false); + return head+body0+body+body1+end; + } + DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, + ssl, key.getBytes(), admin, isclient); + R66Future result = new R66Future(true); + TestPacket packet = new TestPacket("MSG", "CheckConnection", 100); + Message transaction = new Message( + Configuration.configuration.getInternalRunner().getNetworkTransaction(), + result, dbhost, packet); + transaction.run(); + result.awaitUninterruptibly(Configuration.configuration.TIMEOUTCON); + body = REQUEST.Hosts.readBody(); + if (result.isSuccess()) { + body = dbhost.toSpecializedHtml(authentHttp, body, false); + body += "

Connection SUCCESSFUL

"; + } else { + boolean resultShutDown = false; + if (!dbhost.isClient()) { + SocketAddress socketAddress = dbhost.getSocketAddress(); + resultShutDown = + NetworkTransaction.shuttingdownNetworkChannel(socketAddress, null); + } + resultShutDown = resultShutDown || + NetworkTransaction.shuttingdownNetworkChannels(host); + if (resultShutDown) { + body = dbhost.toSpecializedHtml(authentHttp, body, false); + body += "

Connection FAILURE: Disconnection is on going due to " + + + result.getResult().code.mesg + "

"; + } else { + body = dbhost.toSpecializedHtml(authentHttp, body, false); + body += "

Connection FAILURE: " + + result.getResult().code.mesg + "

"; + } + } + } else if ("CloseConn".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + String addr = getTrimValue("address"); + String port = getTrimValue("port"); + String key = getTrimValue("hostkey"); + boolean ssl, admin, isclient; + ssl = params.containsKey("ssl"); + admin = params.containsKey("admin"); + isclient = params.containsKey("isclient"); + head = resetOptionHosts(head, host, addr, ssl); + int iport; + try { + iport = Integer.parseInt(port); + } catch (NumberFormatException e1) { + body0 = body1 = body = ""; + body = "

Cannot find a Host: "+e1.getMessage()+"

"; + head = resetOptionHosts(head, "", "", false); + return head+body0+body+body1+end; + } + DbHostAuth dbhost = new DbHostAuth(dbSession, host, addr, iport, + ssl, key.getBytes(), admin, isclient); + body = REQUEST.Hosts.readBody(); + boolean resultShutDown = false; + if (!dbhost.isClient()) { + SocketAddress socketAddress = dbhost.getSocketAddress(); + resultShutDown = + NetworkTransaction.shuttingdownNetworkChannel(socketAddress, null); + } + resultShutDown = resultShutDown || + NetworkTransaction.shuttingdownNetworkChannels(host); + if (resultShutDown) { + body = dbhost.toSpecializedHtml(authentHttp, body, false); + body += "

Disconnection on going SUCCESSFUL

"; + } else { + body = dbhost.toSpecializedHtml(authentHttp, body, false); + body += "

Disconnection cannot be done

"; + } + } else if ("Delete".equalsIgnoreCase(parm)) { + String host = getTrimValue("host"); + if (host == null || host.length() == 0) { + body0 = body1 = body = ""; + body = "

Not enough data to delete a Host

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + DbHostAuth dbhost; + try { + dbhost = new DbHostAuth(dbSession, host); + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot delete a Host: " + e.getMessage() + + "

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + try { + dbhost.delete(); + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot delete a Host: " + e.getMessage() + + "

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } + body0 = body1 = body = ""; + body = "

Deleted Host: " + host + "

"; + head = resetOptionHosts(head, "", "", false); + return head + body0 + body + body1 + end; + } else { + head = resetOptionHosts(head, "", "", false); + } + body1 = REQUEST.Hosts.readBodyEnd(); + } else { + head = resetOptionHosts(head, "", "", false); + } + return head + body0 + body + body1 + end; + } + + private void createExport(String body, StringBuilder builder, String rule, int mode, int limit, int start) { + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbRule.getFilterPrepareStament(dbSession, + rule, mode); + preparedStatement.executeQuery(); + int i = 0; + while (preparedStatement.getNext()) { + DbRule dbrule = DbRule.getFromStatement(preparedStatement); + String temp = dbrule.toSpecializedHtml(authentHttp, body); + temp = temp.replaceAll("XXXRANKXXX", ""+(start+i)); + builder.append(temp); + i++; + if (i > limit) { + break; + } + } + preparedStatement.realClose(); + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.warn("OpenR66 Web Error {}", e.getMessage()); + } + } + + private String resetOptionRules(String header, + String rule, RequestPacket.TRANSFERMODE mode, int gmode) { + StringBuilder builder = new StringBuilder(header); + WaarpStringUtils.replace(builder, "XXXRULEXXX", rule); + if (mode != null) { + switch (mode) { + case RECVMODE: + WaarpStringUtils.replace(builder, "XXXRECVXXX", "checked"); + break; + case SENDMODE: + WaarpStringUtils.replace(builder, "XXXSENDXXX", "checked"); + break; + case RECVMD5MODE: + WaarpStringUtils.replace(builder, "XXXRECVMXXX", "checked"); + break; + case SENDMD5MODE: + WaarpStringUtils.replace(builder, "XXXSENDMXXX", "checked"); + break; + case RECVTHROUGHMODE: + WaarpStringUtils.replace(builder, "XXXRECVTXXX", "checked"); + break; + case SENDTHROUGHMODE: + WaarpStringUtils.replace(builder, "XXXSENDTXXX", "checked"); + break; + case RECVMD5THROUGHMODE: + WaarpStringUtils.replace(builder, "XXXRECVMTXXX", "checked"); + break; + case SENDMD5THROUGHMODE: + WaarpStringUtils.replace(builder, "XXXSENDMTXXX", "checked"); + break; + case UNKNOWNMODE: + break; + default: + break; + } + } + if (gmode == -1) {// All Recv + WaarpStringUtils.replace(builder, "XXXARECVXXX", "checked"); + } else if (gmode == -2) {// All Send + WaarpStringUtils.replace(builder, "XXXASENDXXX", "checked"); + } else if (gmode == -3) {// All + WaarpStringUtils.replace(builder, "XXXALLXXX", "checked"); + } + return builder.toString(); + } + + private String Rules() { + getParams(); + String head = REQUEST.Rules.readHeader(this); + String end; + end = REQUEST.Rules.readEnd(); + if (params == null) { + head = resetOptionRules(head, "", null, -3); + return head + end; + } + String body0, body, body1; + body0 = body1 = body = ""; + List parms = params.get("ACTION"); + if (parms != null) { + body0 = REQUEST.Rules.readBodyHeader(); + String parm = parms.get(0); + if ("Create".equalsIgnoreCase(parm) || "Update".equalsIgnoreCase(parm)) { + String rule = getTrimValue("rule"); + String hostids = getTrimValue("hostids"); + String recvp = getTrimValue("recvp"); + String sendp = getTrimValue("sendp"); + String archp = getTrimValue("archp"); + String workp = getTrimValue("workp"); + String rpre = getTrimValue("rpre"); + String rpost = getTrimValue("rpost"); + String rerr = getTrimValue("rerr"); + String spre = getTrimValue("spre"); + String spost = getTrimValue("spost"); + String serr = getTrimValue("serr"); + String mode = getTrimValue("mode"); + if (rule == null || mode == null) { + body0 = body1 = body = ""; + body = "

Not enough data to " + parm + " a Rule

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } + int gmode = 0; + + TRANSFERMODE tmode = null; + if (mode.equals("send")) { + tmode = RequestPacket.TRANSFERMODE.SENDMODE; + gmode = -2; + } else if (mode.equals("recv")) { + tmode = RequestPacket.TRANSFERMODE.RECVMODE; + gmode = -1; + } else if (mode.equals("sendmd5")) { + tmode = RequestPacket.TRANSFERMODE.SENDMD5MODE; + gmode = -2; + } else if (mode.equals("recvmd5")) { + tmode = RequestPacket.TRANSFERMODE.RECVMD5MODE; + gmode = -1; + } else if (mode.equals("sendth")) { + tmode = RequestPacket.TRANSFERMODE.SENDTHROUGHMODE; + gmode = -2; + } else if (mode.equals("recvth")) { + tmode = RequestPacket.TRANSFERMODE.RECVTHROUGHMODE; + gmode = -1; + } else if (mode.equals("sendthmd5")) { + tmode = RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE; + gmode = -2; + } else if (mode.equals("recvthmd5")) { + tmode = RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE; + gmode = -1; + } + head = resetOptionRules(head, rule, tmode, gmode); + DbRule dbrule = new DbRule(dbSession, rule, hostids, tmode.ordinal(), + recvp, sendp, archp, workp, rpre, rpost, rerr, spre, spost, serr); + try { + if ("Create".equalsIgnoreCase(parm)) { + dbrule.insert(); + } else { + if (dbrule.exist()) { + dbrule.update(); + } else { + dbrule.insert(); + } + } + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot create a Rule: " + e.getMessage() + + "

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } + body = REQUEST.Rules.readBody(); + body = dbrule.toSpecializedHtml(authentHttp, body); + } else if ("Filter".equalsIgnoreCase(parm)) { + String rule = getTrimValue("rule"); + String mode = getTrimValue("mode"); + TRANSFERMODE tmode; + int gmode = 0; + if (mode.equals("all")) { + gmode = -3; + } else if (mode.equals("send")) { + gmode = -2; + } else if (mode.equals("recv")) { + gmode = -1; + } + head = resetOptionRules(head, rule == null ? "" : rule, + null, gmode); + body = REQUEST.Rules.readBody(); + StringBuilder builder = new StringBuilder(); + boolean specific = false; + int start = 1; + if (params.containsKey("send")) { + tmode = RequestPacket.TRANSFERMODE.SENDMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("recv")) { + tmode = RequestPacket.TRANSFERMODE.RECVMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("sendmd5")) { + tmode = RequestPacket.TRANSFERMODE.SENDMD5MODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("recvmd5")) { + tmode = RequestPacket.TRANSFERMODE.RECVMD5MODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("sendth")) { + tmode = RequestPacket.TRANSFERMODE.SENDTHROUGHMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("recvth")) { + tmode = RequestPacket.TRANSFERMODE.RECVTHROUGHMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("sendthmd5")) { + tmode = RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (params.containsKey("recvthmd5")) { + tmode = RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE; + head = resetOptionRules(head, rule == null ? "" : rule, + tmode, gmode); + specific = true; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } + if (!specific) { + if (gmode == -1) { + // recv + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(), + LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } else if (gmode == -2) { + // send + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal(), LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + createExport(body, builder, rule, + RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal(), + LIMITROW / 4, start); + start += LIMITROW / 4 + 1; + } else { + // all + createExport(body, builder, rule, + -1, LIMITROW, start); + start += LIMITROW + 1; + } + } + body = builder.toString(); + body1 = REQUEST.Rules.readBodyEnd(); + } else if ("Delete".equalsIgnoreCase(parm)) { + String rule = getTrimValue("rule"); + if (rule == null || rule.length() == 0) { + body0 = body1 = body = ""; + body = "

Not enough data to delete a Rule

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } + DbRule dbrule; + try { + dbrule = new DbRule(dbSession, rule); + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot delete a Rule: " + e.getMessage() + + "

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } + try { + dbrule.delete(); + } catch (WaarpDatabaseException e) { + body0 = body1 = body = ""; + body = "

Cannot delete a Rule: " + e.getMessage() + + "

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } + body0 = body1 = body = ""; + body = "

Deleted Rule: " + rule + "

"; + head = resetOptionRules(head, "", null, -3); + return head + body0 + body + body1 + end; + } else { + head = resetOptionRules(head, "", null, -3); + } + body1 = REQUEST.Rules.readBodyEnd(); + } else { + head = resetOptionRules(head, "", null, -3); + } + return head + body0 + body + body1 + end; + } + + private String System() { + getParams(); + if (params == null) { + String system = REQUEST.System.readFileUnique(this); + StringBuilder builder = new StringBuilder(system); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITWXXX.toString(), + Long.toString(Configuration.configuration.serverChannelWriteLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITRXXX.toString(), + Long.toString(Configuration.configuration.serverChannelReadLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYCOMMDXXX.toString(), + Long.toString(Configuration.configuration.delayCommander)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYRETRYXXX.toString(), + Long.toString(Configuration.configuration.delayRetry)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITWXXX.toString(), + Long.toString(Configuration.configuration.serverGlobalWriteLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITRXXX.toString(), + Long.toString(Configuration.configuration.serverGlobalReadLimit)); + return builder.toString(); + } + String extraInformation = null; + if (params.containsKey("ACTION")) { + List action = params.get("ACTION"); + for (String act : action) { + if (act.equalsIgnoreCase("ExportConfig")) { + String directory = Configuration.configuration.baseDirectory + + R66Dir.SEPARATOR + Configuration.configuration.archivePath; + extraInformation = "Export Directory: " + directory + "
"; + try { + RuleFileBasedConfiguration.writeXml(directory, + Configuration.configuration.HOST_ID); + extraInformation += "-Rule are exported.
"; + } catch (WaarpDatabaseNoConnectionException e1) { + } catch (WaarpDatabaseSqlException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + String filename = + directory + R66Dir.SEPARATOR + Configuration.configuration.HOST_ID + + "_Authentications.xml"; + try { + AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, + filename); + extraInformation += "-Authent are exported.
"; + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } catch (OpenR66ProtocolSystemException e) { + } + } else if (act.equalsIgnoreCase("Disconnect")) { + String logon = Logon(); + newSession = true; + clearSession(); + forceClose = true; + return logon; + } else if (act.equalsIgnoreCase("Shutdown")) { + String error; + if (Configuration.configuration.shutdownConfiguration.serviceFuture != null) { + error = error("Shutdown in progress but WARNING: R66 started as a service might not be correctly shown as stopped under Windows Services"); + } else { + error = error("Shutdown in progress"); + } + newSession = true; + clearSession(); + forceClose = true; + shutdown = true; + return error; + } else if (act.equalsIgnoreCase("Validate")) { + String bsessionr = getTrimValue("BSESSR"); + long lsessionr = Configuration.configuration.serverChannelReadLimit; + long lglobalr; + long lsessionw; + long lglobalw; + try { + if (bsessionr != null) { + lsessionr = (Long.parseLong(bsessionr) / 10) * 10; + } + String bglobalr = getTrimValue("BGLOBR"); + lglobalr = Configuration.configuration.serverGlobalReadLimit; + if (bglobalr != null) { + lglobalr = (Long.parseLong(bglobalr) / 10) * 10; + } + String bsessionw = getTrimValue("BSESSW"); + lsessionw = Configuration.configuration.serverChannelWriteLimit; + if (bsessionw != null) { + lsessionw = (Long.parseLong(bsessionw) / 10) * 10; + } + String bglobalw = getTrimValue("BGLOBW"); + lglobalw = Configuration.configuration.serverGlobalWriteLimit; + if (bglobalw != null) { + lglobalw = (Long.parseLong(bglobalw) / 10) * 10; + } + Configuration.configuration.changeNetworkLimit( + lglobalw, lglobalr, lsessionw, lsessionr, + Configuration.configuration.delayLimit); + String dcomm = getTrimValue("DCOM"); + if (dcomm != null) { + Configuration.configuration.delayCommander = Long.parseLong(dcomm); + if (Configuration.configuration.delayCommander <= 100) { + Configuration.configuration.delayCommander = 100; + } + Configuration.configuration.reloadCommanderDelay(); + } + String dret = getTrimValue("DRET"); + if (dret != null) { + Configuration.configuration.delayRetry = Long.parseLong(dret); + if (Configuration.configuration.delayRetry <= 1000) { + Configuration.configuration.delayRetry = 1000; + } + } + extraInformation = "Configuration Saved"; + } catch (NumberFormatException e) { + extraInformation = "Configuration cannot be Saved due to Format error"; + } + } + } + } + String system = REQUEST.System.readFileUnique(this); + StringBuilder builder = new StringBuilder(system); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITWXXX.toString(), + Long.toString(Configuration.configuration.serverChannelWriteLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXSESSIONLIMITRXXX.toString(), + Long.toString(Configuration.configuration.serverChannelReadLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYCOMMDXXX.toString(), + Long.toString(Configuration.configuration.delayCommander)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXDELAYRETRYXXX.toString(), + Long.toString(Configuration.configuration.delayRetry)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITWXXX.toString(), + Long.toString(Configuration.configuration.serverGlobalWriteLimit)); + WaarpStringUtils.replace(builder, REPLACEMENT.XXXXCHANNELLIMITRXXX.toString(), + Long.toString(Configuration.configuration.serverGlobalReadLimit)); + if (extraInformation != null) { + builder.append(extraInformation); + } + return builder.toString(); + } + + private void getParams() { + if (request.getMethod() == HttpMethod.GET) { + params = null; + } else if (request.getMethod() == HttpMethod.POST) { + ChannelBuffer content = request.getContent(); + if (content.readable()) { + String param = content.toString(WaarpStringUtils.UTF8); + QueryStringDecoder queryStringDecoder2 = new QueryStringDecoder("/?" + param); + params = queryStringDecoder2.getParameters(); + } else { + params = null; + } + } + } + + private void clearSession() { + if (admin != null) { + R66Session lsession = sessions.remove(admin.getValue()); + DbSession ldbsession = dbSessions.remove(admin.getValue()); + admin = null; + if (lsession != null) { + lsession.setStatus(75); + lsession.clear(); + } + if (ldbsession != null) { + ldbsession.disconnect(); + DbAdmin.nbHttpSession--; + } + } + } + + private void checkAuthent(MessageEvent e) { + newSession = true; + if (request.getMethod() == HttpMethod.GET) { + String logon = Logon(); + responseContent.append(logon); + clearSession(); + writeResponse(e.getChannel()); + return; + } else if (request.getMethod() == HttpMethod.POST) { + getParams(); + if (params == null) { + String logon = Logon(); + responseContent.append(logon); + clearSession(); + writeResponse(e.getChannel()); + return; + } + } + boolean getMenu = false; + if (params.containsKey("Logon")) { + String name = null, password = null; + List values = null; + if (!params.isEmpty()) { + // get values + if (params.containsKey("name")) { + values = params.get("name"); + if (values != null) { + name = values.get(0); + if (name == null || name.length() == 0) { + getMenu = true; + } + } + } else { + getMenu = true; + } + // search the nb param + if ((!getMenu) && params.containsKey("passwd")) { + values = params.get("passwd"); + if (values != null) { + password = values.get(0); + if (password == null || password.length() == 0) { + getMenu = true; + } else { + getMenu = false; + } + } else { + getMenu = true; + } + } else { + getMenu = true; + } + } else { + getMenu = true; + } + if (!getMenu) { + logger.debug("Name? " + + name.equals(Configuration.configuration.ADMINNAME) + + " Passwd? " + Arrays.equals(password.getBytes(), + Configuration.configuration.getSERVERADMINKEY())); + if (name.equals(Configuration.configuration.ADMINNAME) && + Arrays.equals(password.getBytes(), + Configuration.configuration.getSERVERADMINKEY())) { + authentHttp.getAuth().specialNoSessionAuth(true, + Configuration.configuration.HOST_ID); + authentHttp.setStatus(70); + } else { + getMenu = true; + } + if (!authentHttp.isAuthenticated()) { + authentHttp.setStatus(71); + logger.debug("Still not authenticated: {}", authentHttp); + getMenu = true; + } + logger.debug("Identified: "+authentHttp.getAuth().isIdentified()+":"+authentHttp.isAuthenticated()); + // load DbSession + if (this.dbSession == null) { + try { + if (DbConstant.admin.isConnected) { + this.dbSession = new DbSession(DbConstant.admin, false); + DbAdmin.nbHttpSession++; + this.isPrivateDbSession = true; + } + } catch (WaarpDatabaseNoConnectionException e1) { + // Cannot connect so use default connection + logger.warn("Use default database connection"); + this.dbSession = DbConstant.admin.session; + } + } + } + } else { + getMenu = true; + } + if (getMenu) { + String logon = Logon(); + responseContent.append(logon); + clearSession(); + writeResponse(e.getChannel()); + } else { + String index = index(); + responseContent.append(index); + clearSession(); + admin = new DefaultCookie(R66SESSION, Configuration.configuration.HOST_ID + + Long.toHexString(new Random().nextLong())); + sessions.put(admin.getValue(), this.authentHttp); + authentHttp.setStatus(72); + if (this.isPrivateDbSession) { + dbSessions.put(admin.getValue(), dbSession); + } + logger.debug("CreateSession: " + uriRequest + ":{}", admin); + writeResponse(e.getChannel()); + } + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + HttpRequest request = this.request = (HttpRequest) e.getMessage(); + queryStringDecoder = new QueryStringDecoder(request.getUri()); + uriRequest = queryStringDecoder.getPath(); + logger.debug("Msg: " + uriRequest); + if (uriRequest.contains("gre/") || uriRequest.contains("img/") || + uriRequest.contains("res/")) { + HttpWriteCacheEnable.writeFile(request, + e.getChannel(), Configuration.configuration.httpBasePath + uriRequest, + R66SESSION); + return; + } + checkSession(e.getChannel()); + if (!authentHttp.isAuthenticated()) { + logger.debug("Not Authent: " + uriRequest + ":{}", authentHttp); + checkAuthent(e); + return; + } + String find = uriRequest; + if (uriRequest.charAt(0) == '/') { + find = uriRequest.substring(1); + } + find = find.substring(0, find.indexOf(".")); + REQUEST req = REQUEST.index; + try { + req = REQUEST.valueOf(find); + } catch (IllegalArgumentException e1) { + req = REQUEST.index; + logger.debug("NotFound: " + find + ":" + uriRequest); + } + switch (req) { + case CancelRestart: + responseContent.append(CancelRestart()); + break; + case Export: + responseContent.append(Export()); + break; + case Hosts: + responseContent.append(Hosts()); + break; + case index: + responseContent.append(index()); + break; + case Listing: + responseContent.append(Listing()); + break; + case Logon: + responseContent.append(index()); + break; + case Rules: + responseContent.append(Rules()); + break; + case System: + responseContent.append(System()); + break; + case Transfers: + responseContent.append(Transfers()); + break; + default: + responseContent.append(index()); + break; + } + writeResponse(e.getChannel()); + } + + private void checkSession(Channel channel) { + String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); + if (cookieString != null) { + CookieDecoder cookieDecoder = new CookieDecoder(); + Set cookies = cookieDecoder.decode(cookieString); + if (!cookies.isEmpty()) { + for (Cookie elt : cookies) { + if (elt.getName().equalsIgnoreCase(R66SESSION)) { + logger.debug("Found session: "+elt); + admin = elt; + R66Session session = sessions.get(admin.getValue()); + if (session != null) { + authentHttp = session; + authentHttp.setStatus(73); + } else { + admin = null; + continue; + } + DbSession dbSession = dbSessions.get(admin.getValue()); + if (dbSession != null) { + this.dbSession = dbSession; + } else { + admin = null; + continue; + } + break; + } + } + } + } + if (admin == null) { + logger.debug("NoSession: " + uriRequest + ":{}", admin); + } + } + + private void handleCookies(HttpResponse response) { + String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); + if (cookieString != null) { + CookieDecoder cookieDecoder = new CookieDecoder(); + Set cookies = cookieDecoder.decode(cookieString); + if (!cookies.isEmpty()) { + // Reset the sessions if necessary. + CookieEncoder cookieEncoder = new CookieEncoder(true); + boolean findSession = false; + for (Cookie cookie : cookies) { + if (cookie.getName().equalsIgnoreCase(R66SESSION)) { + if (newSession) { + findSession = false; + } else { + findSession = true; + cookieEncoder.addCookie(cookie); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + cookieEncoder = new CookieEncoder(true); + } + } else { + cookieEncoder.addCookie(cookie); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + cookieEncoder = new CookieEncoder(true); + } + } + newSession = false; + if (!findSession) { + if (admin != null) { + cookieEncoder.addCookie(admin); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + logger.debug("AddSession: " + uriRequest + ":{}", admin); + } + } + } + } else if (admin != null) { + CookieEncoder cookieEncoder = new CookieEncoder(true); + cookieEncoder.addCookie(admin); + logger.debug("AddSession: " + uriRequest + ":{}", admin); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); + } + } + + /** + * Write the response + * + * @param e + */ + private void writeResponse(Channel channel) { + // Convert the response content to a ChannelBuffer. + ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), + WaarpStringUtils.UTF8); + responseContent.setLength(0); + + // Decide whether to close the connection or not. + boolean keepAlive = HttpHeaders.isKeepAlive(request); + boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request + .getHeader(HttpHeaders.Names.CONNECTION)) || + (!keepAlive) || forceClose; + + // Build the response object. + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); + response.setContent(buf); + response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); + if (keepAlive) { + response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); + } + if (!close) { + // There's no need to add 'Content-Length' header + // if this is the last response. + response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, + String.valueOf(buf.readableBytes())); + } + + handleCookies(response); + + // Write the response. + ChannelFuture future = channel.write(response); + // Close the connection after the write operation is done if necessary. + if (close) { + future.addListener(WaarpSslUtility.SSLCLOSE); + } + if (shutdown) { + ChannelUtils.startShutdown(); + } + } + + /** + * Send an error and close + * + * @param ctx + * @param status + */ + private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { + HttpResponse response = new DefaultHttpResponse( + HttpVersion.HTTP_1_1, status); + response.setHeader( + HttpHeaders.Names.CONTENT_TYPE, "text/html"); + responseContent.setLength(0); + responseContent.append(error(status.toString())); + response.setContent(ChannelBuffers.copiedBuffer(responseContent.toString(), + WaarpStringUtils.UTF8)); + clearSession(); + // Close the connection as soon as the error message is sent. + ctx.getChannel().write(response).addListener(WaarpSslUtility.SSLCLOSE); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) + throws Exception { + OpenR66Exception exception = OpenR66ExceptionTrappedFactory + .getExceptionFromTrappedException(e.getChannel(), e); + if (exception != null) { + if (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) { + if (e.getCause() instanceof IOException) { + // Nothing to do + return; + } + logger.warn("Exception in HttpSslHandler {}", exception.getMessage()); + } + if (e.getChannel().isConnected()) { + sendError(ctx, HttpResponseStatus.BAD_REQUEST); + } + } else { + // Nothing to do + return; + } + } + + /* + * (non-Javadoc) + * @see + * org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelOpen(org.jboss.netty.channel. + * ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + Channel channel = e.getChannel(); + Configuration.configuration.getHttpChannelGroup().add(channel); + super.channelOpen(ctx, e); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslPipelineFactory.java index 5dff504f2..f6bc929ae 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/http/adminssl/HttpSslPipelineFactory.java @@ -1,71 +1,71 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.http.adminssl; - -import java.util.concurrent.ExecutorService; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.handler.codec.http.HttpChunkAggregator; -import org.jboss.netty.handler.codec.http.HttpContentCompressor; -import org.jboss.netty.handler.codec.http.HttpRequestDecoder; -import org.jboss.netty.handler.codec.http.HttpResponseEncoder; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.jboss.netty.handler.ssl.SslHandler; -import org.jboss.netty.handler.stream.ChunkedWriteHandler; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * @author Frederic Bregier - * - */ -public class HttpSslPipelineFactory implements ChannelPipelineFactory { - private final ExecutorService executorService; - public boolean useHttpCompression = false; - public boolean enableRenegotiation = false; - - public HttpSslPipelineFactory(boolean useHttpCompression, - boolean enableRenegotiation, - ExecutorService executor) { - this.useHttpCompression = useHttpCompression; - this.enableRenegotiation = enableRenegotiation; - this.executorService = executor; - } - - public ChannelPipeline getPipeline() { - final ChannelPipeline pipeline = Channels.pipeline(); - // Add SSL handler first to encrypt and decrypt everything. - SslHandler sslhandler = Configuration.waarpSslContextFactory.initPipelineFactory(true, - false, enableRenegotiation, executorService); - sslhandler.setIssueHandshake(true); - pipeline.addLast("ssl", sslhandler); - - pipeline.addLast("decoder", new HttpRequestDecoder()); - pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); - pipeline.addLast("encoder", new HttpResponseEncoder()); - pipeline.addLast("pipelineExecutor", new ExecutionHandler( - Configuration.configuration.getHttpPipelineExecutor())); - pipeline.addLast("streamer", new ChunkedWriteHandler()); - if (useHttpCompression) { - pipeline.addLast("deflater", new HttpContentCompressor()); - } - pipeline.addLast("handler", new HttpSslHandler()); - return pipeline; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.http.adminssl; + +import java.util.concurrent.ExecutorService; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.handler.codec.http.HttpChunkAggregator; +import org.jboss.netty.handler.codec.http.HttpContentCompressor; +import org.jboss.netty.handler.codec.http.HttpRequestDecoder; +import org.jboss.netty.handler.codec.http.HttpResponseEncoder; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.jboss.netty.handler.ssl.SslHandler; +import org.jboss.netty.handler.stream.ChunkedWriteHandler; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * @author Frederic Bregier + * + */ +public class HttpSslPipelineFactory implements ChannelPipelineFactory { + private final ExecutorService executorService; + public boolean useHttpCompression = false; + public boolean enableRenegotiation = false; + + public HttpSslPipelineFactory(boolean useHttpCompression, + boolean enableRenegotiation, + ExecutorService executor) { + this.useHttpCompression = useHttpCompression; + this.enableRenegotiation = enableRenegotiation; + this.executorService = executor; + } + + public ChannelPipeline getPipeline() { + final ChannelPipeline pipeline = Channels.pipeline(); + // Add SSL handler first to encrypt and decrypt everything. + SslHandler sslhandler = Configuration.waarpSslContextFactory.initPipelineFactory(true, + false, enableRenegotiation, executorService); + sslhandler.setIssueHandshake(true); + pipeline.addLast("ssl", sslhandler); + + pipeline.addLast("decoder", new HttpRequestDecoder()); + pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); + pipeline.addLast("encoder", new HttpResponseEncoder()); + pipeline.addLast("pipelineExecutor", new ExecutionHandler( + Configuration.configuration.getHttpPipelineExecutor())); + pipeline.addLast("streamer", new ChunkedWriteHandler()); + if (useHttpCompression) { + pipeline.addLast("deflater", new HttpContentCompressor()); + } + pipeline.addLast("handler", new HttpSslHandler()); + return pipeline; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/http/adminssl/package-info.java b/src/main/java/org/waarp/openr66/protocol/http/adminssl/package-info.java index eda2a1a69..87491e713 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/adminssl/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/http/adminssl/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing HTTPS Administration support - * - * @apiviz.landmark - */ -package org.waarp.openr66.protocol.http.adminssl; - +/** + * Classes implementing HTTPS Administration support + * + * @apiviz.landmark + */ +package org.waarp.openr66.protocol.http.adminssl; + diff --git a/src/main/java/org/waarp/openr66/protocol/http/package-info.java b/src/main/java/org/waarp/openr66/protocol/http/package-info.java index 869a0b2fd..e3342679d 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/http/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing HTTP information support - * - * @apiviz.landmark - */ -package org.waarp.openr66.protocol.http; - +/** + * Classes implementing HTTP information support + * + * @apiviz.landmark + */ +package org.waarp.openr66.protocol.http; + diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalChannelReference.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalChannelReference.java index 11102b047..bf614c626 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalChannelReference.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalChannelReference.java @@ -1,640 +1,640 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp. If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.waarp.common.database.DbSession; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.RecvThroughHandler; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.networkhandler.NetworkChannel; -import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; -import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Reference of one object using Local Channel localId and containing local channel and network - * channel. - * - * @author Frederic Bregier - */ -public class LocalChannelReference { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LocalChannelReference.class); - - /** - * Local Channel - */ - private final Channel localChannel; - - /** - * Network Channel - */ - private final Channel networkChannel; - - /** - * Traffic handler associated if any - */ - private ChannelTrafficShapingHandler cts; - - /** - * Associated NetworkChannel - */ - private NetworkChannel networkChannelObject; - - /** - * Network Server Handler - */ - private final NetworkServerHandler networkServerHandler; - - /** - * Local Id - */ - private final Integer localId; - - /** - * Remote Id - */ - private Integer remoteId; - - /** - * Future on Request - */ - private final R66Future futureRequest; - - /** - * Future on Valid Starting Request - */ - private R66Future futureValidRequest = new R66Future(true); - - /** - * Future on Transfer - */ - private R66Future futureEndTransfer = new R66Future(true); - - /** - * Future on Connection - */ - private final R66Future futureConnection = new R66Future(true); - - /** - * Future on Startup - */ - private final R66Future futureStartup = new R66Future(true); - - /** - * Session - */ - private R66Session session; - - /** - * Last error message - */ - private String errorMessage = "NoError"; - - /** - * Last error code - */ - private ErrorCode code = ErrorCode.Unknown; - - /** - * RecvThroughHandler - */ - private RecvThroughHandler recvThroughHandler; - - private boolean isSendThroughMode = false; - /** - * Thread for ClientRunner if any - */ - private ClientRunner clientRunner = null; - - /** - * To be able to check hash once all transfer is over once again - */ - private String hashComputeDuringTransfer = null; - - /** - * - * @param localChannel - * @param networkChannel - * @param remoteId - * @param futureRequest - */ - public LocalChannelReference(Channel localChannel, Channel networkChannel, - Integer remoteId, R66Future futureRequest) { - this.localChannel = localChannel; - this.networkChannel = networkChannel; - networkServerHandler = (NetworkServerHandler) this.networkChannel - .getPipeline().getLast(); - localId = this.localChannel.getId(); - this.remoteId = remoteId; - if (futureRequest == null) { - this.futureRequest = new R66Future(true); - } else { - this.futureRequest = futureRequest; - } - cts = (ChannelTrafficShapingHandler) networkChannel.getPipeline().get( - NetworkServerPipelineFactory.LIMITCHANNEL); - } - - /** - * Special empty LCR constructor - */ - public LocalChannelReference() { - this.localChannel = null; - this.networkChannel = null; - networkServerHandler = null; - localId = 0; - this.futureRequest = new R66Future(true); - } - - /** - * @return the localChannel - */ - public Channel getLocalChannel() { - return localChannel; - } - - /** - * @return the networkChannel - */ - public Channel getNetworkChannel() { - return networkChannel; - } - - /** - * @return the id - */ - public Integer getLocalId() { - return localId; - } - - /** - * @return the remoteId - */ - public Integer getRemoteId() { - return remoteId; - } - - /** - * @return the ChannelTrafficShapingHandler - */ - public ChannelTrafficShapingHandler getChannelTrafficShapingHandler() { - return cts; - } - - /** - * @return the networkChannelObject - */ - public NetworkChannel getNetworkChannelObject() { - return networkChannelObject; - } - - /** - * @param networkChannelObject - * the networkChannelObject to set - */ - public void setNetworkChannelObject(NetworkChannel networkChannelObject) { - this.networkChannelObject = networkChannelObject; - } - - /** - * @return the networkServerHandler - */ - public NetworkServerHandler getNetworkServerHandler() { - return networkServerHandler; - } - - /** - * - * @return the actual dbSession - */ - public DbSession getDbSession() { - if (networkServerHandler != null) { - return networkServerHandler.getDbSession(); - } - return DbConstant.admin.session; - } - - /** - * @param remoteId - * the remoteId to set - */ - public void setRemoteId(Integer remoteId) { - this.remoteId = remoteId; - } - - /** - * @return the session - */ - public R66Session getSession() { - return session; - } - - /** - * @param session - * the session to set - */ - public void setSession(R66Session session) { - this.session = session; - } - - /** - * @return the current errorMessage - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * @param errorMessage - * the errorMessage to set - */ - public void setErrorMessage(String errorMessage, ErrorCode code) { - this.errorMessage = errorMessage; - this.code = code; - } - - /** - * @return the code - */ - public ErrorCode getCurrentCode() { - return code; - } - - /** - * Validate or not the Startup (before connection) - * - * @param validate - */ - public void validateStartup(boolean validate) { - if (futureStartup.isDone()) { - return; - } - if (validate) { - futureStartup.setSuccess(); - } else { - futureStartup.cancel(); - } - } - - /** - * - * @return the futureValidateStartup - */ - public R66Future getFutureValidateStartup() { - try { - if (!futureStartup.await(Configuration.configuration.TIMEOUTCON)) { - validateStartup(false); - return futureStartup; - } - } catch (InterruptedException e) { - validateStartup(false); - return futureStartup; - } - return futureStartup; - } - - /** - * Validate or Invalidate the connection (authentication) - * - * @param validate - */ - public void validateConnection(boolean validate, R66Result result) { - if (futureConnection.isDone()) { - logger.debug("LocalChannelReference already validated: " + - futureConnection.isSuccess()); - return; - } - if (validate) { - futureConnection.setResult(result); - futureConnection.setSuccess(); - } else { - futureConnection.setResult(result); - setErrorMessage(result.getMessage(), result.code); - futureConnection.cancel(); - } - } - - /** - * - * @return the futureValidateConnection - */ - public R66Future getFutureValidateConnection() { - R66Result result; - try { - for (int i = 0; i < Configuration.RETRYNB; i++) { - if (this.networkChannel.isConnected()) { - if (!futureConnection.await(Configuration.configuration.TIMEOUTCON)) { - if (futureConnection.isDone()) { - return futureConnection; - } else { - if (this.networkChannel.isConnected()) { - continue; - } - result = new R66Result( - new OpenR66ProtocolNoConnectionException( - "Out of time"), session, false, - ErrorCode.ConnectionImpossible, null); - validateConnection(false, result); - return futureConnection; - } - } else { - return futureConnection; - } - } else { - break; - } - } - } catch (InterruptedException e) { - result = new R66Result( - new OpenR66ProtocolNoConnectionException( - "Interrupted connection"), session, false, - ErrorCode.ConnectionImpossible, null); - validateConnection(false, result); - return futureConnection; - } - logger.warn("Cannot get Connection due to out of Time: {}", this); - result = new R66Result( - new OpenR66ProtocolNoConnectionException( - "Out of time"), session, false, - ErrorCode.ConnectionImpossible, null); - validateConnection(false, result); - return futureConnection; - } - - /** - * Validate the End of a Transfer - * - * @param finalValue - */ - public void validateEndTransfer(R66Result finalValue) { - if (!futureEndTransfer.isDone()) { - futureEndTransfer.setResult(finalValue); - futureEndTransfer.setSuccess(); - } else { - logger.debug("Could not validate since Already validated: " + - futureEndTransfer.isSuccess() + " " + finalValue); - if (!futureEndTransfer.getResult().isAnswered) { - futureEndTransfer.getResult().isAnswered = finalValue.isAnswered; - } - } - } - - /** - * @return the futureEndTransfer - */ - public R66Future getFutureEndTransfer() { - return futureEndTransfer; - } - - /** - * Special waiter for Send Through method. It reset the EndTransfer future. - * - * @throws OpenR66Exception - */ - public void waitReadyForSendThrough() throws OpenR66Exception { - logger.debug("Wait for End of Prepare Transfer"); - try { - this.futureEndTransfer.await(); - } catch (InterruptedException e) { - throw new OpenR66RunnerErrorException("Interrupted", e); - } - if (this.futureEndTransfer.isSuccess()) { - // reset since transfer will start now - this.futureEndTransfer = new R66Future(true); - } else { - throw this.futureEndTransfer.getResult().exception; - } - } - - /** - * @return the futureValidRequest - */ - public R66Future getFutureValidRequest() { - return futureValidRequest; - } - - /** - * @return the futureRequest - */ - public R66Future getFutureRequest() { - return futureRequest; - } - - /** - * Invalidate the current request - * - * @param finalvalue - */ - public void invalidateRequest(R66Result finalvalue) { - R66Result finalValue = finalvalue; - if (finalValue == null) { - finalValue = new R66Result(session, false, ErrorCode.Unknown, this.session.getRunner()); - } - logger.debug("FET: " + futureEndTransfer.isDone() + ":" + - futureEndTransfer.isSuccess() + " FVR: " + - futureValidRequest.isDone() + ":" + - futureValidRequest.isSuccess() + " FR: " + - futureRequest.isDone() + ":" + futureRequest.isSuccess() + " " + - finalValue.getMessage()); - if (!futureEndTransfer.isDone()) { - futureEndTransfer.setResult(finalValue); - if (finalValue.exception != null) { - futureEndTransfer.setFailure(finalValue.exception); - } else { - futureEndTransfer.cancel(); - } - } - if (!futureValidRequest.isDone()) { - futureValidRequest.setResult(finalValue); - if (finalValue.exception != null) { - futureValidRequest.setFailure(finalValue.exception); - } else { - futureValidRequest.cancel(); - } - } - logger.debug("Invalidate Request", new Exception( - "Trace for Invalidation")); - if (finalValue.code != ErrorCode.ServerOverloaded) { - if (!futureRequest.isDone()) { - setErrorMessage(finalValue.getMessage(), finalValue.code); - futureRequest.setResult(finalValue); - if (finalValue.exception != null) { - futureRequest.setFailure(finalValue.exception); - } else { - futureRequest.cancel(); - } - } else { - logger.debug("Could not invalidate since Already finished: " + - futureEndTransfer.getResult()); - } - } else { - setErrorMessage(finalValue.getMessage(), finalValue.code); - logger.debug("Overloaded"); - } - if (this.session != null) { - DbTaskRunner runner = this.session.getRunner(); - if (runner != null) { - if (runner.isSender()) { - NetworkTransaction.stopRetrieve(this); - } - } - } - } - - /** - * Validate the current Request - * - * @param finalValue - */ - public void validateRequest(R66Result finalValue) { - setErrorMessage("NoError", null); - if (!futureEndTransfer.isDone()) { - logger.debug("Will validate EndTransfer"); - validateEndTransfer(finalValue); - } - if (!futureValidRequest.isDone()) { - futureValidRequest.setResult(finalValue); - futureValidRequest.setSuccess(); - } - logger.debug("Validate Request"); - if (!futureRequest.isDone()) { - if (finalValue.other == null && - session.getBusinessObject() != null && - session.getBusinessObject().getInfo() != null) { - finalValue.other = session.getBusinessObject().getInfo(); - } - futureRequest.setResult(finalValue); - futureRequest.setSuccess(); - } else { - logger.info("Already validated: " + futureRequest.isSuccess() + - " " + finalValue); - if (!futureRequest.getResult().isAnswered) { - futureRequest.getResult().isAnswered = finalValue.isAnswered; - } - } - } - - @Override - public String toString() { - return "LCR: L: " + localId + " R: " + remoteId + "\nStartup[" + - (futureStartup != null ? futureStartup : "noStartup") + "]\nConn[" + - (futureConnection != null ? futureConnection : "noConn") - + "]\nValidRequestRequest[" + - (futureValidRequest != null ? futureValidRequest : "noValidRequest") - + "]\nEndTransfer[" + - (futureEndTransfer != null ? futureEndTransfer : "noEndTransfer") + "]\nRequest[" + - (futureRequest != null ? futureRequest : "noRequest") + "]"; - } - - /** - * @return the recvThroughHandler - */ - public RecvThroughHandler getRecvThroughHandler() { - return recvThroughHandler; - } - - /** - * - * @return True if in RecvThrough Mode - */ - public boolean isRecvThroughMode() { - return recvThroughHandler != null; - } - - /** - * @param recvThroughHandler - * the recvThroughHandler to set - */ - public void setRecvThroughHandler(RecvThroughHandler recvThroughHandler) { - this.recvThroughHandler = recvThroughHandler; - } - - /** - * @return True if in SendThrough Mode - */ - public boolean isSendThroughMode() { - return isSendThroughMode; - } - - /** - * @param isSendThroughMode - * the isSendThroughMode to set - */ - public void setSendThroughMode(boolean isSendThroughMode) { - this.isSendThroughMode = isSendThroughMode; - } - - /** - * @return the clientRunner - */ - public ClientRunner getClientRunner() { - return clientRunner; - } - - /** - * @param clientRunner - * the clientRunner to set - */ - public void setClientRunner(ClientRunner clientRunner) { - this.clientRunner = clientRunner; - } - - /** - * Shortcut to set a new state in Session - * - * @param desiredState - */ - public void sessionNewState(R66FiniteDualStates desiredState) { - if (session != null) { - session.newState(desiredState); - } - } - - /** - * @return the hashComputeDuringTransfer - */ - public String getHashComputeDuringTransfer() { - return hashComputeDuringTransfer; - } - - /** - * @param hashComputeDuringTransfer the hashComputeDuringTransfer to set - */ - public void setHashComputeDuringTransfer(String hashComputeDuringTransfer) { - this.hashComputeDuringTransfer = hashComputeDuringTransfer; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp. If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.waarp.common.database.DbSession; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.RecvThroughHandler; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.networkhandler.NetworkChannel; +import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; +import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Reference of one object using Local Channel localId and containing local channel and network + * channel. + * + * @author Frederic Bregier + */ +public class LocalChannelReference { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LocalChannelReference.class); + + /** + * Local Channel + */ + private final Channel localChannel; + + /** + * Network Channel + */ + private final Channel networkChannel; + + /** + * Traffic handler associated if any + */ + private ChannelTrafficShapingHandler cts; + + /** + * Associated NetworkChannel + */ + private NetworkChannel networkChannelObject; + + /** + * Network Server Handler + */ + private final NetworkServerHandler networkServerHandler; + + /** + * Local Id + */ + private final Integer localId; + + /** + * Remote Id + */ + private Integer remoteId; + + /** + * Future on Request + */ + private final R66Future futureRequest; + + /** + * Future on Valid Starting Request + */ + private R66Future futureValidRequest = new R66Future(true); + + /** + * Future on Transfer + */ + private R66Future futureEndTransfer = new R66Future(true); + + /** + * Future on Connection + */ + private final R66Future futureConnection = new R66Future(true); + + /** + * Future on Startup + */ + private final R66Future futureStartup = new R66Future(true); + + /** + * Session + */ + private R66Session session; + + /** + * Last error message + */ + private String errorMessage = "NoError"; + + /** + * Last error code + */ + private ErrorCode code = ErrorCode.Unknown; + + /** + * RecvThroughHandler + */ + private RecvThroughHandler recvThroughHandler; + + private boolean isSendThroughMode = false; + /** + * Thread for ClientRunner if any + */ + private ClientRunner clientRunner = null; + + /** + * To be able to check hash once all transfer is over once again + */ + private String hashComputeDuringTransfer = null; + + /** + * + * @param localChannel + * @param networkChannel + * @param remoteId + * @param futureRequest + */ + public LocalChannelReference(Channel localChannel, Channel networkChannel, + Integer remoteId, R66Future futureRequest) { + this.localChannel = localChannel; + this.networkChannel = networkChannel; + networkServerHandler = (NetworkServerHandler) this.networkChannel + .getPipeline().getLast(); + localId = this.localChannel.getId(); + this.remoteId = remoteId; + if (futureRequest == null) { + this.futureRequest = new R66Future(true); + } else { + this.futureRequest = futureRequest; + } + cts = (ChannelTrafficShapingHandler) networkChannel.getPipeline().get( + NetworkServerPipelineFactory.LIMITCHANNEL); + } + + /** + * Special empty LCR constructor + */ + public LocalChannelReference() { + this.localChannel = null; + this.networkChannel = null; + networkServerHandler = null; + localId = 0; + this.futureRequest = new R66Future(true); + } + + /** + * @return the localChannel + */ + public Channel getLocalChannel() { + return localChannel; + } + + /** + * @return the networkChannel + */ + public Channel getNetworkChannel() { + return networkChannel; + } + + /** + * @return the id + */ + public Integer getLocalId() { + return localId; + } + + /** + * @return the remoteId + */ + public Integer getRemoteId() { + return remoteId; + } + + /** + * @return the ChannelTrafficShapingHandler + */ + public ChannelTrafficShapingHandler getChannelTrafficShapingHandler() { + return cts; + } + + /** + * @return the networkChannelObject + */ + public NetworkChannel getNetworkChannelObject() { + return networkChannelObject; + } + + /** + * @param networkChannelObject + * the networkChannelObject to set + */ + public void setNetworkChannelObject(NetworkChannel networkChannelObject) { + this.networkChannelObject = networkChannelObject; + } + + /** + * @return the networkServerHandler + */ + public NetworkServerHandler getNetworkServerHandler() { + return networkServerHandler; + } + + /** + * + * @return the actual dbSession + */ + public DbSession getDbSession() { + if (networkServerHandler != null) { + return networkServerHandler.getDbSession(); + } + return DbConstant.admin.session; + } + + /** + * @param remoteId + * the remoteId to set + */ + public void setRemoteId(Integer remoteId) { + this.remoteId = remoteId; + } + + /** + * @return the session + */ + public R66Session getSession() { + return session; + } + + /** + * @param session + * the session to set + */ + public void setSession(R66Session session) { + this.session = session; + } + + /** + * @return the current errorMessage + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * @param errorMessage + * the errorMessage to set + */ + public void setErrorMessage(String errorMessage, ErrorCode code) { + this.errorMessage = errorMessage; + this.code = code; + } + + /** + * @return the code + */ + public ErrorCode getCurrentCode() { + return code; + } + + /** + * Validate or not the Startup (before connection) + * + * @param validate + */ + public void validateStartup(boolean validate) { + if (futureStartup.isDone()) { + return; + } + if (validate) { + futureStartup.setSuccess(); + } else { + futureStartup.cancel(); + } + } + + /** + * + * @return the futureValidateStartup + */ + public R66Future getFutureValidateStartup() { + try { + if (!futureStartup.await(Configuration.configuration.TIMEOUTCON)) { + validateStartup(false); + return futureStartup; + } + } catch (InterruptedException e) { + validateStartup(false); + return futureStartup; + } + return futureStartup; + } + + /** + * Validate or Invalidate the connection (authentication) + * + * @param validate + */ + public void validateConnection(boolean validate, R66Result result) { + if (futureConnection.isDone()) { + logger.debug("LocalChannelReference already validated: " + + futureConnection.isSuccess()); + return; + } + if (validate) { + futureConnection.setResult(result); + futureConnection.setSuccess(); + } else { + futureConnection.setResult(result); + setErrorMessage(result.getMessage(), result.code); + futureConnection.cancel(); + } + } + + /** + * + * @return the futureValidateConnection + */ + public R66Future getFutureValidateConnection() { + R66Result result; + try { + for (int i = 0; i < Configuration.RETRYNB; i++) { + if (this.networkChannel.isConnected()) { + if (!futureConnection.await(Configuration.configuration.TIMEOUTCON)) { + if (futureConnection.isDone()) { + return futureConnection; + } else { + if (this.networkChannel.isConnected()) { + continue; + } + result = new R66Result( + new OpenR66ProtocolNoConnectionException( + "Out of time"), session, false, + ErrorCode.ConnectionImpossible, null); + validateConnection(false, result); + return futureConnection; + } + } else { + return futureConnection; + } + } else { + break; + } + } + } catch (InterruptedException e) { + result = new R66Result( + new OpenR66ProtocolNoConnectionException( + "Interrupted connection"), session, false, + ErrorCode.ConnectionImpossible, null); + validateConnection(false, result); + return futureConnection; + } + logger.warn("Cannot get Connection due to out of Time: {}", this); + result = new R66Result( + new OpenR66ProtocolNoConnectionException( + "Out of time"), session, false, + ErrorCode.ConnectionImpossible, null); + validateConnection(false, result); + return futureConnection; + } + + /** + * Validate the End of a Transfer + * + * @param finalValue + */ + public void validateEndTransfer(R66Result finalValue) { + if (!futureEndTransfer.isDone()) { + futureEndTransfer.setResult(finalValue); + futureEndTransfer.setSuccess(); + } else { + logger.debug("Could not validate since Already validated: " + + futureEndTransfer.isSuccess() + " " + finalValue); + if (!futureEndTransfer.getResult().isAnswered) { + futureEndTransfer.getResult().isAnswered = finalValue.isAnswered; + } + } + } + + /** + * @return the futureEndTransfer + */ + public R66Future getFutureEndTransfer() { + return futureEndTransfer; + } + + /** + * Special waiter for Send Through method. It reset the EndTransfer future. + * + * @throws OpenR66Exception + */ + public void waitReadyForSendThrough() throws OpenR66Exception { + logger.debug("Wait for End of Prepare Transfer"); + try { + this.futureEndTransfer.await(); + } catch (InterruptedException e) { + throw new OpenR66RunnerErrorException("Interrupted", e); + } + if (this.futureEndTransfer.isSuccess()) { + // reset since transfer will start now + this.futureEndTransfer = new R66Future(true); + } else { + throw this.futureEndTransfer.getResult().exception; + } + } + + /** + * @return the futureValidRequest + */ + public R66Future getFutureValidRequest() { + return futureValidRequest; + } + + /** + * @return the futureRequest + */ + public R66Future getFutureRequest() { + return futureRequest; + } + + /** + * Invalidate the current request + * + * @param finalvalue + */ + public void invalidateRequest(R66Result finalvalue) { + R66Result finalValue = finalvalue; + if (finalValue == null) { + finalValue = new R66Result(session, false, ErrorCode.Unknown, this.session.getRunner()); + } + logger.debug("FET: " + futureEndTransfer.isDone() + ":" + + futureEndTransfer.isSuccess() + " FVR: " + + futureValidRequest.isDone() + ":" + + futureValidRequest.isSuccess() + " FR: " + + futureRequest.isDone() + ":" + futureRequest.isSuccess() + " " + + finalValue.getMessage()); + if (!futureEndTransfer.isDone()) { + futureEndTransfer.setResult(finalValue); + if (finalValue.exception != null) { + futureEndTransfer.setFailure(finalValue.exception); + } else { + futureEndTransfer.cancel(); + } + } + if (!futureValidRequest.isDone()) { + futureValidRequest.setResult(finalValue); + if (finalValue.exception != null) { + futureValidRequest.setFailure(finalValue.exception); + } else { + futureValidRequest.cancel(); + } + } + logger.debug("Invalidate Request", new Exception( + "Trace for Invalidation")); + if (finalValue.code != ErrorCode.ServerOverloaded) { + if (!futureRequest.isDone()) { + setErrorMessage(finalValue.getMessage(), finalValue.code); + futureRequest.setResult(finalValue); + if (finalValue.exception != null) { + futureRequest.setFailure(finalValue.exception); + } else { + futureRequest.cancel(); + } + } else { + logger.debug("Could not invalidate since Already finished: " + + futureEndTransfer.getResult()); + } + } else { + setErrorMessage(finalValue.getMessage(), finalValue.code); + logger.debug("Overloaded"); + } + if (this.session != null) { + DbTaskRunner runner = this.session.getRunner(); + if (runner != null) { + if (runner.isSender()) { + NetworkTransaction.stopRetrieve(this); + } + } + } + } + + /** + * Validate the current Request + * + * @param finalValue + */ + public void validateRequest(R66Result finalValue) { + setErrorMessage("NoError", null); + if (!futureEndTransfer.isDone()) { + logger.debug("Will validate EndTransfer"); + validateEndTransfer(finalValue); + } + if (!futureValidRequest.isDone()) { + futureValidRequest.setResult(finalValue); + futureValidRequest.setSuccess(); + } + logger.debug("Validate Request"); + if (!futureRequest.isDone()) { + if (finalValue.other == null && + session.getBusinessObject() != null && + session.getBusinessObject().getInfo() != null) { + finalValue.other = session.getBusinessObject().getInfo(); + } + futureRequest.setResult(finalValue); + futureRequest.setSuccess(); + } else { + logger.info("Already validated: " + futureRequest.isSuccess() + + " " + finalValue); + if (!futureRequest.getResult().isAnswered) { + futureRequest.getResult().isAnswered = finalValue.isAnswered; + } + } + } + + @Override + public String toString() { + return "LCR: L: " + localId + " R: " + remoteId + "\nStartup[" + + (futureStartup != null ? futureStartup : "noStartup") + "]\nConn[" + + (futureConnection != null ? futureConnection : "noConn") + + "]\nValidRequestRequest[" + + (futureValidRequest != null ? futureValidRequest : "noValidRequest") + + "]\nEndTransfer[" + + (futureEndTransfer != null ? futureEndTransfer : "noEndTransfer") + "]\nRequest[" + + (futureRequest != null ? futureRequest : "noRequest") + "]"; + } + + /** + * @return the recvThroughHandler + */ + public RecvThroughHandler getRecvThroughHandler() { + return recvThroughHandler; + } + + /** + * + * @return True if in RecvThrough Mode + */ + public boolean isRecvThroughMode() { + return recvThroughHandler != null; + } + + /** + * @param recvThroughHandler + * the recvThroughHandler to set + */ + public void setRecvThroughHandler(RecvThroughHandler recvThroughHandler) { + this.recvThroughHandler = recvThroughHandler; + } + + /** + * @return True if in SendThrough Mode + */ + public boolean isSendThroughMode() { + return isSendThroughMode; + } + + /** + * @param isSendThroughMode + * the isSendThroughMode to set + */ + public void setSendThroughMode(boolean isSendThroughMode) { + this.isSendThroughMode = isSendThroughMode; + } + + /** + * @return the clientRunner + */ + public ClientRunner getClientRunner() { + return clientRunner; + } + + /** + * @param clientRunner + * the clientRunner to set + */ + public void setClientRunner(ClientRunner clientRunner) { + this.clientRunner = clientRunner; + } + + /** + * Shortcut to set a new state in Session + * + * @param desiredState + */ + public void sessionNewState(R66FiniteDualStates desiredState) { + if (session != null) { + session.newState(desiredState); + } + } + + /** + * @return the hashComputeDuringTransfer + */ + public String getHashComputeDuringTransfer() { + return hashComputeDuringTransfer; + } + + /** + * @param hashComputeDuringTransfer the hashComputeDuringTransfer to set + */ + public void setHashComputeDuringTransfer(String hashComputeDuringTransfer) { + this.hashComputeDuringTransfer = hashComputeDuringTransfer; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientHandler.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientHandler.java index 8dee1a32b..e60eaca5b 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientHandler.java @@ -1,183 +1,183 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import static org.waarp.openr66.context.R66FiniteDualStates.ERROR; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelHandler; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.utils.ChannelCloseTimer; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * @author frederic bregier - */ -public class LocalClientHandler extends SimpleChannelHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LocalClientHandler.class); - - /** - * Local Channel Reference - */ - private volatile LocalChannelReference localChannelReference = null; - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. - * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - logger.debug("Local Client Channel Closed: {}", e.getChannel().getId()); - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - logger - .debug("Local Client Channel Connected: " + - e.getChannel().getId()); - } - - /** - * Initiate the LocalChannelReference - * - * @param channel - * @throws InterruptedException - * @throws OpenR66ProtocolNetworkException - */ - private void initLocalClientHandler(Channel channel) - throws InterruptedException, OpenR66ProtocolNetworkException { - int i = 0; - if (localChannelReference == null) { - for (i = 0; i < Configuration.RETRYNB; i++) { - localChannelReference = Configuration.configuration - .getLocalTransaction().getFromId(channel.getId()); - if (localChannelReference != null) { - return; - } - Thread.sleep(Configuration.RETRYINMS); - } - logger.warn("Cannot find local connection"); - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) - */ - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) - throws Exception { - if (localChannelReference == null) { - initLocalClientHandler(e.getChannel()); - } - // only Startup Packet should arrived here ! - final AbstractLocalPacket packet = (AbstractLocalPacket) e.getMessage(); - if (packet.getType() != LocalPacketFactory.STARTUPPACKET) { - logger.error("Local Client Channel Recv wrong packet: " + - e.getChannel().getId() + " : " + packet.toString()); - throw new OpenR66ProtocolSystemException("Should not be here"); - } - logger.debug("LocalClientHandler initialized: " + - (localChannelReference != null)); - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) - throws Exception { - // informs network of the problem - logger.debug( - "Local Client Channel Exception: {}", e.getChannel().getId(), e - .getCause()); - if (localChannelReference == null) { - initLocalClientHandler(e.getChannel()); - } - if (localChannelReference != null) { - OpenR66Exception exception = OpenR66ExceptionTrappedFactory - .getExceptionFromTrappedException(e.getChannel(), e); - localChannelReference.sessionNewState(ERROR); - if (exception != null) { - if (exception instanceof OpenR66ProtocolShutdownException) { - ChannelUtils.startShutdown(); - logger.debug("Will close channel"); - Channels.close(e.getChannel()); - return; - } else if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { - logger.error("Will close channel", exception); - Channels.close(e.getChannel()); - return; - } else if (exception instanceof OpenR66ProtocolNoConnectionException) { - logger.error("Will close channel", exception); - Channels.close(e.getChannel()); - return; - } - final ErrorPacket errorPacket = new ErrorPacket(exception - .getMessage(), - ErrorCode.RemoteError.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); - if (!localChannelReference.getFutureRequest().isDone()) { - localChannelReference.invalidateRequest(new R66Result( - exception, localChannelReference.getSession(), true, - ErrorCode.Internal, null)); - } - } else { - // Nothing to do - return; - } - } - logger.debug("Will close channel"); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import static org.waarp.openr66.context.R66FiniteDualStates.ERROR; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelHandler; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.utils.ChannelCloseTimer; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * @author frederic bregier + */ +public class LocalClientHandler extends SimpleChannelHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LocalClientHandler.class); + + /** + * Local Channel Reference + */ + private volatile LocalChannelReference localChannelReference = null; + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. + * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + logger.debug("Local Client Channel Closed: {}", e.getChannel().getId()); + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + logger + .debug("Local Client Channel Connected: " + + e.getChannel().getId()); + } + + /** + * Initiate the LocalChannelReference + * + * @param channel + * @throws InterruptedException + * @throws OpenR66ProtocolNetworkException + */ + private void initLocalClientHandler(Channel channel) + throws InterruptedException, OpenR66ProtocolNetworkException { + int i = 0; + if (localChannelReference == null) { + for (i = 0; i < Configuration.RETRYNB; i++) { + localChannelReference = Configuration.configuration + .getLocalTransaction().getFromId(channel.getId()); + if (localChannelReference != null) { + return; + } + Thread.sleep(Configuration.RETRYINMS); + } + logger.warn("Cannot find local connection"); + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) + */ + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) + throws Exception { + if (localChannelReference == null) { + initLocalClientHandler(e.getChannel()); + } + // only Startup Packet should arrived here ! + final AbstractLocalPacket packet = (AbstractLocalPacket) e.getMessage(); + if (packet.getType() != LocalPacketFactory.STARTUPPACKET) { + logger.error("Local Client Channel Recv wrong packet: " + + e.getChannel().getId() + " : " + packet.toString()); + throw new OpenR66ProtocolSystemException("Should not be here"); + } + logger.debug("LocalClientHandler initialized: " + + (localChannelReference != null)); + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) + throws Exception { + // informs network of the problem + logger.debug( + "Local Client Channel Exception: {}", e.getChannel().getId(), e + .getCause()); + if (localChannelReference == null) { + initLocalClientHandler(e.getChannel()); + } + if (localChannelReference != null) { + OpenR66Exception exception = OpenR66ExceptionTrappedFactory + .getExceptionFromTrappedException(e.getChannel(), e); + localChannelReference.sessionNewState(ERROR); + if (exception != null) { + if (exception instanceof OpenR66ProtocolShutdownException) { + ChannelUtils.startShutdown(); + logger.debug("Will close channel"); + Channels.close(e.getChannel()); + return; + } else if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { + logger.error("Will close channel", exception); + Channels.close(e.getChannel()); + return; + } else if (exception instanceof OpenR66ProtocolNoConnectionException) { + logger.error("Will close channel", exception); + Channels.close(e.getChannel()); + return; + } + final ErrorPacket errorPacket = new ErrorPacket(exception + .getMessage(), + ErrorCode.RemoteError.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); + if (!localChannelReference.getFutureRequest().isDone()) { + localChannelReference.invalidateRequest(new R66Result( + exception, localChannelReference.getSession(), true, + ErrorCode.Internal, null)); + } + } else { + // Nothing to do + return; + } + } + logger.debug("Will close channel"); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientPipelineFactory.java index 06a6e5945..62093c1ba 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalClientPipelineFactory.java @@ -1,43 +1,43 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; - -/** - * Pipeline Factory for Local Client - * - * @author Frederic Bregier - */ -public class LocalClientPipelineFactory implements ChannelPipelineFactory { - - public ChannelPipeline getPipeline() throws Exception { - final ChannelPipeline pipeline = Channels.pipeline(); - pipeline.addLast("codec", new LocalPacketCodec()); - pipeline.addLast("pipelineExecutor", new ExecutionHandler( - Configuration.configuration.getLocalClientPipelineExecutor())); - pipeline.addLast("handler", new LocalClientHandler()); - return pipeline; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; + +/** + * Pipeline Factory for Local Client + * + * @author Frederic Bregier + */ +public class LocalClientPipelineFactory implements ChannelPipelineFactory { + + public ChannelPipeline getPipeline() throws Exception { + final ChannelPipeline pipeline = Channels.pipeline(); + pipeline.addLast("codec", new LocalPacketCodec()); + pipeline.addLast("pipelineExecutor", new ExecutionHandler( + Configuration.configuration.getLocalClientPipelineExecutor())); + pipeline.addLast("handler", new LocalClientHandler()); + return pipeline; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerHandler.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerHandler.java index a5b7072f9..aca5ed088 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerHandler.java @@ -1,2584 +1,2584 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTD; -import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTR; -import static org.waarp.openr66.context.R66FiniteDualStates.BUSINESSD; -import static org.waarp.openr66.context.R66FiniteDualStates.CLOSEDCHANNEL; -import static org.waarp.openr66.context.R66FiniteDualStates.DATAR; -import static org.waarp.openr66.context.R66FiniteDualStates.ENDREQUESTR; -import static org.waarp.openr66.context.R66FiniteDualStates.ENDREQUESTS; -import static org.waarp.openr66.context.R66FiniteDualStates.ENDTRANSFERR; -import static org.waarp.openr66.context.R66FiniteDualStates.ENDTRANSFERS; -import static org.waarp.openr66.context.R66FiniteDualStates.ERROR; -import static org.waarp.openr66.context.R66FiniteDualStates.INFORMATION; -import static org.waarp.openr66.context.R66FiniteDualStates.REQUESTD; -import static org.waarp.openr66.context.R66FiniteDualStates.REQUESTR; -import static org.waarp.openr66.context.R66FiniteDualStates.SHUTDOWN; -import static org.waarp.openr66.context.R66FiniteDualStates.STARTUP; -import static org.waarp.openr66.context.R66FiniteDualStates.TEST; -import static org.waarp.openr66.context.R66FiniteDualStates.VALID; -import static org.waarp.openr66.context.R66FiniteDualStates.VALIDOTHER; - -import java.io.File; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.security.NoSuchAlgorithmException; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelFutureListener; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelHandler; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.command.exception.Reply421Exception; -import org.waarp.common.command.exception.Reply530Exception; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseNoDataException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.exception.FileTransferException; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.role.RoleDefault.ROLE; -import org.waarp.openr66.client.AbstractBusinessRequest; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; -import org.waarp.openr66.configuration.RuleFileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.authentication.R66Auth; -import org.waarp.openr66.context.filesystem.R66Dir; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.task.ExecJavaTask; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.context.task.exception.OpenR66RunnerException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessCancelException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessQueryAlreadyFinishedException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessQueryStillRunningException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessRemoteFileNotFoundException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessStopException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotAuthenticatedException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; -import org.waarp.openr66.protocol.localhandler.packet.AuthentPacket; -import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.DataPacket; -import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.EndTransferPacket; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ShutdownPacket; -import org.waarp.openr66.protocol.localhandler.packet.StartupPacket; -import org.waarp.openr66.protocol.localhandler.packet.TestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkChannel; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelCloseTimer; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.FileUtils; -import org.waarp.openr66.protocol.utils.R66Future; -import org.waarp.openr66.protocol.utils.TransferUtils; - -/** - * The local server handler handles real end file operations. - * - * @author frederic bregier - */ -public class LocalServerHandler extends SimpleChannelHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LocalServerHandler.class); - - /** - * Session - */ - private volatile R66Session session; - /** - * Local Channel Reference - */ - private volatile LocalChannelReference localChannelReference; - /** - * Global Digest in receive - */ - private volatile FilesystemBasedDigest globalDigest; - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. - * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { - logger.debug("Local Server Channel Closed: {} {}", - (localChannelReference != null ? localChannelReference - : "no LocalChannelReference"), (session.getRunner() != null ? - session.getRunner().toShortString() : "no runner")); - // clean session objects like files - DbTaskRunner runner = session.getRunner(); - boolean mustFinalize = true; - if (localChannelReference != null && - localChannelReference.getFutureRequest().isDone()) { - // already done - } else { - if (localChannelReference != null) { - R66Future fvr = localChannelReference.getFutureValidRequest(); - try { - fvr.await(); - } catch (InterruptedException e1) { - } - if (fvr.isDone()) { - if (!fvr.isSuccess()) { - // test if remote server was Overloaded - if (fvr.getResult().code == ErrorCode.ServerOverloaded) { - // ignore - mustFinalize = false; - } - } - } - logger.debug("Must Finalize: " + mustFinalize); - if (mustFinalize) { - session.newState(ERROR); - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException( - "Finalize too early at close time But Must Finalize"), - session, true, ErrorCode.FinalOp, runner); // True since closed - try { - tryFinalizeRequest(finalValue); - } catch (OpenR66Exception e2) { - } - } - } - } - if (mustFinalize && runner != null) { - if (runner.isSelfRequested()) { - R66Future transfer = localChannelReference.getFutureRequest(); - // Since requested : log - R66Result result = transfer.getResult(); - if (transfer.isDone() && transfer.isSuccess()) { - logger.info("TRANSFER REQUESTED RESULT:\n SUCCESS\n " + - (result != null ? result.toString() : "no result")); - } else { - logger.error("TRANSFER REQUESTED RESULT:\n FAILURE\n " + - (result != null ? result.toString() : "no result")); - } - } - } - session.setStatus(50); - session.newState(CLOSEDCHANNEL); - session.clear(); - session.setStatus(51); - if (localChannelReference != null) { - if (localChannelReference.getDbSession() != null) { - localChannelReference.getDbSession().endUseConnection(); - logger.debug("End Use Connection"); - } - String requester = - (runner != null && runner.isSelfRequested() && - localChannelReference.getNetworkChannelObject() != null) ? - runner.getRequester() : null; - NetworkTransaction.removeNetworkChannel(localChannelReference - .getNetworkChannel(), e.getChannel(), requester); - /* - * // Only requested can has a remote client if (runner != null && - * runner.isSelfRequested() && localChannelReference.getNetworkChannelObject() != null - * && localChannelReference.getNetworkChannelObject().count <= 0) { - * NetworkTransaction.removeClient(runner.getRequester(), - * localChannelReference.getNetworkChannelObject()); } - */ - session.setStatus(52); - Configuration.configuration.getLocalTransaction().remove(e.getChannel()); - } else { - logger - .error("Local Server Channel Closed but no LocalChannelReference: " + - e.getChannel().getId()); - } - // Now if runner is not yet finished, finish it by force - if (mustFinalize && localChannelReference != null - && (!localChannelReference.getFutureRequest().isDone())) { - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException( - "Finalize too early at close time while Request not yet finished"), - session, true, ErrorCode.FinalOp, runner); - localChannelReference.invalidateRequest(finalValue); - // In case stop the attached thread if any - ClientRunner clientRunner = localChannelReference.getClientRunner(); - if (clientRunner != null) { - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e1) { - } - clientRunner.interrupt(); - } - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { - session = new R66Session(); - session.setStatus(60); - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) - */ - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) - throws OpenR66Exception { - // action as requested and answer if necessary - final AbstractLocalPacket packet = (AbstractLocalPacket) e.getMessage(); - if (packet.getType() == LocalPacketFactory.STARTUPPACKET) { - startup(e.getChannel(), (StartupPacket) packet); - } else { - if (localChannelReference == null) { - logger.error("No LocalChannelReference at " + - packet.getClass().getName()); - session.newState(ERROR); - final ErrorPacket errorPacket = new ErrorPacket( - "No LocalChannelReference at " + - packet.getClass().getName(), - ErrorCode.ConnectionImpossible.getCode(), - ErrorPacket.FORWARDCLOSECODE); - try { - Channels.write(e.getChannel(), errorPacket).await(); - } catch (InterruptedException e1) { - } - localChannelReference.invalidateRequest(new R66Result( - new OpenR66ProtocolSystemException( - "No LocalChannelReference"), session, true, - ErrorCode.ConnectionImpossible, null)); - ChannelUtils.close(e.getChannel()); - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "No LocalChannelReference", packet.getClass().getSimpleName()); - } - return; - } - switch (packet.getType()) { - case LocalPacketFactory.AUTHENTPACKET: { - authent(e.getChannel(), (AuthentPacket) packet); - break; - } - // Already done case LocalPacketFactory.STARTUPPACKET: - case LocalPacketFactory.DATAPACKET: { - session.newState(DATAR); - data(e.getChannel(), (DataPacket) packet); - break; - } - case LocalPacketFactory.VALIDPACKET: { - valid(e.getChannel(), (ValidPacket) packet); - break; - } - case LocalPacketFactory.ERRORPACKET: { - session.newState(ERROR); - errorMesg(e.getChannel(), (ErrorPacket) packet); - break; - } - case LocalPacketFactory.CONNECTERRORPACKET: { - connectionError(e.getChannel(), - (ConnectionErrorPacket) packet); - break; - } - case LocalPacketFactory.REQUESTPACKET: { - request(e.getChannel(), (RequestPacket) packet); - break; - } - case LocalPacketFactory.SHUTDOWNPACKET: { - session.newState(SHUTDOWN); - shutdown(e.getChannel(), (ShutdownPacket) packet); - break; - } - case LocalPacketFactory.STOPPACKET: - case LocalPacketFactory.CANCELPACKET: - case LocalPacketFactory.CONFIMPORTPACKET: - case LocalPacketFactory.CONFEXPORTPACKET: - case LocalPacketFactory.BANDWIDTHPACKET: { - logger.error("Unimplemented Mesg: " + - packet.getClass().getName()); - session.newState(ERROR); - localChannelReference.invalidateRequest(new R66Result( - new OpenR66ProtocolSystemException( - "Not implemented"), session, true, - ErrorCode.Unimplemented, null)); - final ErrorPacket errorPacket = new ErrorPacket( - "Unimplemented Mesg: " + - packet.getClass().getName(), - ErrorCode.Unimplemented.getCode(), - ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); - ChannelUtils.close(e.getChannel()); - break; - } - case LocalPacketFactory.TESTPACKET: { - session.newState(TEST); - test(e.getChannel(), (TestPacket) packet); - break; - } - case LocalPacketFactory.ENDTRANSFERPACKET: { - endTransfer(e.getChannel(), (EndTransferPacket) packet); - break; - } - case LocalPacketFactory.INFORMATIONPACKET: { - session.newState(INFORMATION); - information(e.getChannel(), (InformationPacket) packet); - break; - } - case LocalPacketFactory.ENDREQUESTPACKET: { - endRequest(e.getChannel(), (EndRequestPacket) packet); - break; - } - case LocalPacketFactory.BUSINESSREQUESTPACKET: { - businessRequest(e.getChannel(), (BusinessRequestPacket) packet); - break; - } - default: { - logger - .error("Unknown Mesg: " + - packet.getClass().getName()); - session.newState(ERROR); - localChannelReference.invalidateRequest(new R66Result( - new OpenR66ProtocolSystemException( - "Unknown Message"), session, true, - ErrorCode.Unimplemented, null)); - final ErrorPacket errorPacket = new ErrorPacket( - "Unkown Mesg: " + packet.getClass().getName(), - ErrorCode.Unimplemented.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); - ChannelUtils.close(e.getChannel()); - } - } - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { - // inform clients - logger.debug("Exception and isFinished: "+ - (localChannelReference != null && localChannelReference.getFutureRequest().isDone()), e); - if (localChannelReference != null && localChannelReference.getFutureRequest().isDone()) { - Channels.close(e.getChannel()); - return; - } - OpenR66Exception exception = OpenR66ExceptionTrappedFactory - .getExceptionFromTrappedException(e.getChannel(), e); - ErrorCode code = null; - if (exception != null) { - session.newState(ERROR); - boolean isAnswered = false; - if (exception instanceof OpenR66ProtocolShutdownException) { - logger.warn("Shutdown order received and going from: " + - session.getAuth().getUser()); - if (localChannelReference != null) { - R66Result finalValue = new R66Result(exception, session, true, - ErrorCode.Shutdown, session.getRunner()); - try { - tryFinalizeRequest(finalValue); - } catch (OpenR66RunnerErrorException e2) { - } catch (OpenR66ProtocolSystemException e2) { - } - if (!localChannelReference.getFutureRequest().isDone()) { - try { - session.setFinalizeTransfer(false, finalValue); - } catch (OpenR66RunnerErrorException e1) { - localChannelReference.invalidateRequest(finalValue); - } catch (OpenR66ProtocolSystemException e1) { - localChannelReference.invalidateRequest(finalValue); - } - } - } - // dont'close, thread will do - ChannelUtils.startShutdown(); - // set global shutdown info and before close, send a valid - // shutdown to all - session.setStatus(54); - return; - } else { - if (localChannelReference != null - && localChannelReference.getFutureRequest() != null) { - if (localChannelReference.getFutureRequest().isDone()) { - R66Result result = localChannelReference.getFutureRequest() - .getResult(); - if (result != null) { - isAnswered = result.isAnswered; - } - } - } - if (exception instanceof OpenR66ProtocolNoConnectionException) { - code = ErrorCode.ConnectionImpossible; - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - runner.stopOrCancelRunner(code); - } - } else if (exception instanceof OpenR66ProtocolBusinessCancelException) { - code = ErrorCode.CanceledTransfer; - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - runner.stopOrCancelRunner(code); - } - } else if (exception instanceof OpenR66ProtocolBusinessStopException) { - code = ErrorCode.StoppedTransfer; - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - runner.stopOrCancelRunner(code); - } - } else if (exception instanceof OpenR66ProtocolBusinessQueryAlreadyFinishedException) { - code = ErrorCode.QueryAlreadyFinished; - try { - tryFinalizeRequest(new R66Result(session, true, code, session.getRunner())); - return; - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - } else if (exception instanceof OpenR66ProtocolBusinessQueryStillRunningException) { - code = ErrorCode.QueryStillRunning; - // nothing is to be done - logger.error("Will close channel since ", exception); - Channels.close(e.getChannel()); - session.setStatus(56); - return; - } else if (exception instanceof OpenR66ProtocolBusinessRemoteFileNotFoundException) { - code = ErrorCode.FileNotFound; - } else if (exception instanceof OpenR66RunnerException) { - code = ErrorCode.ExternalOp; - } else if (exception instanceof OpenR66ProtocolNotAuthenticatedException) { - code = ErrorCode.BadAuthent; - } else if (exception instanceof OpenR66ProtocolNetworkException) { - code = ErrorCode.Disconnection; - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException( - "Finalize too early at close time with Network Exception"), - session, true, code, session.getRunner()); - try { - tryFinalizeRequest(finalValue); - } catch (OpenR66Exception e2) { - } - } - } else if (exception instanceof OpenR66ProtocolRemoteShutdownException) { - code = ErrorCode.RemoteShutdown; - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - runner.stopOrCancelRunner(code); - } - } else { - DbTaskRunner runner = session.getRunner(); - if (runner != null) { - switch (runner.getErrorInfo()) { - case InitOk: - case PostProcessingOk: - case PreProcessingOk: - case Running: - case TransferOk: - code = ErrorCode.Internal; - default: - code = runner.getErrorInfo(); - } - } else { - code = ErrorCode.Internal; - } - } - if ((!isAnswered) && - (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) && - (!(exception instanceof OpenR66ProtocolNoConnectionException))) { - if (code == null || code == ErrorCode.Internal) { - code = ErrorCode.RemoteError; - } - final ErrorPacket errorPacket = new ErrorPacket(exception - .getMessage(), - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - errorPacket, true); - } catch (OpenR66ProtocolPacketException e1) { - // should not be - } - } - R66Result finalValue = - new R66Result( - exception, session, true, code, session.getRunner()); - try { - session.setFinalizeTransfer(false, finalValue); - if (localChannelReference != null) { - localChannelReference.invalidateRequest(finalValue); - } - } catch (OpenR66RunnerErrorException e1) { - if (localChannelReference != null) - localChannelReference.invalidateRequest(finalValue); - } catch (OpenR66ProtocolSystemException e1) { - if (localChannelReference != null) - localChannelReference.invalidateRequest(finalValue); - } - } - if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { - logger.error("Will close channel {}", exception.getMessage()); - Channels.close(e.getChannel()); - session.setStatus(56); - return; - } else if (exception instanceof OpenR66ProtocolNoConnectionException) { - logger.error("Will close channel {}", exception.getMessage()); - Channels.close(e.getChannel()); - session.setStatus(57); - return; - } - session.setStatus(58); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - } else { - // Nothing to do - session.setStatus(59); - return; - } - } - - /** - * Startup of the session and the local channel reference - * - * @param channel - * @param packet - * @throws OpenR66ProtocolPacketException - */ - private void startup(Channel channel, StartupPacket packet) - throws OpenR66ProtocolPacketException { - localChannelReference = Configuration.configuration - .getLocalTransaction().getFromId(packet.getLocalId()); - if (localChannelReference == null) { - session.newState(ERROR); - logger.error("Cannot startup"); - ErrorPacket error = new ErrorPacket("Cannot startup connection", - ErrorCode.ConnectionImpossible.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - Channels.write(channel, error).await(); - } catch (InterruptedException e) { - } - // Cannot do writeBack(error, true); - session.setStatus(40); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - NetworkChannel networkChannel = - NetworkTransaction.getNetworkChannel(localChannelReference.getNetworkChannel()); - if (networkChannel != null) { - localChannelReference.setNetworkChannelObject(networkChannel); - } else { - logger.error("No NetworkChannek found!"); - } - session.newState(STARTUP); - localChannelReference.validateStartup(true); - session.setLocalChannelReference(localChannelReference); - Channels.write(channel, packet); - session.setStatus(41); - } - - /** - * Refuse a connection - * - * @param channel - * @param packet - * @param e1 - * @throws OpenR66ProtocolPacketException - */ - private void refusedConnection(Channel channel, AuthentPacket packet, Exception e1) - throws OpenR66ProtocolPacketException { - logger.error("Cannot connect from "+ - localChannelReference.getNetworkChannel().getRemoteAddress()+ - " : " + packet.getHostId(), e1); - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyError( - "Connection not allowed from "+ - localChannelReference.getNetworkChannel().getRemoteAddress() - +" since "+e1.getMessage(), packet.getHostId()); - } - R66Result result = new R66Result( - new OpenR66ProtocolSystemException( - "Connection not allowed from "+ - localChannelReference.getNetworkChannel().getRemoteAddress(), - e1), session, true, - ErrorCode.BadAuthent, null); - localChannelReference.invalidateRequest(result); - session.newState(ERROR); - ErrorPacket error = new ErrorPacket("Connection not allowed", - ErrorCode.BadAuthent.getCode(), - ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - localChannelReference.validateConnection(false, result); - ChannelCloseTimer.closeFutureChannel(channel); - } - - /** - * Authentication - * - * @param channel - * @param packet - * @throws OpenR66ProtocolPacketException - */ - private void authent(Channel channel, AuthentPacket packet) - throws OpenR66ProtocolPacketException { - if (packet.isToValidate()) { - session.newState(AUTHENTR); - } - - if (localChannelReference.getDbSession() != null) { - localChannelReference.getDbSession().useConnection(); - } - try { - session.getAuth().connection(localChannelReference.getDbSession(), - packet.getHostId(), packet.getKey()); - } catch (Reply530Exception e1) { - refusedConnection(channel, packet, e1); - session.setStatus(42); - return; - } catch (Reply421Exception e1) { - session.newState(ERROR); - logger.error("Service unavailable: " + packet.getHostId(), e1); - R66Result result = new R66Result( - new OpenR66ProtocolSystemException("Service unavailable", - e1), session, true, - ErrorCode.ConnectionImpossible, null); - localChannelReference.invalidateRequest(result); - ErrorPacket error = new ErrorPacket("Service unavailable", - ErrorCode.ConnectionImpossible.getCode(), - ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - localChannelReference.validateConnection(false, result); - ChannelCloseTimer.closeFutureChannel(channel); - session.setStatus(43); - return; - } - // Now if configuration say to do so: check remote ip address - if (Configuration.configuration.checkRemoteAddress) { - DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, - packet.getHostId()); - boolean toTest = false; - if (host.isClient()) { - if (Configuration.configuration.checkClientAddress) { - if (host.isNoAddress()) { - // 0.0.0.0 so nothing - toTest = false; - } else { - toTest = true; - } - } - } else { - toTest = true; - } - if (toTest) { - // Real address so compare - String address = host.getAddress(); - InetAddress[] inetAddress = null; - try { - inetAddress = InetAddress.getAllByName(address); - } catch (UnknownHostException e) { - inetAddress = null; - } - if (inetAddress != null) { - InetSocketAddress socketAddress = (InetSocketAddress) session - .getRemoteAddress(); - boolean found = false; - for (int i = 0; i < inetAddress.length; i++) { - if (socketAddress.getAddress().equals(inetAddress[i])) { - found = true; - break; - } - } - if (!found) { - // error - refusedConnection(channel, packet, - new OpenR66ProtocolNotAuthenticatedException( - "Server IP not authenticated: " + - inetAddress[0].toString() + " compare to " - + socketAddress.getAddress().toString())); - session.setStatus(104); - return; - } - } - } - } - R66Result result = new R66Result(session, true, ErrorCode.InitOk, null); - session.newState(AUTHENTD); - localChannelReference.validateConnection(true, result); - logger.debug("Local Server Channel Validated: {} ", - (localChannelReference != null ? localChannelReference - : "no LocalChannelReference")); - session.setStatus(44); - if (packet.isToValidate()) { - // only requested - NetworkTransaction.addClient(localChannelReference.getNetworkChannel(), - packet.getHostId()); - packet.validate(session.getAuth().isSsl()); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); - session.setStatus(98); - } - } - - /** - * Receive a connection error - * - * @param channel - * @param packet - */ - private void connectionError(Channel channel, ConnectionErrorPacket packet) { - // do something according to the error - logger.error(channel.getId() + ": " + packet.toString()); - localChannelReference.invalidateRequest(new R66Result( - new OpenR66ProtocolSystemException(packet.getSheader()), - session, true, ErrorCode.ConnectionImpossible, null)); - // True since closing - session.newState(ERROR); - session.setStatus(45); - Channels.close(channel); - } - - /** - * Class to finalize a runner when the future is over - * - * @author Frederic Bregier - * - */ - private class RunnerChannelFutureListener implements ChannelFutureListener { - private LocalChannelReference localChannelReference; - private R66Result result; - - public RunnerChannelFutureListener(LocalChannelReference localChannelReference, - R66Result result) { - this.localChannelReference = localChannelReference; - this.result = result; - } - - public void operationComplete(ChannelFuture future) throws Exception { - localChannelReference.invalidateRequest( - result); - ChannelCloseTimer.closeFutureChannel(localChannelReference.getLocalChannel()); - } - - } - - /** - * Receive a remote error - * - * @param channel - * @param packet - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - * @throws OpenR66ProtocolBusinessException - */ - private void errorMesg(Channel channel, ErrorPacket packet) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException, - OpenR66ProtocolBusinessException { - // do something according to the error - if (session.getLocalChannelReference().getFutureRequest().isDone()) { - // already canceled or successful - return; - } - logger.error(channel.getId() + ": " + packet.toString()); - session.setStatus(46); - ErrorCode code = ErrorCode.getFromCode(packet.getSmiddle()); - session.getLocalChannelReference().setErrorMessage(packet.getSheader(), code); - OpenR66ProtocolBusinessException exception; - if (code.code == ErrorCode.CanceledTransfer.code) { - exception = - new OpenR66ProtocolBusinessCancelException(packet.getSheader()); - int rank = 0; - DbTaskRunner runner = this.session.getRunner(); - if (runner != null) { - runner.setRankAtStartup(rank); - runner.stopOrCancelRunner(code); - } - R66Result result = new R66Result(exception, session, - true, code, runner); - // now try to inform other - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false). - addListener(new RunnerChannelFutureListener(localChannelReference, result)); - } catch (OpenR66ProtocolPacketException e) { - } - session.setFinalizeTransfer(false, result); - return; - } else if (code.code == ErrorCode.StoppedTransfer.code) { - exception = - new OpenR66ProtocolBusinessStopException(packet.getSheader()); - String[] vars = packet.getSheader().split(" "); - String var = vars[vars.length - 1]; - int rank = Integer.parseInt(var); - DbTaskRunner runner = this.session.getRunner(); - if (runner != null) { - if (rank < runner.getRank()) { - runner.setRankAtStartup(rank); - } - runner.stopOrCancelRunner(code); - } - R66Result result = new R66Result(exception, session, - true, code, runner); - // now try to inform other - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false). - addListener(new RunnerChannelFutureListener(localChannelReference, result)); - } catch (OpenR66ProtocolPacketException e) { - } - session.setFinalizeTransfer(false, result); - return; - } else if (code.code == ErrorCode.QueryAlreadyFinished.code) { - DbTaskRunner runner = session.getRunner(); - if (runner == null) { - exception = - new OpenR66ProtocolBusinessCancelException(packet.toString()); - } else { - if (runner.isSender()) { - exception = - new OpenR66ProtocolBusinessQueryAlreadyFinishedException( - packet.getSheader()); - runner.finishTransferTask(code); - tryFinalizeRequest(new R66Result(exception, session, true, code, runner)); - } else { - exception = - new OpenR66ProtocolBusinessCancelException(packet.toString()); - } - } - throw exception; - } else if (code.code == ErrorCode.QueryStillRunning.code) { - exception = - new OpenR66ProtocolBusinessQueryStillRunningException(packet.getSheader()); - throw exception; - } else if (code.code == ErrorCode.BadAuthent.code) { - exception = - new OpenR66ProtocolNotAuthenticatedException(packet.toString()); - } else if (code.code == ErrorCode.QueryRemotelyUnknown.code) { - exception = - new OpenR66ProtocolBusinessCancelException(packet.toString()); - } else if (code.code == ErrorCode.FileNotFound.code) { - exception = - new OpenR66ProtocolBusinessRemoteFileNotFoundException(packet.toString()); - } else { - exception = - new OpenR66ProtocolBusinessNoWriteBackException(packet.toString()); - } - session.setFinalizeTransfer(false, new R66Result(exception, session, - true, code, session.getRunner())); - throw exception; - } - - /** - * Finalize a request initialization in error - * - * @param channel - * @param code - * @param runner - * @param e1 - * @param packet - * @throws OpenR66ProtocolPacketException - */ - private void endInitRequestInError(Channel channel, ErrorCode code, DbTaskRunner runner, - OpenR66Exception e1, RequestPacket packet) throws OpenR66ProtocolPacketException { - logger.error("TaskRunner initialisation in error: " + code.mesg + " " + session - + " {} runner {}", - e1 != null ? e1.getMessage() : "no exception", - (runner != null ? runner.toShortString() : "no runner")); - localChannelReference.invalidateRequest(new R66Result( - e1, session, true, code, null)); - - if (packet.isToValidate()) { - // / answer with a wrong request since runner is not set on remote host - if (runner != null) { - if (runner.isSender()) { - // In case Wildcard was used - logger.debug("New FILENAME: {}", runner.getOriginalFilename()); - packet.setFilename(runner.getOriginalFilename()); - logger.debug("Rank set: " + runner.getRank()); - packet.setRank(runner.getRank()); - } else { - logger.debug("Rank set: " + runner.getRank()); - packet.setRank(runner.getRank()); - } - } - packet.validate(); - packet.setCode(code.code); - session.newState(ERROR); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, true); - } else { - session.newState(ERROR); - ErrorPacket error = new ErrorPacket( - "TaskRunner initialisation in error: " + e1 - .getMessage() + " for " + packet.toString() + " since " + code.mesg, - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } - session.setStatus(47); - ChannelCloseTimer.closeFutureChannel(channel); - } - - /** - * Receive a request - * - * @param channel - * @param packet - * @throws OpenR66ProtocolNoDataException - * @throws OpenR66ProtocolPacketException - * @throws OpenR66ProtocolBusinessException - * @throws OpenR66ProtocolSystemException - * @throws OpenR66RunnerErrorException - */ - private void request(Channel channel, RequestPacket packet) - throws OpenR66ProtocolNoDataException, OpenR66ProtocolPacketException, - OpenR66RunnerErrorException, OpenR66ProtocolSystemException, - OpenR66ProtocolBusinessException { - session.setStatus(99); - if (!session.isAuthenticated()) { - session.setStatus(48); - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Request received"); - } - // XXX validLimit only on requested side - if (packet.isToValidate()) { - if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib. - notifyOverloaded("Rule: " + packet.getRulename() + " from " - + session.getAuth().toString(), - Configuration.configuration.constraintLimitHandler.lastAlert); - } - logger.info("Limit exceeded when receive request with Rule: " - + packet.getRulename() + " from " + session.getAuth().toString()); - session.setStatus(100); - endInitRequestInError(channel, - ErrorCode.ServerOverloaded, null, - new OpenR66ProtocolNotYetConnectionException( - "Limit exceeded"), packet); - session.setStatus(100); - return; - } - } else if (packet.getCode() == ErrorCode.ServerOverloaded.code) { - // XXX unvalid limit on requested host received - logger.info("TaskRunner initialisation in error: " + ErrorCode.ServerOverloaded.mesg); - localChannelReference.invalidateRequest(new R66Result( - null, session, true, ErrorCode.ServerOverloaded, null)); - session.setStatus(101); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - DbRule rule; - try { - rule = new DbRule(localChannelReference.getDbSession(), packet.getRulename()); - } catch (WaarpDatabaseException e) { - logger.info("Rule is unknown: " + packet.getRulename() + " {}", e.getMessage()); - session.setStatus(49); - endInitRequestInError(channel, - ErrorCode.QueryRemotelyUnknown, null, - new OpenR66ProtocolBusinessException( - "The Transfer is associated with an Unknown Rule: " + - packet.getRulename()), packet); - return; - } - int blocksize = packet.getBlocksize(); - if (packet.isToValidate()) { - if (!rule.checkHostAllow(session.getAuth().getUser())) { - session.setStatus(30); - throw new OpenR66ProtocolNotAuthenticatedException( - "Rule is not allowed for the remote host"); - } - // Check if the blocksize is greater than local value - if (Configuration.configuration.BLOCKSIZE < blocksize) { - blocksize = Configuration.configuration.BLOCKSIZE; - packet = new RequestPacket(packet.getRulename(), packet.getMode(), - packet.getFilename(), blocksize, packet.getRank(), - packet.getSpecialId(), packet.getFileInformation(), packet.getOriginalSize()); - } - } - if (!RequestPacket.isCompatibleMode(rule.mode, packet.getMode())) { - // not compatible Rule and mode in request - throw new OpenR66ProtocolNotAuthenticatedException( - "Rule has not the same mode of transmission: " + rule.mode + " vs " - + packet.getMode()); - } - session.setBlockSize(blocksize); - DbTaskRunner runner; - // requested - boolean isRetrieve = DbTaskRunner.getSenderByRequestPacket(packet); - if (packet.getSpecialId() != DbConstant.ILLEGALVALUE) { - // Reload or create - String requested = DbTaskRunner.getRequested(session, packet); - String requester = DbTaskRunner.getRequester(session, packet); - if (packet.isToValidate()) { - // Id could be a creation or a reload - // Try reload - try { - runner = new DbTaskRunner(localChannelReference.getDbSession(), - session, rule, packet.getSpecialId(), - requester, requested); - runner.setSender(isRetrieve); - if (runner.isAllDone()) { - // truly an error since done - session.setStatus(31); - endInitRequestInError(channel, - ErrorCode.QueryAlreadyFinished, runner, - new OpenR66ProtocolBusinessQueryAlreadyFinishedException( - "The TransferId is associated with a Transfer already finished: " - + - packet.getSpecialId()), packet); - return; - } - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest( - requested + " " + requester + " " - + packet.getSpecialId()); - if (lcr != null) { - // truly an error since still running - session.setStatus(32); - endInitRequestInError(channel, - ErrorCode.QueryStillRunning, runner, - new OpenR66ProtocolBusinessQueryStillRunningException( - "The TransferId is associated with a Transfer still running: " - + - packet.getSpecialId()), packet); - return; - } - // ok to restart - try { - if (runner.restart(false)) { - runner.saveStatus(); - } - } catch (OpenR66RunnerErrorException e) { - } - } catch (WaarpDatabaseNoDataException e) { - // Reception of request from requester host - try { - runner = new DbTaskRunner(localChannelReference.getDbSession(), - session, rule, isRetrieve, packet); - } catch (WaarpDatabaseException e1) { - session.setStatus(33); - endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, - null, new OpenR66DatabaseGlobalException(e), packet); - return; - } - } catch (WaarpDatabaseException e) { - session.setStatus(34); - endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, - new OpenR66DatabaseGlobalException(e), packet); - return; - } - // Change the SpecialID! => could generate an error ? - packet.setSpecialId(runner.getSpecialId()); - } else { - // Id should be a reload - try { - runner = new DbTaskRunner(localChannelReference.getDbSession(), - session, rule, packet.getSpecialId(), - requester, requested); - runner.setSender(isRetrieve); - // FIX check for SelfRequest - if (runner.isSelfRequest()) { - runner.setFilename(runner.getOriginalFilename()); - } - if (! runner.isSender()) { - logger.debug("New filename ? :" +packet.getFilename()); - runner.setOriginalFilename(packet.getFilename()); - runner.setFilename(packet.getFilename()); - } - try { - if (runner.restart(false)) { - if (!runner.isSelfRequest()) { - runner.saveStatus(); - } - } - } catch (OpenR66RunnerErrorException e) { - } - } catch (WaarpDatabaseException e) { - if (localChannelReference.getDbSession() == null) { - // Special case of no database client - try { - runner = new DbTaskRunner(localChannelReference.getDbSession(), - session, rule, isRetrieve, packet); - } catch (WaarpDatabaseException e1) { - session.setStatus(35); - endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, - new OpenR66DatabaseGlobalException(e1), packet); - return; - } - } else { - endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, - new OpenR66DatabaseGlobalException(e), packet); - session.setStatus(36); - return; - } - } - } - } else { - // Very new request - // should not be the case (the requester should always set the id) - logger.error("NO TransferID specified: SHOULD NOT BE THE CASE"); - try { - runner = new DbTaskRunner(localChannelReference.getDbSession(), - session, rule, isRetrieve, packet); - } catch (WaarpDatabaseException e) { - session.setStatus(37); - endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, - new OpenR66DatabaseGlobalException(e), packet); - return; - } - packet.setSpecialId(runner.getSpecialId()); - } - // Check now if request is a valid one - if (packet.getCode() != ErrorCode.InitOk.code) { - // not valid so create an error from there - ErrorCode code = ErrorCode.getFromCode("" + packet.getCode()); - session.setBadRunner(runner, code); - session.newState(ERROR); - logger.error("Bad runner at startup {} {}", packet, session); - ErrorPacket errorPacket = new ErrorPacket(code.mesg, - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - errorMesg(channel, errorPacket); - return; - } - // Receiver can specify a rank different from database - if (runner.isSender()) { - logger.debug("Rank was: " + runner.getRank() + " -> " + packet.getRank()); - runner.setRankAtStartup(packet.getRank()); - } else if (runner.getRank() > packet.getRank()) { - logger.debug("Recv Rank was: " + runner.getRank() + " -> " + packet.getRank()); - // if receiver, change only if current rank is upper proposed rank - runner.setRankAtStartup(packet.getRank()); - } - boolean shouldInformBack = false; - try { - session.setRunner(runner); - if (runner.isSender() && ! runner.isSendThrough()) { - if (packet.getOriginalSize() != runner.getOriginalSize()) { - packet.setOriginalSize(runner.getOriginalSize()); - shouldInformBack = true; - } - } - } catch (OpenR66RunnerErrorException e) { - try { - runner.saveStatus(); - } catch (OpenR66RunnerErrorException e1) { - logger.error("Cannot save Status: " + runner, e1); - } - if (runner.getErrorInfo() == ErrorCode.InitOk || - runner.getErrorInfo() == ErrorCode.PreProcessingOk || - runner.getErrorInfo() == ErrorCode.TransferOk) { - runner.setErrorExecutionStatus(ErrorCode.ExternalOp); - } - logger.error("PreTask in error {}", e.getMessage()); - session.newState(ERROR); - ErrorPacket error = new ErrorPacket("PreTask in error: " + e - .getMessage(), runner.getErrorInfo().getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - try { - session.setFinalizeTransfer(false, new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } catch (OpenR66RunnerErrorException e1) { - localChannelReference.invalidateRequest(new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } catch (OpenR66ProtocolSystemException e1) { - localChannelReference.invalidateRequest(new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } - session.setStatus(38); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - if (packet.isToValidate()) { - session.newState(REQUESTR); - } - if (runner.isFileMoved() && runner.isSender() && runner.isInTransfer() - && runner.getRank() == 0 && (!packet.isToValidate())) { - // File was moved during PreTask and very beginning of the transfer - // and the remote host has already received the request packet - // => Informs the receiver of the new name - logger.debug("Will send a modification of filename due to pretask: " + - runner.getFilename()); - session.newState(VALID); - ValidPacket validPacket = new ValidPacket("Change Filename by Pre action on sender", - runner.getFilename()+" "+packet.getOriginalSize(), - LocalPacketFactory.REQUESTPACKET); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - } else if ((!packet.getFilename().equals(runner.getOriginalFilename())) - && runner.isSender() && runner.isInTransfer() - && runner.getRank() == 0 && (!packet.isToValidate())) { - // File was modify at the very beginning (using wildcards) - // and the remote host has already received the request packet - // => Informs the receiver of the new name - logger.debug("Will send a modification of filename due to wildcard: " + - runner.getFilename()); - session.newState(VALID); - ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", - runner.getFilename()+" "+packet.getOriginalSize(), - LocalPacketFactory.REQUESTPACKET); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - } else if (runner.isSelfRequest() && runner.isSender() && runner.isInTransfer() - && runner.getRank() == 0 && (!packet.isToValidate())) { - // FIX SelfRequest - // File could be modified at the very beginning (using wildcards) - // and the remote host has already received the request packet - // => Informs the receiver of the new name - logger.debug("Will send a modification of filename due to wildcard: " + - runner.getFilename()); - session.newState(VALID); - ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", - runner.getFilename()+" "+packet.getOriginalSize(), - LocalPacketFactory.REQUESTPACKET); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - } else if (shouldInformBack) { - // File length is now known, so inform back - logger.debug("Will send a modification of filename due to wildcard: " + - runner.getFilename()); - session.newState(VALID); - ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", - runner.getFilename()+" "+packet.getOriginalSize(), - LocalPacketFactory.REQUESTPACKET); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - } - session.setReady(true); - Configuration.configuration.getLocalTransaction().setFromId(runner, localChannelReference); - // inform back - if (packet.isToValidate()) { - if (Configuration.configuration.monitoring != null) { - Configuration.configuration.monitoring.lastInActiveTransfer = - System.currentTimeMillis(); - } - if (runner.isSender()) { - // In case Wildcard was used - logger.debug("New FILENAME: {}", runner.getOriginalFilename()); - packet.setFilename(runner.getOriginalFilename()); - logger.debug("Rank set: " + runner.getRank()); - packet.setRank(runner.getRank()); - } else { - logger.debug("Rank set: " + runner.getRank()); - packet.setRank(runner.getRank()); - } - packet.validate(); - session.newState(REQUESTD); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, true); - } else { - session.newState(REQUESTD); - // requester => might be a client - // Save the runner into the session and validate the request so begin transfer - session.getLocalChannelReference().getFutureRequest().runner = runner; - localChannelReference.getFutureValidRequest().setSuccess(); - if (Configuration.configuration.monitoring != null) { - Configuration.configuration.monitoring.lastOutActiveTransfer = - System.currentTimeMillis(); - } - } - // if retrieve => START the retrieve operation except if in Send Through mode - if (runner.isSender()) { - if (runner.isSendThrough()) { - // it is legal to send data from now - logger.debug("Now ready to continue with send through"); - localChannelReference.validateEndTransfer( - new R66Result(session, false, ErrorCode.PreProcessingOk, runner)); - } else { - // Automatically send data now - logger.debug("Now ready to continue with runRetrieve"); - NetworkTransaction.runRetrieve(session, channel); - } - } - session.setStatus(39); - } - - /** - * Receive a data - * - * @param channel - * @param packet - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66ProtocolBusinessException - * @throws OpenR66ProtocolPacketException - */ - private void data(Channel channel, DataPacket packet) - throws OpenR66ProtocolNotAuthenticatedException, - OpenR66ProtocolBusinessException, OpenR66ProtocolPacketException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Data received"); - } - if (!session.isReady()) { - throw new OpenR66ProtocolBusinessException("No request prepared"); - } - if (session.getRunner().isSender()) { - throw new OpenR66ProtocolBusinessException( - "Not in receive MODE but receive a packet"); - } - if (!session.getRunner().continueTransfer()) { - if (localChannelReference.getFutureEndTransfer().isFailed()) { - // nothing to do since already done - session.setStatus(94); - return; - } - session.newState(ERROR); - ErrorPacket error = new ErrorPacket( - "Transfer in error due previously aborted transmission", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - try { - session.setFinalizeTransfer(false, new R66Result( - new OpenR66ProtocolPacketException( - "Transfer was aborted previously"), session, true, - ErrorCode.TransferError, session.getRunner())); - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - session.setStatus(95); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - if (packet.getPacketRank() != session.getRunner().getRank()) { - // Fix the rank if possible - if (packet.getPacketRank() < session.getRunner().getRank()) { - logger.debug("Bad RANK: " + packet.getPacketRank() + " : " + - session.getRunner().getRank()); - session.getRunner().setRankAtStartup(packet.getPacketRank()); - session.getRestart().restartMarker( - session.getRunner().getBlocksize() * - session.getRunner().getRank()); - try { - session.getFile().restartMarker(session.getRestart()); - } catch (CommandAbstractException e) { - logger.error("Bad RANK: " + packet.getPacketRank() + " : " + - session.getRunner().getRank()); - session.newState(ERROR); - try { - session.setFinalizeTransfer(false, new R66Result( - new OpenR66ProtocolPacketException( - "Bad Rank in transmission even after retry: " + - packet.getPacketRank()), session, true, - ErrorCode.TransferError, session.getRunner())); - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - ErrorPacket error = new ErrorPacket( - "Transfer in error due to bad rank transmission", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - session.setStatus(96); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - } else { - // really bad - logger.error("Bad RANK: " + packet.getPacketRank() + " : " + - session.getRunner().getRank()); - session.newState(ERROR); - try { - session.setFinalizeTransfer(false, new R66Result( - new OpenR66ProtocolPacketException( - "Bad Rank in transmission: " + - packet.getPacketRank() + " > " + - session.getRunner().getRank()), session, true, - ErrorCode.TransferError, session.getRunner())); - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - ErrorPacket error = new ErrorPacket( - "Transfer in error due to bad rank transmission", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - session.setStatus(20); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - } - DataBlock dataBlock = new DataBlock(); - // if MD5 check MD5 - if (RequestPacket.isMD5Mode(session.getRunner().getMode())) { - if (!packet.isKeyValid()) { - // Wrong packet - logger.error("Wrong MD5 Packet: {}", packet); - session.newState(ERROR); - try { - session.setFinalizeTransfer(false, new R66Result( - new OpenR66ProtocolPacketException( - "Wrong Packet MD5"), session, true, - ErrorCode.MD5Error, session.getRunner())); - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - ErrorPacket error = new ErrorPacket( - "Transfer in error due to bad MD5", - ErrorCode.MD5Error.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - session.setStatus(21); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - } - if (Configuration.configuration.globalDigest) { - if (globalDigest == null) { - try { - globalDigest = new FilesystemBasedDigest(Configuration.configuration.digest); - } catch (NoSuchAlgorithmException e) { - } - } - FileUtils.computeGlobalHash(globalDigest, packet.getData()); - } - if (session.getRunner().isRecvThrough() && localChannelReference.isRecvThroughMode()) { - localChannelReference.getRecvThroughHandler().writeChannelBuffer(packet.getData()); - session.getRunner().incrementRank(); - } else { - dataBlock.setBlock(packet.getData()); - try { - session.getFile().writeDataBlock(dataBlock); - session.getRunner().incrementRank(); - } catch (FileTransferException e) { - session.newState(ERROR); - try { - session.setFinalizeTransfer(false, new R66Result( - new OpenR66ProtocolSystemException(e), session, true, - ErrorCode.TransferError, session.getRunner())); - } catch (OpenR66RunnerErrorException e1) { - } catch (OpenR66ProtocolSystemException e1) { - } - ErrorPacket error = new ErrorPacket("Transfer in error", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - session.setStatus(22); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - } - } - - /** - * Test reception - * - * @param channel - * @param packet - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66ProtocolPacketException - */ - private void test(Channel channel, TestPacket packet) - throws OpenR66ProtocolNotAuthenticatedException, - OpenR66ProtocolPacketException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Test received"); - } - // simply write back after+1 - packet.update(); - if (packet.getType() == LocalPacketFactory.VALIDPACKET) { - ValidPacket validPacket = new ValidPacket(packet.toString(), null, - LocalPacketFactory.TESTPACKET); - R66Result result = new R66Result(session, true, - ErrorCode.CompleteOk, null); - result.other = validPacket; - session.newState(VALIDOTHER); - localChannelReference.validateRequest(result); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); - logger.warn("Valid TEST MESSAGE from "+ - session.getAuth().getUser()+ - " ["+localChannelReference.getNetworkChannel().getRemoteAddress()+ - "] Msg=" +packet.toString()); - ChannelCloseTimer.closeFutureChannel(channel); - } else { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); - } - } - - /** - * Receive an End of Transfer - * - * @param channel - * @param packet - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - * @throws OpenR66ProtocolNotAuthenticatedException - */ - private void endTransfer(Channel channel, EndTransferPacket packet) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException, - OpenR66ProtocolNotAuthenticatedException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while EndTransfer received"); - } - // Check end of transfer - long originalSize = session.getRunner().getOriginalSize(); - logger.debug("OSize: "+originalSize+" isSender: "+session.getRunner().isSender()); - if (packet.isToValidate()) { - // check if possible originalSize - if (originalSize >= 0) { - try { - if (!session.getRunner().isRecvThrough() && session.getFile().length() != originalSize) { - R66Result result = new R66Result(new OpenR66RunnerErrorException("Final size in error, transfer in error and rank should be reset to 0"), - session, false, ErrorCode.TransferError, session.getRunner()); - localChannelReference.invalidateRequest(result); - throw (OpenR66RunnerErrorException) result.exception; - } - } catch (CommandAbstractException e) { - // ignore - } - } - // check if possible Global Digest - String hash = packet.getOptional(); - if (hash != null && globalDigest != null) { - String localhash = FilesystemBasedDigest.getHex(globalDigest.Final()); - globalDigest = null; - if (! localhash.equalsIgnoreCase(hash)) { - // bad global Hash - //session.getRunner().setRankAtStartup(0); - R66Result result = new R66Result(new OpenR66RunnerErrorException("Global Hash in error, transfer in error and rank should be reset to 0"), - session, false, ErrorCode.MD5Error, session.getRunner()); - localChannelReference.invalidateRequest(result); - throw (OpenR66RunnerErrorException) result.exception; - } else { - localChannelReference.setHashComputeDuringTransfer(localhash); - logger.debug("Global digest ok"); - } - } else if (globalDigest != null) { - String localhash = FilesystemBasedDigest.getHex(globalDigest.Final()); - globalDigest = null; - localChannelReference.setHashComputeDuringTransfer(localhash); - } - globalDigest = null; - session.newState(ENDTRANSFERS); - if (!localChannelReference.getFutureRequest().isDone()) { - // Finish with post Operation - R66Result result = new R66Result(session, false, - ErrorCode.TransferOk, session.getRunner()); - session.newState(ENDTRANSFERR); - session.setFinalizeTransfer(true, result); - // Now can send validation - packet.validate(); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - packet, false); - } catch (OpenR66ProtocolPacketException e) { - // ignore - } - } else { - // in error due to a previous status (like bad MD5) - logger - .error("Error since end of transfer signaled but already done"); - session.setStatus(23); - Channels.close(channel); - return; - } - } else { - session.newState(ENDTRANSFERR); - if (!localChannelReference.getFutureRequest().isDone()) { - // Validation of end of transfer - R66Result result = new R66Result(session, false, - ErrorCode.TransferOk, session.getRunner()); - session.setFinalizeTransfer(true, result); - } - } - } - - /** - * Receive a request of information - * - * @param channel - * @param packet - * @throws CommandAbstractException - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66ProtocolNoDataException - * @throws OpenR66ProtocolPacketException - */ - private void information(Channel channel, InformationPacket packet) - throws OpenR66ProtocolNotAuthenticatedException, - OpenR66ProtocolNoDataException, OpenR66ProtocolPacketException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Information received"); - } - byte request = packet.getRequest(); - DbRule rule; - try { - rule = new DbRule(localChannelReference.getDbSession(), packet.getRulename()); - } catch (WaarpDatabaseException e) { - logger.error("Rule is unknown: " + packet.getRulename(), e); - throw new OpenR66ProtocolNoDataException(e); - } - try { - if (RequestPacket.isRecvMode(rule.mode)) { - session.getDir().changeDirectory(rule.workPath); - } else { - session.getDir().changeDirectory(rule.sendPath); - } - - if (request == InformationPacket.ASKENUM.ASKLIST.ordinal() || - request == InformationPacket.ASKENUM.ASKMLSLIST.ordinal()) { - // ls or mls from current directory - List list; - if (request == InformationPacket.ASKENUM.ASKLIST.ordinal()) { - list = session.getDir().list(packet.getFilename()); - } else { - list = session.getDir().listFull(packet.getFilename(), false); - } - - StringBuilder builder = new StringBuilder(); - for (String elt : list) { - builder.append(elt); - builder.append('\n'); - } - session.newState(VALIDOTHER); - ValidPacket validPacket = new ValidPacket(builder.toString(), "" + list.size(), - LocalPacketFactory.INFORMATIONPACKET); - R66Result result = new R66Result(session, true, - ErrorCode.CompleteOk, null); - result.other = validPacket; - localChannelReference.validateEndTransfer(result); - localChannelReference.validateRequest(result); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - Channels.close(channel); - } else { - // ls pr mls from current directory and filename - R66File file = (R66File) session.getDir().setFile(packet.getFilename(), false); - String sresult = null; - if (request == InformationPacket.ASKENUM.ASKEXIST.ordinal()) { - sresult = "" + file.exists(); - } else if (request == InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal()) { - sresult = session.getDir().fileFull(packet.getFilename(), false); - String[] list = sresult.split("\n"); - sresult = list[1]; - } else { - session.newState(ERROR); - ErrorPacket error = new ErrorPacket("Unknown Request " + request, - ErrorCode.Warning.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - session.newState(VALIDOTHER); - ValidPacket validPacket = new ValidPacket(sresult, "1", - LocalPacketFactory.INFORMATIONPACKET); - R66Result result = new R66Result(session, true, - ErrorCode.CompleteOk, null); - result.other = validPacket; - localChannelReference.validateEndTransfer(result); - localChannelReference.validateRequest(result); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - ChannelCloseTimer.closeFutureChannel(channel); - } - } catch (CommandAbstractException e) { - session.newState(ERROR); - ErrorPacket error = new ErrorPacket("Error while Request " + request + " " - + e.getMessage(), - ErrorCode.Internal.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - ChannelCloseTimer.closeFutureChannel(channel); - } - } - - /** - * Stop or Cancel a Runner - * - * @param id - * @param reqd - * @param reqr - * @param code - * @return True if correctly stopped or canceled - */ - private boolean stopOrCancelRunner(long id, String reqd, String reqr, ErrorCode code) { - try { - DbTaskRunner taskRunner = - new DbTaskRunner(localChannelReference.getDbSession(), session, - null, id, reqr, reqd); - return taskRunner.stopOrCancelRunner(code); - } catch (WaarpDatabaseException e) { - } - return false; - } - - /** - * Receive a validation or a special request - * - * @param channel - * @param packet - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - * @throws OpenR66ProtocolBusinessException - */ - private void valid(Channel channel, ValidPacket packet) - throws OpenR66ProtocolNotAuthenticatedException, - OpenR66RunnerErrorException, OpenR66ProtocolSystemException, - OpenR66ProtocolBusinessException { - if (packet.getTypeValid() != LocalPacketFactory.SHUTDOWNPACKET && - (!session.isAuthenticated())) { - logger.warn("Valid packet received while not authenticated: {} {}", packet, session); - session.newState(ERROR); - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Valid received"); - } - switch (packet.getTypeValid()) { - case LocalPacketFactory.SHUTDOWNPACKET: { - session.newState(SHUTDOWN); - logger.warn("Shutdown received so Will close channel" + - localChannelReference.toString()); - R66Result result = new R66Result( - new OpenR66ProtocolShutdownException(), session, true, - ErrorCode.Shutdown, session.getRunner()); - result.other = packet; - if (session.getRunner() != null && - session.getRunner().isInTransfer()) { - String srank = packet.getSmiddle(); - DbTaskRunner runner = session.getRunner(); - if (srank != null && srank.length() > 0) { - // Save last rank from remote point of view - try { - int rank = Integer.parseInt(srank); - runner.setRankAtStartup(rank); - } catch (NumberFormatException e) { - // ignore - } - session.setFinalizeTransfer(false, result); - } else if (!runner.isSender()) { - // is receiver so informs back for the rank to use next time - int newrank = runner.getRank(); - packet.setSmiddle(Integer.toString(newrank)); - try { - runner.saveStatus(); - } catch (OpenR66RunnerErrorException e) { - } - session.setFinalizeTransfer(false, result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, - true); - } catch (OpenR66ProtocolPacketException e) { - } - } else { - session.setFinalizeTransfer(false, result); - } - } else { - session.setFinalizeTransfer(false, result); - } - session.setStatus(26); - try { - Thread.sleep(Configuration.WAITFORNETOP * 2); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - logger.warn("Will Close Local from Network Channel"); - Configuration.configuration.getLocalTransaction() - .closeLocalChannelsFromNetworkChannel(localChannelReference - .getNetworkChannel()); - NetworkTransaction - .shuttingdownNetworkChannel(localChannelReference - .getNetworkChannel()); - ChannelCloseTimer.closeFutureChannel(channel); - break; - } - case LocalPacketFactory.STOPPACKET: - case LocalPacketFactory.CANCELPACKET: { - session.newState(VALIDOTHER); - // Authentication must be the local server - try { - if (!session.getAuth().getUser().equals( - Configuration.configuration.getHostId(session.getAuth().isSsl()))) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not correctly authenticated"); - } - } catch (OpenR66ProtocolNoSslException e1) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not correctly authenticated since SSL is not supported", e1); - } - // header = ?; middle = requested+blank+requester+blank+specialId - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(packet.getSmiddle()); - // stop the current transfer - R66Result resulttest; - ErrorCode code = (packet.getTypeValid() == LocalPacketFactory.STOPPACKET) ? - ErrorCode.StoppedTransfer : ErrorCode.CanceledTransfer; - if (lcr != null) { - int rank = 0; - if (code == ErrorCode.StoppedTransfer && lcr.getSession() != null) { - DbTaskRunner taskRunner = lcr.getSession().getRunner(); - if (taskRunner != null) { - rank = taskRunner.getRank(); - } - } - session.newState(ERROR); - ErrorPacket error = new ErrorPacket(code.name() + " " + rank, - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - // XXX ChannelUtils.writeAbstractLocalPacket(lcr, error); - // inform local instead of remote - ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); - } catch (Exception e) { - } - resulttest = new R66Result(session, true, - ErrorCode.CompleteOk, session.getRunner()); - } else { - // Transfer is not running - // but maybe need action on database - String[] keys = packet.getSmiddle().split(" "); - long id = Long.parseLong(keys[2]); - if (stopOrCancelRunner(id, keys[0], keys[1], code)) { - resulttest = new R66Result(session, true, - ErrorCode.CompleteOk, session.getRunner()); - } else { - resulttest = new R66Result(session, true, - ErrorCode.TransferOk, session.getRunner()); - } - } - // inform back the requester - ValidPacket valid = new ValidPacket(packet.getSmiddle(), resulttest.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - resulttest.other = packet; - localChannelReference.validateRequest(resulttest); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - session.setStatus(27); - Channels.close(channel); - break; - } - case LocalPacketFactory.REQUESTUSERPACKET: { - session.newState(VALIDOTHER); - // Validate user request - R66Result resulttest = new R66Result(session, true, - ErrorCode.getFromCode(packet.getSmiddle()), null); - resulttest.other = packet; - switch (resulttest.code) { - case CompleteOk: - case InitOk: - case PostProcessingOk: - case PreProcessingOk: - case QueryAlreadyFinished: - case QueryStillRunning: - case Running: - case TransferOk: - break; - default: - localChannelReference.invalidateRequest(resulttest); - session.setStatus(102); - Channels.close(channel); - return; - } - localChannelReference.validateRequest(resulttest); - session.setStatus(28); - Channels.close(channel); - break; - } - case LocalPacketFactory.LOGPACKET: - case LocalPacketFactory.LOGPURGEPACKET: { - session.newState(VALIDOTHER); - // should be from the local server or from an authorized hosts: LOGCONTROL - if (!session.getAuth().isValidRole(ROLE.LOGCONTROL)) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not correctly authenticated"); - } - String sstart = packet.getSheader(); - String sstop = packet.getSmiddle(); - boolean isPurge = (packet.getTypeValid() == LocalPacketFactory.LOGPURGEPACKET) ? - true : false; - Timestamp start = (sstart == null || sstart.length() == 0) ? null : - Timestamp.valueOf(sstart); - Timestamp stop = (sstop == null || sstop.length() == 0) ? null : - Timestamp.valueOf(sstop); - // create export of log and optionally purge them from database - DbPreparedStatement getValid = null; - String filename = Configuration.configuration.baseDirectory + - Configuration.configuration.archivePath + R66Dir.SEPARATOR + - Configuration.configuration.HOST_ID + "_" + System.currentTimeMillis() + - "_runners.xml"; - try { - getValid = - DbTaskRunner.getLogPrepareStatement( - localChannelReference.getDbSession(), - start, stop); - DbTaskRunner.writeXMLWriter(getValid, filename); - } catch (WaarpDatabaseNoConnectionException e1) { - throw new OpenR66ProtocolBusinessException(e1); - } catch (WaarpDatabaseSqlException e1) { - throw new OpenR66ProtocolBusinessException(e1); - } finally { - if (getValid != null) { - getValid.realClose(); - } - } - // in case of purge - int nb = 0; - if (isPurge) { - // purge in same interval all runners with globallaststep - // as ALLDONETASK or ERRORTASK - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "Purge Log Order received", session.getAuth().getUser()); - } - try { - nb = DbTaskRunner.purgeLogPrepareStatement( - localChannelReference.getDbSession(), - start, stop); - } catch (WaarpDatabaseNoConnectionException e) { - throw new OpenR66ProtocolBusinessException(e); - } catch (WaarpDatabaseSqlException e) { - throw new OpenR66ProtocolBusinessException(e); - } - } - R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); - // Now answer - ValidPacket valid = new ValidPacket(filename + " " + nb, result.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - localChannelReference.validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - break; - } - case LocalPacketFactory.CONFEXPORTPACKET: { - session.newState(VALIDOTHER); - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "Export Configuration Order received", session.getAuth().getUser()); - } - String shost = packet.getSheader(); - String srule = packet.getSmiddle(); - boolean bhost = Boolean.parseBoolean(shost); - boolean brule = Boolean.parseBoolean(srule); - String dir = Configuration.configuration.baseDirectory + - Configuration.configuration.archivePath; - String hostname = Configuration.configuration.HOST_ID; - if (bhost) { - String filename = dir + File.separator + hostname + "_Authentications.xml"; - try { - AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, - filename); - shost = filename; - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Error", e); - shost = "#"; - bhost = false; - } catch (WaarpDatabaseSqlException e) { - logger.error("Error", e); - shost = "#"; - bhost = false; - } catch (OpenR66ProtocolSystemException e) { - logger.error("Error", e); - shost = "#"; - bhost = false; - } - } - if (brule) { - try { - srule = RuleFileBasedConfiguration.writeOneXml(dir, hostname); - } catch (WaarpDatabaseNoConnectionException e1) { - logger.error("Error", e1); - srule = "#"; - brule = false; - } catch (WaarpDatabaseSqlException e1) { - logger.error("Error", e1); - srule = "#"; - brule = false; - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Error", e1); - srule = "#"; - brule = false; - } - } - R66Result result = null; - if (brule || bhost) { - result = new R66Result(session, true, ErrorCode.CompleteOk, null); - } else { - result = new R66Result(session, true, ErrorCode.TransferError, null); - } - // Now answer - ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - localChannelReference.validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - break; - } - case LocalPacketFactory.CONFIMPORTPACKET: { - session.newState(VALIDOTHER); - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "Import Configuration Order received", session.getAuth().getUser()); - } - String shost = packet.getSheader(); - String srule = packet.getSmiddle(); - boolean bhostPurge = shost.startsWith("1 "); - shost = shost.substring(2); - boolean brulePurge = srule.startsWith("1 "); - srule = srule.substring(2); - boolean bhost = shost.length() > 0; - boolean brule = srule.length() > 0; - if (bhost) { - DbHostAuth[] oldHosts = null; - if (bhostPurge) { - // Need to first delete all entries - try { - oldHosts = DbHostAuth.deleteAll(DbConstant.admin.session); - } catch (WaarpDatabaseException e) { - // ignore - } - } - String filename = shost; - if (AuthenticationFileBasedConfiguration.loadAuthentication( - Configuration.configuration, - filename)) { - shost = "Host:OK"; - } else { - logger.error("Error in Load Hosts"); - shost = "Host:KO"; - bhost = false; - } - if (!bhost) { - if (oldHosts != null) { - for (DbHostAuth dbHost : oldHosts) { - try { - if (!dbHost.exist()) { - dbHost.insert(); - } - } catch (WaarpDatabaseException e1) { - // ignore - } - } - } - } - } - if (brule) { - DbRule[] oldRules = null; - if (brulePurge) { - // Need to first delete all entries - try { - oldRules = DbRule.deleteAll(DbConstant.admin.session); - } catch (WaarpDatabaseException e) { - // ignore - } - } - File file = new File(srule); - try { - RuleFileBasedConfiguration.getMultipleFromFile(file); - srule = "Rule:OK"; - brule = true; - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Error", e); - srule = "Rule:KO"; - brule = false; - } catch (WaarpDatabaseSqlException e) { - logger.error("Error", e); - srule = "Rule:KO"; - brule = false; - } catch (WaarpDatabaseNoDataException e) { - logger.error("Error", e); - srule = "Rule:KO"; - brule = false; - } catch (WaarpDatabaseException e) { - logger.error("Error", e); - srule = "Rule:KO"; - brule = false; - } - if (!brule) { - if (oldRules != null) { - for (DbRule dbRule : oldRules) { - try { - if (!dbRule.exist()) { - dbRule.insert(); - } - } catch (WaarpDatabaseException e1) { - // ignore - } - } - } - } - } - R66Result result = null; - if (brule || bhost) { - result = new R66Result(session, true, ErrorCode.CompleteOk, null); - } else { - result = new R66Result(session, true, ErrorCode.TransferError, null); - } - // Now answer - ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - localChannelReference.validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - break; - } - case LocalPacketFactory.INFORMATIONPACKET: { - session.newState(VALIDOTHER); - // Validate user request - R66Result resulttest = new R66Result(session, true, - ErrorCode.CompleteOk, null); - resulttest.other = packet; - localChannelReference.validateRequest(resulttest); - Channels.close(channel); - break; - } - case LocalPacketFactory.VALIDPACKET: { - session.newState(VALIDOTHER); - // Try to validate a restarting transfer - // XXX validLimit on requested side - if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { - logger.error("Limit exceeded while asking to relaunch a task" - + packet.getSmiddle()); - session.setStatus(100); - ValidPacket valid; - valid = new ValidPacket(packet.getSmiddle(), - ErrorCode.ServerOverloaded.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - R66Result resulttest = new R66Result(null, session, true, - ErrorCode.Internal, null); - resulttest.other = packet; - localChannelReference.invalidateRequest(resulttest); - // inform back the requester - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - return; - } - // Try to validate a restarting transfer - // header = ?; middle = requested+blank+requester+blank+specialId - // note: might contains one more argument = time to reschedule in yyyyMMddHHmmss format - String[] keys = packet.getSmiddle().split(" "); - ValidPacket valid; - if (keys.length < 3) { - // not enough args - valid = new ValidPacket(packet.getSmiddle(), - ErrorCode.Internal.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - R66Result resulttest = new R66Result( - new OpenR66ProtocolBusinessRemoteFileNotFoundException("Not enough arguments"), - session, true, - ErrorCode.Internal, null); - resulttest.other = packet; - localChannelReference.invalidateRequest(resulttest); - } else { - long id = Long.parseLong(keys[2]); - DbTaskRunner taskRunner = null; - try { - taskRunner = new DbTaskRunner(localChannelReference.getDbSession(), session, - null, id, keys[1], keys[0]); - Timestamp timestart = null; - if (keys.length > 3) { - // time to reschedule in yyyyMMddHHmmss format - logger.debug("Debug: restart with "+keys[3]); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - try { - Date date = dateFormat.parse(keys[3]); - timestart = new Timestamp(date.getTime()); - taskRunner.setStart(timestart); - } catch (ParseException e) { - } - } - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(packet.getSmiddle()); - R66Result resulttest = TransferUtils.restartTransfer(taskRunner, lcr); - valid = new ValidPacket(packet.getSmiddle(), resulttest.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - resulttest.other = packet; - localChannelReference.validateRequest(resulttest); - } catch (WaarpDatabaseException e1) { - valid = new ValidPacket(packet.getSmiddle(), - ErrorCode.Internal.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - R66Result resulttest = new R66Result(new OpenR66DatabaseGlobalException(e1), - session, true, - ErrorCode.Internal, taskRunner); - resulttest.other = packet; - localChannelReference.invalidateRequest(resulttest); - } - } - // inform back the requester - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - break; - } - case LocalPacketFactory.REQUESTPACKET: { - session.newState(VALID); - // The filename from sender is changed due to PreTask so change it too in receiver - String [] fields = packet.getSmiddle().split(" "); - String newfilename = fields[0]; - for (int i = 1; i < fields.length-1; i++) { - newfilename += " "+fields[i]; - } - // potential file size changed - long newSize = -1; - if (fields.length > 1) { - try { - newSize = Long.parseLong(fields[fields.length-1]); - if (session.getRunner() != null) { - session.getRunner().setOriginalSize(newSize); - } - } catch (NumberFormatException e) { - newfilename += " " + fields[fields.length-1]; - } - } - // Pre execution was already done since this packet is only received once - // the request is already validated by the receiver - try { - session.renameReceiverFile(newfilename); - } catch (OpenR66RunnerErrorException e) { - DbTaskRunner runner = session.getRunner(); - runner.saveStatus(); - runner.setErrorExecutionStatus(ErrorCode.FileNotFound); - session.newState(ERROR); - logger.error("File renaming in error {}", e.getMessage()); - ErrorPacket error = new ErrorPacket("File renaming in error: " + e - .getMessage(), runner.getErrorInfo().getCode(), - ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - error, true); - } catch (OpenR66ProtocolPacketException e2) { - } - try { - session.setFinalizeTransfer(false, new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } catch (OpenR66RunnerErrorException e1) { - localChannelReference.invalidateRequest(new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } catch (OpenR66ProtocolSystemException e1) { - localChannelReference.invalidateRequest(new R66Result(e, session, - true, runner.getErrorInfo(), runner)); - } - session.setStatus(97); - ChannelCloseTimer.closeFutureChannel(channel); - return; - } - // Success: No write back at all - break; - } - case LocalPacketFactory.BANDWIDTHPACKET: { - session.newState(VALIDOTHER); - // should be from the local server or from an authorized hosts: LIMIT - if (!session.getAuth().isValidRole(ROLE.LIMIT)) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not correctly authenticated"); - } - String[] splitglobal = packet.getSheader().split(" "); - String[] splitsession = packet.getSmiddle().split(" "); - if (splitglobal.length < 2 || splitsession.length < 2) { - // request of current values - R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); - // Now answer - ValidPacket valid = new ValidPacket(Configuration.configuration.serverGlobalWriteLimit - +" "+Configuration.configuration.serverGlobalReadLimit+ - " "+Configuration.configuration.serverChannelWriteLimit+ - " "+Configuration.configuration.serverChannelReadLimit, result.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - localChannelReference.validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - return; - } - long wgl = (Long.parseLong(splitglobal[0]) / 10) * 10; - long rgl = (Long.parseLong(splitglobal[1]) / 10) * 10; - long wsl = (Long.parseLong(splitsession[0]) / 10) * 10; - long rsl = (Long.parseLong(splitsession[1]) / 10) * 10; - if (wgl < 0) { - wgl = Configuration.configuration.serverGlobalWriteLimit; - } - if (rgl < 0) { - rgl = Configuration.configuration.serverGlobalReadLimit; - } - if (wsl < 0) { - wsl = Configuration.configuration.serverChannelWriteLimit; - } - if (rsl < 0) { - rsl = Configuration.configuration.serverChannelReadLimit; - } - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "Change Bandwidth Limit Order received: Global " + - wgl + ":" + rgl + " (W:R) Local " + wsl + ":" + rsl + " (W:R)", - session.getAuth().getUser()); - } - Configuration.configuration.changeNetworkLimit(wgl, rgl, wsl, rsl, - Configuration.configuration.delayLimit); - R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); - // Now answer - ValidPacket valid = new ValidPacket("Bandwidth changed", result.code.getCode(), - LocalPacketFactory.REQUESTUSERPACKET); - localChannelReference.validateRequest(result); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - valid, true); - } catch (OpenR66ProtocolPacketException e) { - } - Channels.close(channel); - break; - } - case LocalPacketFactory.TESTPACKET: { - session.newState(VALIDOTHER); - logger.info("Valid TEST MESSAGE: " + packet.toString()); - R66Result resulttest = new R66Result(session, true, - ErrorCode.CompleteOk, null); - resulttest.other = packet; - localChannelReference.validateRequest(resulttest); - Channels.close(channel); - break; - } - default: - logger.info("Validation is ignored: " + packet.getTypeValid()); - } - } - - /** - * Receive an End of Request - * - * @param channel - * @param packet - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - * @throws OpenR66ProtocolNotAuthenticatedException - */ - private void endRequest(Channel channel, EndRequestPacket packet) { - // Validate the last post action on a transfer from receiver remote host - logger.info("Valid Request {}\nPacket {}", - localChannelReference, - packet); - DbTaskRunner runner = session.getRunner(); - logger.debug("Runner endRequest: " + (session.getRunner() != null)); - if (runner != null) { - runner.setAllDone(); - try { - runner.saveStatus(); - } catch (OpenR66RunnerErrorException e) { - // ignore - } - } - String optional = null; - if (session.getExtendedProtocol()) { - optional = packet.getOptional(); - } - if (!localChannelReference.getFutureRequest().isDone()) { - // end of request - R66Future transfer = localChannelReference.getFutureEndTransfer(); - try { - transfer.await(); - } catch (InterruptedException e) { - } - if (transfer.isSuccess()) { - if (session.getExtendedProtocol() && session.getBusinessObject() != null) { - if (session.getBusinessObject().getInfo() == null) { - session.getBusinessObject().setInfo(optional); - } else { - String temp = session.getBusinessObject().getInfo(); - session.getBusinessObject().setInfo(optional); - optional = temp; - } - } else if (session.getExtendedProtocol() && - transfer.getResult().other == null && optional != null) { - transfer.getResult().other = optional; - } - localChannelReference.validateRequest(transfer.getResult()); - } - } - session.setStatus(1); - if (packet.isToValidate()) { - session.newState(ENDREQUESTS); - packet.validate(); - if (session.getExtendedProtocol()) { - packet.setOptional(optional); - } - session.newState(ENDREQUESTR); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - packet, true); - } catch (OpenR66ProtocolPacketException e) { - } - } else { - session.newState(ENDREQUESTR); - } - if (runner != null && runner.isSelfRequested()) { - ChannelCloseTimer.closeFutureChannel(channel); - } - } - - /** - * Receive a Shutdown request - * - * @param channel - * @param packet - * @throws OpenR66ProtocolShutdownException - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66ProtocolBusinessException - */ - private void shutdown(Channel channel, ShutdownPacket packet) - throws OpenR66ProtocolShutdownException, - OpenR66ProtocolNotAuthenticatedException, - OpenR66ProtocolBusinessException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while Shutdown received"); - } - // SYSTEM authorization - boolean isAdmin = session.getAuth().isValidRole(ROLE.SYSTEM); - boolean isKeyValid = Configuration.configuration.isKeyValid(packet.getKey()); - if (isAdmin && isKeyValid) { - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyStartStop( - "Shutdown Order received effective in " + - Configuration.configuration.TIMEOUTCON + " ms", - session.getAuth().getUser()); - } - if (Configuration.configuration.shutdownConfiguration.serviceFuture != null) { - logger.warn("R66 started as a service, Windows Services might not shown it as stopped"); - } - throw new OpenR66ProtocolShutdownException("Shutdown Type received"); - } - logger.error("Invalid Shutdown command: from " + session.getAuth().getUser() - + " AdmValid: " + isAdmin + " KeyValid: " + isKeyValid); - throw new OpenR66ProtocolBusinessException("Invalid Shutdown comand"); - } - - /** - * Business Request (channel should stay open) - * - * Note: the thread called should manage all writeback informations, as well as status, channel - * closing if needed or not. - * - * @param channel - * @param packet - * @throws OpenR66ProtocolNotAuthenticatedException - * @throws OpenR66ProtocolPacketException - */ - private void businessRequest(Channel channel, BusinessRequestPacket packet) - throws OpenR66ProtocolNotAuthenticatedException, - OpenR66ProtocolPacketException { - if (!session.isAuthenticated()) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not authenticated while BusinessRequest received"); - } - if (!Configuration.configuration.businessWhiteSet.contains(session.getAuth().getUser())) { - throw new OpenR66ProtocolNotAuthenticatedException( - "Not allow to execute a BusinessRequest"); - } - session.setStatus(200); - String argRule = packet.getSheader(); - int delay = packet.getDelay(); - boolean argTransfer = packet.isToValidate(); - if (argTransfer) { - session.newState(BUSINESSD); - } - ExecJavaTask task = new ExecJavaTask(argRule + " " + - AbstractBusinessRequest.BUSINESSREQUEST + " " + argTransfer, - delay, null, session); - task.run(); - session.setStatus(201); - if (task.isSuccess()) { - session.setStatus(202); - logger.info("Task done: " + argRule); - } else { - R66Result result = task.getFutureCompletion().getResult(); - if (result == null) { - result = new R66Result(session, false, ErrorCode.ExternalOp, session.getRunner()); - } - logger.info("Task in Error:" + argRule + "\n" + result); - if (!result.isAnswered) { - packet.invalidate(); - session.newState(ERROR); - ErrorPacket error = new ErrorPacket( - "BusinessRequest in error: for " + packet.toString() + " since " + - result.getMessage(), - result.code.getCode(), ErrorPacket.FORWARDCLOSECODE); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - session.setStatus(203); - } - session.setStatus(204); - } - } - - /** - * Try to finalize the request if possible - * - * @param errorValue - * in case of Error - * @throws OpenR66ProtocolSystemException - * @throws OpenR66RunnerErrorException - */ - private void tryFinalizeRequest(R66Result errorValue) - throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { - session.tryFinalizeRequest(errorValue); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTD; +import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTR; +import static org.waarp.openr66.context.R66FiniteDualStates.BUSINESSD; +import static org.waarp.openr66.context.R66FiniteDualStates.CLOSEDCHANNEL; +import static org.waarp.openr66.context.R66FiniteDualStates.DATAR; +import static org.waarp.openr66.context.R66FiniteDualStates.ENDREQUESTR; +import static org.waarp.openr66.context.R66FiniteDualStates.ENDREQUESTS; +import static org.waarp.openr66.context.R66FiniteDualStates.ENDTRANSFERR; +import static org.waarp.openr66.context.R66FiniteDualStates.ENDTRANSFERS; +import static org.waarp.openr66.context.R66FiniteDualStates.ERROR; +import static org.waarp.openr66.context.R66FiniteDualStates.INFORMATION; +import static org.waarp.openr66.context.R66FiniteDualStates.REQUESTD; +import static org.waarp.openr66.context.R66FiniteDualStates.REQUESTR; +import static org.waarp.openr66.context.R66FiniteDualStates.SHUTDOWN; +import static org.waarp.openr66.context.R66FiniteDualStates.STARTUP; +import static org.waarp.openr66.context.R66FiniteDualStates.TEST; +import static org.waarp.openr66.context.R66FiniteDualStates.VALID; +import static org.waarp.openr66.context.R66FiniteDualStates.VALIDOTHER; + +import java.io.File; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelFutureListener; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelHandler; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.command.exception.Reply421Exception; +import org.waarp.common.command.exception.Reply530Exception; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.exception.FileTransferException; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.role.RoleDefault.ROLE; +import org.waarp.openr66.client.AbstractBusinessRequest; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; +import org.waarp.openr66.configuration.RuleFileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.authentication.R66Auth; +import org.waarp.openr66.context.filesystem.R66Dir; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.task.ExecJavaTask; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.context.task.exception.OpenR66RunnerException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessCancelException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessQueryAlreadyFinishedException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessQueryStillRunningException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessRemoteFileNotFoundException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessStopException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotAuthenticatedException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; +import org.waarp.openr66.protocol.localhandler.packet.AuthentPacket; +import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.DataPacket; +import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.EndTransferPacket; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ShutdownPacket; +import org.waarp.openr66.protocol.localhandler.packet.StartupPacket; +import org.waarp.openr66.protocol.localhandler.packet.TestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkChannel; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelCloseTimer; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.FileUtils; +import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.openr66.protocol.utils.TransferUtils; + +/** + * The local server handler handles real end file operations. + * + * @author frederic bregier + */ +public class LocalServerHandler extends SimpleChannelHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LocalServerHandler.class); + + /** + * Session + */ + private volatile R66Session session; + /** + * Local Channel Reference + */ + private volatile LocalChannelReference localChannelReference; + /** + * Global Digest in receive + */ + private volatile FilesystemBasedDigest globalDigest; + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. + * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { + logger.debug("Local Server Channel Closed: {} {}", + (localChannelReference != null ? localChannelReference + : "no LocalChannelReference"), (session.getRunner() != null ? + session.getRunner().toShortString() : "no runner")); + // clean session objects like files + DbTaskRunner runner = session.getRunner(); + boolean mustFinalize = true; + if (localChannelReference != null && + localChannelReference.getFutureRequest().isDone()) { + // already done + } else { + if (localChannelReference != null) { + R66Future fvr = localChannelReference.getFutureValidRequest(); + try { + fvr.await(); + } catch (InterruptedException e1) { + } + if (fvr.isDone()) { + if (!fvr.isSuccess()) { + // test if remote server was Overloaded + if (fvr.getResult().code == ErrorCode.ServerOverloaded) { + // ignore + mustFinalize = false; + } + } + } + logger.debug("Must Finalize: " + mustFinalize); + if (mustFinalize) { + session.newState(ERROR); + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException( + "Finalize too early at close time But Must Finalize"), + session, true, ErrorCode.FinalOp, runner); // True since closed + try { + tryFinalizeRequest(finalValue); + } catch (OpenR66Exception e2) { + } + } + } + } + if (mustFinalize && runner != null) { + if (runner.isSelfRequested()) { + R66Future transfer = localChannelReference.getFutureRequest(); + // Since requested : log + R66Result result = transfer.getResult(); + if (transfer.isDone() && transfer.isSuccess()) { + logger.info("TRANSFER REQUESTED RESULT:\n SUCCESS\n " + + (result != null ? result.toString() : "no result")); + } else { + logger.error("TRANSFER REQUESTED RESULT:\n FAILURE\n " + + (result != null ? result.toString() : "no result")); + } + } + } + session.setStatus(50); + session.newState(CLOSEDCHANNEL); + session.clear(); + session.setStatus(51); + if (localChannelReference != null) { + if (localChannelReference.getDbSession() != null) { + localChannelReference.getDbSession().endUseConnection(); + logger.debug("End Use Connection"); + } + String requester = + (runner != null && runner.isSelfRequested() && + localChannelReference.getNetworkChannelObject() != null) ? + runner.getRequester() : null; + NetworkTransaction.removeNetworkChannel(localChannelReference + .getNetworkChannel(), e.getChannel(), requester); + /* + * // Only requested can has a remote client if (runner != null && + * runner.isSelfRequested() && localChannelReference.getNetworkChannelObject() != null + * && localChannelReference.getNetworkChannelObject().count <= 0) { + * NetworkTransaction.removeClient(runner.getRequester(), + * localChannelReference.getNetworkChannelObject()); } + */ + session.setStatus(52); + Configuration.configuration.getLocalTransaction().remove(e.getChannel()); + } else { + logger + .error("Local Server Channel Closed but no LocalChannelReference: " + + e.getChannel().getId()); + } + // Now if runner is not yet finished, finish it by force + if (mustFinalize && localChannelReference != null + && (!localChannelReference.getFutureRequest().isDone())) { + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException( + "Finalize too early at close time while Request not yet finished"), + session, true, ErrorCode.FinalOp, runner); + localChannelReference.invalidateRequest(finalValue); + // In case stop the attached thread if any + ClientRunner clientRunner = localChannelReference.getClientRunner(); + if (clientRunner != null) { + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e1) { + } + clientRunner.interrupt(); + } + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { + session = new R66Session(); + session.setStatus(60); + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) + */ + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) + throws OpenR66Exception { + // action as requested and answer if necessary + final AbstractLocalPacket packet = (AbstractLocalPacket) e.getMessage(); + if (packet.getType() == LocalPacketFactory.STARTUPPACKET) { + startup(e.getChannel(), (StartupPacket) packet); + } else { + if (localChannelReference == null) { + logger.error("No LocalChannelReference at " + + packet.getClass().getName()); + session.newState(ERROR); + final ErrorPacket errorPacket = new ErrorPacket( + "No LocalChannelReference at " + + packet.getClass().getName(), + ErrorCode.ConnectionImpossible.getCode(), + ErrorPacket.FORWARDCLOSECODE); + try { + Channels.write(e.getChannel(), errorPacket).await(); + } catch (InterruptedException e1) { + } + localChannelReference.invalidateRequest(new R66Result( + new OpenR66ProtocolSystemException( + "No LocalChannelReference"), session, true, + ErrorCode.ConnectionImpossible, null)); + ChannelUtils.close(e.getChannel()); + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "No LocalChannelReference", packet.getClass().getSimpleName()); + } + return; + } + switch (packet.getType()) { + case LocalPacketFactory.AUTHENTPACKET: { + authent(e.getChannel(), (AuthentPacket) packet); + break; + } + // Already done case LocalPacketFactory.STARTUPPACKET: + case LocalPacketFactory.DATAPACKET: { + session.newState(DATAR); + data(e.getChannel(), (DataPacket) packet); + break; + } + case LocalPacketFactory.VALIDPACKET: { + valid(e.getChannel(), (ValidPacket) packet); + break; + } + case LocalPacketFactory.ERRORPACKET: { + session.newState(ERROR); + errorMesg(e.getChannel(), (ErrorPacket) packet); + break; + } + case LocalPacketFactory.CONNECTERRORPACKET: { + connectionError(e.getChannel(), + (ConnectionErrorPacket) packet); + break; + } + case LocalPacketFactory.REQUESTPACKET: { + request(e.getChannel(), (RequestPacket) packet); + break; + } + case LocalPacketFactory.SHUTDOWNPACKET: { + session.newState(SHUTDOWN); + shutdown(e.getChannel(), (ShutdownPacket) packet); + break; + } + case LocalPacketFactory.STOPPACKET: + case LocalPacketFactory.CANCELPACKET: + case LocalPacketFactory.CONFIMPORTPACKET: + case LocalPacketFactory.CONFEXPORTPACKET: + case LocalPacketFactory.BANDWIDTHPACKET: { + logger.error("Unimplemented Mesg: " + + packet.getClass().getName()); + session.newState(ERROR); + localChannelReference.invalidateRequest(new R66Result( + new OpenR66ProtocolSystemException( + "Not implemented"), session, true, + ErrorCode.Unimplemented, null)); + final ErrorPacket errorPacket = new ErrorPacket( + "Unimplemented Mesg: " + + packet.getClass().getName(), + ErrorCode.Unimplemented.getCode(), + ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); + ChannelUtils.close(e.getChannel()); + break; + } + case LocalPacketFactory.TESTPACKET: { + session.newState(TEST); + test(e.getChannel(), (TestPacket) packet); + break; + } + case LocalPacketFactory.ENDTRANSFERPACKET: { + endTransfer(e.getChannel(), (EndTransferPacket) packet); + break; + } + case LocalPacketFactory.INFORMATIONPACKET: { + session.newState(INFORMATION); + information(e.getChannel(), (InformationPacket) packet); + break; + } + case LocalPacketFactory.ENDREQUESTPACKET: { + endRequest(e.getChannel(), (EndRequestPacket) packet); + break; + } + case LocalPacketFactory.BUSINESSREQUESTPACKET: { + businessRequest(e.getChannel(), (BusinessRequestPacket) packet); + break; + } + default: { + logger + .error("Unknown Mesg: " + + packet.getClass().getName()); + session.newState(ERROR); + localChannelReference.invalidateRequest(new R66Result( + new OpenR66ProtocolSystemException( + "Unknown Message"), session, true, + ErrorCode.Unimplemented, null)); + final ErrorPacket errorPacket = new ErrorPacket( + "Unkown Mesg: " + packet.getClass().getName(), + ErrorCode.Unimplemented.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, errorPacket, true); + ChannelUtils.close(e.getChannel()); + } + } + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + // inform clients + logger.debug("Exception and isFinished: "+ + (localChannelReference != null && localChannelReference.getFutureRequest().isDone()), e); + if (localChannelReference != null && localChannelReference.getFutureRequest().isDone()) { + Channels.close(e.getChannel()); + return; + } + OpenR66Exception exception = OpenR66ExceptionTrappedFactory + .getExceptionFromTrappedException(e.getChannel(), e); + ErrorCode code = null; + if (exception != null) { + session.newState(ERROR); + boolean isAnswered = false; + if (exception instanceof OpenR66ProtocolShutdownException) { + logger.warn("Shutdown order received and going from: " + + session.getAuth().getUser()); + if (localChannelReference != null) { + R66Result finalValue = new R66Result(exception, session, true, + ErrorCode.Shutdown, session.getRunner()); + try { + tryFinalizeRequest(finalValue); + } catch (OpenR66RunnerErrorException e2) { + } catch (OpenR66ProtocolSystemException e2) { + } + if (!localChannelReference.getFutureRequest().isDone()) { + try { + session.setFinalizeTransfer(false, finalValue); + } catch (OpenR66RunnerErrorException e1) { + localChannelReference.invalidateRequest(finalValue); + } catch (OpenR66ProtocolSystemException e1) { + localChannelReference.invalidateRequest(finalValue); + } + } + } + // dont'close, thread will do + ChannelUtils.startShutdown(); + // set global shutdown info and before close, send a valid + // shutdown to all + session.setStatus(54); + return; + } else { + if (localChannelReference != null + && localChannelReference.getFutureRequest() != null) { + if (localChannelReference.getFutureRequest().isDone()) { + R66Result result = localChannelReference.getFutureRequest() + .getResult(); + if (result != null) { + isAnswered = result.isAnswered; + } + } + } + if (exception instanceof OpenR66ProtocolNoConnectionException) { + code = ErrorCode.ConnectionImpossible; + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + runner.stopOrCancelRunner(code); + } + } else if (exception instanceof OpenR66ProtocolBusinessCancelException) { + code = ErrorCode.CanceledTransfer; + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + runner.stopOrCancelRunner(code); + } + } else if (exception instanceof OpenR66ProtocolBusinessStopException) { + code = ErrorCode.StoppedTransfer; + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + runner.stopOrCancelRunner(code); + } + } else if (exception instanceof OpenR66ProtocolBusinessQueryAlreadyFinishedException) { + code = ErrorCode.QueryAlreadyFinished; + try { + tryFinalizeRequest(new R66Result(session, true, code, session.getRunner())); + return; + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + } else if (exception instanceof OpenR66ProtocolBusinessQueryStillRunningException) { + code = ErrorCode.QueryStillRunning; + // nothing is to be done + logger.error("Will close channel since ", exception); + Channels.close(e.getChannel()); + session.setStatus(56); + return; + } else if (exception instanceof OpenR66ProtocolBusinessRemoteFileNotFoundException) { + code = ErrorCode.FileNotFound; + } else if (exception instanceof OpenR66RunnerException) { + code = ErrorCode.ExternalOp; + } else if (exception instanceof OpenR66ProtocolNotAuthenticatedException) { + code = ErrorCode.BadAuthent; + } else if (exception instanceof OpenR66ProtocolNetworkException) { + code = ErrorCode.Disconnection; + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException( + "Finalize too early at close time with Network Exception"), + session, true, code, session.getRunner()); + try { + tryFinalizeRequest(finalValue); + } catch (OpenR66Exception e2) { + } + } + } else if (exception instanceof OpenR66ProtocolRemoteShutdownException) { + code = ErrorCode.RemoteShutdown; + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + runner.stopOrCancelRunner(code); + } + } else { + DbTaskRunner runner = session.getRunner(); + if (runner != null) { + switch (runner.getErrorInfo()) { + case InitOk: + case PostProcessingOk: + case PreProcessingOk: + case Running: + case TransferOk: + code = ErrorCode.Internal; + default: + code = runner.getErrorInfo(); + } + } else { + code = ErrorCode.Internal; + } + } + if ((!isAnswered) && + (!(exception instanceof OpenR66ProtocolBusinessNoWriteBackException)) && + (!(exception instanceof OpenR66ProtocolNoConnectionException))) { + if (code == null || code == ErrorCode.Internal) { + code = ErrorCode.RemoteError; + } + final ErrorPacket errorPacket = new ErrorPacket(exception + .getMessage(), + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + errorPacket, true); + } catch (OpenR66ProtocolPacketException e1) { + // should not be + } + } + R66Result finalValue = + new R66Result( + exception, session, true, code, session.getRunner()); + try { + session.setFinalizeTransfer(false, finalValue); + if (localChannelReference != null) { + localChannelReference.invalidateRequest(finalValue); + } + } catch (OpenR66RunnerErrorException e1) { + if (localChannelReference != null) + localChannelReference.invalidateRequest(finalValue); + } catch (OpenR66ProtocolSystemException e1) { + if (localChannelReference != null) + localChannelReference.invalidateRequest(finalValue); + } + } + if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { + logger.error("Will close channel {}", exception.getMessage()); + Channels.close(e.getChannel()); + session.setStatus(56); + return; + } else if (exception instanceof OpenR66ProtocolNoConnectionException) { + logger.error("Will close channel {}", exception.getMessage()); + Channels.close(e.getChannel()); + session.setStatus(57); + return; + } + session.setStatus(58); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + } else { + // Nothing to do + session.setStatus(59); + return; + } + } + + /** + * Startup of the session and the local channel reference + * + * @param channel + * @param packet + * @throws OpenR66ProtocolPacketException + */ + private void startup(Channel channel, StartupPacket packet) + throws OpenR66ProtocolPacketException { + localChannelReference = Configuration.configuration + .getLocalTransaction().getFromId(packet.getLocalId()); + if (localChannelReference == null) { + session.newState(ERROR); + logger.error("Cannot startup"); + ErrorPacket error = new ErrorPacket("Cannot startup connection", + ErrorCode.ConnectionImpossible.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + Channels.write(channel, error).await(); + } catch (InterruptedException e) { + } + // Cannot do writeBack(error, true); + session.setStatus(40); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + NetworkChannel networkChannel = + NetworkTransaction.getNetworkChannel(localChannelReference.getNetworkChannel()); + if (networkChannel != null) { + localChannelReference.setNetworkChannelObject(networkChannel); + } else { + logger.error("No NetworkChannek found!"); + } + session.newState(STARTUP); + localChannelReference.validateStartup(true); + session.setLocalChannelReference(localChannelReference); + Channels.write(channel, packet); + session.setStatus(41); + } + + /** + * Refuse a connection + * + * @param channel + * @param packet + * @param e1 + * @throws OpenR66ProtocolPacketException + */ + private void refusedConnection(Channel channel, AuthentPacket packet, Exception e1) + throws OpenR66ProtocolPacketException { + logger.error("Cannot connect from "+ + localChannelReference.getNetworkChannel().getRemoteAddress()+ + " : " + packet.getHostId(), e1); + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyError( + "Connection not allowed from "+ + localChannelReference.getNetworkChannel().getRemoteAddress() + +" since "+e1.getMessage(), packet.getHostId()); + } + R66Result result = new R66Result( + new OpenR66ProtocolSystemException( + "Connection not allowed from "+ + localChannelReference.getNetworkChannel().getRemoteAddress(), + e1), session, true, + ErrorCode.BadAuthent, null); + localChannelReference.invalidateRequest(result); + session.newState(ERROR); + ErrorPacket error = new ErrorPacket("Connection not allowed", + ErrorCode.BadAuthent.getCode(), + ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + localChannelReference.validateConnection(false, result); + ChannelCloseTimer.closeFutureChannel(channel); + } + + /** + * Authentication + * + * @param channel + * @param packet + * @throws OpenR66ProtocolPacketException + */ + private void authent(Channel channel, AuthentPacket packet) + throws OpenR66ProtocolPacketException { + if (packet.isToValidate()) { + session.newState(AUTHENTR); + } + + if (localChannelReference.getDbSession() != null) { + localChannelReference.getDbSession().useConnection(); + } + try { + session.getAuth().connection(localChannelReference.getDbSession(), + packet.getHostId(), packet.getKey()); + } catch (Reply530Exception e1) { + refusedConnection(channel, packet, e1); + session.setStatus(42); + return; + } catch (Reply421Exception e1) { + session.newState(ERROR); + logger.error("Service unavailable: " + packet.getHostId(), e1); + R66Result result = new R66Result( + new OpenR66ProtocolSystemException("Service unavailable", + e1), session, true, + ErrorCode.ConnectionImpossible, null); + localChannelReference.invalidateRequest(result); + ErrorPacket error = new ErrorPacket("Service unavailable", + ErrorCode.ConnectionImpossible.getCode(), + ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + localChannelReference.validateConnection(false, result); + ChannelCloseTimer.closeFutureChannel(channel); + session.setStatus(43); + return; + } + // Now if configuration say to do so: check remote ip address + if (Configuration.configuration.checkRemoteAddress) { + DbHostAuth host = R66Auth.getServerAuth(DbConstant.admin.session, + packet.getHostId()); + boolean toTest = false; + if (host.isClient()) { + if (Configuration.configuration.checkClientAddress) { + if (host.isNoAddress()) { + // 0.0.0.0 so nothing + toTest = false; + } else { + toTest = true; + } + } + } else { + toTest = true; + } + if (toTest) { + // Real address so compare + String address = host.getAddress(); + InetAddress[] inetAddress = null; + try { + inetAddress = InetAddress.getAllByName(address); + } catch (UnknownHostException e) { + inetAddress = null; + } + if (inetAddress != null) { + InetSocketAddress socketAddress = (InetSocketAddress) session + .getRemoteAddress(); + boolean found = false; + for (int i = 0; i < inetAddress.length; i++) { + if (socketAddress.getAddress().equals(inetAddress[i])) { + found = true; + break; + } + } + if (!found) { + // error + refusedConnection(channel, packet, + new OpenR66ProtocolNotAuthenticatedException( + "Server IP not authenticated: " + + inetAddress[0].toString() + " compare to " + + socketAddress.getAddress().toString())); + session.setStatus(104); + return; + } + } + } + } + R66Result result = new R66Result(session, true, ErrorCode.InitOk, null); + session.newState(AUTHENTD); + localChannelReference.validateConnection(true, result); + logger.debug("Local Server Channel Validated: {} ", + (localChannelReference != null ? localChannelReference + : "no LocalChannelReference")); + session.setStatus(44); + if (packet.isToValidate()) { + // only requested + NetworkTransaction.addClient(localChannelReference.getNetworkChannel(), + packet.getHostId()); + packet.validate(session.getAuth().isSsl()); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); + session.setStatus(98); + } + } + + /** + * Receive a connection error + * + * @param channel + * @param packet + */ + private void connectionError(Channel channel, ConnectionErrorPacket packet) { + // do something according to the error + logger.error(channel.getId() + ": " + packet.toString()); + localChannelReference.invalidateRequest(new R66Result( + new OpenR66ProtocolSystemException(packet.getSheader()), + session, true, ErrorCode.ConnectionImpossible, null)); + // True since closing + session.newState(ERROR); + session.setStatus(45); + Channels.close(channel); + } + + /** + * Class to finalize a runner when the future is over + * + * @author Frederic Bregier + * + */ + private class RunnerChannelFutureListener implements ChannelFutureListener { + private LocalChannelReference localChannelReference; + private R66Result result; + + public RunnerChannelFutureListener(LocalChannelReference localChannelReference, + R66Result result) { + this.localChannelReference = localChannelReference; + this.result = result; + } + + public void operationComplete(ChannelFuture future) throws Exception { + localChannelReference.invalidateRequest( + result); + ChannelCloseTimer.closeFutureChannel(localChannelReference.getLocalChannel()); + } + + } + + /** + * Receive a remote error + * + * @param channel + * @param packet + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + * @throws OpenR66ProtocolBusinessException + */ + private void errorMesg(Channel channel, ErrorPacket packet) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException, + OpenR66ProtocolBusinessException { + // do something according to the error + if (session.getLocalChannelReference().getFutureRequest().isDone()) { + // already canceled or successful + return; + } + logger.error(channel.getId() + ": " + packet.toString()); + session.setStatus(46); + ErrorCode code = ErrorCode.getFromCode(packet.getSmiddle()); + session.getLocalChannelReference().setErrorMessage(packet.getSheader(), code); + OpenR66ProtocolBusinessException exception; + if (code.code == ErrorCode.CanceledTransfer.code) { + exception = + new OpenR66ProtocolBusinessCancelException(packet.getSheader()); + int rank = 0; + DbTaskRunner runner = this.session.getRunner(); + if (runner != null) { + runner.setRankAtStartup(rank); + runner.stopOrCancelRunner(code); + } + R66Result result = new R66Result(exception, session, + true, code, runner); + // now try to inform other + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false). + addListener(new RunnerChannelFutureListener(localChannelReference, result)); + } catch (OpenR66ProtocolPacketException e) { + } + session.setFinalizeTransfer(false, result); + return; + } else if (code.code == ErrorCode.StoppedTransfer.code) { + exception = + new OpenR66ProtocolBusinessStopException(packet.getSheader()); + String[] vars = packet.getSheader().split(" "); + String var = vars[vars.length - 1]; + int rank = Integer.parseInt(var); + DbTaskRunner runner = this.session.getRunner(); + if (runner != null) { + if (rank < runner.getRank()) { + runner.setRankAtStartup(rank); + } + runner.stopOrCancelRunner(code); + } + R66Result result = new R66Result(exception, session, + true, code, runner); + // now try to inform other + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false). + addListener(new RunnerChannelFutureListener(localChannelReference, result)); + } catch (OpenR66ProtocolPacketException e) { + } + session.setFinalizeTransfer(false, result); + return; + } else if (code.code == ErrorCode.QueryAlreadyFinished.code) { + DbTaskRunner runner = session.getRunner(); + if (runner == null) { + exception = + new OpenR66ProtocolBusinessCancelException(packet.toString()); + } else { + if (runner.isSender()) { + exception = + new OpenR66ProtocolBusinessQueryAlreadyFinishedException( + packet.getSheader()); + runner.finishTransferTask(code); + tryFinalizeRequest(new R66Result(exception, session, true, code, runner)); + } else { + exception = + new OpenR66ProtocolBusinessCancelException(packet.toString()); + } + } + throw exception; + } else if (code.code == ErrorCode.QueryStillRunning.code) { + exception = + new OpenR66ProtocolBusinessQueryStillRunningException(packet.getSheader()); + throw exception; + } else if (code.code == ErrorCode.BadAuthent.code) { + exception = + new OpenR66ProtocolNotAuthenticatedException(packet.toString()); + } else if (code.code == ErrorCode.QueryRemotelyUnknown.code) { + exception = + new OpenR66ProtocolBusinessCancelException(packet.toString()); + } else if (code.code == ErrorCode.FileNotFound.code) { + exception = + new OpenR66ProtocolBusinessRemoteFileNotFoundException(packet.toString()); + } else { + exception = + new OpenR66ProtocolBusinessNoWriteBackException(packet.toString()); + } + session.setFinalizeTransfer(false, new R66Result(exception, session, + true, code, session.getRunner())); + throw exception; + } + + /** + * Finalize a request initialization in error + * + * @param channel + * @param code + * @param runner + * @param e1 + * @param packet + * @throws OpenR66ProtocolPacketException + */ + private void endInitRequestInError(Channel channel, ErrorCode code, DbTaskRunner runner, + OpenR66Exception e1, RequestPacket packet) throws OpenR66ProtocolPacketException { + logger.error("TaskRunner initialisation in error: " + code.mesg + " " + session + + " {} runner {}", + e1 != null ? e1.getMessage() : "no exception", + (runner != null ? runner.toShortString() : "no runner")); + localChannelReference.invalidateRequest(new R66Result( + e1, session, true, code, null)); + + if (packet.isToValidate()) { + // / answer with a wrong request since runner is not set on remote host + if (runner != null) { + if (runner.isSender()) { + // In case Wildcard was used + logger.debug("New FILENAME: {}", runner.getOriginalFilename()); + packet.setFilename(runner.getOriginalFilename()); + logger.debug("Rank set: " + runner.getRank()); + packet.setRank(runner.getRank()); + } else { + logger.debug("Rank set: " + runner.getRank()); + packet.setRank(runner.getRank()); + } + } + packet.validate(); + packet.setCode(code.code); + session.newState(ERROR); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, true); + } else { + session.newState(ERROR); + ErrorPacket error = new ErrorPacket( + "TaskRunner initialisation in error: " + e1 + .getMessage() + " for " + packet.toString() + " since " + code.mesg, + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } + session.setStatus(47); + ChannelCloseTimer.closeFutureChannel(channel); + } + + /** + * Receive a request + * + * @param channel + * @param packet + * @throws OpenR66ProtocolNoDataException + * @throws OpenR66ProtocolPacketException + * @throws OpenR66ProtocolBusinessException + * @throws OpenR66ProtocolSystemException + * @throws OpenR66RunnerErrorException + */ + private void request(Channel channel, RequestPacket packet) + throws OpenR66ProtocolNoDataException, OpenR66ProtocolPacketException, + OpenR66RunnerErrorException, OpenR66ProtocolSystemException, + OpenR66ProtocolBusinessException { + session.setStatus(99); + if (!session.isAuthenticated()) { + session.setStatus(48); + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Request received"); + } + // XXX validLimit only on requested side + if (packet.isToValidate()) { + if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib. + notifyOverloaded("Rule: " + packet.getRulename() + " from " + + session.getAuth().toString(), + Configuration.configuration.constraintLimitHandler.lastAlert); + } + logger.info("Limit exceeded when receive request with Rule: " + + packet.getRulename() + " from " + session.getAuth().toString()); + session.setStatus(100); + endInitRequestInError(channel, + ErrorCode.ServerOverloaded, null, + new OpenR66ProtocolNotYetConnectionException( + "Limit exceeded"), packet); + session.setStatus(100); + return; + } + } else if (packet.getCode() == ErrorCode.ServerOverloaded.code) { + // XXX unvalid limit on requested host received + logger.info("TaskRunner initialisation in error: " + ErrorCode.ServerOverloaded.mesg); + localChannelReference.invalidateRequest(new R66Result( + null, session, true, ErrorCode.ServerOverloaded, null)); + session.setStatus(101); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + DbRule rule; + try { + rule = new DbRule(localChannelReference.getDbSession(), packet.getRulename()); + } catch (WaarpDatabaseException e) { + logger.info("Rule is unknown: " + packet.getRulename() + " {}", e.getMessage()); + session.setStatus(49); + endInitRequestInError(channel, + ErrorCode.QueryRemotelyUnknown, null, + new OpenR66ProtocolBusinessException( + "The Transfer is associated with an Unknown Rule: " + + packet.getRulename()), packet); + return; + } + int blocksize = packet.getBlocksize(); + if (packet.isToValidate()) { + if (!rule.checkHostAllow(session.getAuth().getUser())) { + session.setStatus(30); + throw new OpenR66ProtocolNotAuthenticatedException( + "Rule is not allowed for the remote host"); + } + // Check if the blocksize is greater than local value + if (Configuration.configuration.BLOCKSIZE < blocksize) { + blocksize = Configuration.configuration.BLOCKSIZE; + packet = new RequestPacket(packet.getRulename(), packet.getMode(), + packet.getFilename(), blocksize, packet.getRank(), + packet.getSpecialId(), packet.getFileInformation(), packet.getOriginalSize()); + } + } + if (!RequestPacket.isCompatibleMode(rule.mode, packet.getMode())) { + // not compatible Rule and mode in request + throw new OpenR66ProtocolNotAuthenticatedException( + "Rule has not the same mode of transmission: " + rule.mode + " vs " + + packet.getMode()); + } + session.setBlockSize(blocksize); + DbTaskRunner runner; + // requested + boolean isRetrieve = DbTaskRunner.getSenderByRequestPacket(packet); + if (packet.getSpecialId() != DbConstant.ILLEGALVALUE) { + // Reload or create + String requested = DbTaskRunner.getRequested(session, packet); + String requester = DbTaskRunner.getRequester(session, packet); + if (packet.isToValidate()) { + // Id could be a creation or a reload + // Try reload + try { + runner = new DbTaskRunner(localChannelReference.getDbSession(), + session, rule, packet.getSpecialId(), + requester, requested); + runner.setSender(isRetrieve); + if (runner.isAllDone()) { + // truly an error since done + session.setStatus(31); + endInitRequestInError(channel, + ErrorCode.QueryAlreadyFinished, runner, + new OpenR66ProtocolBusinessQueryAlreadyFinishedException( + "The TransferId is associated with a Transfer already finished: " + + + packet.getSpecialId()), packet); + return; + } + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest( + requested + " " + requester + " " + + packet.getSpecialId()); + if (lcr != null) { + // truly an error since still running + session.setStatus(32); + endInitRequestInError(channel, + ErrorCode.QueryStillRunning, runner, + new OpenR66ProtocolBusinessQueryStillRunningException( + "The TransferId is associated with a Transfer still running: " + + + packet.getSpecialId()), packet); + return; + } + // ok to restart + try { + if (runner.restart(false)) { + runner.saveStatus(); + } + } catch (OpenR66RunnerErrorException e) { + } + } catch (WaarpDatabaseNoDataException e) { + // Reception of request from requester host + try { + runner = new DbTaskRunner(localChannelReference.getDbSession(), + session, rule, isRetrieve, packet); + } catch (WaarpDatabaseException e1) { + session.setStatus(33); + endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, + null, new OpenR66DatabaseGlobalException(e), packet); + return; + } + } catch (WaarpDatabaseException e) { + session.setStatus(34); + endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, + new OpenR66DatabaseGlobalException(e), packet); + return; + } + // Change the SpecialID! => could generate an error ? + packet.setSpecialId(runner.getSpecialId()); + } else { + // Id should be a reload + try { + runner = new DbTaskRunner(localChannelReference.getDbSession(), + session, rule, packet.getSpecialId(), + requester, requested); + runner.setSender(isRetrieve); + // FIX check for SelfRequest + if (runner.isSelfRequest()) { + runner.setFilename(runner.getOriginalFilename()); + } + if (! runner.isSender()) { + logger.debug("New filename ? :" +packet.getFilename()); + runner.setOriginalFilename(packet.getFilename()); + runner.setFilename(packet.getFilename()); + } + try { + if (runner.restart(false)) { + if (!runner.isSelfRequest()) { + runner.saveStatus(); + } + } + } catch (OpenR66RunnerErrorException e) { + } + } catch (WaarpDatabaseException e) { + if (localChannelReference.getDbSession() == null) { + // Special case of no database client + try { + runner = new DbTaskRunner(localChannelReference.getDbSession(), + session, rule, isRetrieve, packet); + } catch (WaarpDatabaseException e1) { + session.setStatus(35); + endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, + new OpenR66DatabaseGlobalException(e1), packet); + return; + } + } else { + endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, + new OpenR66DatabaseGlobalException(e), packet); + session.setStatus(36); + return; + } + } + } + } else { + // Very new request + // should not be the case (the requester should always set the id) + logger.error("NO TransferID specified: SHOULD NOT BE THE CASE"); + try { + runner = new DbTaskRunner(localChannelReference.getDbSession(), + session, rule, isRetrieve, packet); + } catch (WaarpDatabaseException e) { + session.setStatus(37); + endInitRequestInError(channel, ErrorCode.QueryRemotelyUnknown, null, + new OpenR66DatabaseGlobalException(e), packet); + return; + } + packet.setSpecialId(runner.getSpecialId()); + } + // Check now if request is a valid one + if (packet.getCode() != ErrorCode.InitOk.code) { + // not valid so create an error from there + ErrorCode code = ErrorCode.getFromCode("" + packet.getCode()); + session.setBadRunner(runner, code); + session.newState(ERROR); + logger.error("Bad runner at startup {} {}", packet, session); + ErrorPacket errorPacket = new ErrorPacket(code.mesg, + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + errorMesg(channel, errorPacket); + return; + } + // Receiver can specify a rank different from database + if (runner.isSender()) { + logger.debug("Rank was: " + runner.getRank() + " -> " + packet.getRank()); + runner.setRankAtStartup(packet.getRank()); + } else if (runner.getRank() > packet.getRank()) { + logger.debug("Recv Rank was: " + runner.getRank() + " -> " + packet.getRank()); + // if receiver, change only if current rank is upper proposed rank + runner.setRankAtStartup(packet.getRank()); + } + boolean shouldInformBack = false; + try { + session.setRunner(runner); + if (runner.isSender() && ! runner.isSendThrough()) { + if (packet.getOriginalSize() != runner.getOriginalSize()) { + packet.setOriginalSize(runner.getOriginalSize()); + shouldInformBack = true; + } + } + } catch (OpenR66RunnerErrorException e) { + try { + runner.saveStatus(); + } catch (OpenR66RunnerErrorException e1) { + logger.error("Cannot save Status: " + runner, e1); + } + if (runner.getErrorInfo() == ErrorCode.InitOk || + runner.getErrorInfo() == ErrorCode.PreProcessingOk || + runner.getErrorInfo() == ErrorCode.TransferOk) { + runner.setErrorExecutionStatus(ErrorCode.ExternalOp); + } + logger.error("PreTask in error {}", e.getMessage()); + session.newState(ERROR); + ErrorPacket error = new ErrorPacket("PreTask in error: " + e + .getMessage(), runner.getErrorInfo().getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + try { + session.setFinalizeTransfer(false, new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } catch (OpenR66RunnerErrorException e1) { + localChannelReference.invalidateRequest(new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } catch (OpenR66ProtocolSystemException e1) { + localChannelReference.invalidateRequest(new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } + session.setStatus(38); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + if (packet.isToValidate()) { + session.newState(REQUESTR); + } + if (runner.isFileMoved() && runner.isSender() && runner.isInTransfer() + && runner.getRank() == 0 && (!packet.isToValidate())) { + // File was moved during PreTask and very beginning of the transfer + // and the remote host has already received the request packet + // => Informs the receiver of the new name + logger.debug("Will send a modification of filename due to pretask: " + + runner.getFilename()); + session.newState(VALID); + ValidPacket validPacket = new ValidPacket("Change Filename by Pre action on sender", + runner.getFilename()+" "+packet.getOriginalSize(), + LocalPacketFactory.REQUESTPACKET); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + } else if ((!packet.getFilename().equals(runner.getOriginalFilename())) + && runner.isSender() && runner.isInTransfer() + && runner.getRank() == 0 && (!packet.isToValidate())) { + // File was modify at the very beginning (using wildcards) + // and the remote host has already received the request packet + // => Informs the receiver of the new name + logger.debug("Will send a modification of filename due to wildcard: " + + runner.getFilename()); + session.newState(VALID); + ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", + runner.getFilename()+" "+packet.getOriginalSize(), + LocalPacketFactory.REQUESTPACKET); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + } else if (runner.isSelfRequest() && runner.isSender() && runner.isInTransfer() + && runner.getRank() == 0 && (!packet.isToValidate())) { + // FIX SelfRequest + // File could be modified at the very beginning (using wildcards) + // and the remote host has already received the request packet + // => Informs the receiver of the new name + logger.debug("Will send a modification of filename due to wildcard: " + + runner.getFilename()); + session.newState(VALID); + ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", + runner.getFilename()+" "+packet.getOriginalSize(), + LocalPacketFactory.REQUESTPACKET); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + } else if (shouldInformBack) { + // File length is now known, so inform back + logger.debug("Will send a modification of filename due to wildcard: " + + runner.getFilename()); + session.newState(VALID); + ValidPacket validPacket = new ValidPacket("Change Filename by Wildcard on sender", + runner.getFilename()+" "+packet.getOriginalSize(), + LocalPacketFactory.REQUESTPACKET); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + } + session.setReady(true); + Configuration.configuration.getLocalTransaction().setFromId(runner, localChannelReference); + // inform back + if (packet.isToValidate()) { + if (Configuration.configuration.monitoring != null) { + Configuration.configuration.monitoring.lastInActiveTransfer = + System.currentTimeMillis(); + } + if (runner.isSender()) { + // In case Wildcard was used + logger.debug("New FILENAME: {}", runner.getOriginalFilename()); + packet.setFilename(runner.getOriginalFilename()); + logger.debug("Rank set: " + runner.getRank()); + packet.setRank(runner.getRank()); + } else { + logger.debug("Rank set: " + runner.getRank()); + packet.setRank(runner.getRank()); + } + packet.validate(); + session.newState(REQUESTD); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, true); + } else { + session.newState(REQUESTD); + // requester => might be a client + // Save the runner into the session and validate the request so begin transfer + session.getLocalChannelReference().getFutureRequest().runner = runner; + localChannelReference.getFutureValidRequest().setSuccess(); + if (Configuration.configuration.monitoring != null) { + Configuration.configuration.monitoring.lastOutActiveTransfer = + System.currentTimeMillis(); + } + } + // if retrieve => START the retrieve operation except if in Send Through mode + if (runner.isSender()) { + if (runner.isSendThrough()) { + // it is legal to send data from now + logger.debug("Now ready to continue with send through"); + localChannelReference.validateEndTransfer( + new R66Result(session, false, ErrorCode.PreProcessingOk, runner)); + } else { + // Automatically send data now + logger.debug("Now ready to continue with runRetrieve"); + NetworkTransaction.runRetrieve(session, channel); + } + } + session.setStatus(39); + } + + /** + * Receive a data + * + * @param channel + * @param packet + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66ProtocolBusinessException + * @throws OpenR66ProtocolPacketException + */ + private void data(Channel channel, DataPacket packet) + throws OpenR66ProtocolNotAuthenticatedException, + OpenR66ProtocolBusinessException, OpenR66ProtocolPacketException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Data received"); + } + if (!session.isReady()) { + throw new OpenR66ProtocolBusinessException("No request prepared"); + } + if (session.getRunner().isSender()) { + throw new OpenR66ProtocolBusinessException( + "Not in receive MODE but receive a packet"); + } + if (!session.getRunner().continueTransfer()) { + if (localChannelReference.getFutureEndTransfer().isFailed()) { + // nothing to do since already done + session.setStatus(94); + return; + } + session.newState(ERROR); + ErrorPacket error = new ErrorPacket( + "Transfer in error due previously aborted transmission", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + try { + session.setFinalizeTransfer(false, new R66Result( + new OpenR66ProtocolPacketException( + "Transfer was aborted previously"), session, true, + ErrorCode.TransferError, session.getRunner())); + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + session.setStatus(95); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + if (packet.getPacketRank() != session.getRunner().getRank()) { + // Fix the rank if possible + if (packet.getPacketRank() < session.getRunner().getRank()) { + logger.debug("Bad RANK: " + packet.getPacketRank() + " : " + + session.getRunner().getRank()); + session.getRunner().setRankAtStartup(packet.getPacketRank()); + session.getRestart().restartMarker( + session.getRunner().getBlocksize() * + session.getRunner().getRank()); + try { + session.getFile().restartMarker(session.getRestart()); + } catch (CommandAbstractException e) { + logger.error("Bad RANK: " + packet.getPacketRank() + " : " + + session.getRunner().getRank()); + session.newState(ERROR); + try { + session.setFinalizeTransfer(false, new R66Result( + new OpenR66ProtocolPacketException( + "Bad Rank in transmission even after retry: " + + packet.getPacketRank()), session, true, + ErrorCode.TransferError, session.getRunner())); + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + ErrorPacket error = new ErrorPacket( + "Transfer in error due to bad rank transmission", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + session.setStatus(96); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + } else { + // really bad + logger.error("Bad RANK: " + packet.getPacketRank() + " : " + + session.getRunner().getRank()); + session.newState(ERROR); + try { + session.setFinalizeTransfer(false, new R66Result( + new OpenR66ProtocolPacketException( + "Bad Rank in transmission: " + + packet.getPacketRank() + " > " + + session.getRunner().getRank()), session, true, + ErrorCode.TransferError, session.getRunner())); + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + ErrorPacket error = new ErrorPacket( + "Transfer in error due to bad rank transmission", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + session.setStatus(20); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + } + DataBlock dataBlock = new DataBlock(); + // if MD5 check MD5 + if (RequestPacket.isMD5Mode(session.getRunner().getMode())) { + if (!packet.isKeyValid()) { + // Wrong packet + logger.error("Wrong MD5 Packet: {}", packet); + session.newState(ERROR); + try { + session.setFinalizeTransfer(false, new R66Result( + new OpenR66ProtocolPacketException( + "Wrong Packet MD5"), session, true, + ErrorCode.MD5Error, session.getRunner())); + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + ErrorPacket error = new ErrorPacket( + "Transfer in error due to bad MD5", + ErrorCode.MD5Error.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + session.setStatus(21); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + } + if (Configuration.configuration.globalDigest) { + if (globalDigest == null) { + try { + globalDigest = new FilesystemBasedDigest(Configuration.configuration.digest); + } catch (NoSuchAlgorithmException e) { + } + } + FileUtils.computeGlobalHash(globalDigest, packet.getData()); + } + if (session.getRunner().isRecvThrough() && localChannelReference.isRecvThroughMode()) { + localChannelReference.getRecvThroughHandler().writeChannelBuffer(packet.getData()); + session.getRunner().incrementRank(); + } else { + dataBlock.setBlock(packet.getData()); + try { + session.getFile().writeDataBlock(dataBlock); + session.getRunner().incrementRank(); + } catch (FileTransferException e) { + session.newState(ERROR); + try { + session.setFinalizeTransfer(false, new R66Result( + new OpenR66ProtocolSystemException(e), session, true, + ErrorCode.TransferError, session.getRunner())); + } catch (OpenR66RunnerErrorException e1) { + } catch (OpenR66ProtocolSystemException e1) { + } + ErrorPacket error = new ErrorPacket("Transfer in error", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + session.setStatus(22); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + } + } + + /** + * Test reception + * + * @param channel + * @param packet + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66ProtocolPacketException + */ + private void test(Channel channel, TestPacket packet) + throws OpenR66ProtocolNotAuthenticatedException, + OpenR66ProtocolPacketException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Test received"); + } + // simply write back after+1 + packet.update(); + if (packet.getType() == LocalPacketFactory.VALIDPACKET) { + ValidPacket validPacket = new ValidPacket(packet.toString(), null, + LocalPacketFactory.TESTPACKET); + R66Result result = new R66Result(session, true, + ErrorCode.CompleteOk, null); + result.other = validPacket; + session.newState(VALIDOTHER); + localChannelReference.validateRequest(result); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); + logger.warn("Valid TEST MESSAGE from "+ + session.getAuth().getUser()+ + " ["+localChannelReference.getNetworkChannel().getRemoteAddress()+ + "] Msg=" +packet.toString()); + ChannelCloseTimer.closeFutureChannel(channel); + } else { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); + } + } + + /** + * Receive an End of Transfer + * + * @param channel + * @param packet + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + * @throws OpenR66ProtocolNotAuthenticatedException + */ + private void endTransfer(Channel channel, EndTransferPacket packet) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException, + OpenR66ProtocolNotAuthenticatedException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while EndTransfer received"); + } + // Check end of transfer + long originalSize = session.getRunner().getOriginalSize(); + logger.debug("OSize: "+originalSize+" isSender: "+session.getRunner().isSender()); + if (packet.isToValidate()) { + // check if possible originalSize + if (originalSize >= 0) { + try { + if (!session.getRunner().isRecvThrough() && session.getFile().length() != originalSize) { + R66Result result = new R66Result(new OpenR66RunnerErrorException("Final size in error, transfer in error and rank should be reset to 0"), + session, false, ErrorCode.TransferError, session.getRunner()); + localChannelReference.invalidateRequest(result); + throw (OpenR66RunnerErrorException) result.exception; + } + } catch (CommandAbstractException e) { + // ignore + } + } + // check if possible Global Digest + String hash = packet.getOptional(); + if (hash != null && globalDigest != null) { + String localhash = FilesystemBasedDigest.getHex(globalDigest.Final()); + globalDigest = null; + if (! localhash.equalsIgnoreCase(hash)) { + // bad global Hash + //session.getRunner().setRankAtStartup(0); + R66Result result = new R66Result(new OpenR66RunnerErrorException("Global Hash in error, transfer in error and rank should be reset to 0"), + session, false, ErrorCode.MD5Error, session.getRunner()); + localChannelReference.invalidateRequest(result); + throw (OpenR66RunnerErrorException) result.exception; + } else { + localChannelReference.setHashComputeDuringTransfer(localhash); + logger.debug("Global digest ok"); + } + } else if (globalDigest != null) { + String localhash = FilesystemBasedDigest.getHex(globalDigest.Final()); + globalDigest = null; + localChannelReference.setHashComputeDuringTransfer(localhash); + } + globalDigest = null; + session.newState(ENDTRANSFERS); + if (!localChannelReference.getFutureRequest().isDone()) { + // Finish with post Operation + R66Result result = new R66Result(session, false, + ErrorCode.TransferOk, session.getRunner()); + session.newState(ENDTRANSFERR); + session.setFinalizeTransfer(true, result); + // Now can send validation + packet.validate(); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + packet, false); + } catch (OpenR66ProtocolPacketException e) { + // ignore + } + } else { + // in error due to a previous status (like bad MD5) + logger + .error("Error since end of transfer signaled but already done"); + session.setStatus(23); + Channels.close(channel); + return; + } + } else { + session.newState(ENDTRANSFERR); + if (!localChannelReference.getFutureRequest().isDone()) { + // Validation of end of transfer + R66Result result = new R66Result(session, false, + ErrorCode.TransferOk, session.getRunner()); + session.setFinalizeTransfer(true, result); + } + } + } + + /** + * Receive a request of information + * + * @param channel + * @param packet + * @throws CommandAbstractException + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66ProtocolNoDataException + * @throws OpenR66ProtocolPacketException + */ + private void information(Channel channel, InformationPacket packet) + throws OpenR66ProtocolNotAuthenticatedException, + OpenR66ProtocolNoDataException, OpenR66ProtocolPacketException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Information received"); + } + byte request = packet.getRequest(); + DbRule rule; + try { + rule = new DbRule(localChannelReference.getDbSession(), packet.getRulename()); + } catch (WaarpDatabaseException e) { + logger.error("Rule is unknown: " + packet.getRulename(), e); + throw new OpenR66ProtocolNoDataException(e); + } + try { + if (RequestPacket.isRecvMode(rule.mode)) { + session.getDir().changeDirectory(rule.workPath); + } else { + session.getDir().changeDirectory(rule.sendPath); + } + + if (request == InformationPacket.ASKENUM.ASKLIST.ordinal() || + request == InformationPacket.ASKENUM.ASKMLSLIST.ordinal()) { + // ls or mls from current directory + List list; + if (request == InformationPacket.ASKENUM.ASKLIST.ordinal()) { + list = session.getDir().list(packet.getFilename()); + } else { + list = session.getDir().listFull(packet.getFilename(), false); + } + + StringBuilder builder = new StringBuilder(); + for (String elt : list) { + builder.append(elt); + builder.append('\n'); + } + session.newState(VALIDOTHER); + ValidPacket validPacket = new ValidPacket(builder.toString(), "" + list.size(), + LocalPacketFactory.INFORMATIONPACKET); + R66Result result = new R66Result(session, true, + ErrorCode.CompleteOk, null); + result.other = validPacket; + localChannelReference.validateEndTransfer(result); + localChannelReference.validateRequest(result); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + Channels.close(channel); + } else { + // ls pr mls from current directory and filename + R66File file = (R66File) session.getDir().setFile(packet.getFilename(), false); + String sresult = null; + if (request == InformationPacket.ASKENUM.ASKEXIST.ordinal()) { + sresult = "" + file.exists(); + } else if (request == InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal()) { + sresult = session.getDir().fileFull(packet.getFilename(), false); + String[] list = sresult.split("\n"); + sresult = list[1]; + } else { + session.newState(ERROR); + ErrorPacket error = new ErrorPacket("Unknown Request " + request, + ErrorCode.Warning.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + session.newState(VALIDOTHER); + ValidPacket validPacket = new ValidPacket(sresult, "1", + LocalPacketFactory.INFORMATIONPACKET); + R66Result result = new R66Result(session, true, + ErrorCode.CompleteOk, null); + result.other = validPacket; + localChannelReference.validateEndTransfer(result); + localChannelReference.validateRequest(result); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + ChannelCloseTimer.closeFutureChannel(channel); + } + } catch (CommandAbstractException e) { + session.newState(ERROR); + ErrorPacket error = new ErrorPacket("Error while Request " + request + " " + + e.getMessage(), + ErrorCode.Internal.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + ChannelCloseTimer.closeFutureChannel(channel); + } + } + + /** + * Stop or Cancel a Runner + * + * @param id + * @param reqd + * @param reqr + * @param code + * @return True if correctly stopped or canceled + */ + private boolean stopOrCancelRunner(long id, String reqd, String reqr, ErrorCode code) { + try { + DbTaskRunner taskRunner = + new DbTaskRunner(localChannelReference.getDbSession(), session, + null, id, reqr, reqd); + return taskRunner.stopOrCancelRunner(code); + } catch (WaarpDatabaseException e) { + } + return false; + } + + /** + * Receive a validation or a special request + * + * @param channel + * @param packet + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + * @throws OpenR66ProtocolBusinessException + */ + private void valid(Channel channel, ValidPacket packet) + throws OpenR66ProtocolNotAuthenticatedException, + OpenR66RunnerErrorException, OpenR66ProtocolSystemException, + OpenR66ProtocolBusinessException { + if (packet.getTypeValid() != LocalPacketFactory.SHUTDOWNPACKET && + (!session.isAuthenticated())) { + logger.warn("Valid packet received while not authenticated: {} {}", packet, session); + session.newState(ERROR); + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Valid received"); + } + switch (packet.getTypeValid()) { + case LocalPacketFactory.SHUTDOWNPACKET: { + session.newState(SHUTDOWN); + logger.warn("Shutdown received so Will close channel" + + localChannelReference.toString()); + R66Result result = new R66Result( + new OpenR66ProtocolShutdownException(), session, true, + ErrorCode.Shutdown, session.getRunner()); + result.other = packet; + if (session.getRunner() != null && + session.getRunner().isInTransfer()) { + String srank = packet.getSmiddle(); + DbTaskRunner runner = session.getRunner(); + if (srank != null && srank.length() > 0) { + // Save last rank from remote point of view + try { + int rank = Integer.parseInt(srank); + runner.setRankAtStartup(rank); + } catch (NumberFormatException e) { + // ignore + } + session.setFinalizeTransfer(false, result); + } else if (!runner.isSender()) { + // is receiver so informs back for the rank to use next time + int newrank = runner.getRank(); + packet.setSmiddle(Integer.toString(newrank)); + try { + runner.saveStatus(); + } catch (OpenR66RunnerErrorException e) { + } + session.setFinalizeTransfer(false, result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, + true); + } catch (OpenR66ProtocolPacketException e) { + } + } else { + session.setFinalizeTransfer(false, result); + } + } else { + session.setFinalizeTransfer(false, result); + } + session.setStatus(26); + try { + Thread.sleep(Configuration.WAITFORNETOP * 2); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + logger.warn("Will Close Local from Network Channel"); + Configuration.configuration.getLocalTransaction() + .closeLocalChannelsFromNetworkChannel(localChannelReference + .getNetworkChannel()); + NetworkTransaction + .shuttingdownNetworkChannel(localChannelReference + .getNetworkChannel()); + ChannelCloseTimer.closeFutureChannel(channel); + break; + } + case LocalPacketFactory.STOPPACKET: + case LocalPacketFactory.CANCELPACKET: { + session.newState(VALIDOTHER); + // Authentication must be the local server + try { + if (!session.getAuth().getUser().equals( + Configuration.configuration.getHostId(session.getAuth().isSsl()))) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not correctly authenticated"); + } + } catch (OpenR66ProtocolNoSslException e1) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not correctly authenticated since SSL is not supported", e1); + } + // header = ?; middle = requested+blank+requester+blank+specialId + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(packet.getSmiddle()); + // stop the current transfer + R66Result resulttest; + ErrorCode code = (packet.getTypeValid() == LocalPacketFactory.STOPPACKET) ? + ErrorCode.StoppedTransfer : ErrorCode.CanceledTransfer; + if (lcr != null) { + int rank = 0; + if (code == ErrorCode.StoppedTransfer && lcr.getSession() != null) { + DbTaskRunner taskRunner = lcr.getSession().getRunner(); + if (taskRunner != null) { + rank = taskRunner.getRank(); + } + } + session.newState(ERROR); + ErrorPacket error = new ErrorPacket(code.name() + " " + rank, + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + // XXX ChannelUtils.writeAbstractLocalPacket(lcr, error); + // inform local instead of remote + ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); + } catch (Exception e) { + } + resulttest = new R66Result(session, true, + ErrorCode.CompleteOk, session.getRunner()); + } else { + // Transfer is not running + // but maybe need action on database + String[] keys = packet.getSmiddle().split(" "); + long id = Long.parseLong(keys[2]); + if (stopOrCancelRunner(id, keys[0], keys[1], code)) { + resulttest = new R66Result(session, true, + ErrorCode.CompleteOk, session.getRunner()); + } else { + resulttest = new R66Result(session, true, + ErrorCode.TransferOk, session.getRunner()); + } + } + // inform back the requester + ValidPacket valid = new ValidPacket(packet.getSmiddle(), resulttest.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + resulttest.other = packet; + localChannelReference.validateRequest(resulttest); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + session.setStatus(27); + Channels.close(channel); + break; + } + case LocalPacketFactory.REQUESTUSERPACKET: { + session.newState(VALIDOTHER); + // Validate user request + R66Result resulttest = new R66Result(session, true, + ErrorCode.getFromCode(packet.getSmiddle()), null); + resulttest.other = packet; + switch (resulttest.code) { + case CompleteOk: + case InitOk: + case PostProcessingOk: + case PreProcessingOk: + case QueryAlreadyFinished: + case QueryStillRunning: + case Running: + case TransferOk: + break; + default: + localChannelReference.invalidateRequest(resulttest); + session.setStatus(102); + Channels.close(channel); + return; + } + localChannelReference.validateRequest(resulttest); + session.setStatus(28); + Channels.close(channel); + break; + } + case LocalPacketFactory.LOGPACKET: + case LocalPacketFactory.LOGPURGEPACKET: { + session.newState(VALIDOTHER); + // should be from the local server or from an authorized hosts: LOGCONTROL + if (!session.getAuth().isValidRole(ROLE.LOGCONTROL)) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not correctly authenticated"); + } + String sstart = packet.getSheader(); + String sstop = packet.getSmiddle(); + boolean isPurge = (packet.getTypeValid() == LocalPacketFactory.LOGPURGEPACKET) ? + true : false; + Timestamp start = (sstart == null || sstart.length() == 0) ? null : + Timestamp.valueOf(sstart); + Timestamp stop = (sstop == null || sstop.length() == 0) ? null : + Timestamp.valueOf(sstop); + // create export of log and optionally purge them from database + DbPreparedStatement getValid = null; + String filename = Configuration.configuration.baseDirectory + + Configuration.configuration.archivePath + R66Dir.SEPARATOR + + Configuration.configuration.HOST_ID + "_" + System.currentTimeMillis() + + "_runners.xml"; + try { + getValid = + DbTaskRunner.getLogPrepareStatement( + localChannelReference.getDbSession(), + start, stop); + DbTaskRunner.writeXMLWriter(getValid, filename); + } catch (WaarpDatabaseNoConnectionException e1) { + throw new OpenR66ProtocolBusinessException(e1); + } catch (WaarpDatabaseSqlException e1) { + throw new OpenR66ProtocolBusinessException(e1); + } finally { + if (getValid != null) { + getValid.realClose(); + } + } + // in case of purge + int nb = 0; + if (isPurge) { + // purge in same interval all runners with globallaststep + // as ALLDONETASK or ERRORTASK + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "Purge Log Order received", session.getAuth().getUser()); + } + try { + nb = DbTaskRunner.purgeLogPrepareStatement( + localChannelReference.getDbSession(), + start, stop); + } catch (WaarpDatabaseNoConnectionException e) { + throw new OpenR66ProtocolBusinessException(e); + } catch (WaarpDatabaseSqlException e) { + throw new OpenR66ProtocolBusinessException(e); + } + } + R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); + // Now answer + ValidPacket valid = new ValidPacket(filename + " " + nb, result.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + localChannelReference.validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + break; + } + case LocalPacketFactory.CONFEXPORTPACKET: { + session.newState(VALIDOTHER); + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "Export Configuration Order received", session.getAuth().getUser()); + } + String shost = packet.getSheader(); + String srule = packet.getSmiddle(); + boolean bhost = Boolean.parseBoolean(shost); + boolean brule = Boolean.parseBoolean(srule); + String dir = Configuration.configuration.baseDirectory + + Configuration.configuration.archivePath; + String hostname = Configuration.configuration.HOST_ID; + if (bhost) { + String filename = dir + File.separator + hostname + "_Authentications.xml"; + try { + AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, + filename); + shost = filename; + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Error", e); + shost = "#"; + bhost = false; + } catch (WaarpDatabaseSqlException e) { + logger.error("Error", e); + shost = "#"; + bhost = false; + } catch (OpenR66ProtocolSystemException e) { + logger.error("Error", e); + shost = "#"; + bhost = false; + } + } + if (brule) { + try { + srule = RuleFileBasedConfiguration.writeOneXml(dir, hostname); + } catch (WaarpDatabaseNoConnectionException e1) { + logger.error("Error", e1); + srule = "#"; + brule = false; + } catch (WaarpDatabaseSqlException e1) { + logger.error("Error", e1); + srule = "#"; + brule = false; + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Error", e1); + srule = "#"; + brule = false; + } + } + R66Result result = null; + if (brule || bhost) { + result = new R66Result(session, true, ErrorCode.CompleteOk, null); + } else { + result = new R66Result(session, true, ErrorCode.TransferError, null); + } + // Now answer + ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + localChannelReference.validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + break; + } + case LocalPacketFactory.CONFIMPORTPACKET: { + session.newState(VALIDOTHER); + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "Import Configuration Order received", session.getAuth().getUser()); + } + String shost = packet.getSheader(); + String srule = packet.getSmiddle(); + boolean bhostPurge = shost.startsWith("1 "); + shost = shost.substring(2); + boolean brulePurge = srule.startsWith("1 "); + srule = srule.substring(2); + boolean bhost = shost.length() > 0; + boolean brule = srule.length() > 0; + if (bhost) { + DbHostAuth[] oldHosts = null; + if (bhostPurge) { + // Need to first delete all entries + try { + oldHosts = DbHostAuth.deleteAll(DbConstant.admin.session); + } catch (WaarpDatabaseException e) { + // ignore + } + } + String filename = shost; + if (AuthenticationFileBasedConfiguration.loadAuthentication( + Configuration.configuration, + filename)) { + shost = "Host:OK"; + } else { + logger.error("Error in Load Hosts"); + shost = "Host:KO"; + bhost = false; + } + if (!bhost) { + if (oldHosts != null) { + for (DbHostAuth dbHost : oldHosts) { + try { + if (!dbHost.exist()) { + dbHost.insert(); + } + } catch (WaarpDatabaseException e1) { + // ignore + } + } + } + } + } + if (brule) { + DbRule[] oldRules = null; + if (brulePurge) { + // Need to first delete all entries + try { + oldRules = DbRule.deleteAll(DbConstant.admin.session); + } catch (WaarpDatabaseException e) { + // ignore + } + } + File file = new File(srule); + try { + RuleFileBasedConfiguration.getMultipleFromFile(file); + srule = "Rule:OK"; + brule = true; + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Error", e); + srule = "Rule:KO"; + brule = false; + } catch (WaarpDatabaseSqlException e) { + logger.error("Error", e); + srule = "Rule:KO"; + brule = false; + } catch (WaarpDatabaseNoDataException e) { + logger.error("Error", e); + srule = "Rule:KO"; + brule = false; + } catch (WaarpDatabaseException e) { + logger.error("Error", e); + srule = "Rule:KO"; + brule = false; + } + if (!brule) { + if (oldRules != null) { + for (DbRule dbRule : oldRules) { + try { + if (!dbRule.exist()) { + dbRule.insert(); + } + } catch (WaarpDatabaseException e1) { + // ignore + } + } + } + } + } + R66Result result = null; + if (brule || bhost) { + result = new R66Result(session, true, ErrorCode.CompleteOk, null); + } else { + result = new R66Result(session, true, ErrorCode.TransferError, null); + } + // Now answer + ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + localChannelReference.validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + break; + } + case LocalPacketFactory.INFORMATIONPACKET: { + session.newState(VALIDOTHER); + // Validate user request + R66Result resulttest = new R66Result(session, true, + ErrorCode.CompleteOk, null); + resulttest.other = packet; + localChannelReference.validateRequest(resulttest); + Channels.close(channel); + break; + } + case LocalPacketFactory.VALIDPACKET: { + session.newState(VALIDOTHER); + // Try to validate a restarting transfer + // XXX validLimit on requested side + if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { + logger.error("Limit exceeded while asking to relaunch a task" + + packet.getSmiddle()); + session.setStatus(100); + ValidPacket valid; + valid = new ValidPacket(packet.getSmiddle(), + ErrorCode.ServerOverloaded.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + R66Result resulttest = new R66Result(null, session, true, + ErrorCode.Internal, null); + resulttest.other = packet; + localChannelReference.invalidateRequest(resulttest); + // inform back the requester + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + return; + } + // Try to validate a restarting transfer + // header = ?; middle = requested+blank+requester+blank+specialId + // note: might contains one more argument = time to reschedule in yyyyMMddHHmmss format + String[] keys = packet.getSmiddle().split(" "); + ValidPacket valid; + if (keys.length < 3) { + // not enough args + valid = new ValidPacket(packet.getSmiddle(), + ErrorCode.Internal.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + R66Result resulttest = new R66Result( + new OpenR66ProtocolBusinessRemoteFileNotFoundException("Not enough arguments"), + session, true, + ErrorCode.Internal, null); + resulttest.other = packet; + localChannelReference.invalidateRequest(resulttest); + } else { + long id = Long.parseLong(keys[2]); + DbTaskRunner taskRunner = null; + try { + taskRunner = new DbTaskRunner(localChannelReference.getDbSession(), session, + null, id, keys[1], keys[0]); + Timestamp timestart = null; + if (keys.length > 3) { + // time to reschedule in yyyyMMddHHmmss format + logger.debug("Debug: restart with "+keys[3]); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + try { + Date date = dateFormat.parse(keys[3]); + timestart = new Timestamp(date.getTime()); + taskRunner.setStart(timestart); + } catch (ParseException e) { + } + } + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(packet.getSmiddle()); + R66Result resulttest = TransferUtils.restartTransfer(taskRunner, lcr); + valid = new ValidPacket(packet.getSmiddle(), resulttest.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + resulttest.other = packet; + localChannelReference.validateRequest(resulttest); + } catch (WaarpDatabaseException e1) { + valid = new ValidPacket(packet.getSmiddle(), + ErrorCode.Internal.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + R66Result resulttest = new R66Result(new OpenR66DatabaseGlobalException(e1), + session, true, + ErrorCode.Internal, taskRunner); + resulttest.other = packet; + localChannelReference.invalidateRequest(resulttest); + } + } + // inform back the requester + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + break; + } + case LocalPacketFactory.REQUESTPACKET: { + session.newState(VALID); + // The filename from sender is changed due to PreTask so change it too in receiver + String [] fields = packet.getSmiddle().split(" "); + String newfilename = fields[0]; + for (int i = 1; i < fields.length-1; i++) { + newfilename += " "+fields[i]; + } + // potential file size changed + long newSize = -1; + if (fields.length > 1) { + try { + newSize = Long.parseLong(fields[fields.length-1]); + if (session.getRunner() != null) { + session.getRunner().setOriginalSize(newSize); + } + } catch (NumberFormatException e) { + newfilename += " " + fields[fields.length-1]; + } + } + // Pre execution was already done since this packet is only received once + // the request is already validated by the receiver + try { + session.renameReceiverFile(newfilename); + } catch (OpenR66RunnerErrorException e) { + DbTaskRunner runner = session.getRunner(); + runner.saveStatus(); + runner.setErrorExecutionStatus(ErrorCode.FileNotFound); + session.newState(ERROR); + logger.error("File renaming in error {}", e.getMessage()); + ErrorPacket error = new ErrorPacket("File renaming in error: " + e + .getMessage(), runner.getErrorInfo().getCode(), + ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + error, true); + } catch (OpenR66ProtocolPacketException e2) { + } + try { + session.setFinalizeTransfer(false, new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } catch (OpenR66RunnerErrorException e1) { + localChannelReference.invalidateRequest(new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } catch (OpenR66ProtocolSystemException e1) { + localChannelReference.invalidateRequest(new R66Result(e, session, + true, runner.getErrorInfo(), runner)); + } + session.setStatus(97); + ChannelCloseTimer.closeFutureChannel(channel); + return; + } + // Success: No write back at all + break; + } + case LocalPacketFactory.BANDWIDTHPACKET: { + session.newState(VALIDOTHER); + // should be from the local server or from an authorized hosts: LIMIT + if (!session.getAuth().isValidRole(ROLE.LIMIT)) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not correctly authenticated"); + } + String[] splitglobal = packet.getSheader().split(" "); + String[] splitsession = packet.getSmiddle().split(" "); + if (splitglobal.length < 2 || splitsession.length < 2) { + // request of current values + R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); + // Now answer + ValidPacket valid = new ValidPacket(Configuration.configuration.serverGlobalWriteLimit + +" "+Configuration.configuration.serverGlobalReadLimit+ + " "+Configuration.configuration.serverChannelWriteLimit+ + " "+Configuration.configuration.serverChannelReadLimit, result.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + localChannelReference.validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + return; + } + long wgl = (Long.parseLong(splitglobal[0]) / 10) * 10; + long rgl = (Long.parseLong(splitglobal[1]) / 10) * 10; + long wsl = (Long.parseLong(splitsession[0]) / 10) * 10; + long rsl = (Long.parseLong(splitsession[1]) / 10) * 10; + if (wgl < 0) { + wgl = Configuration.configuration.serverGlobalWriteLimit; + } + if (rgl < 0) { + rgl = Configuration.configuration.serverGlobalReadLimit; + } + if (wsl < 0) { + wsl = Configuration.configuration.serverChannelWriteLimit; + } + if (rsl < 0) { + rsl = Configuration.configuration.serverChannelReadLimit; + } + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "Change Bandwidth Limit Order received: Global " + + wgl + ":" + rgl + " (W:R) Local " + wsl + ":" + rsl + " (W:R)", + session.getAuth().getUser()); + } + Configuration.configuration.changeNetworkLimit(wgl, rgl, wsl, rsl, + Configuration.configuration.delayLimit); + R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); + // Now answer + ValidPacket valid = new ValidPacket("Bandwidth changed", result.code.getCode(), + LocalPacketFactory.REQUESTUSERPACKET); + localChannelReference.validateRequest(result); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + valid, true); + } catch (OpenR66ProtocolPacketException e) { + } + Channels.close(channel); + break; + } + case LocalPacketFactory.TESTPACKET: { + session.newState(VALIDOTHER); + logger.info("Valid TEST MESSAGE: " + packet.toString()); + R66Result resulttest = new R66Result(session, true, + ErrorCode.CompleteOk, null); + resulttest.other = packet; + localChannelReference.validateRequest(resulttest); + Channels.close(channel); + break; + } + default: + logger.info("Validation is ignored: " + packet.getTypeValid()); + } + } + + /** + * Receive an End of Request + * + * @param channel + * @param packet + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + * @throws OpenR66ProtocolNotAuthenticatedException + */ + private void endRequest(Channel channel, EndRequestPacket packet) { + // Validate the last post action on a transfer from receiver remote host + logger.info("Valid Request {}\nPacket {}", + localChannelReference, + packet); + DbTaskRunner runner = session.getRunner(); + logger.debug("Runner endRequest: " + (session.getRunner() != null)); + if (runner != null) { + runner.setAllDone(); + try { + runner.saveStatus(); + } catch (OpenR66RunnerErrorException e) { + // ignore + } + } + String optional = null; + if (session.getExtendedProtocol()) { + optional = packet.getOptional(); + } + if (!localChannelReference.getFutureRequest().isDone()) { + // end of request + R66Future transfer = localChannelReference.getFutureEndTransfer(); + try { + transfer.await(); + } catch (InterruptedException e) { + } + if (transfer.isSuccess()) { + if (session.getExtendedProtocol() && session.getBusinessObject() != null) { + if (session.getBusinessObject().getInfo() == null) { + session.getBusinessObject().setInfo(optional); + } else { + String temp = session.getBusinessObject().getInfo(); + session.getBusinessObject().setInfo(optional); + optional = temp; + } + } else if (session.getExtendedProtocol() && + transfer.getResult().other == null && optional != null) { + transfer.getResult().other = optional; + } + localChannelReference.validateRequest(transfer.getResult()); + } + } + session.setStatus(1); + if (packet.isToValidate()) { + session.newState(ENDREQUESTS); + packet.validate(); + if (session.getExtendedProtocol()) { + packet.setOptional(optional); + } + session.newState(ENDREQUESTR); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + packet, true); + } catch (OpenR66ProtocolPacketException e) { + } + } else { + session.newState(ENDREQUESTR); + } + if (runner != null && runner.isSelfRequested()) { + ChannelCloseTimer.closeFutureChannel(channel); + } + } + + /** + * Receive a Shutdown request + * + * @param channel + * @param packet + * @throws OpenR66ProtocolShutdownException + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66ProtocolBusinessException + */ + private void shutdown(Channel channel, ShutdownPacket packet) + throws OpenR66ProtocolShutdownException, + OpenR66ProtocolNotAuthenticatedException, + OpenR66ProtocolBusinessException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while Shutdown received"); + } + // SYSTEM authorization + boolean isAdmin = session.getAuth().isValidRole(ROLE.SYSTEM); + boolean isKeyValid = Configuration.configuration.isKeyValid(packet.getKey()); + if (isAdmin && isKeyValid) { + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyStartStop( + "Shutdown Order received effective in " + + Configuration.configuration.TIMEOUTCON + " ms", + session.getAuth().getUser()); + } + if (Configuration.configuration.shutdownConfiguration.serviceFuture != null) { + logger.warn("R66 started as a service, Windows Services might not shown it as stopped"); + } + throw new OpenR66ProtocolShutdownException("Shutdown Type received"); + } + logger.error("Invalid Shutdown command: from " + session.getAuth().getUser() + + " AdmValid: " + isAdmin + " KeyValid: " + isKeyValid); + throw new OpenR66ProtocolBusinessException("Invalid Shutdown comand"); + } + + /** + * Business Request (channel should stay open) + * + * Note: the thread called should manage all writeback informations, as well as status, channel + * closing if needed or not. + * + * @param channel + * @param packet + * @throws OpenR66ProtocolNotAuthenticatedException + * @throws OpenR66ProtocolPacketException + */ + private void businessRequest(Channel channel, BusinessRequestPacket packet) + throws OpenR66ProtocolNotAuthenticatedException, + OpenR66ProtocolPacketException { + if (!session.isAuthenticated()) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not authenticated while BusinessRequest received"); + } + if (!Configuration.configuration.businessWhiteSet.contains(session.getAuth().getUser())) { + throw new OpenR66ProtocolNotAuthenticatedException( + "Not allow to execute a BusinessRequest"); + } + session.setStatus(200); + String argRule = packet.getSheader(); + int delay = packet.getDelay(); + boolean argTransfer = packet.isToValidate(); + if (argTransfer) { + session.newState(BUSINESSD); + } + ExecJavaTask task = new ExecJavaTask(argRule + " " + + AbstractBusinessRequest.BUSINESSREQUEST + " " + argTransfer, + delay, null, session); + task.run(); + session.setStatus(201); + if (task.isSuccess()) { + session.setStatus(202); + logger.info("Task done: " + argRule); + } else { + R66Result result = task.getFutureCompletion().getResult(); + if (result == null) { + result = new R66Result(session, false, ErrorCode.ExternalOp, session.getRunner()); + } + logger.info("Task in Error:" + argRule + "\n" + result); + if (!result.isAnswered) { + packet.invalidate(); + session.newState(ERROR); + ErrorPacket error = new ErrorPacket( + "BusinessRequest in error: for " + packet.toString() + " since " + + result.getMessage(), + result.code.getCode(), ErrorPacket.FORWARDCLOSECODE); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + session.setStatus(203); + } + session.setStatus(204); + } + } + + /** + * Try to finalize the request if possible + * + * @param errorValue + * in case of Error + * @throws OpenR66ProtocolSystemException + * @throws OpenR66RunnerErrorException + */ + private void tryFinalizeRequest(R66Result errorValue) + throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException { + session.tryFinalizeRequest(errorValue); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerPipelineFactory.java index e59c0edbf..22c087d36 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalServerPipelineFactory.java @@ -1,44 +1,44 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; - -/** - * Pipeline Factory for Local Server - * - * @author Frederic Bregier - */ -public class LocalServerPipelineFactory implements ChannelPipelineFactory { - - public ChannelPipeline getPipeline() throws Exception { - final ChannelPipeline pipeline = Channels.pipeline(); - pipeline.addLast("codec", new LocalPacketCodec()); - ExecutionHandler handler = new ExecutionHandler( - Configuration.configuration.getLocalPipelineExecutor()); - pipeline.addLast("pipelineExecutor", handler); - pipeline.addLast("handler", new LocalServerHandler()); - return pipeline; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; + +/** + * Pipeline Factory for Local Server + * + * @author Frederic Bregier + */ +public class LocalServerPipelineFactory implements ChannelPipelineFactory { + + public ChannelPipeline getPipeline() throws Exception { + final ChannelPipeline pipeline = Channels.pipeline(); + pipeline.addLast("codec", new LocalPacketCodec()); + ExecutionHandler handler = new ExecutionHandler( + Configuration.configuration.getLocalPipelineExecutor()); + pipeline.addLast("pipelineExecutor", handler); + pipeline.addLast("handler", new LocalServerHandler()); + return pipeline; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java index b055bbc59..0db51f0a1 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java @@ -1,528 +1,528 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp. If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import java.util.Collection; -import java.util.Iterator; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.jboss.netty.bootstrap.ClientBootstrap; -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelFutureListener; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.group.ChannelGroup; -import org.jboss.netty.channel.group.DefaultChannelGroup; -import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; -import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; -import org.jboss.netty.channel.local.LocalAddress; -import org.jboss.netty.util.Timeout; -import org.jboss.netty.util.TimerTask; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.StartupPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * This class handles Local Transaction connections - * - * @author frederic bregier - */ -public class LocalTransaction { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(LocalTransaction.class); - - /** - * HashMap of LocalChannelReference using LocalChannelId - */ - final ConcurrentHashMap localChannelHashMap = new ConcurrentHashMap(); - - /** - * HashMap of Validation of LocalChannelReference using LocalChannelId - */ - final ConcurrentHashMap validLocalChannelHashMap = new ConcurrentHashMap(); - - /** - * HashMap of LocalChannelReference using requested_requester_specialId - */ - final ConcurrentHashMap localChannelHashMapExternal = new ConcurrentHashMap(); - - /** - * Remover from HashMap - */ - private final ChannelFutureListener remover = new ChannelFutureListener() { - public void operationComplete( - ChannelFuture future) { - remove(future - .getChannel()); - } - }; - - private final ChannelFactory channelServerFactory = new DefaultLocalServerChannelFactory(); - - private final ServerBootstrap serverBootstrap = new ServerBootstrap( - channelServerFactory); - - private final Channel serverChannel; - - private final LocalAddress socketLocalServerAddress = new LocalAddress( - "0"); - - private final ChannelFactory channelClientFactory = new DefaultLocalClientChannelFactory(); - - private final ClientBootstrap clientBootstrap = new ClientBootstrap( - channelClientFactory); - - private final ChannelGroup localChannelGroup = new DefaultChannelGroup( - "LocalChannels"); - - /** - * Constructor - */ - public LocalTransaction() { - serverBootstrap.setPipelineFactory(new LocalServerPipelineFactory()); - serverBootstrap.setOption("connectTimeoutMillis", - Configuration.configuration.TIMEOUTCON); - serverChannel = serverBootstrap.bind(socketLocalServerAddress); - localChannelGroup.add(serverChannel); - clientBootstrap.setPipelineFactory(new LocalClientPipelineFactory()); - } - - /** - * Get the corresponding LocalChannelReference - * - * @param remoteId - * @param localId - * @return the LocalChannelReference - * @throws OpenR66ProtocolSystemException - */ - public LocalChannelReference getClient(Integer remoteId, Integer localId) - throws OpenR66ProtocolSystemException { - LocalChannelReference localChannelReference = getFromId(localId); - if (localChannelReference != null) { - if (localChannelReference.getRemoteId() != remoteId) { - localChannelReference.setRemoteId(remoteId); - } - return localChannelReference; - } - throw new OpenR66ProtocolSystemException( - "Cannot find LocalChannelReference"); - } - - /** - * Create a new Client - * - * @param networkChannel - * @param remoteId - * @param futureRequest - * @return the LocalChannelReference - * @throws OpenR66ProtocolSystemException - */ - public LocalChannelReference createNewClient(Channel networkChannel, - Integer remoteId, R66Future futureRequest) - throws OpenR66ProtocolSystemException { - ChannelFuture channelFuture = null; - logger.debug("Status LocalChannelServer: {} {}", serverChannel - .getClass().getName(), serverChannel.getConfig() - .getConnectTimeoutMillis() + " " + serverChannel.isBound()); - R66Future validLCR = new R66Future(true); - validLocalChannelHashMap.put(remoteId, validLCR); - for (int i = 0; i < Configuration.RETRYNB; i++) { - channelFuture = clientBootstrap.connect(socketLocalServerAddress); - try { - channelFuture.await(); - } catch (InterruptedException e1) { - validLCR.cancel(); - validLocalChannelHashMap.remove(remoteId); - logger.error("LocalChannelServer Interrupted: " + - serverChannel.getClass().getName() + " " + - serverChannel.getConfig().getConnectTimeoutMillis() + - " " + serverChannel.isBound()); - throw new OpenR66ProtocolSystemException( - "Interruption - Cannot connect to local handler: " + - socketLocalServerAddress + " " + - serverChannel.isBound() + " " + serverChannel, - e1); - } - if (channelFuture.isSuccess()) { - final Channel channel = channelFuture.getChannel(); - localChannelGroup.add(channel); - final LocalChannelReference localChannelReference = new LocalChannelReference( - channel, networkChannel, remoteId, futureRequest); - logger.debug("Create LocalChannel entry: " + i + " {}", - localChannelReference); - channel.getCloseFuture().addListener(remover); - localChannelHashMap.put(channel.getId(), localChannelReference); - try { - NetworkTransaction.addLocalChannelToNetworkChannel( - networkChannel, channel); - } catch (OpenR66ProtocolRemoteShutdownException e) { - validLCR.cancel(); - validLocalChannelHashMap.remove(remoteId); - Channels.close(channel); - throw new OpenR66ProtocolSystemException( - "Cannot connect to local handler", e); - } - // Now send first a Startup message - StartupPacket startup = new StartupPacket( - localChannelReference.getLocalId()); - try { - Channels.write(channel, startup).await(); - } catch (InterruptedException e) { - logger.error("Can't connect to local server due to interruption" + i); - validLCR.cancel(); - validLocalChannelHashMap.remove(remoteId); - throw new OpenR66ProtocolSystemException( - "Cannot connect to local handler", e); - } - validLCR.setSuccess(); - return localChannelReference; - } else { - logger.error("Can't connect to local server " + i); - } - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - validLCR.cancel(); - validLocalChannelHashMap.remove(remoteId); - throw new OpenR66ProtocolSystemException( - "Cannot connect to local handler", e); - } - } - validLCR.cancel(); - validLocalChannelHashMap.remove(remoteId); - logger.error("LocalChannelServer: " + - serverChannel.getClass().getName() + " " + - serverChannel.getConfig().getConnectTimeoutMillis() + " " + - serverChannel.isBound()); - throw new OpenR66ProtocolSystemException( - "Cannot connect to local handler: " + socketLocalServerAddress + - " " + serverChannel.isBound() + " " + serverChannel, - channelFuture.getCause()); - } - - /** - * - * @param id - * @return the LocalChannelReference - */ - public LocalChannelReference getFromId(Integer id) { - for (int i = 0; i < Configuration.RETRYNB * 4; i++) { - LocalChannelReference lcr = localChannelHashMap.get(id); - if (lcr == null) { - /* - * R66Future future = validLocalChannelHashMap.get(id); - * logger.debug("DEBUG Future ValidLocalChannel: not found: " + id + (future != - * null)); if (future != null) { try { - * future.await(Configuration.configuration.TIMEOUTCON); } catch - * (InterruptedException e) { return localChannelHashMap.get(id); } - * logger.debug("DEBUG Future ValidLocalChannel: " + id + future.isDone() + ":" + - * future.isSuccess()); if (future.isSuccess()) { return - * localChannelHashMap.get(id); } else if (future.isFailed()) { return null; } } - * else { logger.debug("DEBUG Future ValidLocalChannel: Sleep" + id); try { - * Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e) { } - * continue; } - */ - try { - Thread.sleep(Configuration.RETRYINMS * 2); - } catch (InterruptedException e) { - } - } else { - return lcr; - } - } - return localChannelHashMap.get(id); - } - - /** - * Remove one local channel - * - * @param channel - */ - public void remove(Channel channel) { - LocalChannelReference localChannelReference = localChannelHashMap - .remove(channel.getId()); - if (localChannelReference != null) { - logger.debug("Remove LocalChannel"); - R66Future validLCR = validLocalChannelHashMap - .remove(localChannelReference.getRemoteId()); - if (validLCR != null) { - validLCR.cancel(); - } - DbTaskRunner runner = null; - if (localChannelReference.getSession() != null) { - runner = localChannelReference.getSession().getRunner(); - } - R66Result result = new R66Result( - new OpenR66ProtocolSystemException( - "While closing Local Channel"), - localChannelReference.getSession(), false, - ErrorCode.ConnectionImpossible, runner); - localChannelReference.validateConnection(false, result); - if (localChannelReference.getSession() != null) { - if (runner != null) { - String key = runner.getKey(); - localChannelHashMapExternal.remove(key); - } - } - } - } - - /** - * - * @param runner - * @param lcr - */ - public void setFromId(DbTaskRunner runner, LocalChannelReference lcr) { - String key = runner.getKey(); - localChannelHashMapExternal.put(key, lcr); - } - - /** - * - * @param key - * as "requested requester specialId" - * @return the LocalChannelReference - */ - public LocalChannelReference getFromRequest(String key) { - return localChannelHashMapExternal.get(key); - } - - /** - * - * @return the number of active local channels - */ - public int getNumberLocalChannel() { - return localChannelHashMap.size(); - } - - private static class CloseLocalChannelsFromNetworkChannelTast implements TimerTask { - - LocalTransaction localTransaction; - AtomicInteger semaphore; - LocalChannelReference localChannelReference; - boolean analysis; - - public CloseLocalChannelsFromNetworkChannelTast( - LocalTransaction localTransaction, - AtomicInteger semaphore, - LocalChannelReference localChannelReference) { - this.localTransaction = localTransaction; - this.semaphore = semaphore; - this.localChannelReference = localChannelReference; - analysis = true; - } - - public void run(Timeout timeout) { - // give a chance for the LocalChannel to stop normally - if (analysis) { - boolean wait = false; - if (!localChannelReference.getFutureRequest().isDone()) { - if (localChannelReference.getFutureValidRequest().isDone() && - localChannelReference.getFutureValidRequest() - .isFailed()) { - logger.debug("Already currently on finalize"); - wait = true; - } else { - R66Result finalValue = new R66Result( - localChannelReference.getSession(), true, - ErrorCode.Shutdown, null); - if (localChannelReference.getSession() != null) { - try { - localChannelReference.getSession() - .tryFinalizeRequest(finalValue); - } catch (OpenR66RunnerErrorException e) { - } catch (OpenR66ProtocolSystemException e) { - } - } - } - } - if (wait) { - this.analysis = false; - Configuration.configuration.getTimerClose().newTimeout(this, - Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS); - return; - } - } - logger.debug("Will close local channel"); - try { - Channels.close(localChannelReference.getLocalChannel()).await(); - } catch (InterruptedException e) { - } - localTransaction.remove(localChannelReference.getLocalChannel()); - semaphore.decrementAndGet(); - } - - } - - /** - * Close all Local Channels from the NetworkChannel - * - * @param networkChannel - */ - public void closeLocalChannelsFromNetworkChannel(Channel networkChannel) { - Collection collection = localChannelHashMap - .values(); - AtomicInteger semaphore = new AtomicInteger(); - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - LocalChannelReference localChannelReference = iterator.next(); - if (localChannelReference.getNetworkChannel().compareTo( - networkChannel) == 0) { - semaphore.incrementAndGet(); - CloseLocalChannelsFromNetworkChannelTast task = - new CloseLocalChannelsFromNetworkChannelTast(this, - semaphore, localChannelReference); - Configuration.configuration.getTimerClose().newTimeout(task, - Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS); - } - } - while (true) { - if (semaphore.get() == 0) { - break; - } - try { - Thread.sleep(Configuration.RETRYINMS * 2); - } catch (InterruptedException e) { - break; - } - } - } - - /** - * Debug function (while shutdown for instance) - */ - public void debugPrintActiveLocalChannels() { - Collection collection = localChannelHashMap - .values(); - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - LocalChannelReference localChannelReference = iterator.next(); - logger.debug("Will close local channel: {}", localChannelReference); - logger.debug( - " Containing: {}", - (localChannelReference.getSession() != null ? localChannelReference - .getSession() : "no session")); - } - } - - /** - * Informs all remote client that the server is shutting down - */ - public void shutdownLocalChannels() { - Collection collection = localChannelHashMap - .values(); - Iterator iterator = collection.iterator(); - ValidPacket packet = new ValidPacket("Shutdown forced", null, - LocalPacketFactory.SHUTDOWNPACKET); - ChannelBuffer buffer = null; - while (iterator.hasNext()) { - LocalChannelReference localChannelReference = iterator.next(); - logger.debug("Inform Shutdown {}", localChannelReference); - packet.setSmiddle(null); - // If a transfer is running, save the current rank and inform remote - // host - if (localChannelReference.getSession() != null) { - R66Session session = localChannelReference.getSession(); - DbTaskRunner runner = session.getRunner(); - if (runner != null && runner.isInTransfer()) { - if (!runner.isSender()) { - int newrank = runner.getRank(); - packet.setSmiddle(Integer.toString(newrank)); - } - // Save File status - try { - runner.saveStatus(); - } catch (OpenR66RunnerErrorException e) { - } - R66Result result = new R66Result( - new OpenR66ProtocolShutdownException(), session, - true, ErrorCode.Shutdown, runner); - result.other = packet; - try { - buffer = packet.getLocalPacket(); - } catch (OpenR66ProtocolPacketException e1) { - } - localChannelReference - .sessionNewState(R66FiniteDualStates.SHUTDOWN); - NetworkPacket message = new NetworkPacket( - localChannelReference.getLocalId(), - localChannelReference.getRemoteId(), - packet.getType(), buffer); - try { - Channels.write(localChannelReference.getNetworkChannel(), - message).await(); - } catch (InterruptedException e1) { - } - try { - session.setFinalizeTransfer(false, result); - } catch (OpenR66RunnerErrorException e) { - } catch (OpenR66ProtocolSystemException e) { - } - } - Channels.close(localChannelReference.getLocalChannel()); - continue; - } - try { - buffer = packet.getLocalPacket(); - } catch (OpenR66ProtocolPacketException e1) { - } - NetworkPacket message = new NetworkPacket( - localChannelReference.getLocalId(), - localChannelReference.getRemoteId(), packet.getType(), - buffer); - Channels.write(localChannelReference.getNetworkChannel(), message); - } - } - - /** - * Close All Local Channels - */ - public void closeAll() { - logger.debug("close All Local Channels"); - localChannelGroup.close().awaitUninterruptibly(); - clientBootstrap.releaseExternalResources(); - channelClientFactory.releaseExternalResources(); - serverBootstrap.releaseExternalResources(); - channelServerFactory.releaseExternalResources(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp. If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelFutureListener; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.group.ChannelGroup; +import org.jboss.netty.channel.group.DefaultChannelGroup; +import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; +import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; +import org.jboss.netty.channel.local.LocalAddress; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.TimerTask; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.StartupPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * This class handles Local Transaction connections + * + * @author frederic bregier + */ +public class LocalTransaction { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(LocalTransaction.class); + + /** + * HashMap of LocalChannelReference using LocalChannelId + */ + final ConcurrentHashMap localChannelHashMap = new ConcurrentHashMap(); + + /** + * HashMap of Validation of LocalChannelReference using LocalChannelId + */ + final ConcurrentHashMap validLocalChannelHashMap = new ConcurrentHashMap(); + + /** + * HashMap of LocalChannelReference using requested_requester_specialId + */ + final ConcurrentHashMap localChannelHashMapExternal = new ConcurrentHashMap(); + + /** + * Remover from HashMap + */ + private final ChannelFutureListener remover = new ChannelFutureListener() { + public void operationComplete( + ChannelFuture future) { + remove(future + .getChannel()); + } + }; + + private final ChannelFactory channelServerFactory = new DefaultLocalServerChannelFactory(); + + private final ServerBootstrap serverBootstrap = new ServerBootstrap( + channelServerFactory); + + private final Channel serverChannel; + + private final LocalAddress socketLocalServerAddress = new LocalAddress( + "0"); + + private final ChannelFactory channelClientFactory = new DefaultLocalClientChannelFactory(); + + private final ClientBootstrap clientBootstrap = new ClientBootstrap( + channelClientFactory); + + private final ChannelGroup localChannelGroup = new DefaultChannelGroup( + "LocalChannels"); + + /** + * Constructor + */ + public LocalTransaction() { + serverBootstrap.setPipelineFactory(new LocalServerPipelineFactory()); + serverBootstrap.setOption("connectTimeoutMillis", + Configuration.configuration.TIMEOUTCON); + serverChannel = serverBootstrap.bind(socketLocalServerAddress); + localChannelGroup.add(serverChannel); + clientBootstrap.setPipelineFactory(new LocalClientPipelineFactory()); + } + + /** + * Get the corresponding LocalChannelReference + * + * @param remoteId + * @param localId + * @return the LocalChannelReference + * @throws OpenR66ProtocolSystemException + */ + public LocalChannelReference getClient(Integer remoteId, Integer localId) + throws OpenR66ProtocolSystemException { + LocalChannelReference localChannelReference = getFromId(localId); + if (localChannelReference != null) { + if (localChannelReference.getRemoteId() != remoteId) { + localChannelReference.setRemoteId(remoteId); + } + return localChannelReference; + } + throw new OpenR66ProtocolSystemException( + "Cannot find LocalChannelReference"); + } + + /** + * Create a new Client + * + * @param networkChannel + * @param remoteId + * @param futureRequest + * @return the LocalChannelReference + * @throws OpenR66ProtocolSystemException + */ + public LocalChannelReference createNewClient(Channel networkChannel, + Integer remoteId, R66Future futureRequest) + throws OpenR66ProtocolSystemException { + ChannelFuture channelFuture = null; + logger.debug("Status LocalChannelServer: {} {}", serverChannel + .getClass().getName(), serverChannel.getConfig() + .getConnectTimeoutMillis() + " " + serverChannel.isBound()); + R66Future validLCR = new R66Future(true); + validLocalChannelHashMap.put(remoteId, validLCR); + for (int i = 0; i < Configuration.RETRYNB; i++) { + channelFuture = clientBootstrap.connect(socketLocalServerAddress); + try { + channelFuture.await(); + } catch (InterruptedException e1) { + validLCR.cancel(); + validLocalChannelHashMap.remove(remoteId); + logger.error("LocalChannelServer Interrupted: " + + serverChannel.getClass().getName() + " " + + serverChannel.getConfig().getConnectTimeoutMillis() + + " " + serverChannel.isBound()); + throw new OpenR66ProtocolSystemException( + "Interruption - Cannot connect to local handler: " + + socketLocalServerAddress + " " + + serverChannel.isBound() + " " + serverChannel, + e1); + } + if (channelFuture.isSuccess()) { + final Channel channel = channelFuture.getChannel(); + localChannelGroup.add(channel); + final LocalChannelReference localChannelReference = new LocalChannelReference( + channel, networkChannel, remoteId, futureRequest); + logger.debug("Create LocalChannel entry: " + i + " {}", + localChannelReference); + channel.getCloseFuture().addListener(remover); + localChannelHashMap.put(channel.getId(), localChannelReference); + try { + NetworkTransaction.addLocalChannelToNetworkChannel( + networkChannel, channel); + } catch (OpenR66ProtocolRemoteShutdownException e) { + validLCR.cancel(); + validLocalChannelHashMap.remove(remoteId); + Channels.close(channel); + throw new OpenR66ProtocolSystemException( + "Cannot connect to local handler", e); + } + // Now send first a Startup message + StartupPacket startup = new StartupPacket( + localChannelReference.getLocalId()); + try { + Channels.write(channel, startup).await(); + } catch (InterruptedException e) { + logger.error("Can't connect to local server due to interruption" + i); + validLCR.cancel(); + validLocalChannelHashMap.remove(remoteId); + throw new OpenR66ProtocolSystemException( + "Cannot connect to local handler", e); + } + validLCR.setSuccess(); + return localChannelReference; + } else { + logger.error("Can't connect to local server " + i); + } + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + validLCR.cancel(); + validLocalChannelHashMap.remove(remoteId); + throw new OpenR66ProtocolSystemException( + "Cannot connect to local handler", e); + } + } + validLCR.cancel(); + validLocalChannelHashMap.remove(remoteId); + logger.error("LocalChannelServer: " + + serverChannel.getClass().getName() + " " + + serverChannel.getConfig().getConnectTimeoutMillis() + " " + + serverChannel.isBound()); + throw new OpenR66ProtocolSystemException( + "Cannot connect to local handler: " + socketLocalServerAddress + + " " + serverChannel.isBound() + " " + serverChannel, + channelFuture.getCause()); + } + + /** + * + * @param id + * @return the LocalChannelReference + */ + public LocalChannelReference getFromId(Integer id) { + for (int i = 0; i < Configuration.RETRYNB * 4; i++) { + LocalChannelReference lcr = localChannelHashMap.get(id); + if (lcr == null) { + /* + * R66Future future = validLocalChannelHashMap.get(id); + * logger.debug("DEBUG Future ValidLocalChannel: not found: " + id + (future != + * null)); if (future != null) { try { + * future.await(Configuration.configuration.TIMEOUTCON); } catch + * (InterruptedException e) { return localChannelHashMap.get(id); } + * logger.debug("DEBUG Future ValidLocalChannel: " + id + future.isDone() + ":" + + * future.isSuccess()); if (future.isSuccess()) { return + * localChannelHashMap.get(id); } else if (future.isFailed()) { return null; } } + * else { logger.debug("DEBUG Future ValidLocalChannel: Sleep" + id); try { + * Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e) { } + * continue; } + */ + try { + Thread.sleep(Configuration.RETRYINMS * 2); + } catch (InterruptedException e) { + } + } else { + return lcr; + } + } + return localChannelHashMap.get(id); + } + + /** + * Remove one local channel + * + * @param channel + */ + public void remove(Channel channel) { + LocalChannelReference localChannelReference = localChannelHashMap + .remove(channel.getId()); + if (localChannelReference != null) { + logger.debug("Remove LocalChannel"); + R66Future validLCR = validLocalChannelHashMap + .remove(localChannelReference.getRemoteId()); + if (validLCR != null) { + validLCR.cancel(); + } + DbTaskRunner runner = null; + if (localChannelReference.getSession() != null) { + runner = localChannelReference.getSession().getRunner(); + } + R66Result result = new R66Result( + new OpenR66ProtocolSystemException( + "While closing Local Channel"), + localChannelReference.getSession(), false, + ErrorCode.ConnectionImpossible, runner); + localChannelReference.validateConnection(false, result); + if (localChannelReference.getSession() != null) { + if (runner != null) { + String key = runner.getKey(); + localChannelHashMapExternal.remove(key); + } + } + } + } + + /** + * + * @param runner + * @param lcr + */ + public void setFromId(DbTaskRunner runner, LocalChannelReference lcr) { + String key = runner.getKey(); + localChannelHashMapExternal.put(key, lcr); + } + + /** + * + * @param key + * as "requested requester specialId" + * @return the LocalChannelReference + */ + public LocalChannelReference getFromRequest(String key) { + return localChannelHashMapExternal.get(key); + } + + /** + * + * @return the number of active local channels + */ + public int getNumberLocalChannel() { + return localChannelHashMap.size(); + } + + private static class CloseLocalChannelsFromNetworkChannelTast implements TimerTask { + + LocalTransaction localTransaction; + AtomicInteger semaphore; + LocalChannelReference localChannelReference; + boolean analysis; + + public CloseLocalChannelsFromNetworkChannelTast( + LocalTransaction localTransaction, + AtomicInteger semaphore, + LocalChannelReference localChannelReference) { + this.localTransaction = localTransaction; + this.semaphore = semaphore; + this.localChannelReference = localChannelReference; + analysis = true; + } + + public void run(Timeout timeout) { + // give a chance for the LocalChannel to stop normally + if (analysis) { + boolean wait = false; + if (!localChannelReference.getFutureRequest().isDone()) { + if (localChannelReference.getFutureValidRequest().isDone() && + localChannelReference.getFutureValidRequest() + .isFailed()) { + logger.debug("Already currently on finalize"); + wait = true; + } else { + R66Result finalValue = new R66Result( + localChannelReference.getSession(), true, + ErrorCode.Shutdown, null); + if (localChannelReference.getSession() != null) { + try { + localChannelReference.getSession() + .tryFinalizeRequest(finalValue); + } catch (OpenR66RunnerErrorException e) { + } catch (OpenR66ProtocolSystemException e) { + } + } + } + } + if (wait) { + this.analysis = false; + Configuration.configuration.getTimerClose().newTimeout(this, + Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS); + return; + } + } + logger.debug("Will close local channel"); + try { + Channels.close(localChannelReference.getLocalChannel()).await(); + } catch (InterruptedException e) { + } + localTransaction.remove(localChannelReference.getLocalChannel()); + semaphore.decrementAndGet(); + } + + } + + /** + * Close all Local Channels from the NetworkChannel + * + * @param networkChannel + */ + public void closeLocalChannelsFromNetworkChannel(Channel networkChannel) { + Collection collection = localChannelHashMap + .values(); + AtomicInteger semaphore = new AtomicInteger(); + Iterator iterator = collection.iterator(); + while (iterator.hasNext()) { + LocalChannelReference localChannelReference = iterator.next(); + if (localChannelReference.getNetworkChannel().compareTo( + networkChannel) == 0) { + semaphore.incrementAndGet(); + CloseLocalChannelsFromNetworkChannelTast task = + new CloseLocalChannelsFromNetworkChannelTast(this, + semaphore, localChannelReference); + Configuration.configuration.getTimerClose().newTimeout(task, + Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS); + } + } + while (true) { + if (semaphore.get() == 0) { + break; + } + try { + Thread.sleep(Configuration.RETRYINMS * 2); + } catch (InterruptedException e) { + break; + } + } + } + + /** + * Debug function (while shutdown for instance) + */ + public void debugPrintActiveLocalChannels() { + Collection collection = localChannelHashMap + .values(); + Iterator iterator = collection.iterator(); + while (iterator.hasNext()) { + LocalChannelReference localChannelReference = iterator.next(); + logger.debug("Will close local channel: {}", localChannelReference); + logger.debug( + " Containing: {}", + (localChannelReference.getSession() != null ? localChannelReference + .getSession() : "no session")); + } + } + + /** + * Informs all remote client that the server is shutting down + */ + public void shutdownLocalChannels() { + Collection collection = localChannelHashMap + .values(); + Iterator iterator = collection.iterator(); + ValidPacket packet = new ValidPacket("Shutdown forced", null, + LocalPacketFactory.SHUTDOWNPACKET); + ChannelBuffer buffer = null; + while (iterator.hasNext()) { + LocalChannelReference localChannelReference = iterator.next(); + logger.debug("Inform Shutdown {}", localChannelReference); + packet.setSmiddle(null); + // If a transfer is running, save the current rank and inform remote + // host + if (localChannelReference.getSession() != null) { + R66Session session = localChannelReference.getSession(); + DbTaskRunner runner = session.getRunner(); + if (runner != null && runner.isInTransfer()) { + if (!runner.isSender()) { + int newrank = runner.getRank(); + packet.setSmiddle(Integer.toString(newrank)); + } + // Save File status + try { + runner.saveStatus(); + } catch (OpenR66RunnerErrorException e) { + } + R66Result result = new R66Result( + new OpenR66ProtocolShutdownException(), session, + true, ErrorCode.Shutdown, runner); + result.other = packet; + try { + buffer = packet.getLocalPacket(); + } catch (OpenR66ProtocolPacketException e1) { + } + localChannelReference + .sessionNewState(R66FiniteDualStates.SHUTDOWN); + NetworkPacket message = new NetworkPacket( + localChannelReference.getLocalId(), + localChannelReference.getRemoteId(), + packet.getType(), buffer); + try { + Channels.write(localChannelReference.getNetworkChannel(), + message).await(); + } catch (InterruptedException e1) { + } + try { + session.setFinalizeTransfer(false, result); + } catch (OpenR66RunnerErrorException e) { + } catch (OpenR66ProtocolSystemException e) { + } + } + Channels.close(localChannelReference.getLocalChannel()); + continue; + } + try { + buffer = packet.getLocalPacket(); + } catch (OpenR66ProtocolPacketException e1) { + } + NetworkPacket message = new NetworkPacket( + localChannelReference.getLocalId(), + localChannelReference.getRemoteId(), packet.getType(), + buffer); + Channels.write(localChannelReference.getNetworkChannel(), message); + } + } + + /** + * Close All Local Channels + */ + public void closeAll() { + logger.debug("close All Local Channels"); + localChannelGroup.close().awaitUninterruptibly(); + clientBootstrap.releaseExternalResources(); + channelClientFactory.releaseExternalResources(); + serverBootstrap.releaseExternalResources(); + channelServerFactory.releaseExternalResources(); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/Monitoring.java b/src/main/java/org/waarp/openr66/protocol/localhandler/Monitoring.java index 40b076cb2..e9922d6e5 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/Monitoring.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/Monitoring.java @@ -1,1431 +1,1431 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import java.util.Date; - -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.database.model.DbModelFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.commander.CommanderNoDb; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.snmp.R66PrivateMib; -import org.waarp.snmp.WaarpSnmpAgent; -import org.waarp.snmp.interf.WaarpInterfaceMonitor; -import org.waarp.snmp.r66.WaarpPrivateMib.MibLevel; -import org.waarp.snmp.r66.WaarpPrivateMib.WaarpDetailedValuesIndex; -import org.waarp.snmp.r66.WaarpPrivateMib.WaarpErrorValuesIndex; -import org.waarp.snmp.r66.WaarpPrivateMib.WaarpGlobalValuesIndex; - -/** - * Monitoring class as an helper to get values of interest. Also used by SNMP support. - * - * @author Frederic Bregier - * - */ -public class Monitoring implements WaarpInterfaceMonitor { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(Monitoring.class); - - public WaarpSnmpAgent agent; - - // global informations - public long nbNetworkConnection = 0; - public long secondsRunning = 0; - public long nbThread = 0; - public long bandwidthIn = 0; - public long bandwidthOut = 0; - - // Internal data - private long startMonitor = System.currentTimeMillis(); - private long pastLimit = 0; - private long currentLimit = 0; - private long minimalDelay = 0; - private long lastTry = 0; - private DbSession dbSession = null; - private TrafficCounter trafficCounter = - Configuration.configuration - .getGlobalTrafficShapingHandler() - .getTrafficCounter(); - - // Overall status including past, future and current transfers - private DbPreparedStatement countInfo = null; - - // Current situation of all transfers, running or not - private DbPreparedStatement countInActiveTransfer = null; - private DbPreparedStatement countOutActiveTransfer = null; - private DbPreparedStatement countInTotalTransfer = null; - private DbPreparedStatement countOutTotalTransfer = null; - private DbPreparedStatement countInErrorTransfer = null; - private DbPreparedStatement countOutErrorTransfer = null; - private DbPreparedStatement countStepAllTransfer = null; - private DbPreparedStatement countStepNotask = null; - private DbPreparedStatement countStepPretask = null; - private DbPreparedStatement countStepTransfer = null; - private DbPreparedStatement countStepPosttask = null; - private DbPreparedStatement countStepAllDone = null; - private DbPreparedStatement countStepError = null; - - // First on Running Transfers only - private DbPreparedStatement countAllRunningStep = null; - private DbPreparedStatement countRunningStep = null; - private DbPreparedStatement countInitOkStep = null; - private DbPreparedStatement countPreProcessingOkStep = null; - private DbPreparedStatement countTransferOkStep = null; - private DbPreparedStatement countPostProcessingOkStep = null; - private DbPreparedStatement countCompleteOkStep = null; - - // Error Status on all transfers - private DbPreparedStatement countStatus = null; - - // Overall status including past, future and current transfers - public long nbCountInfoUnknown = 0; - public long nbCountInfoNotUpdated = 0; - public long nbCountInfoInterrupted = 0; - public long nbCountInfoToSubmit = 0; - public long nbCountInfoError = 0; - public long nbCountInfoRunning = 0; - public long nbCountInfoDone = 0; - - public long nbInActiveTransfer = 0; - public long nbOutActiveTransfer = 0; - public long lastInActiveTransfer = System.currentTimeMillis(); - public long lastOutActiveTransfer = System.currentTimeMillis(); - public long nbInTotalTransfer = 0; - public long nbOutTotalTransfer = 0; - public long nbInErrorTransfer = 0; - public long nbOutErrorTransfer = 0; - - // Current situation of all transfers, running or not - public long nbCountStepAllTransfer = 0; - public long nbCountStepNotask = 0; - public long nbCountStepPretask = 0; - public long nbCountStepTransfer = 0; - public long nbCountStepPosttask = 0; - public long nbCountStepAllDone = 0; - public long nbCountStepError = 0; - - // First on Running Transfers only - public long nbCountAllRunningStep = 0; - public long nbCountRunningStep = 0; - public long nbCountInitOkStep = 0; - public long nbCountPreProcessingOkStep = 0; - public long nbCountTransferOkStep = 0; - public long nbCountPostProcessingOkStep = 0; - public long nbCountCompleteOkStep = 0; - - // Error Status on all transfers - public long nbCountStatusConnectionImpossible = 0; - public long nbCountStatusServerOverloaded = 0; - public long nbCountStatusBadAuthent = 0; - public long nbCountStatusExternalOp = 0; - public long nbCountStatusTransferError = 0; - public long nbCountStatusMD5Error = 0; - public long nbCountStatusDisconnection = 0; - public long nbCountStatusFinalOp = 0; - public long nbCountStatusUnimplemented = 0; - public long nbCountStatusInternal = 0; - public long nbCountStatusWarning = 0; - public long nbCountStatusQueryAlreadyFinished = 0; - public long nbCountStatusQueryStillRunning = 0; - public long nbCountStatusNotKnownHost = 0; - public long nbCountStatusQueryRemotelyUnknown = 0; - public long nbCountStatusCommandNotFound = 0; - public long nbCountStatusPassThroughMode = 0; - public long nbCountStatusRemoteShutdown = 0; - public long nbCountStatusShutdown = 0; - public long nbCountStatusRemoteError = 0; - public long nbCountStatusStopped = 0; - public long nbCountStatusCanceled = 0; - public long nbCountStatusFileNotFound = 0; - public long nbCountStatusUnknown = 0; - - /** - * @param pastLimit - * @param minimalDelay - * @param session - */ - public Monitoring(long pastLimit, long minimalDelay, DbSession session) { - this.pastLimit = pastLimit; - this.minimalDelay = minimalDelay; - if (session != null) { - dbSession = session; - } else { - dbSession = DbConstant.admin.session; - } - this.initialize(); - } - - /** - * Initialize the Db Requests after constructor or after use of releaseResources - */ - public void initialize() { - if (dbSession == null || dbSession.isDisconnected) { - logger.warn("Cannot Initialize monitoring"); - return; - } - try { - logger.debug("Initialize monitoring"); - // Overall status including past, future and current transfers - countInfo = DbTaskRunner.getCountInfoPrepareStatement(dbSession); - // Count of Active/All In/Out transfers - countInActiveTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, - true, true); - countOutActiveTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, - false, true); - countInTotalTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, - true, false); - countOutTotalTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, - false, false); - - countInErrorTransfer = DbTaskRunner.getCountInOutErrorPrepareStatement(dbSession, true); - countOutErrorTransfer = DbTaskRunner.getCountInOutErrorPrepareStatement(dbSession, - false); - - // Current situation of all transfers, running or not - countStepAllTransfer = DbTaskRunner.getCountStepPrepareStatement( - dbSession, null); - countStepNotask = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.NOTASK); - countStepPretask = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.PRETASK); - countStepTransfer = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.TRANSFERTASK); - countStepPosttask = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.POSTTASK); - countStepAllDone = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.ALLDONETASK); - countStepError = DbTaskRunner.getCountStepPrepareStatement( - dbSession, TASKSTEP.ERRORTASK); - - // First on Running Transfers only - countAllRunningStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, - null); - countRunningStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, - ErrorCode.Running); - countInitOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, - ErrorCode.InitOk); - countPreProcessingOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement( - dbSession, - ErrorCode.PreProcessingOk); - countTransferOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, - ErrorCode.TransferOk); - countPostProcessingOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement( - dbSession, - ErrorCode.PostProcessingOk); - countCompleteOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, - ErrorCode.CompleteOk); - - // Error Status on all transfers - countStatus = DbTaskRunner.getCountStatusPrepareStatement(dbSession); - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } - } - - /** - * Release all Db Requests - */ - public void releaseResources() { - if (dbSession == null || dbSession.isDisconnected) { - return; - } - try { - logger.debug("Release monitoring"); - // Overall status including past, future and current transfers - countInfo.realClose(); - - countInActiveTransfer.realClose(); - countOutActiveTransfer.realClose(); - countInTotalTransfer.realClose(); - countOutTotalTransfer.realClose(); - countInErrorTransfer.realClose(); - countOutErrorTransfer.realClose(); - - // Current situation of all transfers, running or not - countStepAllTransfer.realClose(); - countStepNotask.realClose(); - countStepPretask.realClose(); - countStepTransfer.realClose(); - countStepPosttask.realClose(); - countStepAllDone.realClose(); - countStepError.realClose(); - - // First on Running Transfers only - countAllRunningStep.realClose(); - countRunningStep.realClose(); - countInitOkStep.realClose(); - countPreProcessingOkStep.realClose(); - countTransferOkStep.realClose(); - countPostProcessingOkStep.realClose(); - countCompleteOkStep.realClose(); - - // Error Status on all transfers - countStatus.realClose(); - } catch (NullPointerException e) { - } - } - - /** - * - * @return the last Time in ms of the execution - */ - public long lastRunTimeMs() { - return lastTry; - } - - /** - * Default execution of testing with default pastLimit - */ - public void run() { - this.run(-1, false); - } - - /** - * - * @param nbSecond - * as specific PastLimit - */ - public void run(long nbSecond) { - this.run(nbSecond, false); - } - - /** - * Default execution of testing with default pastLimit - * - * @param detail - * as to get detailed information - */ - public void run(boolean detail) { - this.run(-1, detail); - } - - /** - * - * @return False if too early, else return True - */ - private boolean reCompute() { - long limitDate = System.currentTimeMillis(); - if (limitDate < lastTry + minimalDelay) { - // too early - return false; - } - lastTry = limitDate; - return true; - } - - /** - * - * @param nbSecond - * as specific PastLimit - * @param detail - * as to get detailed information - */ - public void run(long nbSecond, boolean detail) { - synchronized (trafficCounter) { - long limitDate = System.currentTimeMillis(); - long nbMs = pastLimit; - if (nbSecond <= 0) { - nbMs = pastLimit; - } else { - nbMs = nbSecond * 1000; - } - if (dbSession == null || dbSession.isDisconnected) { - nbNetworkConnection = - Configuration.configuration.getHttpChannelGroup().size() + - Configuration.configuration.getServerChannelGroup().size(); - bandwidthIn = trafficCounter.getLastReadThroughput() >> 7;// B/s -> Kb/s - bandwidthOut = trafficCounter.getLastWriteThroughput() >> 7; - nbThread = Thread.activeCount(); - secondsRunning = (limitDate - startMonitor) / 1000; - - if (!reCompute()) { - // too early - return; - } - limitDate -= nbMs; - currentLimit = limitDate; - // Update value - // Overall status including past, future and current transfers - nbCountInfoToSubmit = CommanderNoDb.todoList.size(); - if (Configuration.configuration.getInternalRunner() != null) { - nbCountInfoRunning = Configuration.configuration.getInternalRunner() - .nbInternalRunner(); - } else { - nbCountInfoRunning = Configuration.configuration.getServerChannelGroup().size(); - } - // Current situation of all transfers, running or not - nbCountAllRunningStep = nbCountInfoRunning; - } else { - nbNetworkConnection = DbAdmin.getNbConnection(); - bandwidthIn = trafficCounter.getLastReadThroughput() >> 7;// B/s -> Kb/s - bandwidthOut = trafficCounter.getLastWriteThroughput() >> 7; - nbThread = Thread.activeCount(); - secondsRunning = (limitDate - startMonitor) / 1000; - - if (!reCompute()) { - // too early - return; - } - limitDate -= nbMs; - currentLimit = limitDate; - // Update value - try { - // Overall status including past, future and current transfers - nbCountInfoUnknown = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.UNKNOWN, limitDate); - nbCountInfoNotUpdated = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.NOTUPDATED, limitDate); - nbCountInfoInterrupted = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.INTERRUPTED, limitDate); - nbCountInfoToSubmit = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.TOSUBMIT, limitDate); - nbCountInfoError = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.INERROR, limitDate); - nbCountInfoRunning = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.RUNNING, limitDate); - nbCountInfoDone = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.DONE, limitDate); - - // Current situation of all transfers, running or not - DbTaskRunner.finishSelectOrCountPrepareStatement(countInActiveTransfer, - limitDate); - nbInActiveTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInActiveTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutActiveTransfer, - limitDate); - nbOutActiveTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutActiveTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countInTotalTransfer, - limitDate); - nbInTotalTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInTotalTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutTotalTransfer, - limitDate); - nbOutTotalTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutTotalTransfer); - - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutErrorTransfer, - limitDate); - nbOutErrorTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutErrorTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countInErrorTransfer, - limitDate); - nbInErrorTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInErrorTransfer); - - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllTransfer, - limitDate); - nbCountStepAllTransfer = DbTaskRunner - .getResultCountPrepareStatement(countStepAllTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepNotask, limitDate); - nbCountStepNotask = DbTaskRunner - .getResultCountPrepareStatement(countStepNotask); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPretask, limitDate); - nbCountStepPretask = DbTaskRunner - .getResultCountPrepareStatement(countStepPretask); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepTransfer, limitDate); - nbCountStepTransfer = DbTaskRunner - .getResultCountPrepareStatement(countStepTransfer); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPosttask, limitDate); - nbCountStepPosttask = DbTaskRunner - .getResultCountPrepareStatement(countStepPosttask); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllDone, limitDate); - nbCountStepAllDone = DbTaskRunner - .getResultCountPrepareStatement(countStepAllDone); - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepError, limitDate); - nbCountStepError = DbTaskRunner.getResultCountPrepareStatement(countStepError); - - DbTaskRunner - .finishSelectOrCountPrepareStatement(countAllRunningStep, limitDate); - nbCountAllRunningStep = DbTaskRunner - .getResultCountPrepareStatement(countAllRunningStep); - - if (detail) { - // First on Running Transfers only - DbTaskRunner.finishSelectOrCountPrepareStatement(countRunningStep, - limitDate); - nbCountRunningStep = DbTaskRunner - .getResultCountPrepareStatement(countRunningStep); - DbTaskRunner - .finishSelectOrCountPrepareStatement(countInitOkStep, limitDate); - nbCountInitOkStep = DbTaskRunner - .getResultCountPrepareStatement(countInitOkStep); - DbTaskRunner.finishSelectOrCountPrepareStatement(countPreProcessingOkStep, - limitDate); - nbCountPreProcessingOkStep = DbTaskRunner - .getResultCountPrepareStatement(countPreProcessingOkStep); - DbTaskRunner.finishSelectOrCountPrepareStatement(countTransferOkStep, - limitDate); - nbCountTransferOkStep = DbTaskRunner - .getResultCountPrepareStatement(countTransferOkStep); - DbTaskRunner.finishSelectOrCountPrepareStatement(countPostProcessingOkStep, - limitDate); - nbCountPostProcessingOkStep = DbTaskRunner - .getResultCountPrepareStatement(countPostProcessingOkStep); - DbTaskRunner.finishSelectOrCountPrepareStatement(countCompleteOkStep, - limitDate); - nbCountCompleteOkStep = DbTaskRunner - .getResultCountPrepareStatement(countCompleteOkStep); - - // Error Status on all transfers - nbCountStatusConnectionImpossible = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.ConnectionImpossible, limitDate); - nbCountStatusServerOverloaded = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.ServerOverloaded, limitDate); - nbCountStatusBadAuthent = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.BadAuthent, limitDate); - nbCountStatusExternalOp = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.ExternalOp, limitDate); - nbCountStatusTransferError = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.TransferError, limitDate); - nbCountStatusMD5Error = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.MD5Error, limitDate); - nbCountStatusDisconnection = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Disconnection, limitDate); - nbCountStatusFinalOp = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.FinalOp, limitDate); - nbCountStatusUnimplemented = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Unimplemented, limitDate); - nbCountStatusInternal = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Internal, limitDate); - nbCountStatusWarning = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Warning, limitDate); - nbCountStatusQueryAlreadyFinished = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.QueryAlreadyFinished, limitDate); - nbCountStatusQueryStillRunning = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.QueryStillRunning, limitDate); - nbCountStatusNotKnownHost = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.NotKnownHost, limitDate); - nbCountStatusQueryRemotelyUnknown = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.QueryRemotelyUnknown, limitDate); - nbCountStatusCommandNotFound = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.CommandNotFound, limitDate); - nbCountStatusPassThroughMode = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.PassThroughMode, limitDate); - nbCountStatusRemoteShutdown = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.RemoteShutdown, limitDate); - nbCountStatusShutdown = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Shutdown, limitDate); - nbCountStatusRemoteError = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.RemoteError, limitDate); - nbCountStatusStopped = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.StoppedTransfer, limitDate); - nbCountStatusCanceled = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.CanceledTransfer, limitDate); - nbCountStatusFileNotFound = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.FileNotFound, limitDate); - nbCountStatusUnknown = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Unknown, limitDate); - } - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } - } - } - } - - /** - * @param detail - * @return The XML representation of the current status - */ - public String exportXml(boolean detail) { - StringBuilder builder = new StringBuilder(); - builder.append(""); - // Global Informations - builder.append(""); - builder.append(Configuration.configuration.HOST_ID); - builder.append(""); - builder.append(""); - builder.append(new Date()); - builder.append(""); - builder.append(""); - builder.append(new Date(lastTry)); - builder.append(""); - builder.append(""); - builder.append(new Date(currentLimit)); - builder.append(""); - builder.append(""); - builder.append(secondsRunning); - builder.append(""); - builder.append(""); - builder.append(nbNetworkConnection); - builder.append(""); - builder.append(""); - builder.append(nbThread); - builder.append(""); - builder.append(""); - builder.append(bandwidthIn); - builder.append(""); - builder.append(""); - builder.append(bandwidthOut); - builder.append(""); - - // Overall status including past, future and current transfers - builder.append(""); - builder.append(""); - builder.append(nbCountStepAllTransfer); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoUnknown); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoNotUpdated); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoInterrupted); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoToSubmit); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoError); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoRunning); - builder.append(""); - builder.append(""); - builder.append(nbCountInfoDone); - builder.append(""); - builder.append(""); - builder.append(nbInActiveTransfer); - builder.append(""); - builder.append(""); - builder.append(nbOutActiveTransfer); - builder.append(""); - builder.append(""); - builder.append((new Date(lastInActiveTransfer)).toString()); - builder.append(""); - builder.append(""); - builder.append((new Date(lastOutActiveTransfer)).toString()); - builder.append(""); - builder.append(""); - builder.append(nbInTotalTransfer); - builder.append(""); - builder.append(""); - builder.append(nbOutTotalTransfer); - builder.append(""); - builder.append(""); - builder.append(nbInErrorTransfer); - builder.append(""); - builder.append(""); - builder.append(nbOutErrorTransfer); - builder.append(""); - builder.append(""); - - // Current situation of all transfers, running or not - builder.append(""); - builder.append(""); - builder.append(nbCountStepNotask); - builder.append(""); - builder.append(""); - builder.append(nbCountStepPretask); - builder.append(""); - builder.append(""); - builder.append(nbCountStepTransfer); - builder.append(""); - builder.append(""); - builder.append(nbCountStepPosttask); - builder.append(""); - builder.append(""); - builder.append(nbCountStepAllDone); - builder.append(""); - builder.append(""); - builder.append(nbCountStepError); - builder.append(""); - builder.append(""); - - // On Running Transfers only - builder.append(""); - builder.append(""); - builder.append(nbCountAllRunningStep); - builder.append(""); - if (detail) { - builder.append(""); - builder.append(nbCountRunningStep); - builder.append(""); - builder.append(""); - builder.append(nbCountInitOkStep); - builder.append(""); - builder.append(""); - builder.append(nbCountPreProcessingOkStep); - builder.append(""); - builder.append(""); - builder.append(nbCountTransferOkStep); - builder.append(""); - builder.append(""); - builder.append(nbCountPostProcessingOkStep); - builder.append(""); - builder.append(""); - builder.append(nbCountCompleteOkStep); - builder.append(""); - } - builder.append(""); - - if (detail) { - // Error Status on all transfers - builder.append(""); - builder.append(""); - builder.append(nbCountStatusConnectionImpossible); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusServerOverloaded); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusBadAuthent); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusExternalOp); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusTransferError); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusMD5Error); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusDisconnection); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusFinalOp); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusUnimplemented); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusInternal); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusWarning); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusQueryAlreadyFinished); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusQueryStillRunning); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusNotKnownHost); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusQueryRemotelyUnknown); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusCommandNotFound); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusPassThroughMode); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusRemoteShutdown); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusShutdown); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusRemoteError); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusStopped); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusCanceled); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusFileNotFound); - builder.append(""); - builder.append(""); - builder.append(nbCountStatusUnknown); - builder.append(""); - builder.append(""); - } - builder.append(""); - return builder.toString(); - } - - public void setAgent(WaarpSnmpAgent agent) { - this.agent = agent; - this.lastInActiveTransfer = this.agent.getUptimeSystemTime(); - this.lastOutActiveTransfer = this.agent.getUptimeSystemTime(); - } - - /** - * Update the value for one particular MIB entry - * - * @param type - * @param entry - */ - public void run(int type, int entry) { - long nbMs = Configuration.configuration.agentSnmp.getUptime() + 100; - MibLevel level = MibLevel.values()[type]; - switch (level) { - case globalInfo:// Global - if (((R66PrivateMib) this.agent.mib).rowGlobal != null) - run(nbMs, WaarpGlobalValuesIndex.values()[entry]); - return; - case detailedInfo:// Detailed - if (((R66PrivateMib) this.agent.mib).rowDetailed != null) - run(nbMs, WaarpDetailedValuesIndex.values()[entry]); - return; - case errorInfo:// Error - if (((R66PrivateMib) this.agent.mib).rowError != null) - run(nbMs, WaarpErrorValuesIndex.values()[entry]); - return; - case staticInfo: - break; - case trapInfo: - break; - default: - break; - } - } - - /** - * Update a value in Global MIB part - * - * @param rank - * @param value - */ - protected void updateGlobalValue(int rank, long value) { - ((R66PrivateMib) this.agent.mib).rowGlobal.setValue(rank, value); - } - - /** - * Update a value in Detailed MIB part - * - * @param rank - * @param value - */ - protected void updateDetailedValue(int rank, long value) { - ((R66PrivateMib) this.agent.mib).rowDetailed.setValue(rank, value); - } - - /** - * Update a value in Error MIB part - * - * @param rank - * @param value - */ - protected void updateErrorValue(int rank, long value) { - ((R66PrivateMib) this.agent.mib).rowError.setValue(rank, value); - } - - /** - * Update a value in Global MIB part - * - * @param nbMs - * @param entry - */ - protected void run(long nbMs, WaarpGlobalValuesIndex entry) { - synchronized (trafficCounter) { - long val = 0; - long limitDate = System.currentTimeMillis() - nbMs; - if (dbSession == null || dbSession.isDisconnected) { - switch (entry) { - case applUptime: - return; - case applOperStatus: - return; - case applLastChange: - return; - case applInboundAssociations: - updateGlobalValue(entry.ordinal(), nbInActiveTransfer); - return; - case applOutboundAssociations: - updateGlobalValue(entry.ordinal(), nbOutActiveTransfer); - return; - case applAccumInboundAssociations: - updateGlobalValue(entry.ordinal(), nbInTotalTransfer); - return; - case applAccumOutboundAssociations: - updateGlobalValue(entry.ordinal(), nbOutTotalTransfer); - return; - case applLastInboundActivity: - val = (lastInActiveTransfer - - this.agent.getUptimeSystemTime()) / 10; - if (val < 0) - val = 0; - updateGlobalValue(entry.ordinal(), val); - return; - case applLastOutboundActivity: - val = (lastOutActiveTransfer - - this.agent.getUptimeSystemTime()) / 10; - if (val < 0) - val = 0; - updateGlobalValue(entry.ordinal(), val); - return; - case applRejectedInboundAssociations: - updateGlobalValue(entry.ordinal(), nbInErrorTransfer); - return; - case applFailedOutboundAssociations: - updateGlobalValue(entry.ordinal(), nbOutErrorTransfer); - return; - case applInboundBandwidthKBS: - val = trafficCounter.getLastReadThroughput() >> 10;// B/s -> KB/s - updateGlobalValue(entry.ordinal(), val); - return; - case applOutboundBandwidthKBS: - val = trafficCounter.getLastWriteThroughput() >> 10; - updateGlobalValue(entry.ordinal(), val); - return; - case nbInfoUnknown: - updateGlobalValue(entry.ordinal(), nbCountInfoUnknown); - return; - case nbInfoNotUpdated: - updateGlobalValue(entry.ordinal(), nbCountInfoNotUpdated); - return; - case nbInfoInterrupted: - updateGlobalValue(entry.ordinal(), nbCountInfoInterrupted); - return; - case nbInfoToSubmit: - nbCountInfoToSubmit = CommanderNoDb.todoList.size(); - updateGlobalValue(entry.ordinal(), nbCountInfoToSubmit); - return; - case nbInfoError: - updateGlobalValue(entry.ordinal(), nbCountInfoError); - return; - case nbInfoRunning: - nbCountInfoRunning = Configuration.configuration.getInternalRunner() - .nbInternalRunner(); - updateGlobalValue(entry.ordinal(), nbCountInfoRunning); - return; - case nbInfoDone: - updateGlobalValue(entry.ordinal(), nbCountInfoDone); - return; - case nbStepAllTransfer: - updateGlobalValue(entry.ordinal(), nbCountStepAllTransfer); - return; - case memoryTotal: - return; - case memoryFree: - return; - case memoryUsed: - return; - case nbThreads: - nbThread = Thread.activeCount(); - updateGlobalValue(entry.ordinal(), nbThread); - return; - case nbNetworkConnection: - nbNetworkConnection = - Configuration.configuration.getHttpChannelGroup().size() + - Configuration.configuration.getServerChannelGroup().size(); - updateGlobalValue(entry.ordinal(), nbNetworkConnection); - return; - } - return; - } - // Global - try { - switch (entry) { - case applUptime: - return; - case applOperStatus: - return; - case applLastChange: - return; - case applInboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countInActiveTransfer, - limitDate); - nbInActiveTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInActiveTransfer); - updateGlobalValue(entry.ordinal(), nbInActiveTransfer); - return; - case applOutboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutActiveTransfer, - limitDate); - nbOutActiveTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutActiveTransfer); - updateGlobalValue(entry.ordinal(), nbOutActiveTransfer); - return; - case applAccumInboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countInTotalTransfer, - limitDate); - nbInTotalTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInTotalTransfer); - updateGlobalValue(entry.ordinal(), nbInTotalTransfer); - return; - case applAccumOutboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutTotalTransfer, - limitDate); - nbOutTotalTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutTotalTransfer); - updateGlobalValue(entry.ordinal(), nbOutTotalTransfer); - return; - case applLastInboundActivity: - val = (lastInActiveTransfer - - this.agent.getUptimeSystemTime()) / 10; - if (val < 0) - val = 0; - updateGlobalValue(entry.ordinal(), val); - return; - case applLastOutboundActivity: - val = (lastOutActiveTransfer - - this.agent.getUptimeSystemTime()) / 10; - if (val < 0) - val = 0; - updateGlobalValue(entry.ordinal(), val); - return; - case applRejectedInboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countInErrorTransfer, - limitDate); - nbInErrorTransfer = DbTaskRunner - .getResultCountPrepareStatement(countInErrorTransfer); - updateGlobalValue(entry.ordinal(), nbInErrorTransfer); - return; - case applFailedOutboundAssociations: - DbTaskRunner.finishSelectOrCountPrepareStatement(countOutErrorTransfer, - limitDate); - nbOutErrorTransfer = DbTaskRunner - .getResultCountPrepareStatement(countOutErrorTransfer); - updateGlobalValue(entry.ordinal(), nbOutErrorTransfer); - return; - case applInboundBandwidthKBS: - val = trafficCounter.getLastReadThroughput() >> 10;// B/s -> KB/s - updateGlobalValue(entry.ordinal(), val); - return; - case applOutboundBandwidthKBS: - val = trafficCounter.getLastWriteThroughput() >> 10; - updateGlobalValue(entry.ordinal(), val); - return; - case nbInfoUnknown: - nbCountInfoUnknown = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.UNKNOWN, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoUnknown); - return; - case nbInfoNotUpdated: - nbCountInfoNotUpdated = DbTaskRunner.getResultCountPrepareStatement( - countInfo, - UpdatedInfo.NOTUPDATED, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoNotUpdated); - return; - case nbInfoInterrupted: - nbCountInfoInterrupted = DbTaskRunner.getResultCountPrepareStatement( - countInfo, - UpdatedInfo.INTERRUPTED, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoInterrupted); - return; - case nbInfoToSubmit: - nbCountInfoToSubmit = DbTaskRunner.getResultCountPrepareStatement( - countInfo, - UpdatedInfo.TOSUBMIT, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoToSubmit); - return; - case nbInfoError: - nbCountInfoError = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.INERROR, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoError); - return; - case nbInfoRunning: - nbCountInfoRunning = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.RUNNING, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoRunning); - return; - case nbInfoDone: - nbCountInfoDone = DbTaskRunner.getResultCountPrepareStatement(countInfo, - UpdatedInfo.DONE, limitDate); - updateGlobalValue(entry.ordinal(), nbCountInfoDone); - return; - case nbStepAllTransfer: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllTransfer, - limitDate); - nbCountStepAllTransfer = DbTaskRunner - .getResultCountPrepareStatement(countStepAllTransfer); - updateGlobalValue(entry.ordinal(), nbCountStepAllTransfer); - return; - case memoryTotal: - return; - case memoryFree: - return; - case memoryUsed: - return; - case nbThreads: - nbThread = Thread.activeCount(); - updateGlobalValue(entry.ordinal(), nbThread); - return; - case nbNetworkConnection: - nbNetworkConnection = DbAdmin.getNbConnection(); - updateGlobalValue(entry.ordinal(), nbNetworkConnection); - return; - } - } catch (WaarpDatabaseNoConnectionException e) { - } catch (WaarpDatabaseSqlException e) { - } - } - } - - /** - * Update a value in Detailed MIB part - * - * @param nbMs - * @param entry - */ - protected void run(long nbMs, WaarpDetailedValuesIndex entry) { - synchronized (trafficCounter) { - long limitDate = System.currentTimeMillis() - nbMs; - if (dbSession == null || dbSession.isDisconnected) { - switch (entry) { - case nbStepNotask: - updateDetailedValue(entry.ordinal(), nbCountStepNotask); - return; - case nbStepPretask: - updateDetailedValue(entry.ordinal(), nbCountStepPretask); - return; - case nbStepTransfer: - updateDetailedValue(entry.ordinal(), nbCountStepTransfer); - return; - case nbStepPosttask: - updateDetailedValue(entry.ordinal(), nbCountStepPosttask); - return; - case nbStepAllDone: - updateDetailedValue(entry.ordinal(), nbCountStepAllDone); - return; - case nbStepError: - updateDetailedValue(entry.ordinal(), nbCountStepError); - return; - case nbAllRunningStep: - nbCountAllRunningStep = Configuration.configuration.getInternalRunner() - .nbInternalRunner(); - updateDetailedValue(entry.ordinal(), nbCountAllRunningStep); - return; - case nbRunningStep: - updateDetailedValue(entry.ordinal(), nbCountRunningStep); - return; - case nbInitOkStep: - updateDetailedValue(entry.ordinal(), nbCountInitOkStep); - return; - case nbPreProcessingOkStep: - updateDetailedValue(entry.ordinal(), nbCountPreProcessingOkStep); - return; - case nbTransferOkStep: - updateDetailedValue(entry.ordinal(), nbCountTransferOkStep); - return; - case nbPostProcessingOkStep: - updateDetailedValue(entry.ordinal(), nbCountPostProcessingOkStep); - return; - case nbCompleteOkStep: - updateDetailedValue(entry.ordinal(), nbCountCompleteOkStep); - return; - } - return; - } - // Detailed - try { - switch (entry) { - case nbStepNotask: - DbTaskRunner - .finishSelectOrCountPrepareStatement(countStepNotask, limitDate); - nbCountStepNotask = DbTaskRunner - .getResultCountPrepareStatement(countStepNotask); - updateDetailedValue(entry.ordinal(), nbCountStepNotask); - return; - case nbStepPretask: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPretask, - limitDate); - nbCountStepPretask = DbTaskRunner - .getResultCountPrepareStatement(countStepPretask); - updateDetailedValue(entry.ordinal(), nbCountStepPretask); - return; - case nbStepTransfer: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepTransfer, - limitDate); - nbCountStepTransfer = DbTaskRunner - .getResultCountPrepareStatement(countStepTransfer); - updateDetailedValue(entry.ordinal(), nbCountStepTransfer); - return; - case nbStepPosttask: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPosttask, - limitDate); - nbCountStepPosttask = DbTaskRunner - .getResultCountPrepareStatement(countStepPosttask); - updateDetailedValue(entry.ordinal(), nbCountStepPosttask); - return; - case nbStepAllDone: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllDone, - limitDate); - nbCountStepAllDone = DbTaskRunner - .getResultCountPrepareStatement(countStepAllDone); - updateDetailedValue(entry.ordinal(), nbCountStepAllDone); - return; - case nbStepError: - DbTaskRunner.finishSelectOrCountPrepareStatement(countStepError, limitDate); - nbCountStepError = DbTaskRunner - .getResultCountPrepareStatement(countStepError); - updateDetailedValue(entry.ordinal(), nbCountStepError); - return; - case nbAllRunningStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countAllRunningStep, - limitDate); - nbCountAllRunningStep = DbTaskRunner - .getResultCountPrepareStatement(countAllRunningStep); - updateDetailedValue(entry.ordinal(), nbCountAllRunningStep); - return; - case nbRunningStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countRunningStep, - limitDate); - nbCountRunningStep = DbTaskRunner - .getResultCountPrepareStatement(countRunningStep); - updateDetailedValue(entry.ordinal(), nbCountRunningStep); - return; - case nbInitOkStep: - DbTaskRunner - .finishSelectOrCountPrepareStatement(countInitOkStep, limitDate); - nbCountInitOkStep = DbTaskRunner - .getResultCountPrepareStatement(countInitOkStep); - updateDetailedValue(entry.ordinal(), nbCountInitOkStep); - return; - case nbPreProcessingOkStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countPreProcessingOkStep, - limitDate); - nbCountPreProcessingOkStep = DbTaskRunner - .getResultCountPrepareStatement(countPreProcessingOkStep); - updateDetailedValue(entry.ordinal(), nbCountPreProcessingOkStep); - return; - case nbTransferOkStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countTransferOkStep, - limitDate); - nbCountTransferOkStep = DbTaskRunner - .getResultCountPrepareStatement(countTransferOkStep); - updateDetailedValue(entry.ordinal(), nbCountTransferOkStep); - return; - case nbPostProcessingOkStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countPostProcessingOkStep, - limitDate); - nbCountPostProcessingOkStep = DbTaskRunner - .getResultCountPrepareStatement(countPostProcessingOkStep); - updateDetailedValue(entry.ordinal(), nbCountPostProcessingOkStep); - return; - case nbCompleteOkStep: - DbTaskRunner.finishSelectOrCountPrepareStatement(countCompleteOkStep, - limitDate); - nbCountCompleteOkStep = DbTaskRunner - .getResultCountPrepareStatement(countCompleteOkStep); - updateDetailedValue(entry.ordinal(), nbCountCompleteOkStep); - return; - } - } catch (WaarpDatabaseNoConnectionException e) { - logger.info("Database No Connection Error: Cannot execute Monitoring", e); - try { - DbModelFactory.dbModel.validConnection(dbSession); - } catch (WaarpDatabaseNoConnectionException e1) { - } - } catch (WaarpDatabaseSqlException e) { - logger.info("Database No Connection Error: Cannot execute Monitoring", e); - try { - DbModelFactory.dbModel.validConnection(dbSession); - } catch (WaarpDatabaseNoConnectionException e1) { - } - } - } - } - - /** - * Update a value in Error MIB part - * - * @param nbMs - * @param entry - */ - protected void run(long nbMs, WaarpErrorValuesIndex entry) { - synchronized (trafficCounter) { - long limitDate = System.currentTimeMillis() - nbMs; - if (dbSession == null || dbSession.isDisconnected) { - return; - } - // Error - switch (entry) { - case nbStatusConnectionImpossible: - nbCountStatusConnectionImpossible = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.ConnectionImpossible, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusConnectionImpossible); - return; - case nbStatusServerOverloaded: - nbCountStatusServerOverloaded = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.ServerOverloaded, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusServerOverloaded); - return; - case nbStatusBadAuthent: - nbCountStatusBadAuthent = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.BadAuthent, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusBadAuthent); - return; - case nbStatusExternalOp: - nbCountStatusExternalOp = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.ExternalOp, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusExternalOp); - return; - case nbStatusTransferError: - nbCountStatusTransferError = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.TransferError, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusTransferError); - return; - case nbStatusMD5Error: - nbCountStatusMD5Error = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.MD5Error, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusMD5Error); - return; - case nbStatusDisconnection: - nbCountStatusDisconnection = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Disconnection, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusDisconnection); - return; - case nbStatusFinalOp: - nbCountStatusFinalOp = DbTaskRunner.getResultCountPrepareStatement(countStatus, - ErrorCode.FinalOp, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusFinalOp); - return; - case nbStatusUnimplemented: - nbCountStatusUnimplemented = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Unimplemented, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusUnimplemented); - return; - case nbStatusInternal: - nbCountStatusInternal = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Internal, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusInternal); - return; - case nbStatusWarning: - nbCountStatusWarning = DbTaskRunner.getResultCountPrepareStatement(countStatus, - ErrorCode.Warning, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusWarning); - return; - case nbStatusQueryAlreadyFinished: - nbCountStatusQueryAlreadyFinished = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.QueryAlreadyFinished, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusQueryAlreadyFinished); - return; - case nbStatusQueryStillRunning: - nbCountStatusQueryStillRunning = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.QueryStillRunning, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusQueryStillRunning); - return; - case nbStatusNotKnownHost: - nbCountStatusNotKnownHost = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.NotKnownHost, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusNotKnownHost); - return; - case nbStatusQueryRemotelyUnknown: - nbCountStatusQueryRemotelyUnknown = DbTaskRunner - .getResultCountPrepareStatement(countStatus, - ErrorCode.QueryRemotelyUnknown, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusQueryRemotelyUnknown); - return; - case nbStatusCommandNotFound: - nbCountStatusCommandNotFound = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.CommandNotFound, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusCommandNotFound); - return; - case nbStatusPassThroughMode: - nbCountStatusPassThroughMode = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.PassThroughMode, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusPassThroughMode); - return; - case nbStatusRemoteShutdown: - nbCountStatusRemoteShutdown = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.RemoteShutdown, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusRemoteShutdown); - return; - case nbStatusShutdown: - nbCountStatusShutdown = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.Shutdown, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusShutdown); - return; - case nbStatusRemoteError: - nbCountStatusRemoteError = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.RemoteError, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusRemoteError); - return; - case nbStatusStopped: - nbCountStatusStopped = DbTaskRunner.getResultCountPrepareStatement(countStatus, - ErrorCode.StoppedTransfer, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusStopped); - return; - case nbStatusCanceled: - nbCountStatusCanceled = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.CanceledTransfer, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusCanceled); - return; - case nbStatusFileNotFound: - nbCountStatusFileNotFound = DbTaskRunner.getResultCountPrepareStatement( - countStatus, - ErrorCode.FileNotFound, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusFileNotFound); - return; - case nbStatusUnknown: - nbCountStatusUnknown = DbTaskRunner.getResultCountPrepareStatement(countStatus, - ErrorCode.Unknown, limitDate); - updateErrorValue(entry.ordinal(), nbCountStatusUnknown); - return; - } - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import java.util.Date; + +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.database.model.DbModelFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.commander.CommanderNoDb; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.snmp.R66PrivateMib; +import org.waarp.snmp.WaarpSnmpAgent; +import org.waarp.snmp.interf.WaarpInterfaceMonitor; +import org.waarp.snmp.r66.WaarpPrivateMib.MibLevel; +import org.waarp.snmp.r66.WaarpPrivateMib.WaarpDetailedValuesIndex; +import org.waarp.snmp.r66.WaarpPrivateMib.WaarpErrorValuesIndex; +import org.waarp.snmp.r66.WaarpPrivateMib.WaarpGlobalValuesIndex; + +/** + * Monitoring class as an helper to get values of interest. Also used by SNMP support. + * + * @author Frederic Bregier + * + */ +public class Monitoring implements WaarpInterfaceMonitor { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(Monitoring.class); + + public WaarpSnmpAgent agent; + + // global informations + public long nbNetworkConnection = 0; + public long secondsRunning = 0; + public long nbThread = 0; + public long bandwidthIn = 0; + public long bandwidthOut = 0; + + // Internal data + private long startMonitor = System.currentTimeMillis(); + private long pastLimit = 0; + private long currentLimit = 0; + private long minimalDelay = 0; + private long lastTry = 0; + private DbSession dbSession = null; + private TrafficCounter trafficCounter = + Configuration.configuration + .getGlobalTrafficShapingHandler() + .getTrafficCounter(); + + // Overall status including past, future and current transfers + private DbPreparedStatement countInfo = null; + + // Current situation of all transfers, running or not + private DbPreparedStatement countInActiveTransfer = null; + private DbPreparedStatement countOutActiveTransfer = null; + private DbPreparedStatement countInTotalTransfer = null; + private DbPreparedStatement countOutTotalTransfer = null; + private DbPreparedStatement countInErrorTransfer = null; + private DbPreparedStatement countOutErrorTransfer = null; + private DbPreparedStatement countStepAllTransfer = null; + private DbPreparedStatement countStepNotask = null; + private DbPreparedStatement countStepPretask = null; + private DbPreparedStatement countStepTransfer = null; + private DbPreparedStatement countStepPosttask = null; + private DbPreparedStatement countStepAllDone = null; + private DbPreparedStatement countStepError = null; + + // First on Running Transfers only + private DbPreparedStatement countAllRunningStep = null; + private DbPreparedStatement countRunningStep = null; + private DbPreparedStatement countInitOkStep = null; + private DbPreparedStatement countPreProcessingOkStep = null; + private DbPreparedStatement countTransferOkStep = null; + private DbPreparedStatement countPostProcessingOkStep = null; + private DbPreparedStatement countCompleteOkStep = null; + + // Error Status on all transfers + private DbPreparedStatement countStatus = null; + + // Overall status including past, future and current transfers + public long nbCountInfoUnknown = 0; + public long nbCountInfoNotUpdated = 0; + public long nbCountInfoInterrupted = 0; + public long nbCountInfoToSubmit = 0; + public long nbCountInfoError = 0; + public long nbCountInfoRunning = 0; + public long nbCountInfoDone = 0; + + public long nbInActiveTransfer = 0; + public long nbOutActiveTransfer = 0; + public long lastInActiveTransfer = System.currentTimeMillis(); + public long lastOutActiveTransfer = System.currentTimeMillis(); + public long nbInTotalTransfer = 0; + public long nbOutTotalTransfer = 0; + public long nbInErrorTransfer = 0; + public long nbOutErrorTransfer = 0; + + // Current situation of all transfers, running or not + public long nbCountStepAllTransfer = 0; + public long nbCountStepNotask = 0; + public long nbCountStepPretask = 0; + public long nbCountStepTransfer = 0; + public long nbCountStepPosttask = 0; + public long nbCountStepAllDone = 0; + public long nbCountStepError = 0; + + // First on Running Transfers only + public long nbCountAllRunningStep = 0; + public long nbCountRunningStep = 0; + public long nbCountInitOkStep = 0; + public long nbCountPreProcessingOkStep = 0; + public long nbCountTransferOkStep = 0; + public long nbCountPostProcessingOkStep = 0; + public long nbCountCompleteOkStep = 0; + + // Error Status on all transfers + public long nbCountStatusConnectionImpossible = 0; + public long nbCountStatusServerOverloaded = 0; + public long nbCountStatusBadAuthent = 0; + public long nbCountStatusExternalOp = 0; + public long nbCountStatusTransferError = 0; + public long nbCountStatusMD5Error = 0; + public long nbCountStatusDisconnection = 0; + public long nbCountStatusFinalOp = 0; + public long nbCountStatusUnimplemented = 0; + public long nbCountStatusInternal = 0; + public long nbCountStatusWarning = 0; + public long nbCountStatusQueryAlreadyFinished = 0; + public long nbCountStatusQueryStillRunning = 0; + public long nbCountStatusNotKnownHost = 0; + public long nbCountStatusQueryRemotelyUnknown = 0; + public long nbCountStatusCommandNotFound = 0; + public long nbCountStatusPassThroughMode = 0; + public long nbCountStatusRemoteShutdown = 0; + public long nbCountStatusShutdown = 0; + public long nbCountStatusRemoteError = 0; + public long nbCountStatusStopped = 0; + public long nbCountStatusCanceled = 0; + public long nbCountStatusFileNotFound = 0; + public long nbCountStatusUnknown = 0; + + /** + * @param pastLimit + * @param minimalDelay + * @param session + */ + public Monitoring(long pastLimit, long minimalDelay, DbSession session) { + this.pastLimit = pastLimit; + this.minimalDelay = minimalDelay; + if (session != null) { + dbSession = session; + } else { + dbSession = DbConstant.admin.session; + } + this.initialize(); + } + + /** + * Initialize the Db Requests after constructor or after use of releaseResources + */ + public void initialize() { + if (dbSession == null || dbSession.isDisconnected) { + logger.warn("Cannot Initialize monitoring"); + return; + } + try { + logger.debug("Initialize monitoring"); + // Overall status including past, future and current transfers + countInfo = DbTaskRunner.getCountInfoPrepareStatement(dbSession); + // Count of Active/All In/Out transfers + countInActiveTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, + true, true); + countOutActiveTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, + false, true); + countInTotalTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, + true, false); + countOutTotalTransfer = DbTaskRunner.getCountInOutRunningPrepareStatement(dbSession, + false, false); + + countInErrorTransfer = DbTaskRunner.getCountInOutErrorPrepareStatement(dbSession, true); + countOutErrorTransfer = DbTaskRunner.getCountInOutErrorPrepareStatement(dbSession, + false); + + // Current situation of all transfers, running or not + countStepAllTransfer = DbTaskRunner.getCountStepPrepareStatement( + dbSession, null); + countStepNotask = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.NOTASK); + countStepPretask = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.PRETASK); + countStepTransfer = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.TRANSFERTASK); + countStepPosttask = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.POSTTASK); + countStepAllDone = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.ALLDONETASK); + countStepError = DbTaskRunner.getCountStepPrepareStatement( + dbSession, TASKSTEP.ERRORTASK); + + // First on Running Transfers only + countAllRunningStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, + null); + countRunningStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, + ErrorCode.Running); + countInitOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, + ErrorCode.InitOk); + countPreProcessingOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement( + dbSession, + ErrorCode.PreProcessingOk); + countTransferOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, + ErrorCode.TransferOk); + countPostProcessingOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement( + dbSession, + ErrorCode.PostProcessingOk); + countCompleteOkStep = DbTaskRunner.getCountStatusRunningPrepareStatement(dbSession, + ErrorCode.CompleteOk); + + // Error Status on all transfers + countStatus = DbTaskRunner.getCountStatusPrepareStatement(dbSession); + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } + } + + /** + * Release all Db Requests + */ + public void releaseResources() { + if (dbSession == null || dbSession.isDisconnected) { + return; + } + try { + logger.debug("Release monitoring"); + // Overall status including past, future and current transfers + countInfo.realClose(); + + countInActiveTransfer.realClose(); + countOutActiveTransfer.realClose(); + countInTotalTransfer.realClose(); + countOutTotalTransfer.realClose(); + countInErrorTransfer.realClose(); + countOutErrorTransfer.realClose(); + + // Current situation of all transfers, running or not + countStepAllTransfer.realClose(); + countStepNotask.realClose(); + countStepPretask.realClose(); + countStepTransfer.realClose(); + countStepPosttask.realClose(); + countStepAllDone.realClose(); + countStepError.realClose(); + + // First on Running Transfers only + countAllRunningStep.realClose(); + countRunningStep.realClose(); + countInitOkStep.realClose(); + countPreProcessingOkStep.realClose(); + countTransferOkStep.realClose(); + countPostProcessingOkStep.realClose(); + countCompleteOkStep.realClose(); + + // Error Status on all transfers + countStatus.realClose(); + } catch (NullPointerException e) { + } + } + + /** + * + * @return the last Time in ms of the execution + */ + public long lastRunTimeMs() { + return lastTry; + } + + /** + * Default execution of testing with default pastLimit + */ + public void run() { + this.run(-1, false); + } + + /** + * + * @param nbSecond + * as specific PastLimit + */ + public void run(long nbSecond) { + this.run(nbSecond, false); + } + + /** + * Default execution of testing with default pastLimit + * + * @param detail + * as to get detailed information + */ + public void run(boolean detail) { + this.run(-1, detail); + } + + /** + * + * @return False if too early, else return True + */ + private boolean reCompute() { + long limitDate = System.currentTimeMillis(); + if (limitDate < lastTry + minimalDelay) { + // too early + return false; + } + lastTry = limitDate; + return true; + } + + /** + * + * @param nbSecond + * as specific PastLimit + * @param detail + * as to get detailed information + */ + public void run(long nbSecond, boolean detail) { + synchronized (trafficCounter) { + long limitDate = System.currentTimeMillis(); + long nbMs = pastLimit; + if (nbSecond <= 0) { + nbMs = pastLimit; + } else { + nbMs = nbSecond * 1000; + } + if (dbSession == null || dbSession.isDisconnected) { + nbNetworkConnection = + Configuration.configuration.getHttpChannelGroup().size() + + Configuration.configuration.getServerChannelGroup().size(); + bandwidthIn = trafficCounter.getLastReadThroughput() >> 7;// B/s -> Kb/s + bandwidthOut = trafficCounter.getLastWriteThroughput() >> 7; + nbThread = Thread.activeCount(); + secondsRunning = (limitDate - startMonitor) / 1000; + + if (!reCompute()) { + // too early + return; + } + limitDate -= nbMs; + currentLimit = limitDate; + // Update value + // Overall status including past, future and current transfers + nbCountInfoToSubmit = CommanderNoDb.todoList.size(); + if (Configuration.configuration.getInternalRunner() != null) { + nbCountInfoRunning = Configuration.configuration.getInternalRunner() + .nbInternalRunner(); + } else { + nbCountInfoRunning = Configuration.configuration.getServerChannelGroup().size(); + } + // Current situation of all transfers, running or not + nbCountAllRunningStep = nbCountInfoRunning; + } else { + nbNetworkConnection = DbAdmin.getNbConnection(); + bandwidthIn = trafficCounter.getLastReadThroughput() >> 7;// B/s -> Kb/s + bandwidthOut = trafficCounter.getLastWriteThroughput() >> 7; + nbThread = Thread.activeCount(); + secondsRunning = (limitDate - startMonitor) / 1000; + + if (!reCompute()) { + // too early + return; + } + limitDate -= nbMs; + currentLimit = limitDate; + // Update value + try { + // Overall status including past, future and current transfers + nbCountInfoUnknown = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.UNKNOWN, limitDate); + nbCountInfoNotUpdated = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.NOTUPDATED, limitDate); + nbCountInfoInterrupted = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.INTERRUPTED, limitDate); + nbCountInfoToSubmit = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.TOSUBMIT, limitDate); + nbCountInfoError = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.INERROR, limitDate); + nbCountInfoRunning = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.RUNNING, limitDate); + nbCountInfoDone = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.DONE, limitDate); + + // Current situation of all transfers, running or not + DbTaskRunner.finishSelectOrCountPrepareStatement(countInActiveTransfer, + limitDate); + nbInActiveTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInActiveTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutActiveTransfer, + limitDate); + nbOutActiveTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutActiveTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countInTotalTransfer, + limitDate); + nbInTotalTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInTotalTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutTotalTransfer, + limitDate); + nbOutTotalTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutTotalTransfer); + + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutErrorTransfer, + limitDate); + nbOutErrorTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutErrorTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countInErrorTransfer, + limitDate); + nbInErrorTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInErrorTransfer); + + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllTransfer, + limitDate); + nbCountStepAllTransfer = DbTaskRunner + .getResultCountPrepareStatement(countStepAllTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepNotask, limitDate); + nbCountStepNotask = DbTaskRunner + .getResultCountPrepareStatement(countStepNotask); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPretask, limitDate); + nbCountStepPretask = DbTaskRunner + .getResultCountPrepareStatement(countStepPretask); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepTransfer, limitDate); + nbCountStepTransfer = DbTaskRunner + .getResultCountPrepareStatement(countStepTransfer); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPosttask, limitDate); + nbCountStepPosttask = DbTaskRunner + .getResultCountPrepareStatement(countStepPosttask); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllDone, limitDate); + nbCountStepAllDone = DbTaskRunner + .getResultCountPrepareStatement(countStepAllDone); + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepError, limitDate); + nbCountStepError = DbTaskRunner.getResultCountPrepareStatement(countStepError); + + DbTaskRunner + .finishSelectOrCountPrepareStatement(countAllRunningStep, limitDate); + nbCountAllRunningStep = DbTaskRunner + .getResultCountPrepareStatement(countAllRunningStep); + + if (detail) { + // First on Running Transfers only + DbTaskRunner.finishSelectOrCountPrepareStatement(countRunningStep, + limitDate); + nbCountRunningStep = DbTaskRunner + .getResultCountPrepareStatement(countRunningStep); + DbTaskRunner + .finishSelectOrCountPrepareStatement(countInitOkStep, limitDate); + nbCountInitOkStep = DbTaskRunner + .getResultCountPrepareStatement(countInitOkStep); + DbTaskRunner.finishSelectOrCountPrepareStatement(countPreProcessingOkStep, + limitDate); + nbCountPreProcessingOkStep = DbTaskRunner + .getResultCountPrepareStatement(countPreProcessingOkStep); + DbTaskRunner.finishSelectOrCountPrepareStatement(countTransferOkStep, + limitDate); + nbCountTransferOkStep = DbTaskRunner + .getResultCountPrepareStatement(countTransferOkStep); + DbTaskRunner.finishSelectOrCountPrepareStatement(countPostProcessingOkStep, + limitDate); + nbCountPostProcessingOkStep = DbTaskRunner + .getResultCountPrepareStatement(countPostProcessingOkStep); + DbTaskRunner.finishSelectOrCountPrepareStatement(countCompleteOkStep, + limitDate); + nbCountCompleteOkStep = DbTaskRunner + .getResultCountPrepareStatement(countCompleteOkStep); + + // Error Status on all transfers + nbCountStatusConnectionImpossible = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.ConnectionImpossible, limitDate); + nbCountStatusServerOverloaded = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.ServerOverloaded, limitDate); + nbCountStatusBadAuthent = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.BadAuthent, limitDate); + nbCountStatusExternalOp = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.ExternalOp, limitDate); + nbCountStatusTransferError = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.TransferError, limitDate); + nbCountStatusMD5Error = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.MD5Error, limitDate); + nbCountStatusDisconnection = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Disconnection, limitDate); + nbCountStatusFinalOp = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.FinalOp, limitDate); + nbCountStatusUnimplemented = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Unimplemented, limitDate); + nbCountStatusInternal = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Internal, limitDate); + nbCountStatusWarning = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Warning, limitDate); + nbCountStatusQueryAlreadyFinished = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.QueryAlreadyFinished, limitDate); + nbCountStatusQueryStillRunning = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.QueryStillRunning, limitDate); + nbCountStatusNotKnownHost = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.NotKnownHost, limitDate); + nbCountStatusQueryRemotelyUnknown = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.QueryRemotelyUnknown, limitDate); + nbCountStatusCommandNotFound = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.CommandNotFound, limitDate); + nbCountStatusPassThroughMode = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.PassThroughMode, limitDate); + nbCountStatusRemoteShutdown = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.RemoteShutdown, limitDate); + nbCountStatusShutdown = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Shutdown, limitDate); + nbCountStatusRemoteError = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.RemoteError, limitDate); + nbCountStatusStopped = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.StoppedTransfer, limitDate); + nbCountStatusCanceled = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.CanceledTransfer, limitDate); + nbCountStatusFileNotFound = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.FileNotFound, limitDate); + nbCountStatusUnknown = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Unknown, limitDate); + } + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } + } + } + } + + /** + * @param detail + * @return The XML representation of the current status + */ + public String exportXml(boolean detail) { + StringBuilder builder = new StringBuilder(); + builder.append(""); + // Global Informations + builder.append(""); + builder.append(Configuration.configuration.HOST_ID); + builder.append(""); + builder.append(""); + builder.append(new Date()); + builder.append(""); + builder.append(""); + builder.append(new Date(lastTry)); + builder.append(""); + builder.append(""); + builder.append(new Date(currentLimit)); + builder.append(""); + builder.append(""); + builder.append(secondsRunning); + builder.append(""); + builder.append(""); + builder.append(nbNetworkConnection); + builder.append(""); + builder.append(""); + builder.append(nbThread); + builder.append(""); + builder.append(""); + builder.append(bandwidthIn); + builder.append(""); + builder.append(""); + builder.append(bandwidthOut); + builder.append(""); + + // Overall status including past, future and current transfers + builder.append(""); + builder.append(""); + builder.append(nbCountStepAllTransfer); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoUnknown); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoNotUpdated); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoInterrupted); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoToSubmit); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoError); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoRunning); + builder.append(""); + builder.append(""); + builder.append(nbCountInfoDone); + builder.append(""); + builder.append(""); + builder.append(nbInActiveTransfer); + builder.append(""); + builder.append(""); + builder.append(nbOutActiveTransfer); + builder.append(""); + builder.append(""); + builder.append((new Date(lastInActiveTransfer)).toString()); + builder.append(""); + builder.append(""); + builder.append((new Date(lastOutActiveTransfer)).toString()); + builder.append(""); + builder.append(""); + builder.append(nbInTotalTransfer); + builder.append(""); + builder.append(""); + builder.append(nbOutTotalTransfer); + builder.append(""); + builder.append(""); + builder.append(nbInErrorTransfer); + builder.append(""); + builder.append(""); + builder.append(nbOutErrorTransfer); + builder.append(""); + builder.append(""); + + // Current situation of all transfers, running or not + builder.append(""); + builder.append(""); + builder.append(nbCountStepNotask); + builder.append(""); + builder.append(""); + builder.append(nbCountStepPretask); + builder.append(""); + builder.append(""); + builder.append(nbCountStepTransfer); + builder.append(""); + builder.append(""); + builder.append(nbCountStepPosttask); + builder.append(""); + builder.append(""); + builder.append(nbCountStepAllDone); + builder.append(""); + builder.append(""); + builder.append(nbCountStepError); + builder.append(""); + builder.append(""); + + // On Running Transfers only + builder.append(""); + builder.append(""); + builder.append(nbCountAllRunningStep); + builder.append(""); + if (detail) { + builder.append(""); + builder.append(nbCountRunningStep); + builder.append(""); + builder.append(""); + builder.append(nbCountInitOkStep); + builder.append(""); + builder.append(""); + builder.append(nbCountPreProcessingOkStep); + builder.append(""); + builder.append(""); + builder.append(nbCountTransferOkStep); + builder.append(""); + builder.append(""); + builder.append(nbCountPostProcessingOkStep); + builder.append(""); + builder.append(""); + builder.append(nbCountCompleteOkStep); + builder.append(""); + } + builder.append(""); + + if (detail) { + // Error Status on all transfers + builder.append(""); + builder.append(""); + builder.append(nbCountStatusConnectionImpossible); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusServerOverloaded); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusBadAuthent); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusExternalOp); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusTransferError); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusMD5Error); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusDisconnection); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusFinalOp); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusUnimplemented); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusInternal); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusWarning); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusQueryAlreadyFinished); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusQueryStillRunning); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusNotKnownHost); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusQueryRemotelyUnknown); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusCommandNotFound); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusPassThroughMode); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusRemoteShutdown); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusShutdown); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusRemoteError); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusStopped); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusCanceled); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusFileNotFound); + builder.append(""); + builder.append(""); + builder.append(nbCountStatusUnknown); + builder.append(""); + builder.append(""); + } + builder.append(""); + return builder.toString(); + } + + public void setAgent(WaarpSnmpAgent agent) { + this.agent = agent; + this.lastInActiveTransfer = this.agent.getUptimeSystemTime(); + this.lastOutActiveTransfer = this.agent.getUptimeSystemTime(); + } + + /** + * Update the value for one particular MIB entry + * + * @param type + * @param entry + */ + public void run(int type, int entry) { + long nbMs = Configuration.configuration.agentSnmp.getUptime() + 100; + MibLevel level = MibLevel.values()[type]; + switch (level) { + case globalInfo:// Global + if (((R66PrivateMib) this.agent.mib).rowGlobal != null) + run(nbMs, WaarpGlobalValuesIndex.values()[entry]); + return; + case detailedInfo:// Detailed + if (((R66PrivateMib) this.agent.mib).rowDetailed != null) + run(nbMs, WaarpDetailedValuesIndex.values()[entry]); + return; + case errorInfo:// Error + if (((R66PrivateMib) this.agent.mib).rowError != null) + run(nbMs, WaarpErrorValuesIndex.values()[entry]); + return; + case staticInfo: + break; + case trapInfo: + break; + default: + break; + } + } + + /** + * Update a value in Global MIB part + * + * @param rank + * @param value + */ + protected void updateGlobalValue(int rank, long value) { + ((R66PrivateMib) this.agent.mib).rowGlobal.setValue(rank, value); + } + + /** + * Update a value in Detailed MIB part + * + * @param rank + * @param value + */ + protected void updateDetailedValue(int rank, long value) { + ((R66PrivateMib) this.agent.mib).rowDetailed.setValue(rank, value); + } + + /** + * Update a value in Error MIB part + * + * @param rank + * @param value + */ + protected void updateErrorValue(int rank, long value) { + ((R66PrivateMib) this.agent.mib).rowError.setValue(rank, value); + } + + /** + * Update a value in Global MIB part + * + * @param nbMs + * @param entry + */ + protected void run(long nbMs, WaarpGlobalValuesIndex entry) { + synchronized (trafficCounter) { + long val = 0; + long limitDate = System.currentTimeMillis() - nbMs; + if (dbSession == null || dbSession.isDisconnected) { + switch (entry) { + case applUptime: + return; + case applOperStatus: + return; + case applLastChange: + return; + case applInboundAssociations: + updateGlobalValue(entry.ordinal(), nbInActiveTransfer); + return; + case applOutboundAssociations: + updateGlobalValue(entry.ordinal(), nbOutActiveTransfer); + return; + case applAccumInboundAssociations: + updateGlobalValue(entry.ordinal(), nbInTotalTransfer); + return; + case applAccumOutboundAssociations: + updateGlobalValue(entry.ordinal(), nbOutTotalTransfer); + return; + case applLastInboundActivity: + val = (lastInActiveTransfer - + this.agent.getUptimeSystemTime()) / 10; + if (val < 0) + val = 0; + updateGlobalValue(entry.ordinal(), val); + return; + case applLastOutboundActivity: + val = (lastOutActiveTransfer - + this.agent.getUptimeSystemTime()) / 10; + if (val < 0) + val = 0; + updateGlobalValue(entry.ordinal(), val); + return; + case applRejectedInboundAssociations: + updateGlobalValue(entry.ordinal(), nbInErrorTransfer); + return; + case applFailedOutboundAssociations: + updateGlobalValue(entry.ordinal(), nbOutErrorTransfer); + return; + case applInboundBandwidthKBS: + val = trafficCounter.getLastReadThroughput() >> 10;// B/s -> KB/s + updateGlobalValue(entry.ordinal(), val); + return; + case applOutboundBandwidthKBS: + val = trafficCounter.getLastWriteThroughput() >> 10; + updateGlobalValue(entry.ordinal(), val); + return; + case nbInfoUnknown: + updateGlobalValue(entry.ordinal(), nbCountInfoUnknown); + return; + case nbInfoNotUpdated: + updateGlobalValue(entry.ordinal(), nbCountInfoNotUpdated); + return; + case nbInfoInterrupted: + updateGlobalValue(entry.ordinal(), nbCountInfoInterrupted); + return; + case nbInfoToSubmit: + nbCountInfoToSubmit = CommanderNoDb.todoList.size(); + updateGlobalValue(entry.ordinal(), nbCountInfoToSubmit); + return; + case nbInfoError: + updateGlobalValue(entry.ordinal(), nbCountInfoError); + return; + case nbInfoRunning: + nbCountInfoRunning = Configuration.configuration.getInternalRunner() + .nbInternalRunner(); + updateGlobalValue(entry.ordinal(), nbCountInfoRunning); + return; + case nbInfoDone: + updateGlobalValue(entry.ordinal(), nbCountInfoDone); + return; + case nbStepAllTransfer: + updateGlobalValue(entry.ordinal(), nbCountStepAllTransfer); + return; + case memoryTotal: + return; + case memoryFree: + return; + case memoryUsed: + return; + case nbThreads: + nbThread = Thread.activeCount(); + updateGlobalValue(entry.ordinal(), nbThread); + return; + case nbNetworkConnection: + nbNetworkConnection = + Configuration.configuration.getHttpChannelGroup().size() + + Configuration.configuration.getServerChannelGroup().size(); + updateGlobalValue(entry.ordinal(), nbNetworkConnection); + return; + } + return; + } + // Global + try { + switch (entry) { + case applUptime: + return; + case applOperStatus: + return; + case applLastChange: + return; + case applInboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countInActiveTransfer, + limitDate); + nbInActiveTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInActiveTransfer); + updateGlobalValue(entry.ordinal(), nbInActiveTransfer); + return; + case applOutboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutActiveTransfer, + limitDate); + nbOutActiveTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutActiveTransfer); + updateGlobalValue(entry.ordinal(), nbOutActiveTransfer); + return; + case applAccumInboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countInTotalTransfer, + limitDate); + nbInTotalTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInTotalTransfer); + updateGlobalValue(entry.ordinal(), nbInTotalTransfer); + return; + case applAccumOutboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutTotalTransfer, + limitDate); + nbOutTotalTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutTotalTransfer); + updateGlobalValue(entry.ordinal(), nbOutTotalTransfer); + return; + case applLastInboundActivity: + val = (lastInActiveTransfer - + this.agent.getUptimeSystemTime()) / 10; + if (val < 0) + val = 0; + updateGlobalValue(entry.ordinal(), val); + return; + case applLastOutboundActivity: + val = (lastOutActiveTransfer - + this.agent.getUptimeSystemTime()) / 10; + if (val < 0) + val = 0; + updateGlobalValue(entry.ordinal(), val); + return; + case applRejectedInboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countInErrorTransfer, + limitDate); + nbInErrorTransfer = DbTaskRunner + .getResultCountPrepareStatement(countInErrorTransfer); + updateGlobalValue(entry.ordinal(), nbInErrorTransfer); + return; + case applFailedOutboundAssociations: + DbTaskRunner.finishSelectOrCountPrepareStatement(countOutErrorTransfer, + limitDate); + nbOutErrorTransfer = DbTaskRunner + .getResultCountPrepareStatement(countOutErrorTransfer); + updateGlobalValue(entry.ordinal(), nbOutErrorTransfer); + return; + case applInboundBandwidthKBS: + val = trafficCounter.getLastReadThroughput() >> 10;// B/s -> KB/s + updateGlobalValue(entry.ordinal(), val); + return; + case applOutboundBandwidthKBS: + val = trafficCounter.getLastWriteThroughput() >> 10; + updateGlobalValue(entry.ordinal(), val); + return; + case nbInfoUnknown: + nbCountInfoUnknown = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.UNKNOWN, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoUnknown); + return; + case nbInfoNotUpdated: + nbCountInfoNotUpdated = DbTaskRunner.getResultCountPrepareStatement( + countInfo, + UpdatedInfo.NOTUPDATED, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoNotUpdated); + return; + case nbInfoInterrupted: + nbCountInfoInterrupted = DbTaskRunner.getResultCountPrepareStatement( + countInfo, + UpdatedInfo.INTERRUPTED, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoInterrupted); + return; + case nbInfoToSubmit: + nbCountInfoToSubmit = DbTaskRunner.getResultCountPrepareStatement( + countInfo, + UpdatedInfo.TOSUBMIT, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoToSubmit); + return; + case nbInfoError: + nbCountInfoError = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.INERROR, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoError); + return; + case nbInfoRunning: + nbCountInfoRunning = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.RUNNING, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoRunning); + return; + case nbInfoDone: + nbCountInfoDone = DbTaskRunner.getResultCountPrepareStatement(countInfo, + UpdatedInfo.DONE, limitDate); + updateGlobalValue(entry.ordinal(), nbCountInfoDone); + return; + case nbStepAllTransfer: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllTransfer, + limitDate); + nbCountStepAllTransfer = DbTaskRunner + .getResultCountPrepareStatement(countStepAllTransfer); + updateGlobalValue(entry.ordinal(), nbCountStepAllTransfer); + return; + case memoryTotal: + return; + case memoryFree: + return; + case memoryUsed: + return; + case nbThreads: + nbThread = Thread.activeCount(); + updateGlobalValue(entry.ordinal(), nbThread); + return; + case nbNetworkConnection: + nbNetworkConnection = DbAdmin.getNbConnection(); + updateGlobalValue(entry.ordinal(), nbNetworkConnection); + return; + } + } catch (WaarpDatabaseNoConnectionException e) { + } catch (WaarpDatabaseSqlException e) { + } + } + } + + /** + * Update a value in Detailed MIB part + * + * @param nbMs + * @param entry + */ + protected void run(long nbMs, WaarpDetailedValuesIndex entry) { + synchronized (trafficCounter) { + long limitDate = System.currentTimeMillis() - nbMs; + if (dbSession == null || dbSession.isDisconnected) { + switch (entry) { + case nbStepNotask: + updateDetailedValue(entry.ordinal(), nbCountStepNotask); + return; + case nbStepPretask: + updateDetailedValue(entry.ordinal(), nbCountStepPretask); + return; + case nbStepTransfer: + updateDetailedValue(entry.ordinal(), nbCountStepTransfer); + return; + case nbStepPosttask: + updateDetailedValue(entry.ordinal(), nbCountStepPosttask); + return; + case nbStepAllDone: + updateDetailedValue(entry.ordinal(), nbCountStepAllDone); + return; + case nbStepError: + updateDetailedValue(entry.ordinal(), nbCountStepError); + return; + case nbAllRunningStep: + nbCountAllRunningStep = Configuration.configuration.getInternalRunner() + .nbInternalRunner(); + updateDetailedValue(entry.ordinal(), nbCountAllRunningStep); + return; + case nbRunningStep: + updateDetailedValue(entry.ordinal(), nbCountRunningStep); + return; + case nbInitOkStep: + updateDetailedValue(entry.ordinal(), nbCountInitOkStep); + return; + case nbPreProcessingOkStep: + updateDetailedValue(entry.ordinal(), nbCountPreProcessingOkStep); + return; + case nbTransferOkStep: + updateDetailedValue(entry.ordinal(), nbCountTransferOkStep); + return; + case nbPostProcessingOkStep: + updateDetailedValue(entry.ordinal(), nbCountPostProcessingOkStep); + return; + case nbCompleteOkStep: + updateDetailedValue(entry.ordinal(), nbCountCompleteOkStep); + return; + } + return; + } + // Detailed + try { + switch (entry) { + case nbStepNotask: + DbTaskRunner + .finishSelectOrCountPrepareStatement(countStepNotask, limitDate); + nbCountStepNotask = DbTaskRunner + .getResultCountPrepareStatement(countStepNotask); + updateDetailedValue(entry.ordinal(), nbCountStepNotask); + return; + case nbStepPretask: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPretask, + limitDate); + nbCountStepPretask = DbTaskRunner + .getResultCountPrepareStatement(countStepPretask); + updateDetailedValue(entry.ordinal(), nbCountStepPretask); + return; + case nbStepTransfer: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepTransfer, + limitDate); + nbCountStepTransfer = DbTaskRunner + .getResultCountPrepareStatement(countStepTransfer); + updateDetailedValue(entry.ordinal(), nbCountStepTransfer); + return; + case nbStepPosttask: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepPosttask, + limitDate); + nbCountStepPosttask = DbTaskRunner + .getResultCountPrepareStatement(countStepPosttask); + updateDetailedValue(entry.ordinal(), nbCountStepPosttask); + return; + case nbStepAllDone: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepAllDone, + limitDate); + nbCountStepAllDone = DbTaskRunner + .getResultCountPrepareStatement(countStepAllDone); + updateDetailedValue(entry.ordinal(), nbCountStepAllDone); + return; + case nbStepError: + DbTaskRunner.finishSelectOrCountPrepareStatement(countStepError, limitDate); + nbCountStepError = DbTaskRunner + .getResultCountPrepareStatement(countStepError); + updateDetailedValue(entry.ordinal(), nbCountStepError); + return; + case nbAllRunningStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countAllRunningStep, + limitDate); + nbCountAllRunningStep = DbTaskRunner + .getResultCountPrepareStatement(countAllRunningStep); + updateDetailedValue(entry.ordinal(), nbCountAllRunningStep); + return; + case nbRunningStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countRunningStep, + limitDate); + nbCountRunningStep = DbTaskRunner + .getResultCountPrepareStatement(countRunningStep); + updateDetailedValue(entry.ordinal(), nbCountRunningStep); + return; + case nbInitOkStep: + DbTaskRunner + .finishSelectOrCountPrepareStatement(countInitOkStep, limitDate); + nbCountInitOkStep = DbTaskRunner + .getResultCountPrepareStatement(countInitOkStep); + updateDetailedValue(entry.ordinal(), nbCountInitOkStep); + return; + case nbPreProcessingOkStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countPreProcessingOkStep, + limitDate); + nbCountPreProcessingOkStep = DbTaskRunner + .getResultCountPrepareStatement(countPreProcessingOkStep); + updateDetailedValue(entry.ordinal(), nbCountPreProcessingOkStep); + return; + case nbTransferOkStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countTransferOkStep, + limitDate); + nbCountTransferOkStep = DbTaskRunner + .getResultCountPrepareStatement(countTransferOkStep); + updateDetailedValue(entry.ordinal(), nbCountTransferOkStep); + return; + case nbPostProcessingOkStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countPostProcessingOkStep, + limitDate); + nbCountPostProcessingOkStep = DbTaskRunner + .getResultCountPrepareStatement(countPostProcessingOkStep); + updateDetailedValue(entry.ordinal(), nbCountPostProcessingOkStep); + return; + case nbCompleteOkStep: + DbTaskRunner.finishSelectOrCountPrepareStatement(countCompleteOkStep, + limitDate); + nbCountCompleteOkStep = DbTaskRunner + .getResultCountPrepareStatement(countCompleteOkStep); + updateDetailedValue(entry.ordinal(), nbCountCompleteOkStep); + return; + } + } catch (WaarpDatabaseNoConnectionException e) { + logger.info("Database No Connection Error: Cannot execute Monitoring", e); + try { + DbModelFactory.dbModel.validConnection(dbSession); + } catch (WaarpDatabaseNoConnectionException e1) { + } + } catch (WaarpDatabaseSqlException e) { + logger.info("Database No Connection Error: Cannot execute Monitoring", e); + try { + DbModelFactory.dbModel.validConnection(dbSession); + } catch (WaarpDatabaseNoConnectionException e1) { + } + } + } + } + + /** + * Update a value in Error MIB part + * + * @param nbMs + * @param entry + */ + protected void run(long nbMs, WaarpErrorValuesIndex entry) { + synchronized (trafficCounter) { + long limitDate = System.currentTimeMillis() - nbMs; + if (dbSession == null || dbSession.isDisconnected) { + return; + } + // Error + switch (entry) { + case nbStatusConnectionImpossible: + nbCountStatusConnectionImpossible = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.ConnectionImpossible, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusConnectionImpossible); + return; + case nbStatusServerOverloaded: + nbCountStatusServerOverloaded = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.ServerOverloaded, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusServerOverloaded); + return; + case nbStatusBadAuthent: + nbCountStatusBadAuthent = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.BadAuthent, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusBadAuthent); + return; + case nbStatusExternalOp: + nbCountStatusExternalOp = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.ExternalOp, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusExternalOp); + return; + case nbStatusTransferError: + nbCountStatusTransferError = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.TransferError, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusTransferError); + return; + case nbStatusMD5Error: + nbCountStatusMD5Error = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.MD5Error, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusMD5Error); + return; + case nbStatusDisconnection: + nbCountStatusDisconnection = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Disconnection, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusDisconnection); + return; + case nbStatusFinalOp: + nbCountStatusFinalOp = DbTaskRunner.getResultCountPrepareStatement(countStatus, + ErrorCode.FinalOp, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusFinalOp); + return; + case nbStatusUnimplemented: + nbCountStatusUnimplemented = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Unimplemented, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusUnimplemented); + return; + case nbStatusInternal: + nbCountStatusInternal = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Internal, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusInternal); + return; + case nbStatusWarning: + nbCountStatusWarning = DbTaskRunner.getResultCountPrepareStatement(countStatus, + ErrorCode.Warning, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusWarning); + return; + case nbStatusQueryAlreadyFinished: + nbCountStatusQueryAlreadyFinished = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.QueryAlreadyFinished, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusQueryAlreadyFinished); + return; + case nbStatusQueryStillRunning: + nbCountStatusQueryStillRunning = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.QueryStillRunning, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusQueryStillRunning); + return; + case nbStatusNotKnownHost: + nbCountStatusNotKnownHost = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.NotKnownHost, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusNotKnownHost); + return; + case nbStatusQueryRemotelyUnknown: + nbCountStatusQueryRemotelyUnknown = DbTaskRunner + .getResultCountPrepareStatement(countStatus, + ErrorCode.QueryRemotelyUnknown, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusQueryRemotelyUnknown); + return; + case nbStatusCommandNotFound: + nbCountStatusCommandNotFound = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.CommandNotFound, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusCommandNotFound); + return; + case nbStatusPassThroughMode: + nbCountStatusPassThroughMode = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.PassThroughMode, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusPassThroughMode); + return; + case nbStatusRemoteShutdown: + nbCountStatusRemoteShutdown = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.RemoteShutdown, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusRemoteShutdown); + return; + case nbStatusShutdown: + nbCountStatusShutdown = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.Shutdown, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusShutdown); + return; + case nbStatusRemoteError: + nbCountStatusRemoteError = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.RemoteError, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusRemoteError); + return; + case nbStatusStopped: + nbCountStatusStopped = DbTaskRunner.getResultCountPrepareStatement(countStatus, + ErrorCode.StoppedTransfer, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusStopped); + return; + case nbStatusCanceled: + nbCountStatusCanceled = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.CanceledTransfer, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusCanceled); + return; + case nbStatusFileNotFound: + nbCountStatusFileNotFound = DbTaskRunner.getResultCountPrepareStatement( + countStatus, + ErrorCode.FileNotFound, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusFileNotFound); + return; + case nbStatusUnknown: + nbCountStatusUnknown = DbTaskRunner.getResultCountPrepareStatement(countStatus, + ErrorCode.Unknown, limitDate); + updateErrorValue(entry.ordinal(), nbCountStatusUnknown); + return; + } + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/RetrieveRunner.java b/src/main/java/org/waarp/openr66/protocol/localhandler/RetrieveRunner.java index 86be733fe..ca14822b8 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/RetrieveRunner.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/RetrieveRunner.java @@ -1,317 +1,317 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFuture; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Retrieve transfer runner - * - * @author Frederic Bregier - * - */ -public class RetrieveRunner extends Thread { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(RetrieveRunner.class); - - private final R66Session session; - - private final LocalChannelReference localChannelReference; - - private final Channel channel; - - private boolean done = false; - - protected AtomicBoolean running = new AtomicBoolean(true); - - protected RetrieveRunner() { - // empty constructor - this.session = null; - this.localChannelReference = null; - this.channel = null; - } - - /** - * - * @param session - * @param channel - * local channel - */ - public RetrieveRunner(R66Session session, Channel channel) { - this.session = session; - localChannelReference = this.session.getLocalChannelReference(); - this.channel = channel; - } - - /** - * Try to stop the runner - */ - public void stopRunner() { - running.set(false); - } - - /* - * (non-Javadoc) - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - boolean requestValidDone = false; - try { - Thread.currentThread().setName("RetrieveRunner: " + channel.getId()); - try { - if (session.getRunner().getGloballaststep() == TASKSTEP.POSTTASK.ordinal()) { - logger.debug("Restart from POSTTASK: EndTransfer"); - // restart from PostTask global step so just end now - try { - ChannelUtils.writeEndTransfer(localChannelReference); - } catch (OpenR66ProtocolPacketException e) { - transferInError(e); - logger.error("End Retrieve in Error"); - return; - } - } else { - logger.debug("Start retrieve operation (send)"); - session.getFile().retrieveBlocking(running); - } - } catch (OpenR66RunnerErrorException e) { - transferInError(e); - logger.info("End Retrieve in Error"); - return; - } catch (OpenR66ProtocolSystemException e) { - transferInError(e); - logger.info("End Retrieve in Error"); - return; - } - if (running.get()) { - try { - localChannelReference.getFutureEndTransfer().await(); - } catch (InterruptedException e1) { - } - } - logger.debug("Await future End Transfer done: " + - localChannelReference.getFutureEndTransfer().isSuccess()); - if (localChannelReference.getFutureEndTransfer().isDone() && - localChannelReference.getFutureEndTransfer().isSuccess()) { - // send a validation - requestValidDone = true; - localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); - EndRequestPacket validPacket = new EndRequestPacket(ErrorCode.CompleteOk.ordinal()); - if (session.getExtendedProtocol() && - session.getBusinessObject() != null && - session.getBusinessObject().getInfo() != null) { - validPacket.setOptional(session.getBusinessObject().getInfo()); - } - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); - } catch (OpenR66ProtocolPacketException e) { - } - if (!localChannelReference.getFutureRequest().awaitUninterruptibly( - Configuration.configuration.TIMEOUTCON)) { - // valid it however - session.getRunner().setAllDone(); - try { - session.getRunner().saveStatus(); - } catch (OpenR66RunnerErrorException e) { - // ignore - } - localChannelReference.validateRequest(localChannelReference - .getFutureEndTransfer().getResult()); - } - if (session.getRunner() != null && session.getRunner().isSelfRequested()) { - ChannelUtils.close(localChannelReference.getLocalChannel()); - } - done = true; - } else { - if (localChannelReference.getFutureEndTransfer().isDone()) { - // Done and Not Success => error - if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { - localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket( - localChannelReference.getErrorMessage(), - localChannelReference.getFutureEndTransfer().getResult().code - .getCode(), - ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, - true); - } catch (OpenR66ProtocolPacketException e) { - } - } - } - if (!localChannelReference.getFutureRequest().isDone()) { - R66Result result = localChannelReference.getFutureEndTransfer().getResult(); - if (result == null) { - result = - new R66Result(session, false, ErrorCode.TransferError, - session.getRunner()); - } - localChannelReference.invalidateRequest(result); - } - done = true; - logger.info("End Retrieve in Error"); - } - } finally { - if (!done) { - if (localChannelReference.getFutureEndTransfer().isDone() && - localChannelReference.getFutureEndTransfer().isSuccess()) { - if (!requestValidDone) { - localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); - EndRequestPacket validPacket = new EndRequestPacket( - ErrorCode.CompleteOk.ordinal()); - if (session.getExtendedProtocol() && - session.getBusinessObject() != null && - session.getBusinessObject().getInfo() != null) { - validPacket.setOptional(session.getBusinessObject().getInfo()); - } - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, - validPacket, true); - } catch (OpenR66ProtocolPacketException e) { - } - } - session.getRunner().setAllDone(); - try { - session.getRunner().saveStatus(); - } catch (OpenR66RunnerErrorException e) { - // ignore - } - localChannelReference.validateRequest(localChannelReference - .getFutureEndTransfer().getResult()); - if (session.getRunner() != null && session.getRunner().isSelfRequested()) { - ChannelUtils.close(localChannelReference.getLocalChannel()); - } - } else { - if (localChannelReference.getFutureEndTransfer().isDone()) { - if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { - localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket( - localChannelReference.getErrorMessage(), - localChannelReference.getFutureEndTransfer().getResult().code - .getCode(), - ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, - true); - } catch (OpenR66ProtocolPacketException e) { - } - } - } else { - R66Result result = localChannelReference.getFutureEndTransfer().getResult(); - if (result == null) { - result = - new R66Result(session, false, ErrorCode.TransferError, - session.getRunner()); - } - localChannelReference.invalidateRequest(result); - } - } - } - NetworkTransaction.normalEndRetrieve(localChannelReference); - } - } - - private void transferInError(OpenR66Exception e) { - R66Result result = new R66Result(e, session, true, - ErrorCode.TransferError, session.getRunner()); - logger.error("Transfer in error", e); - session.newState(R66FiniteDualStates.ERROR); - ErrorPacket error = new ErrorPacket("Transfer in error", - ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e1) { - } - localChannelReference.invalidateRequest(result); - ChannelUtils.close(channel); - done = true; - } - - /** - * Write the next block when the channel is ready to prevent OOM - * - * @param block - * @param localChannelReference - * @return the ChannelFuture on the write operation - * @throws OpenR66ProtocolPacketException - * @throws OpenR66RunnerErrorException - * @throws OpenR66ProtocolSystemException - */ - public static ChannelFuture writeWhenPossible( - DataBlock block, LocalChannelReference localChannelReference) - throws OpenR66ProtocolPacketException, OpenR66RunnerErrorException, - OpenR66ProtocolSystemException { - return ChannelUtils.writeBackDataBlock(localChannelReference, block); - // XXX Keep this in case the bug comes back - /* - * // Test if channel is writable in order to prevent OOM if (! - * localChannelReference.getNetworkChannel().isWritable()) { return - * ChannelUtils.writeBackDataBlock(localChannelReference, block); } else if - * (Configuration.configuration.anyBandwidthLimitation) { // Patch to limit the impact when - * no real reason to wait for writing // double computation of traffic but ok long wait = - * ChannelUtils.willBeWaitingWriting(localChannelReference, block.getByteCount()); if (wait - * == 0) { ChannelUtils.writeBackDataBlock(localChannelReference, block); return - * Channels.succeededFuture(localChannelReference.getNetworkChannel()); } return - * ChannelUtils.writeBackDataBlock(localChannelReference, block); } else { - * ChannelUtils.writeBackDataBlock(localChannelReference, block); return - * Channels.succeededFuture(localChannelReference.getNetworkChannel()); } - */ - } - - /** - * Utility method for send through mode - * - * @param data - * the data byte, if null it is the last block - * @return the DataBlock associated to the data - */ - public static DataBlock transformToDataBlock(byte[] data) { - DataBlock block = new DataBlock(); - if (data == null) { - // last block - block.setEOF(true); - } else { - block.setBlock(ChannelBuffers.wrappedBuffer(data)); - } - return block; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.packet.EndRequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Retrieve transfer runner + * + * @author Frederic Bregier + * + */ +public class RetrieveRunner extends Thread { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(RetrieveRunner.class); + + private final R66Session session; + + private final LocalChannelReference localChannelReference; + + private final Channel channel; + + private boolean done = false; + + protected AtomicBoolean running = new AtomicBoolean(true); + + protected RetrieveRunner() { + // empty constructor + this.session = null; + this.localChannelReference = null; + this.channel = null; + } + + /** + * + * @param session + * @param channel + * local channel + */ + public RetrieveRunner(R66Session session, Channel channel) { + this.session = session; + localChannelReference = this.session.getLocalChannelReference(); + this.channel = channel; + } + + /** + * Try to stop the runner + */ + public void stopRunner() { + running.set(false); + } + + /* + * (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + boolean requestValidDone = false; + try { + Thread.currentThread().setName("RetrieveRunner: " + channel.getId()); + try { + if (session.getRunner().getGloballaststep() == TASKSTEP.POSTTASK.ordinal()) { + logger.debug("Restart from POSTTASK: EndTransfer"); + // restart from PostTask global step so just end now + try { + ChannelUtils.writeEndTransfer(localChannelReference); + } catch (OpenR66ProtocolPacketException e) { + transferInError(e); + logger.error("End Retrieve in Error"); + return; + } + } else { + logger.debug("Start retrieve operation (send)"); + session.getFile().retrieveBlocking(running); + } + } catch (OpenR66RunnerErrorException e) { + transferInError(e); + logger.info("End Retrieve in Error"); + return; + } catch (OpenR66ProtocolSystemException e) { + transferInError(e); + logger.info("End Retrieve in Error"); + return; + } + if (running.get()) { + try { + localChannelReference.getFutureEndTransfer().await(); + } catch (InterruptedException e1) { + } + } + logger.debug("Await future End Transfer done: " + + localChannelReference.getFutureEndTransfer().isSuccess()); + if (localChannelReference.getFutureEndTransfer().isDone() && + localChannelReference.getFutureEndTransfer().isSuccess()) { + // send a validation + requestValidDone = true; + localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); + EndRequestPacket validPacket = new EndRequestPacket(ErrorCode.CompleteOk.ordinal()); + if (session.getExtendedProtocol() && + session.getBusinessObject() != null && + session.getBusinessObject().getInfo() != null) { + validPacket.setOptional(session.getBusinessObject().getInfo()); + } + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, validPacket, true); + } catch (OpenR66ProtocolPacketException e) { + } + if (!localChannelReference.getFutureRequest().awaitUninterruptibly( + Configuration.configuration.TIMEOUTCON)) { + // valid it however + session.getRunner().setAllDone(); + try { + session.getRunner().saveStatus(); + } catch (OpenR66RunnerErrorException e) { + // ignore + } + localChannelReference.validateRequest(localChannelReference + .getFutureEndTransfer().getResult()); + } + if (session.getRunner() != null && session.getRunner().isSelfRequested()) { + ChannelUtils.close(localChannelReference.getLocalChannel()); + } + done = true; + } else { + if (localChannelReference.getFutureEndTransfer().isDone()) { + // Done and Not Success => error + if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { + localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket( + localChannelReference.getErrorMessage(), + localChannelReference.getFutureEndTransfer().getResult().code + .getCode(), + ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, + true); + } catch (OpenR66ProtocolPacketException e) { + } + } + } + if (!localChannelReference.getFutureRequest().isDone()) { + R66Result result = localChannelReference.getFutureEndTransfer().getResult(); + if (result == null) { + result = + new R66Result(session, false, ErrorCode.TransferError, + session.getRunner()); + } + localChannelReference.invalidateRequest(result); + } + done = true; + logger.info("End Retrieve in Error"); + } + } finally { + if (!done) { + if (localChannelReference.getFutureEndTransfer().isDone() && + localChannelReference.getFutureEndTransfer().isSuccess()) { + if (!requestValidDone) { + localChannelReference.sessionNewState(R66FiniteDualStates.ENDREQUESTS); + EndRequestPacket validPacket = new EndRequestPacket( + ErrorCode.CompleteOk.ordinal()); + if (session.getExtendedProtocol() && + session.getBusinessObject() != null && + session.getBusinessObject().getInfo() != null) { + validPacket.setOptional(session.getBusinessObject().getInfo()); + } + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + validPacket, true); + } catch (OpenR66ProtocolPacketException e) { + } + } + session.getRunner().setAllDone(); + try { + session.getRunner().saveStatus(); + } catch (OpenR66RunnerErrorException e) { + // ignore + } + localChannelReference.validateRequest(localChannelReference + .getFutureEndTransfer().getResult()); + if (session.getRunner() != null && session.getRunner().isSelfRequested()) { + ChannelUtils.close(localChannelReference.getLocalChannel()); + } + } else { + if (localChannelReference.getFutureEndTransfer().isDone()) { + if (!localChannelReference.getFutureEndTransfer().getResult().isAnswered) { + localChannelReference.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket( + localChannelReference.getErrorMessage(), + localChannelReference.getFutureEndTransfer().getResult().code + .getCode(), + ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, + true); + } catch (OpenR66ProtocolPacketException e) { + } + } + } else { + R66Result result = localChannelReference.getFutureEndTransfer().getResult(); + if (result == null) { + result = + new R66Result(session, false, ErrorCode.TransferError, + session.getRunner()); + } + localChannelReference.invalidateRequest(result); + } + } + } + NetworkTransaction.normalEndRetrieve(localChannelReference); + } + } + + private void transferInError(OpenR66Exception e) { + R66Result result = new R66Result(e, session, true, + ErrorCode.TransferError, session.getRunner()); + logger.error("Transfer in error", e); + session.newState(R66FiniteDualStates.ERROR); + ErrorPacket error = new ErrorPacket("Transfer in error", + ErrorCode.TransferError.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e1) { + } + localChannelReference.invalidateRequest(result); + ChannelUtils.close(channel); + done = true; + } + + /** + * Write the next block when the channel is ready to prevent OOM + * + * @param block + * @param localChannelReference + * @return the ChannelFuture on the write operation + * @throws OpenR66ProtocolPacketException + * @throws OpenR66RunnerErrorException + * @throws OpenR66ProtocolSystemException + */ + public static ChannelFuture writeWhenPossible( + DataBlock block, LocalChannelReference localChannelReference) + throws OpenR66ProtocolPacketException, OpenR66RunnerErrorException, + OpenR66ProtocolSystemException { + return ChannelUtils.writeBackDataBlock(localChannelReference, block); + // XXX Keep this in case the bug comes back + /* + * // Test if channel is writable in order to prevent OOM if (! + * localChannelReference.getNetworkChannel().isWritable()) { return + * ChannelUtils.writeBackDataBlock(localChannelReference, block); } else if + * (Configuration.configuration.anyBandwidthLimitation) { // Patch to limit the impact when + * no real reason to wait for writing // double computation of traffic but ok long wait = + * ChannelUtils.willBeWaitingWriting(localChannelReference, block.getByteCount()); if (wait + * == 0) { ChannelUtils.writeBackDataBlock(localChannelReference, block); return + * Channels.succeededFuture(localChannelReference.getNetworkChannel()); } return + * ChannelUtils.writeBackDataBlock(localChannelReference, block); } else { + * ChannelUtils.writeBackDataBlock(localChannelReference, block); return + * Channels.succeededFuture(localChannelReference.getNetworkChannel()); } + */ + } + + /** + * Utility method for send through mode + * + * @param data + * the data byte, if null it is the last block + * @return the DataBlock associated to the data + */ + public static DataBlock transformToDataBlock(byte[] data) { + DataBlock block = new DataBlock(); + if (data == null) { + // last block + block.setEOF(true); + } else { + block.setBlock(ChannelBuffers.wrappedBuffer(data)); + } + return block; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/package-info.java b/src/main/java/org/waarp/openr66/protocol/localhandler/package-info.java index c4aff058a..914e06f54 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/package-info.java @@ -1,8 +1,8 @@ -/** - * Classes implementing LocalHandlers (real work) - * - * @apiviz.landmark - * @apiviz.uses {@link org.waarp.openr66.protocol.localhandler.packet} - */ -package org.waarp.openr66.protocol.localhandler; - +/** + * Classes implementing LocalHandlers (real work) + * + * @apiviz.landmark + * @apiviz.uses {@link org.waarp.openr66.protocol.localhandler.packet} + */ +package org.waarp.openr66.protocol.localhandler; + diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AbstractLocalPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AbstractLocalPacket.java index abcd82ba4..148350c8d 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AbstractLocalPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AbstractLocalPacket.java @@ -1,117 +1,117 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * This class represents Abstract Packet with its header, middle and end parts. A Packet is composed - * of one Header part, one Middle part (data), and one End part. Header: length field (4 bytes) = - * Middle length field (4 bytes), End length field (4 bytes), type field (1 byte), ...
- * Middle: (Middle length field bytes)
- * End: (End length field bytes) = code status field (4 bytes), ...
- * - * @author frederic bregier - */ -public abstract class AbstractLocalPacket { - protected ChannelBuffer header; - - protected ChannelBuffer middle; - - protected ChannelBuffer end; - - public AbstractLocalPacket(ChannelBuffer header, ChannelBuffer middle, - ChannelBuffer end) { - this.header = header; - this.middle = middle; - this.end = end; - } - - public AbstractLocalPacket() { - header = null; - middle = null; - end = null; - } - - /** - * Prepare the Header buffer - * - * @throws OpenR66ProtocolPacketException - */ - public abstract void createHeader() throws OpenR66ProtocolPacketException; - - /** - * Prepare the Middle buffer - * - * @throws OpenR66ProtocolPacketException - */ - public abstract void createMiddle() throws OpenR66ProtocolPacketException; - - /** - * Prepare the End buffer - * - * @throws OpenR66ProtocolPacketException - */ - public abstract void createEnd() throws OpenR66ProtocolPacketException; - - /** - * - * @return the type of Packet - */ - public abstract byte getType(); - - @Override - public abstract String toString(); - - /** - * - * @return the ChannelBuffer as LocalPacket - * @throws OpenR66ProtocolPacketException - */ - public ChannelBuffer getLocalPacket() throws OpenR66ProtocolPacketException { - final ChannelBuffer buf = ChannelBuffers.buffer(4 * 3 + 1);// 3 header - // lengths+type - if (header == null) { - createHeader(); - } - final ChannelBuffer newHeader = header != null ? header - : ChannelBuffers.EMPTY_BUFFER; - final int headerLength = 4 * 2 + 1 + newHeader.readableBytes(); - if (middle == null) { - createMiddle(); - } - final ChannelBuffer newMiddle = middle != null ? middle - : ChannelBuffers.EMPTY_BUFFER; - final int middleLength = newMiddle.readableBytes(); - if (end == null) { - createEnd(); - } - final ChannelBuffer newEnd = end != null ? end - : ChannelBuffers.EMPTY_BUFFER; - final int endLength = newEnd.readableBytes(); - buf.writeInt(headerLength); - buf.writeInt(middleLength); - buf.writeInt(endLength); - buf.writeByte(getType()); - final ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer( - buf, newHeader, newMiddle, newEnd); - return channelBuffer; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * This class represents Abstract Packet with its header, middle and end parts. A Packet is composed + * of one Header part, one Middle part (data), and one End part. Header: length field (4 bytes) = + * Middle length field (4 bytes), End length field (4 bytes), type field (1 byte), ...
+ * Middle: (Middle length field bytes)
+ * End: (End length field bytes) = code status field (4 bytes), ...
+ * + * @author frederic bregier + */ +public abstract class AbstractLocalPacket { + protected ChannelBuffer header; + + protected ChannelBuffer middle; + + protected ChannelBuffer end; + + public AbstractLocalPacket(ChannelBuffer header, ChannelBuffer middle, + ChannelBuffer end) { + this.header = header; + this.middle = middle; + this.end = end; + } + + public AbstractLocalPacket() { + header = null; + middle = null; + end = null; + } + + /** + * Prepare the Header buffer + * + * @throws OpenR66ProtocolPacketException + */ + public abstract void createHeader() throws OpenR66ProtocolPacketException; + + /** + * Prepare the Middle buffer + * + * @throws OpenR66ProtocolPacketException + */ + public abstract void createMiddle() throws OpenR66ProtocolPacketException; + + /** + * Prepare the End buffer + * + * @throws OpenR66ProtocolPacketException + */ + public abstract void createEnd() throws OpenR66ProtocolPacketException; + + /** + * + * @return the type of Packet + */ + public abstract byte getType(); + + @Override + public abstract String toString(); + + /** + * + * @return the ChannelBuffer as LocalPacket + * @throws OpenR66ProtocolPacketException + */ + public ChannelBuffer getLocalPacket() throws OpenR66ProtocolPacketException { + final ChannelBuffer buf = ChannelBuffers.buffer(4 * 3 + 1);// 3 header + // lengths+type + if (header == null) { + createHeader(); + } + final ChannelBuffer newHeader = header != null ? header + : ChannelBuffers.EMPTY_BUFFER; + final int headerLength = 4 * 2 + 1 + newHeader.readableBytes(); + if (middle == null) { + createMiddle(); + } + final ChannelBuffer newMiddle = middle != null ? middle + : ChannelBuffers.EMPTY_BUFFER; + final int middleLength = newMiddle.readableBytes(); + if (end == null) { + createEnd(); + } + final ChannelBuffer newEnd = end != null ? end + : ChannelBuffers.EMPTY_BUFFER; + final int endLength = newEnd.readableBytes(); + buf.writeInt(headerLength); + buf.writeInt(middleLength); + buf.writeInt(endLength); + buf.writeByte(getType()); + final ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer( + buf, newHeader, newMiddle, newEnd); + return channelBuffer; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AuthentPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AuthentPacket.java index fbe110a6a..91b68ad1a 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AuthentPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/AuthentPacket.java @@ -1,198 +1,198 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Request Authentication class - * - * header = "hostId" middle = "key bytes" end = localId + way - * - * @author frederic bregier - */ -public class AuthentPacket extends AbstractLocalPacket { - private static final byte ASKVALIDATE = 0; - - private static final byte ANSWERVALIDATE = 1; - - private final Integer localId; - - private byte way; - - private String hostId; - - private byte[] key; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new AuthentPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static AuthentPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (endLength < 5) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength > 0) { - buf.readBytes(bmiddle); - } - Integer newId = buf.readInt(); - byte valid = buf.readByte(); - final String sheader = new String(bheader); - return new AuthentPacket(sheader, bmiddle, newId, valid); - } - - /** - * @param hostId - * @param key - * @param newId - * @param valid - */ - private AuthentPacket(String hostId, byte[] key, Integer newId, byte valid) { - this.hostId = hostId; - this.key = key; - localId = newId; - way = valid; - } - - /** - * @param hostId - * @param key - * @param newId - */ - public AuthentPacket(String hostId, byte[] key, Integer newId) { - this.hostId = hostId; - this.key = key; - localId = newId; - way = ASKVALIDATE; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.buffer(5); - end.writeInt(localId); - end.writeByte(way); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (hostId == null) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - header = ChannelBuffers.wrappedBuffer(hostId.getBytes()); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - if (key == null) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - middle = ChannelBuffers.wrappedBuffer(key); - } - - @Override - public byte getType() { - return LocalPacketFactory.AUTHENTPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "AuthentPacket: " + hostId + " " + localId + " " + way; - } - - /** - * @return the hostId - */ - public String getHostId() { - return hostId; - } - - /** - * @return the key - */ - public byte[] getKey() { - return key; - } - - /** - * @return the localId - */ - public Integer getLocalId() { - return localId; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == ASKVALIDATE; - } - - /** - * Validate the connection - */ - public void validate(boolean isSSL) { - way = ANSWERVALIDATE; - try { - hostId = Configuration.configuration.getHostId(isSSL); - } catch (OpenR66ProtocolNoSslException e) { - hostId = Configuration.configuration.HOST_ID; - } - key = FilesystemBasedDigest.passwdCrypt(Configuration.configuration.HOST_AUTH.getHostkey()); - header = null; - middle = null; - end = null; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Request Authentication class + * + * header = "hostId" middle = "key bytes" end = localId + way + * + * @author frederic bregier + */ +public class AuthentPacket extends AbstractLocalPacket { + private static final byte ASKVALIDATE = 0; + + private static final byte ANSWERVALIDATE = 1; + + private final Integer localId; + + private byte way; + + private String hostId; + + private byte[] key; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new AuthentPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static AuthentPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (endLength < 5) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength > 0) { + buf.readBytes(bmiddle); + } + Integer newId = buf.readInt(); + byte valid = buf.readByte(); + final String sheader = new String(bheader); + return new AuthentPacket(sheader, bmiddle, newId, valid); + } + + /** + * @param hostId + * @param key + * @param newId + * @param valid + */ + private AuthentPacket(String hostId, byte[] key, Integer newId, byte valid) { + this.hostId = hostId; + this.key = key; + localId = newId; + way = valid; + } + + /** + * @param hostId + * @param key + * @param newId + */ + public AuthentPacket(String hostId, byte[] key, Integer newId) { + this.hostId = hostId; + this.key = key; + localId = newId; + way = ASKVALIDATE; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.buffer(5); + end.writeInt(localId); + end.writeByte(way); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (hostId == null) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + header = ChannelBuffers.wrappedBuffer(hostId.getBytes()); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + if (key == null) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + middle = ChannelBuffers.wrappedBuffer(key); + } + + @Override + public byte getType() { + return LocalPacketFactory.AUTHENTPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "AuthentPacket: " + hostId + " " + localId + " " + way; + } + + /** + * @return the hostId + */ + public String getHostId() { + return hostId; + } + + /** + * @return the key + */ + public byte[] getKey() { + return key; + } + + /** + * @return the localId + */ + public Integer getLocalId() { + return localId; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == ASKVALIDATE; + } + + /** + * Validate the connection + */ + public void validate(boolean isSSL) { + way = ANSWERVALIDATE; + try { + hostId = Configuration.configuration.getHostId(isSSL); + } catch (OpenR66ProtocolNoSslException e) { + hostId = Configuration.configuration.HOST_ID; + } + key = FilesystemBasedDigest.passwdCrypt(Configuration.configuration.HOST_AUTH.getHostkey()); + header = null; + middle = null; + end = null; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/BusinessRequestPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/BusinessRequestPacket.java index cae31962e..a0a743ae8 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/BusinessRequestPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/BusinessRequestPacket.java @@ -1,166 +1,166 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Business Request Message class for packet - * - * 1 string and on integer and one byte:
- * - sheader = full text with class at first place - smiddle = integer - send = byte - * - * @author frederic bregier - */ -public class BusinessRequestPacket extends AbstractLocalPacket { - private static final byte ASKVALIDATE = 0; - - private static final byte ANSWERVALIDATE = 1; - private static final byte ANSWERINVALIDATE = 2; - - private String sheader; - - private int delay = 0; - - private byte way; - - public static BusinessRequestPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - final byte[] bheader = new byte[headerLength - 1]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength != 4) { - throw new OpenR66ProtocolPacketException("Packet not correct"); - } - int delay = buf.readInt(); - if (endLength != 1) { - throw new OpenR66ProtocolPacketException("Packet not correct"); - } - byte valid = buf.readByte(); - return new BusinessRequestPacket(new String(bheader), delay, valid); - } - - public BusinessRequestPacket(String header, int delay, byte way) { - this.sheader = header; - this.delay = delay; - this.way = way; - } - - public BusinessRequestPacket(String header, int delay) { - this.sheader = header; - this.delay = delay; - this.way = ASKVALIDATE; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.buffer(1); - end.writeByte(way); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - middle = ChannelBuffers.buffer(4); - middle.writeInt(delay); - } - - @Override - public byte getType() { - return LocalPacketFactory.BUSINESSREQUESTPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "BusinessRequestPacket: " + sheader + ":" + delay + ":" + way; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == ASKVALIDATE; - } - - /** - * Validate the request - */ - public void validate() { - way = ANSWERVALIDATE; - header = null; - middle = null; - end = null; - } - - /** - * Invalidate the request - */ - public void invalidate() { - way = ANSWERINVALIDATE; - header = null; - middle = null; - end = null; - } - - /** - * @return the sheader - */ - public String getSheader() { - return sheader; - } - - /** - * @return the delay - */ - public int getDelay() { - return delay; - } - - /** - * @param delay - * the delay to set - */ - public void setDelay(int delay) { - this.delay = delay; - middle = null; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Business Request Message class for packet + * + * 1 string and on integer and one byte:
+ * - sheader = full text with class at first place - smiddle = integer - send = byte + * + * @author frederic bregier + */ +public class BusinessRequestPacket extends AbstractLocalPacket { + private static final byte ASKVALIDATE = 0; + + private static final byte ANSWERVALIDATE = 1; + private static final byte ANSWERINVALIDATE = 2; + + private String sheader; + + private int delay = 0; + + private byte way; + + public static BusinessRequestPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + final byte[] bheader = new byte[headerLength - 1]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength != 4) { + throw new OpenR66ProtocolPacketException("Packet not correct"); + } + int delay = buf.readInt(); + if (endLength != 1) { + throw new OpenR66ProtocolPacketException("Packet not correct"); + } + byte valid = buf.readByte(); + return new BusinessRequestPacket(new String(bheader), delay, valid); + } + + public BusinessRequestPacket(String header, int delay, byte way) { + this.sheader = header; + this.delay = delay; + this.way = way; + } + + public BusinessRequestPacket(String header, int delay) { + this.sheader = header; + this.delay = delay; + this.way = ASKVALIDATE; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.buffer(1); + end.writeByte(way); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + middle = ChannelBuffers.buffer(4); + middle.writeInt(delay); + } + + @Override + public byte getType() { + return LocalPacketFactory.BUSINESSREQUESTPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "BusinessRequestPacket: " + sheader + ":" + delay + ":" + way; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == ASKVALIDATE; + } + + /** + * Validate the request + */ + public void validate() { + way = ANSWERVALIDATE; + header = null; + middle = null; + end = null; + } + + /** + * Invalidate the request + */ + public void invalidate() { + way = ANSWERINVALIDATE; + header = null; + middle = null; + end = null; + } + + /** + * @return the sheader + */ + public String getSheader() { + return sheader; + } + + /** + * @return the delay + */ + public int getDelay() { + return delay; + } + + /** + * @param delay + * the delay to set + */ + public void setDelay(int delay) { + this.delay = delay; + middle = null; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ConnectionErrorPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ConnectionErrorPacket.java index 81e73a849..6c66abe72 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ConnectionErrorPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ConnectionErrorPacket.java @@ -1,127 +1,127 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Connection Error Message class for packet - * - * 2 strings: sheader,smiddle - * - * @author frederic bregier - */ -public class ConnectionErrorPacket extends AbstractLocalPacket { - - private final String sheader; - - private final String smiddle; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new ErrorPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static ConnectionErrorPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength > 0) { - buf.readBytes(bmiddle); - } - return new ConnectionErrorPacket(new String(bheader), new String( - bmiddle)); - } - - /** - * @param header - * @param middle - */ - public ConnectionErrorPacket(String header, String middle) { - sheader = header; - smiddle = middle; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (sheader != null) { - header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - if (smiddle != null) { - middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "ConnectionErrorPacket: " + sheader + ":" + smiddle; - } - - @Override - public byte getType() { - return LocalPacketFactory.CONNECTERRORPACKET; - } - - /** - * @return the sheader - */ - public String getSheader() { - return sheader; - } - - /** - * @return the smiddle - */ - public String getSmiddle() { - return smiddle; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Connection Error Message class for packet + * + * 2 strings: sheader,smiddle + * + * @author frederic bregier + */ +public class ConnectionErrorPacket extends AbstractLocalPacket { + + private final String sheader; + + private final String smiddle; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new ErrorPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static ConnectionErrorPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength > 0) { + buf.readBytes(bmiddle); + } + return new ConnectionErrorPacket(new String(bheader), new String( + bmiddle)); + } + + /** + * @param header + * @param middle + */ + public ConnectionErrorPacket(String header, String middle) { + sheader = header; + smiddle = middle; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (sheader != null) { + header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + if (smiddle != null) { + middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "ConnectionErrorPacket: " + sheader + ":" + smiddle; + } + + @Override + public byte getType() { + return LocalPacketFactory.CONNECTERRORPACKET; + } + + /** + * @return the sheader + */ + public String getSheader() { + return sheader; + } + + /** + * @return the smiddle + */ + public String getSmiddle() { + return smiddle; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/DataPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/DataPacket.java index a4b694d2a..724914b8d 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/DataPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/DataPacket.java @@ -1,164 +1,164 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.utils.FileUtils; - -/** - * Data packet - * - * header = packetRank middle = data - * - * @author frederic bregier - */ -public class DataPacket extends AbstractLocalPacket { - private final int packetRank; - - private final int lengthPacket; - - private final ChannelBuffer data; - - private final ChannelBuffer key; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new DataPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static DataPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - int packetRank = buf.readInt(); - ChannelBuffer data = buf.readBytes(middleLength); - int readerIndex = buf.readerIndex(); - ChannelBuffer key; - if (endLength > 0) { - key = buf.slice(readerIndex, endLength); - buf.skipBytes(endLength); - } else { - key = ChannelBuffers.EMPTY_BUFFER; - } - return new DataPacket(packetRank, data, key); - } - - /** - * @param packetRank - * @param data - * @param key - */ - public DataPacket(int packetRank, ChannelBuffer data, ChannelBuffer key) { - this.packetRank = packetRank; - this.data = data; - this.key = key == null ? ChannelBuffers.EMPTY_BUFFER : key; - lengthPacket = data.readableBytes(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = key; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - header = ChannelBuffers.buffer(4); - header.writeInt(packetRank); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - middle = data; - } - - @Override - public byte getType() { - return LocalPacketFactory.DATAPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "DataPacket: " + packetRank + ":" + lengthPacket; - } - - /** - * @return the packetRank - */ - public int getPacketRank() { - return packetRank; - } - - /** - * @return the lengthPacket - */ - public int getLengthPacket() { - return lengthPacket; - } - - /** - * @return the data - */ - public ChannelBuffer getData() { - return data; - } - - /** - * @return the key - */ - public ChannelBuffer getKey() { - return key; - } - - /** - * - * @return True if the MD5 key is valid (or no key is set) - */ - public boolean isKeyValid() { - if (key == null || key == ChannelBuffers.EMPTY_BUFFER) { - return true; - } - ChannelBuffer newbufkey = FileUtils.getHash(data); - return ChannelBuffers.equals(key, newbufkey); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.utils.FileUtils; + +/** + * Data packet + * + * header = packetRank middle = data + * + * @author frederic bregier + */ +public class DataPacket extends AbstractLocalPacket { + private final int packetRank; + + private final int lengthPacket; + + private final ChannelBuffer data; + + private final ChannelBuffer key; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new DataPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static DataPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + int packetRank = buf.readInt(); + ChannelBuffer data = buf.readBytes(middleLength); + int readerIndex = buf.readerIndex(); + ChannelBuffer key; + if (endLength > 0) { + key = buf.slice(readerIndex, endLength); + buf.skipBytes(endLength); + } else { + key = ChannelBuffers.EMPTY_BUFFER; + } + return new DataPacket(packetRank, data, key); + } + + /** + * @param packetRank + * @param data + * @param key + */ + public DataPacket(int packetRank, ChannelBuffer data, ChannelBuffer key) { + this.packetRank = packetRank; + this.data = data; + this.key = key == null ? ChannelBuffers.EMPTY_BUFFER : key; + lengthPacket = data.readableBytes(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = key; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + header = ChannelBuffers.buffer(4); + header.writeInt(packetRank); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + middle = data; + } + + @Override + public byte getType() { + return LocalPacketFactory.DATAPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "DataPacket: " + packetRank + ":" + lengthPacket; + } + + /** + * @return the packetRank + */ + public int getPacketRank() { + return packetRank; + } + + /** + * @return the lengthPacket + */ + public int getLengthPacket() { + return lengthPacket; + } + + /** + * @return the data + */ + public ChannelBuffer getData() { + return data; + } + + /** + * @return the key + */ + public ChannelBuffer getKey() { + return key; + } + + /** + * + * @return True if the MD5 key is valid (or no key is set) + */ + public boolean isKeyValid() { + if (key == null || key == ChannelBuffers.EMPTY_BUFFER) { + return true; + } + ChannelBuffer newbufkey = FileUtils.getHash(data); + return ChannelBuffers.equals(key, newbufkey); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndRequestPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndRequestPacket.java index b54fb6bbf..69aaf3bad 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndRequestPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndRequestPacket.java @@ -1,187 +1,187 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import java.nio.charset.Charset; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * End of Request class - * - * header = Error.code middle = way end = might be empty - * - * @author frederic bregier - */ -public class EndRequestPacket extends AbstractLocalPacket { - private static final byte ASKVALIDATE = 0; - - private static final byte ANSWERVALIDATE = 1; - - private final int code; - - private byte way; - - private String optional; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new EndTransferPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static EndRequestPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 != 4) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength != 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final int bheader = buf.readInt(); - byte valid = buf.readByte(); - String optional; - if (endLength > 0) { - optional = buf.toString(buf.readerIndex(), endLength, Charset.defaultCharset()); - buf.skipBytes(endLength); - return new EndRequestPacket(bheader, valid, optional); - } - return new EndRequestPacket(bheader, valid); - } - - /** - * @param code - * @param valid - * @param optional - */ - private EndRequestPacket(int code, byte valid, String optional) { - this.code = code; - way = valid; - this.optional = optional; - } - - /** - * @param code - * @param valid - */ - private EndRequestPacket(int code, byte valid) { - this.code = code; - way = valid; - } - - /** - * @param code - */ - public EndRequestPacket(int code) { - this.code = code; - way = ASKVALIDATE; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() { - if (optional == null) { - end = ChannelBuffers.EMPTY_BUFFER; - } else { - end = ChannelBuffers.copiedBuffer(optional, Charset.defaultCharset()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() { - header = ChannelBuffers.buffer(4); - header.writeInt(code); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() { - byte[] newbytes = { - way }; - middle = ChannelBuffers.wrappedBuffer(newbytes); - } - - @Override - public byte getType() { - return LocalPacketFactory.ENDREQUESTPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "EndRequestPacket: " + code + " " + way + (optional != null ? " " + optional : ""); - } - - /** - * @return the code - */ - public int getCode() { - return code; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == ASKVALIDATE; - } - - /** - * Validate the connection - */ - public void validate() { - way = ANSWERVALIDATE; - header = null; - middle = null; - end = null; - } - - /** - * @return the optional - */ - public String getOptional() { - return optional; - } - - /** - * @param optional - * the optional to set - */ - public void setOptional(String optional) { - this.optional = optional; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import java.nio.charset.Charset; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * End of Request class + * + * header = Error.code middle = way end = might be empty + * + * @author frederic bregier + */ +public class EndRequestPacket extends AbstractLocalPacket { + private static final byte ASKVALIDATE = 0; + + private static final byte ANSWERVALIDATE = 1; + + private final int code; + + private byte way; + + private String optional; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new EndTransferPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static EndRequestPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 != 4) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength != 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final int bheader = buf.readInt(); + byte valid = buf.readByte(); + String optional; + if (endLength > 0) { + optional = buf.toString(buf.readerIndex(), endLength, Charset.defaultCharset()); + buf.skipBytes(endLength); + return new EndRequestPacket(bheader, valid, optional); + } + return new EndRequestPacket(bheader, valid); + } + + /** + * @param code + * @param valid + * @param optional + */ + private EndRequestPacket(int code, byte valid, String optional) { + this.code = code; + way = valid; + this.optional = optional; + } + + /** + * @param code + * @param valid + */ + private EndRequestPacket(int code, byte valid) { + this.code = code; + way = valid; + } + + /** + * @param code + */ + public EndRequestPacket(int code) { + this.code = code; + way = ASKVALIDATE; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() { + if (optional == null) { + end = ChannelBuffers.EMPTY_BUFFER; + } else { + end = ChannelBuffers.copiedBuffer(optional, Charset.defaultCharset()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() { + header = ChannelBuffers.buffer(4); + header.writeInt(code); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() { + byte[] newbytes = { + way }; + middle = ChannelBuffers.wrappedBuffer(newbytes); + } + + @Override + public byte getType() { + return LocalPacketFactory.ENDREQUESTPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "EndRequestPacket: " + code + " " + way + (optional != null ? " " + optional : ""); + } + + /** + * @return the code + */ + public int getCode() { + return code; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == ASKVALIDATE; + } + + /** + * Validate the connection + */ + public void validate() { + way = ANSWERVALIDATE; + header = null; + middle = null; + end = null; + } + + /** + * @return the optional + */ + public String getOptional() { + return optional; + } + + /** + * @param optional + * the optional to set + */ + public void setOptional(String optional) { + this.optional = optional; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndTransferPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndTransferPacket.java index 130eb7426..5991526d8 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndTransferPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/EndTransferPacket.java @@ -1,197 +1,197 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import java.nio.charset.Charset; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * End of Transfer class - * - * header = "request" middle = way end = might be empty - * - * @author frederic bregier - */ -public class EndTransferPacket extends AbstractLocalPacket { - private static final byte ASKVALIDATE = 0; - - private static final byte ANSWERVALIDATE = 1; - - private final byte request; - - private byte way; - - private String hashOptional; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new EndTransferPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static EndTransferPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 != 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength != 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final byte bheader = buf.readByte(); - byte valid = buf.readByte(); - String optional; - if (endLength > 0) { - optional = buf.toString(buf.readerIndex(), endLength, Charset.defaultCharset()); - buf.skipBytes(endLength); - return new EndTransferPacket(bheader, valid, optional); - } - return new EndTransferPacket(bheader, valid); - } - - /** - * @param request - * @param valid - * @param hashOptional - */ - private EndTransferPacket(byte request, byte valid, String hashOptional) { - this.request = request; - way = valid; - this.hashOptional = hashOptional; - } - - /** - * @param request - * @param valid - */ - private EndTransferPacket(byte request, byte valid) { - this.request = request; - way = valid; - } - - /** - * @param request - */ - public EndTransferPacket(byte request) { - this.request = request; - way = ASKVALIDATE; - } - /** - * @param request - * @param hashOptional - */ - public EndTransferPacket(byte request, String hashOptional) { - this.request = request; - way = ASKVALIDATE; - this.hashOptional = hashOptional; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() { - if (hashOptional == null) { - end = ChannelBuffers.EMPTY_BUFFER; - } else { - end = ChannelBuffers.copiedBuffer(hashOptional, Charset.defaultCharset()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() { - byte[] newbytes = { - request }; - header = ChannelBuffers.wrappedBuffer(newbytes); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() { - byte[] newbytes = { - way }; - middle = ChannelBuffers.wrappedBuffer(newbytes); - } - - @Override - public byte getType() { - return LocalPacketFactory.ENDTRANSFERPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "EndTransferPacket: " + request + " " + way + - (hashOptional != null ? " " + hashOptional : ""); - } - - /** - * @return the requestId - */ - public byte getRequest() { - return request; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == ASKVALIDATE; - } - - /** - * Validate the connection - */ - public void validate() { - way = ANSWERVALIDATE; - header = null; - middle = null; - end = null; - } - - /** - * @return the optional - */ - public String getOptional() { - return hashOptional; - } - - /** - * @param optional - * the optional to set - */ - public void setOptional(String optional) { - this.hashOptional = optional; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import java.nio.charset.Charset; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * End of Transfer class + * + * header = "request" middle = way end = might be empty + * + * @author frederic bregier + */ +public class EndTransferPacket extends AbstractLocalPacket { + private static final byte ASKVALIDATE = 0; + + private static final byte ANSWERVALIDATE = 1; + + private final byte request; + + private byte way; + + private String hashOptional; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new EndTransferPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static EndTransferPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 != 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength != 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final byte bheader = buf.readByte(); + byte valid = buf.readByte(); + String optional; + if (endLength > 0) { + optional = buf.toString(buf.readerIndex(), endLength, Charset.defaultCharset()); + buf.skipBytes(endLength); + return new EndTransferPacket(bheader, valid, optional); + } + return new EndTransferPacket(bheader, valid); + } + + /** + * @param request + * @param valid + * @param hashOptional + */ + private EndTransferPacket(byte request, byte valid, String hashOptional) { + this.request = request; + way = valid; + this.hashOptional = hashOptional; + } + + /** + * @param request + * @param valid + */ + private EndTransferPacket(byte request, byte valid) { + this.request = request; + way = valid; + } + + /** + * @param request + */ + public EndTransferPacket(byte request) { + this.request = request; + way = ASKVALIDATE; + } + /** + * @param request + * @param hashOptional + */ + public EndTransferPacket(byte request, String hashOptional) { + this.request = request; + way = ASKVALIDATE; + this.hashOptional = hashOptional; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() { + if (hashOptional == null) { + end = ChannelBuffers.EMPTY_BUFFER; + } else { + end = ChannelBuffers.copiedBuffer(hashOptional, Charset.defaultCharset()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() { + byte[] newbytes = { + request }; + header = ChannelBuffers.wrappedBuffer(newbytes); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() { + byte[] newbytes = { + way }; + middle = ChannelBuffers.wrappedBuffer(newbytes); + } + + @Override + public byte getType() { + return LocalPacketFactory.ENDTRANSFERPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "EndTransferPacket: " + request + " " + way + + (hashOptional != null ? " " + hashOptional : ""); + } + + /** + * @return the requestId + */ + public byte getRequest() { + return request; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == ASKVALIDATE; + } + + /** + * Validate the connection + */ + public void validate() { + way = ANSWERVALIDATE; + header = null; + middle = null; + end = null; + } + + /** + * @return the optional + */ + public String getOptional() { + return hashOptional; + } + + /** + * @param optional + * the optional to set + */ + public void setOptional(String optional) { + this.hashOptional = optional; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ErrorPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ErrorPacket.java index af24f77f5..98d313957 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ErrorPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ErrorPacket.java @@ -1,150 +1,150 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Error Message class for packet - * - * 2 strings+1 error code: sheader,smiddle,code - * - * @author frederic bregier - */ -public class ErrorPacket extends AbstractLocalPacket { - public static final int IGNORECODE = 0; - - public static final int CLOSECODE = 1; - - public static final int FORWARDCODE = 2; - - public static final int FORWARDCLOSECODE = 3; - - private final String sheader; - - private final String smiddle; - - private final int code; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new ErrorPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static ErrorPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength > 0) { - buf.readBytes(bmiddle); - } - if (endLength != 4) { - throw new OpenR66ProtocolPacketException("Packet not correct"); - } - return new ErrorPacket(new String(bheader), new String(bmiddle), buf - .readInt()); - } - - /** - * @param header - * @param middle - * @param code - */ - public ErrorPacket(String header, String middle, int code) { - sheader = header; - smiddle = middle; - this.code = code; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.buffer(4); - end.writeInt(code); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (sheader != null) { - header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - if (smiddle != null) { - middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "ErrorPacket:(" + code + ":" + smiddle + ") " + sheader; - } - - @Override - public byte getType() { - return LocalPacketFactory.ERRORPACKET; - } - - /** - * @return the sheader - */ - public String getSheader() { - return sheader; - } - - /** - * @return the smiddle - */ - public String getSmiddle() { - return smiddle; - } - - /** - * @return the code - */ - public int getCode() { - return code; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Error Message class for packet + * + * 2 strings+1 error code: sheader,smiddle,code + * + * @author frederic bregier + */ +public class ErrorPacket extends AbstractLocalPacket { + public static final int IGNORECODE = 0; + + public static final int CLOSECODE = 1; + + public static final int FORWARDCODE = 2; + + public static final int FORWARDCLOSECODE = 3; + + private final String sheader; + + private final String smiddle; + + private final int code; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new ErrorPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static ErrorPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength > 0) { + buf.readBytes(bmiddle); + } + if (endLength != 4) { + throw new OpenR66ProtocolPacketException("Packet not correct"); + } + return new ErrorPacket(new String(bheader), new String(bmiddle), buf + .readInt()); + } + + /** + * @param header + * @param middle + * @param code + */ + public ErrorPacket(String header, String middle, int code) { + sheader = header; + smiddle = middle; + this.code = code; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.buffer(4); + end.writeInt(code); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (sheader != null) { + header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + if (smiddle != null) { + middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "ErrorPacket:(" + code + ":" + smiddle + ") " + sheader; + } + + @Override + public byte getType() { + return LocalPacketFactory.ERRORPACKET; + } + + /** + * @return the sheader + */ + public String getSheader() { + return sheader; + } + + /** + * @return the smiddle + */ + public String getSmiddle() { + return smiddle; + } + + /** + * @return the code + */ + public int getCode() { + return code; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/InformationPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/InformationPacket.java index c2ec96610..1dc88fb44 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/InformationPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/InformationPacket.java @@ -1,157 +1,157 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Information of files class - * - * header = "rulename" middle = requestedInfo end = "FILENAME" - * - * @author frederic bregier - */ -public class InformationPacket extends AbstractLocalPacket { - - public static enum ASKENUM { - ASKEXIST, ASKMLSDETAIL, ASKLIST, ASKMLSLIST; - } - - private final String rulename; - - private final byte requestedInfo; - - private final String filename; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new EndTransferPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static InformationPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength != 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bend = new byte[endLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - byte request = buf.readByte(); - if (endLength > 0) { - buf.readBytes(bend); - } - final String sheader = new String(bheader); - final String send = new String(bend); - return new InformationPacket(sheader, request, send); - } - - /** - * @param rulename - * @param request - * @param filename - */ - public InformationPacket(String rulename, byte request, String filename) { - this.rulename = rulename; - this.requestedInfo = request; - this.filename = filename; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() { - if (filename != null) { - end = ChannelBuffers.wrappedBuffer(filename.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (rulename == null) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - header = ChannelBuffers.wrappedBuffer(rulename.getBytes()); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() { - byte[] newbytes = { - requestedInfo }; - middle = ChannelBuffers.wrappedBuffer(newbytes); - } - - @Override - public byte getType() { - return LocalPacketFactory.INFORMATIONPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "InformationPacket: " + requestedInfo + " " + rulename + " " + filename; - } - - /** - * @return the requestId - */ - public byte getRequest() { - return requestedInfo; - } - - /** - * @return the rulename - */ - public String getRulename() { - return rulename; - } - - /** - * @return the filename - */ - public String getFilename() { - if (filename != null) { - return filename; - } else { - return ""; - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Information of files class + * + * header = "rulename" middle = requestedInfo end = "FILENAME" + * + * @author frederic bregier + */ +public class InformationPacket extends AbstractLocalPacket { + + public static enum ASKENUM { + ASKEXIST, ASKMLSDETAIL, ASKLIST, ASKMLSLIST; + } + + private final String rulename; + + private final byte requestedInfo; + + private final String filename; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new EndTransferPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static InformationPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength != 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bend = new byte[endLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + byte request = buf.readByte(); + if (endLength > 0) { + buf.readBytes(bend); + } + final String sheader = new String(bheader); + final String send = new String(bend); + return new InformationPacket(sheader, request, send); + } + + /** + * @param rulename + * @param request + * @param filename + */ + public InformationPacket(String rulename, byte request, String filename) { + this.rulename = rulename; + this.requestedInfo = request; + this.filename = filename; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() { + if (filename != null) { + end = ChannelBuffers.wrappedBuffer(filename.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (rulename == null) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + header = ChannelBuffers.wrappedBuffer(rulename.getBytes()); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() { + byte[] newbytes = { + requestedInfo }; + middle = ChannelBuffers.wrappedBuffer(newbytes); + } + + @Override + public byte getType() { + return LocalPacketFactory.INFORMATIONPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "InformationPacket: " + requestedInfo + " " + rulename + " " + filename; + } + + /** + * @return the requestId + */ + public byte getRequest() { + return requestedInfo; + } + + /** + * @return the rulename + */ + public String getRulename() { + return rulename; + } + + /** + * @return the filename + */ + public String getFilename() { + if (filename != null) { + return filename; + } else { + return ""; + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/KeepAlivePacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/KeepAlivePacket.java index 307cb26e3..fede30054 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/KeepAlivePacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/KeepAlivePacket.java @@ -1,128 +1,128 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Keep Alive class - * - * header = empty middle = way end = empty - * - * @author frederic bregier - */ -public class KeepAlivePacket extends AbstractLocalPacket { - private static final byte ASKVALIDATE = 0; - - private static final byte ANSWERVALIDATE = 1; - - private byte way; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new EndTransferPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static KeepAlivePacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (middleLength != 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - byte valid = buf.readByte(); - return new KeepAlivePacket(valid); - } - - /** - * @param valid - */ - private KeepAlivePacket(byte valid) { - way = valid; - } - - /** - */ - public KeepAlivePacket() { - way = ASKVALIDATE; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() { - end = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() { - header = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() { - byte[] newbytes = { - way }; - middle = ChannelBuffers.wrappedBuffer(newbytes); - } - - @Override - public byte getType() { - return LocalPacketFactory.KEEPALIVEPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "KeepAlivePacket: " + way; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == ASKVALIDATE; - } - - /** - * Validate the connection - */ - public void validate() { - way = ANSWERVALIDATE; - header = null; - middle = null; - end = null; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Keep Alive class + * + * header = empty middle = way end = empty + * + * @author frederic bregier + */ +public class KeepAlivePacket extends AbstractLocalPacket { + private static final byte ASKVALIDATE = 0; + + private static final byte ANSWERVALIDATE = 1; + + private byte way; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new EndTransferPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static KeepAlivePacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (middleLength != 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + byte valid = buf.readByte(); + return new KeepAlivePacket(valid); + } + + /** + * @param valid + */ + private KeepAlivePacket(byte valid) { + way = valid; + } + + /** + */ + public KeepAlivePacket() { + way = ASKVALIDATE; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() { + end = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() { + header = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() { + byte[] newbytes = { + way }; + middle = ChannelBuffers.wrappedBuffer(newbytes); + } + + @Override + public byte getType() { + return LocalPacketFactory.KEEPALIVEPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "KeepAlivePacket: " + way; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == ASKVALIDATE; + } + + /** + * Validate the connection + */ + public void validate() { + way = ANSWERVALIDATE; + header = null; + middle = null; + end = null; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketCodec.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketCodec.java index 9d6b7146f..eb206fa6c 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketCodec.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketCodec.java @@ -1,104 +1,104 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelDownstreamHandler; -import org.jboss.netty.channel.ChannelEvent; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.handler.codec.frame.FrameDecoder; -import org.waarp.common.exception.InvalidArgumentException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Local Packet Decoder - * - * @author Frederic Bregier - */ -public class LocalPacketCodec extends FrameDecoder implements - ChannelDownstreamHandler { - - /* - * (non-Javadoc) - * @see org.jboss.netty.handler.codec.frame.FrameDecoder#decode(org.jboss.netty - * .channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, - * org.jboss.netty.buffer.ChannelBuffer) - */ - @Override - protected Object decode(ChannelHandlerContext ctx, Channel channel, - ChannelBuffer buf) throws Exception { - // Make sure if the length field was received. - if (buf.readableBytes() < 4) { - // The length field was not received yet - return null. - // This method will be invoked again when more packets are - // received and appended to the buffer. - return null; - } - return decodeNetworkPacket(buf); - } - - public static AbstractLocalPacket decodeNetworkPacket(ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - // Mark the current buffer position - buf.markReaderIndex(); - // Read the length field - final int length = buf.readInt(); - if (buf.readableBytes() < length) { - buf.resetReaderIndex(); - return null; - } - // Now we can read the header - // Header: Header length field (4 bytes) = Middle length field (4 - // bytes), End length field (4 bytes), type field (1 byte), ... - final int middleLength = buf.readInt(); - final int endLength = buf.readInt(); - // check if the packet is complete - if (middleLength + endLength + length - 8 > buf.readableBytes()) { - buf.resetReaderIndex(); - return null; - } - // createPacketFromChannelBuffer read the buffer - return LocalPacketFactory.createPacketFromChannelBuffer(length - 8, - middleLength, endLength, buf); - } - - public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) - throws Exception { - if (e instanceof MessageEvent) { - final MessageEvent evt = (MessageEvent) e; - if (evt.getMessage() instanceof ChannelBuffer) { - Channels.write(ctx, evt.getFuture(), evt.getMessage()); - return; - } - if (!(evt.getMessage() instanceof AbstractLocalPacket)) { - throw new InvalidArgumentException("Incorrect write object: " + - evt.getMessage().getClass().getName()); - } - final AbstractLocalPacket packet = (AbstractLocalPacket) evt - .getMessage(); - final ChannelBuffer buf = packet.getLocalPacket(); - Channels.write(ctx, evt.getFuture(), buf); - } else { - ctx.sendDownstream(e); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelDownstreamHandler; +import org.jboss.netty.channel.ChannelEvent; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.handler.codec.frame.FrameDecoder; +import org.waarp.common.exception.InvalidArgumentException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Local Packet Decoder + * + * @author Frederic Bregier + */ +public class LocalPacketCodec extends FrameDecoder implements + ChannelDownstreamHandler { + + /* + * (non-Javadoc) + * @see org.jboss.netty.handler.codec.frame.FrameDecoder#decode(org.jboss.netty + * .channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, + * org.jboss.netty.buffer.ChannelBuffer) + */ + @Override + protected Object decode(ChannelHandlerContext ctx, Channel channel, + ChannelBuffer buf) throws Exception { + // Make sure if the length field was received. + if (buf.readableBytes() < 4) { + // The length field was not received yet - return null. + // This method will be invoked again when more packets are + // received and appended to the buffer. + return null; + } + return decodeNetworkPacket(buf); + } + + public static AbstractLocalPacket decodeNetworkPacket(ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + // Mark the current buffer position + buf.markReaderIndex(); + // Read the length field + final int length = buf.readInt(); + if (buf.readableBytes() < length) { + buf.resetReaderIndex(); + return null; + } + // Now we can read the header + // Header: Header length field (4 bytes) = Middle length field (4 + // bytes), End length field (4 bytes), type field (1 byte), ... + final int middleLength = buf.readInt(); + final int endLength = buf.readInt(); + // check if the packet is complete + if (middleLength + endLength + length - 8 > buf.readableBytes()) { + buf.resetReaderIndex(); + return null; + } + // createPacketFromChannelBuffer read the buffer + return LocalPacketFactory.createPacketFromChannelBuffer(length - 8, + middleLength, endLength, buf); + } + + public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) + throws Exception { + if (e instanceof MessageEvent) { + final MessageEvent evt = (MessageEvent) e; + if (evt.getMessage() instanceof ChannelBuffer) { + Channels.write(ctx, evt.getFuture(), evt.getMessage()); + return; + } + if (!(evt.getMessage() instanceof AbstractLocalPacket)) { + throw new InvalidArgumentException("Incorrect write object: " + + evt.getMessage().getClass().getName()); + } + final AbstractLocalPacket packet = (AbstractLocalPacket) evt + .getMessage(); + final ChannelBuffer buf = packet.getLocalPacket(); + Channels.write(ctx, evt.getFuture(), buf); + } else { + ctx.sendDownstream(e); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketFactory.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketFactory.java index 9999bc7f3..5452f91a3 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketFactory.java @@ -1,151 +1,151 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Factory to create Packet according to type from a buffer - * - * @author Frederic Bregier - */ -public class LocalPacketFactory { - public static final byte AUTHENTPACKET = 1; - - public static final byte STARTUPPACKET = 2; - - public static final byte DATAPACKET = 3; - - public static final byte VALIDPACKET = 4; - - public static final byte ERRORPACKET = 5; - - public static final byte CONNECTERRORPACKET = 6; - - public static final byte REQUESTPACKET = 7; - - public static final byte SHUTDOWNPACKET = 8; - - public static final byte STOPPACKET = 9; - - public static final byte CANCELPACKET = 10; - - public static final byte CONFEXPORTPACKET = 11; - - public static final byte CONFIMPORTPACKET = 12; - - public static final byte TESTPACKET = 13; - - public static final byte ENDTRANSFERPACKET = 14; - - public static final byte REQUESTUSERPACKET = 15; - - public static final byte LOGPACKET = 16; - - public static final byte LOGPURGEPACKET = 17; - - public static final byte INFORMATIONPACKET = 18; - - public static final byte BANDWIDTHPACKET = 19; - - public static final byte ENDREQUESTPACKET = 20; - - public static final byte KEEPALIVEPACKET = 21; - // New Protocol message => Extended protocol - public static final byte BUSINESSREQUESTPACKET = 22; - - public static final byte NOOPPACKET = 23; - - /** - * This method create a Packet from the ChannelBuffer. - * - * @param headerLength - * length of the header from the current position of the buffer - * @param middleLength - * @param endLength - * @param buf - * @return the newly created Packet - * @throws OpenR66ProtocolPacketException - */ - public static AbstractLocalPacket createPacketFromChannelBuffer( - int headerLength, int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - final byte packetType = buf.readByte(); - switch (packetType) { - case AUTHENTPACKET: - return AuthentPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case STARTUPPACKET: - return StartupPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case DATAPACKET: - return DataPacket.createFromBuffer(headerLength, middleLength, - endLength, buf); - case VALIDPACKET: - return ValidPacket.createFromBuffer(headerLength, middleLength, - endLength, buf); - case ERRORPACKET: - return ErrorPacket.createFromBuffer(headerLength, middleLength, - endLength, buf); - case CONNECTERRORPACKET: - return ConnectionErrorPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case REQUESTPACKET: - return RequestPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case SHUTDOWNPACKET: - return ShutdownPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case STOPPACKET: - case CANCELPACKET: - case REQUESTUSERPACKET: - case LOGPACKET: - case LOGPURGEPACKET: - case CONFEXPORTPACKET: - case CONFIMPORTPACKET: - case BANDWIDTHPACKET: - throw new OpenR66ProtocolPacketException( - "Unimplemented Packet Type received: " + packetType); - case TESTPACKET: - return TestPacket.createFromBuffer(headerLength, middleLength, - endLength, buf); - case ENDTRANSFERPACKET: - return EndTransferPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case INFORMATIONPACKET: - return InformationPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case ENDREQUESTPACKET: - return EndRequestPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case KEEPALIVEPACKET: - return KeepAlivePacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case BUSINESSREQUESTPACKET: - return BusinessRequestPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - case NOOPPACKET: - return NoOpPacket.createFromBuffer(headerLength, - middleLength, endLength, buf); - default: - throw new OpenR66ProtocolPacketException( - "Unvalid Packet Type received: " + packetType); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Factory to create Packet according to type from a buffer + * + * @author Frederic Bregier + */ +public class LocalPacketFactory { + public static final byte AUTHENTPACKET = 1; + + public static final byte STARTUPPACKET = 2; + + public static final byte DATAPACKET = 3; + + public static final byte VALIDPACKET = 4; + + public static final byte ERRORPACKET = 5; + + public static final byte CONNECTERRORPACKET = 6; + + public static final byte REQUESTPACKET = 7; + + public static final byte SHUTDOWNPACKET = 8; + + public static final byte STOPPACKET = 9; + + public static final byte CANCELPACKET = 10; + + public static final byte CONFEXPORTPACKET = 11; + + public static final byte CONFIMPORTPACKET = 12; + + public static final byte TESTPACKET = 13; + + public static final byte ENDTRANSFERPACKET = 14; + + public static final byte REQUESTUSERPACKET = 15; + + public static final byte LOGPACKET = 16; + + public static final byte LOGPURGEPACKET = 17; + + public static final byte INFORMATIONPACKET = 18; + + public static final byte BANDWIDTHPACKET = 19; + + public static final byte ENDREQUESTPACKET = 20; + + public static final byte KEEPALIVEPACKET = 21; + // New Protocol message => Extended protocol + public static final byte BUSINESSREQUESTPACKET = 22; + + public static final byte NOOPPACKET = 23; + + /** + * This method create a Packet from the ChannelBuffer. + * + * @param headerLength + * length of the header from the current position of the buffer + * @param middleLength + * @param endLength + * @param buf + * @return the newly created Packet + * @throws OpenR66ProtocolPacketException + */ + public static AbstractLocalPacket createPacketFromChannelBuffer( + int headerLength, int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + final byte packetType = buf.readByte(); + switch (packetType) { + case AUTHENTPACKET: + return AuthentPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case STARTUPPACKET: + return StartupPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case DATAPACKET: + return DataPacket.createFromBuffer(headerLength, middleLength, + endLength, buf); + case VALIDPACKET: + return ValidPacket.createFromBuffer(headerLength, middleLength, + endLength, buf); + case ERRORPACKET: + return ErrorPacket.createFromBuffer(headerLength, middleLength, + endLength, buf); + case CONNECTERRORPACKET: + return ConnectionErrorPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case REQUESTPACKET: + return RequestPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case SHUTDOWNPACKET: + return ShutdownPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case STOPPACKET: + case CANCELPACKET: + case REQUESTUSERPACKET: + case LOGPACKET: + case LOGPURGEPACKET: + case CONFEXPORTPACKET: + case CONFIMPORTPACKET: + case BANDWIDTHPACKET: + throw new OpenR66ProtocolPacketException( + "Unimplemented Packet Type received: " + packetType); + case TESTPACKET: + return TestPacket.createFromBuffer(headerLength, middleLength, + endLength, buf); + case ENDTRANSFERPACKET: + return EndTransferPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case INFORMATIONPACKET: + return InformationPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case ENDREQUESTPACKET: + return EndRequestPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case KEEPALIVEPACKET: + return KeepAlivePacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case BUSINESSREQUESTPACKET: + return BusinessRequestPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + case NOOPPACKET: + return NoOpPacket.createFromBuffer(headerLength, + middleLength, endLength, buf); + default: + throw new OpenR66ProtocolPacketException( + "Unvalid Packet Type received: " + packetType); + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketSizeEstimator.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketSizeEstimator.java index 902ee53bc..1fad2d380 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketSizeEstimator.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/LocalPacketSizeEstimator.java @@ -1,46 +1,46 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.util.DefaultObjectSizeEstimator; -import org.jboss.netty.util.ObjectSizeEstimator; - -/** - * Local Packet size estimator - * - * @author Frederic Bregier - * - */ -public class LocalPacketSizeEstimator implements ObjectSizeEstimator { - private DefaultObjectSizeEstimator internal = new DefaultObjectSizeEstimator(); - - /* - * (non-Javadoc) - * @see org.jboss.netty.handler.execution.ObjectSizeEstimator#estimateSize(java .lang.Object) - */ - public int estimateSize(Object o) { - if (!(o instanceof AbstractLocalPacket)) { - // Type unimplemented - return internal.estimateSize(o); - } - AbstractLocalPacket packet = (AbstractLocalPacket) o; - int size = packet.header.readableBytes() + packet.middle.readableBytes() + - packet.end.readableBytes(); - return size; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.util.DefaultObjectSizeEstimator; +import org.jboss.netty.util.ObjectSizeEstimator; + +/** + * Local Packet size estimator + * + * @author Frederic Bregier + * + */ +public class LocalPacketSizeEstimator implements ObjectSizeEstimator { + private DefaultObjectSizeEstimator internal = new DefaultObjectSizeEstimator(); + + /* + * (non-Javadoc) + * @see org.jboss.netty.handler.execution.ObjectSizeEstimator#estimateSize(java .lang.Object) + */ + public int estimateSize(Object o) { + if (!(o instanceof AbstractLocalPacket)) { + // Type unimplemented + return internal.estimateSize(o); + } + AbstractLocalPacket packet = (AbstractLocalPacket) o; + int size = packet.header.readableBytes() + packet.middle.readableBytes() + + packet.end.readableBytes(); + return size; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/NoOpPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/NoOpPacket.java index bda6c44c7..413c6e19d 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/NoOpPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/NoOpPacket.java @@ -1,88 +1,88 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * No Op class - * - * header = empty middle = empty end = empty - * - * @author frederic bregier - */ -public class NoOpPacket extends AbstractLocalPacket { - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new EndTransferPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static NoOpPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - return new NoOpPacket(); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() { - end = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() { - header = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() { - middle = ChannelBuffers.EMPTY_BUFFER; - } - - @Override - public byte getType() { - return LocalPacketFactory.NOOPPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "NoOpPacket"; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * No Op class + * + * header = empty middle = empty end = empty + * + * @author frederic bregier + */ +public class NoOpPacket extends AbstractLocalPacket { + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new EndTransferPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static NoOpPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + return new NoOpPacket(); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() { + end = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() { + header = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() { + middle = ChannelBuffers.EMPTY_BUFFER; + } + + @Override + public byte getType() { + return LocalPacketFactory.NOOPPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "NoOpPacket"; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/RequestPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/RequestPacket.java index 4daa1ebce..581ed093e 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/RequestPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/RequestPacket.java @@ -1,453 +1,453 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Request class - * - * header = "rulename MODETRANS" middle = way+"FILENAME BLOCKSIZE RANK specialId code (optional length)" end = - * "fileInformation" - * - * @author frederic bregier - */ -public class RequestPacket extends AbstractLocalPacket { - public static enum TRANSFERMODE { - UNKNOWNMODE, SENDMODE, RECVMODE, SENDMD5MODE, RECVMD5MODE, - SENDTHROUGHMODE, RECVTHROUGHMODE, SENDMD5THROUGHMODE, RECVMD5THROUGHMODE; - } - - private static final byte REQVALIDATE = 0; - - private static final byte REQANSWERVALIDATE = 1; - - private final String rulename; - - private final int mode; - - private String filename; - - private final int blocksize; - - private int rank; - - private long specialId; - - private byte way; - - private char code; - - private long originalSize; - - private final String fileInformation; - - /** - * - * @param mode - * @return the same mode (RECV or SEND) in MD5 version - */ - public static int getModeMD5(int mode) { - switch (mode) { - case 1: - case 2: - case 5: - case 6: - return mode + 2; - } - return mode; - } - - /** - * - * @param mode - * @return true if this mode is a RECV(MD5) mode - */ - public static boolean isRecvMode(int mode) { - return (mode == TRANSFERMODE.RECVMODE.ordinal() || - mode == TRANSFERMODE.RECVMD5MODE.ordinal() || - mode == TRANSFERMODE.RECVTHROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE - .ordinal()); - } - - /** - * - * @param mode - * @param isRequested - * @return True if this mode is a THROUGH (MD5) mode - */ - public static boolean isSendThroughMode(int mode, boolean isRequested) { - return ((!isRequested && isSendThroughMode(mode)) || (isRequested && isRecvThroughMode(mode))); - } - - /** - * - * @param mode - * @return True if this mode is a SEND THROUGH (MD5) mode - */ - public static boolean isSendThroughMode(int mode) { - return (mode == TRANSFERMODE.SENDTHROUGHMODE.ordinal() || mode == TRANSFERMODE.SENDMD5THROUGHMODE - .ordinal()); - } - - /** - * - * @param mode - * @param isRequested - * @return True if this mode is a THROUGH (MD5) mode - */ - public static boolean isRecvThroughMode(int mode, boolean isRequested) { - return ((!isRequested && isRecvThroughMode(mode)) || (isRequested && isSendThroughMode(mode))); - } - - /** - * - * @param mode - * @return True if this mode is a RECV THROUGH (MD5) mode - */ - public static boolean isRecvThroughMode(int mode) { - return (mode == TRANSFERMODE.RECVTHROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE - .ordinal()); - } - - public static boolean isSendMode(int mode) { - return ! isRecvMode(mode); - } - /** - * - * @param mode - * @return True if this mode is a THROUGH mode (with or without MD5) - */ - public static boolean isThroughMode(int mode) { - return mode >= TRANSFERMODE.SENDTHROUGHMODE.ordinal() && - mode <= TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(); - } - - /** - * - * @param mode - * @return true if this mode is a MD5 mode - */ - public static boolean isMD5Mode(int mode) { - return (mode == TRANSFERMODE.RECVMD5MODE.ordinal() || - mode == TRANSFERMODE.SENDMD5MODE.ordinal() || - mode == TRANSFERMODE.SENDMD5THROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE - .ordinal()); - } - - /** - * - * @param mode1 - * @param mode2 - * @return true if both modes are compatible (both send, or both recv) - */ - public static boolean isCompatibleMode(int mode1, int mode2) { - return ((RequestPacket.isRecvMode(mode1) && RequestPacket.isRecvMode(mode2)) - || ((!RequestPacket.isRecvMode(mode1)) && (!RequestPacket.isRecvMode(mode2)))); - } - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new RequestPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static RequestPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - if (middleLength <= 1) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength - 1]; - final byte[] bend = new byte[endLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - byte valid = buf.readByte(); - if (middleLength > 1) { - buf.readBytes(bmiddle); - } - if (endLength > 0) { - buf.readBytes(bend); - } - final String sheader = new String(bheader); - final String smiddle = new String(bmiddle); - final String send = new String(bend); - final String[] aheader = sheader.split(" "); - if (aheader.length != 2) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final String[] amiddle = smiddle.split(" "); - if (amiddle.length < 5) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - int blocksize = Integer.parseInt(amiddle[1]); - if (blocksize < 100) { - blocksize = Configuration.configuration.BLOCKSIZE; - } - int rank = Integer.parseInt(amiddle[2]); - long specialId = Long.parseLong(amiddle[3]); - char code = amiddle[4].charAt(0); - long originalSize = -1; - if (amiddle.length > 5) { - originalSize = Long.parseLong(amiddle[5]); - } - return new RequestPacket(aheader[0], Integer.parseInt(aheader[1]), - amiddle[0], blocksize, rank, specialId, valid, send, code, originalSize); - } - - /** - * @param rulename - * @param mode - * @param filename - * @param blocksize - * @param rank - * @param specialId - * @param valid - * @param fileInformation - * @param code - * @param originalSize - */ - private RequestPacket(String rulename, int mode, String filename, - int blocksize, int rank, long specialId, byte valid, - String fileInformation, char code, long originalSize) { - this.rulename = rulename; - this.mode = mode; - this.filename = filename; - if (blocksize < 100) { - this.blocksize = Configuration.configuration.BLOCKSIZE; - } else { - this.blocksize = blocksize; - } - this.rank = rank; - this.specialId = specialId; - way = valid; - this.fileInformation = fileInformation; - this.code = code; - this.originalSize = originalSize; - } - - /** - * @param rulename - * @param mode - * @param filename - * @param blocksize - * @param rank - * @param specialId - * @param fileInformation - */ - public RequestPacket(String rulename, int mode, String filename, - int blocksize, int rank, long specialId, String fileInformation, long originalSize) { - this(rulename, mode, filename, blocksize, rank, specialId, - REQVALIDATE, fileInformation, ErrorCode.InitOk.code, originalSize); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - if (fileInformation != null) { - end = ChannelBuffers.wrappedBuffer(fileInformation.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (rulename == null || mode <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - header = ChannelBuffers.wrappedBuffer(rulename.getBytes(), " " - .getBytes(), Integer.toString(mode).getBytes()); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - if (filename == null) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - byte[] away = new byte[1]; - away[0] = way; - middle = ChannelBuffers.wrappedBuffer(away, filename.getBytes(), " " - .getBytes(), Integer.toString(blocksize).getBytes(), " " - .getBytes(), Integer.toString(rank).getBytes(), " ".getBytes(), - Long.toString(specialId).getBytes(), " ".getBytes(), - Character.toString(code).getBytes(), " ".getBytes(), Long.toString(originalSize).getBytes()); - } - - @Override - public byte getType() { - return LocalPacketFactory.REQUESTPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "RequestPacket: " + rulename + " : " + mode + " : " + filename + - " : " + fileInformation + " : " + blocksize + " : " + rank + - " : " + way + " : " + code + " : "+ originalSize; - } - - /** - * @return the rulename - */ - public String getRulename() { - return rulename; - } - - /** - * @return the filename - */ - public String getFilename() { - return filename; - } - - /** - * @return the mode - */ - public int getMode() { - return mode; - } - - /** - * - * @return True if this packet concerns a Retrieve operation - */ - public boolean isRetrieve() { - return isRecvMode(mode); - } - - /** - * @return the fileInformation - */ - public String getFileInformation() { - return fileInformation; - } - - /** - * @return the blocksize - */ - public int getBlocksize() { - return blocksize; - } - - /** - * @return the rank - */ - public int getRank() { - return rank; - } - - /** - * @param rank - * the rank to set - */ - public void setRank(int rank) { - this.rank = rank; - } - - /** - * @return the originalSize - */ - public long getOriginalSize() { - return originalSize; - } - - /** - * @param originalSize the originalSize to set - */ - public void setOriginalSize(long originalSize) { - this.originalSize = originalSize; - } - - /** - * @param specialId - * the specialId to set - */ - public void setSpecialId(long specialId) { - this.specialId = specialId; - } - - /** - * @return the specialId - */ - public long getSpecialId() { - return specialId; - } - - /** - * @return True if this packet is to be validated - */ - public boolean isToValidate() { - return way == REQVALIDATE; - } - - /** - * Validate the request - */ - public void validate() { - way = REQANSWERVALIDATE; - middle = null; - } - - /** - * @param filename - * the filename to set - */ - public void setFilename(String filename) { - this.filename = filename; - } - - /** - * @return the code - */ - public char getCode() { - return code; - } - - /** - * @param code - * the code to set - */ - public void setCode(char code) { - this.code = code; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Request class + * + * header = "rulename MODETRANS" middle = way+"FILENAME BLOCKSIZE RANK specialId code (optional length)" end = + * "fileInformation" + * + * @author frederic bregier + */ +public class RequestPacket extends AbstractLocalPacket { + public static enum TRANSFERMODE { + UNKNOWNMODE, SENDMODE, RECVMODE, SENDMD5MODE, RECVMD5MODE, + SENDTHROUGHMODE, RECVTHROUGHMODE, SENDMD5THROUGHMODE, RECVMD5THROUGHMODE; + } + + private static final byte REQVALIDATE = 0; + + private static final byte REQANSWERVALIDATE = 1; + + private final String rulename; + + private final int mode; + + private String filename; + + private final int blocksize; + + private int rank; + + private long specialId; + + private byte way; + + private char code; + + private long originalSize; + + private final String fileInformation; + + /** + * + * @param mode + * @return the same mode (RECV or SEND) in MD5 version + */ + public static int getModeMD5(int mode) { + switch (mode) { + case 1: + case 2: + case 5: + case 6: + return mode + 2; + } + return mode; + } + + /** + * + * @param mode + * @return true if this mode is a RECV(MD5) mode + */ + public static boolean isRecvMode(int mode) { + return (mode == TRANSFERMODE.RECVMODE.ordinal() || + mode == TRANSFERMODE.RECVMD5MODE.ordinal() || + mode == TRANSFERMODE.RECVTHROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE + .ordinal()); + } + + /** + * + * @param mode + * @param isRequested + * @return True if this mode is a THROUGH (MD5) mode + */ + public static boolean isSendThroughMode(int mode, boolean isRequested) { + return ((!isRequested && isSendThroughMode(mode)) || (isRequested && isRecvThroughMode(mode))); + } + + /** + * + * @param mode + * @return True if this mode is a SEND THROUGH (MD5) mode + */ + public static boolean isSendThroughMode(int mode) { + return (mode == TRANSFERMODE.SENDTHROUGHMODE.ordinal() || mode == TRANSFERMODE.SENDMD5THROUGHMODE + .ordinal()); + } + + /** + * + * @param mode + * @param isRequested + * @return True if this mode is a THROUGH (MD5) mode + */ + public static boolean isRecvThroughMode(int mode, boolean isRequested) { + return ((!isRequested && isRecvThroughMode(mode)) || (isRequested && isSendThroughMode(mode))); + } + + /** + * + * @param mode + * @return True if this mode is a RECV THROUGH (MD5) mode + */ + public static boolean isRecvThroughMode(int mode) { + return (mode == TRANSFERMODE.RECVTHROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE + .ordinal()); + } + + public static boolean isSendMode(int mode) { + return ! isRecvMode(mode); + } + /** + * + * @param mode + * @return True if this mode is a THROUGH mode (with or without MD5) + */ + public static boolean isThroughMode(int mode) { + return mode >= TRANSFERMODE.SENDTHROUGHMODE.ordinal() && + mode <= TRANSFERMODE.RECVMD5THROUGHMODE.ordinal(); + } + + /** + * + * @param mode + * @return true if this mode is a MD5 mode + */ + public static boolean isMD5Mode(int mode) { + return (mode == TRANSFERMODE.RECVMD5MODE.ordinal() || + mode == TRANSFERMODE.SENDMD5MODE.ordinal() || + mode == TRANSFERMODE.SENDMD5THROUGHMODE.ordinal() || mode == TRANSFERMODE.RECVMD5THROUGHMODE + .ordinal()); + } + + /** + * + * @param mode1 + * @param mode2 + * @return true if both modes are compatible (both send, or both recv) + */ + public static boolean isCompatibleMode(int mode1, int mode2) { + return ((RequestPacket.isRecvMode(mode1) && RequestPacket.isRecvMode(mode2)) + || ((!RequestPacket.isRecvMode(mode1)) && (!RequestPacket.isRecvMode(mode2)))); + } + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new RequestPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static RequestPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + if (middleLength <= 1) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength - 1]; + final byte[] bend = new byte[endLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + byte valid = buf.readByte(); + if (middleLength > 1) { + buf.readBytes(bmiddle); + } + if (endLength > 0) { + buf.readBytes(bend); + } + final String sheader = new String(bheader); + final String smiddle = new String(bmiddle); + final String send = new String(bend); + final String[] aheader = sheader.split(" "); + if (aheader.length != 2) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final String[] amiddle = smiddle.split(" "); + if (amiddle.length < 5) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + int blocksize = Integer.parseInt(amiddle[1]); + if (blocksize < 100) { + blocksize = Configuration.configuration.BLOCKSIZE; + } + int rank = Integer.parseInt(amiddle[2]); + long specialId = Long.parseLong(amiddle[3]); + char code = amiddle[4].charAt(0); + long originalSize = -1; + if (amiddle.length > 5) { + originalSize = Long.parseLong(amiddle[5]); + } + return new RequestPacket(aheader[0], Integer.parseInt(aheader[1]), + amiddle[0], blocksize, rank, specialId, valid, send, code, originalSize); + } + + /** + * @param rulename + * @param mode + * @param filename + * @param blocksize + * @param rank + * @param specialId + * @param valid + * @param fileInformation + * @param code + * @param originalSize + */ + private RequestPacket(String rulename, int mode, String filename, + int blocksize, int rank, long specialId, byte valid, + String fileInformation, char code, long originalSize) { + this.rulename = rulename; + this.mode = mode; + this.filename = filename; + if (blocksize < 100) { + this.blocksize = Configuration.configuration.BLOCKSIZE; + } else { + this.blocksize = blocksize; + } + this.rank = rank; + this.specialId = specialId; + way = valid; + this.fileInformation = fileInformation; + this.code = code; + this.originalSize = originalSize; + } + + /** + * @param rulename + * @param mode + * @param filename + * @param blocksize + * @param rank + * @param specialId + * @param fileInformation + */ + public RequestPacket(String rulename, int mode, String filename, + int blocksize, int rank, long specialId, String fileInformation, long originalSize) { + this(rulename, mode, filename, blocksize, rank, specialId, + REQVALIDATE, fileInformation, ErrorCode.InitOk.code, originalSize); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + if (fileInformation != null) { + end = ChannelBuffers.wrappedBuffer(fileInformation.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (rulename == null || mode <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + header = ChannelBuffers.wrappedBuffer(rulename.getBytes(), " " + .getBytes(), Integer.toString(mode).getBytes()); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + if (filename == null) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + byte[] away = new byte[1]; + away[0] = way; + middle = ChannelBuffers.wrappedBuffer(away, filename.getBytes(), " " + .getBytes(), Integer.toString(blocksize).getBytes(), " " + .getBytes(), Integer.toString(rank).getBytes(), " ".getBytes(), + Long.toString(specialId).getBytes(), " ".getBytes(), + Character.toString(code).getBytes(), " ".getBytes(), Long.toString(originalSize).getBytes()); + } + + @Override + public byte getType() { + return LocalPacketFactory.REQUESTPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "RequestPacket: " + rulename + " : " + mode + " : " + filename + + " : " + fileInformation + " : " + blocksize + " : " + rank + + " : " + way + " : " + code + " : "+ originalSize; + } + + /** + * @return the rulename + */ + public String getRulename() { + return rulename; + } + + /** + * @return the filename + */ + public String getFilename() { + return filename; + } + + /** + * @return the mode + */ + public int getMode() { + return mode; + } + + /** + * + * @return True if this packet concerns a Retrieve operation + */ + public boolean isRetrieve() { + return isRecvMode(mode); + } + + /** + * @return the fileInformation + */ + public String getFileInformation() { + return fileInformation; + } + + /** + * @return the blocksize + */ + public int getBlocksize() { + return blocksize; + } + + /** + * @return the rank + */ + public int getRank() { + return rank; + } + + /** + * @param rank + * the rank to set + */ + public void setRank(int rank) { + this.rank = rank; + } + + /** + * @return the originalSize + */ + public long getOriginalSize() { + return originalSize; + } + + /** + * @param originalSize the originalSize to set + */ + public void setOriginalSize(long originalSize) { + this.originalSize = originalSize; + } + + /** + * @param specialId + * the specialId to set + */ + public void setSpecialId(long specialId) { + this.specialId = specialId; + } + + /** + * @return the specialId + */ + public long getSpecialId() { + return specialId; + } + + /** + * @return True if this packet is to be validated + */ + public boolean isToValidate() { + return way == REQVALIDATE; + } + + /** + * Validate the request + */ + public void validate() { + way = REQANSWERVALIDATE; + middle = null; + } + + /** + * @param filename + * the filename to set + */ + public void setFilename(String filename) { + this.filename = filename; + } + + /** + * @return the code + */ + public char getCode() { + return code; + } + + /** + * @param code + * the code to set + */ + public void setCode(char code) { + this.code = code; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ShutdownPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ShutdownPacket.java index 286a2f29c..08d24f7ec 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ShutdownPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ShutdownPacket.java @@ -1,112 +1,112 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Shutdown Message class for packet - * - * 1 string: spassword(or key) - * - * @author frederic bregier - */ -public class ShutdownPacket extends AbstractLocalPacket { - private final byte[] key; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new ShutdownPacket from buffer - * @throws OpenR66ProtocolPacketException - */ - public static ShutdownPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) - throws OpenR66ProtocolPacketException { - if (headerLength - 1 <= 0) { - throw new OpenR66ProtocolPacketException("Not enough data"); - } - final byte[] bpassword = new byte[headerLength - 1]; - if (headerLength - 1 > 0) { - buf.readBytes(bpassword); - } - return new ShutdownPacket(bpassword); - } - - /** - * @param spassword - */ - public ShutdownPacket(byte[] spassword) { - key = spassword; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (key != null) { - header = ChannelBuffers.wrappedBuffer(key); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - middle = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "ShutdownPacket"; - } - - @Override - public byte getType() { - return LocalPacketFactory.SHUTDOWNPACKET; - } - - /** - * @return the key - */ - public byte[] getKey() { - return key; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Shutdown Message class for packet + * + * 1 string: spassword(or key) + * + * @author frederic bregier + */ +public class ShutdownPacket extends AbstractLocalPacket { + private final byte[] key; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new ShutdownPacket from buffer + * @throws OpenR66ProtocolPacketException + */ + public static ShutdownPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) + throws OpenR66ProtocolPacketException { + if (headerLength - 1 <= 0) { + throw new OpenR66ProtocolPacketException("Not enough data"); + } + final byte[] bpassword = new byte[headerLength - 1]; + if (headerLength - 1 > 0) { + buf.readBytes(bpassword); + } + return new ShutdownPacket(bpassword); + } + + /** + * @param spassword + */ + public ShutdownPacket(byte[] spassword) { + key = spassword; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (key != null) { + header = ChannelBuffers.wrappedBuffer(key); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + middle = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "ShutdownPacket"; + } + + @Override + public byte getType() { + return LocalPacketFactory.SHUTDOWNPACKET; + } + + /** + * @return the key + */ + public byte[] getKey() { + return key; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/StartupPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/StartupPacket.java index 3141965de..a07b71b3b 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/StartupPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/StartupPacket.java @@ -1,103 +1,103 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Startup Message class - * - * 1 localId (Integer): localId - * - * @author frederic bregier - */ -public class StartupPacket extends AbstractLocalPacket { - private final Integer localId; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new ValidPacket from buffer - */ - public static StartupPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) { - Integer newId = buf.readInt(); - return new StartupPacket(newId); - } - - /** - * @param newId - */ - public StartupPacket(Integer newId) { - localId = newId; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - header = ChannelBuffers.buffer(4); - header.writeInt(localId); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - middle = ChannelBuffers.EMPTY_BUFFER; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "StartupPacket: " + localId; - } - - @Override - public byte getType() { - return LocalPacketFactory.STARTUPPACKET; - } - - /** - * @return the localId - */ - public Integer getLocalId() { - return localId; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Startup Message class + * + * 1 localId (Integer): localId + * + * @author frederic bregier + */ +public class StartupPacket extends AbstractLocalPacket { + private final Integer localId; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new ValidPacket from buffer + */ + public static StartupPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) { + Integer newId = buf.readInt(); + return new StartupPacket(newId); + } + + /** + * @param newId + */ + public StartupPacket(Integer newId) { + localId = newId; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + header = ChannelBuffers.buffer(4); + header.writeInt(localId); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + middle = ChannelBuffers.EMPTY_BUFFER; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "StartupPacket: " + localId; + } + + @Override + public byte getType() { + return LocalPacketFactory.STARTUPPACKET; + } + + /** + * @return the localId + */ + public Integer getLocalId() { + return localId; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/TestPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/TestPacket.java index bb1799cca..51b2c4154 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/TestPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/TestPacket.java @@ -1,109 +1,109 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Test class for packet - * - * 3 strings: sheader,smiddle,send - * - * @author frederic bregier - */ -public class TestPacket extends AbstractLocalPacket { - public static final int pingpong = 100; - - private final String sheader; - - private final String smiddle; - - private int code = 0; - - public static TestPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) { - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength]; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength > 0) { - buf.readBytes(bmiddle); - } - return new TestPacket(new String(bheader), new String(bmiddle), buf - .readInt()); - } - - public TestPacket(String header, String middle, int code) { - sheader = header; - smiddle = middle; - this.code = code; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.buffer(4); - end.writeInt(code); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); - } - - @Override - public byte getType() { - if (code > pingpong) { - return LocalPacketFactory.VALIDPACKET; - } - return LocalPacketFactory.TESTPACKET; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "TestPacket: " + sheader + ":" + smiddle + ":" + code; - } - - public void update() { - code++; - end = null; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Test class for packet + * + * 3 strings: sheader,smiddle,send + * + * @author frederic bregier + */ +public class TestPacket extends AbstractLocalPacket { + public static final int pingpong = 100; + + private final String sheader; + + private final String smiddle; + + private int code = 0; + + public static TestPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) { + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength]; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength > 0) { + buf.readBytes(bmiddle); + } + return new TestPacket(new String(bheader), new String(bmiddle), buf + .readInt()); + } + + public TestPacket(String header, String middle, int code) { + sheader = header; + smiddle = middle; + this.code = code; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.buffer(4); + end.writeInt(code); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); + } + + @Override + public byte getType() { + if (code > pingpong) { + return LocalPacketFactory.VALIDPACKET; + } + return LocalPacketFactory.TESTPACKET; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "TestPacket: " + sheader + ":" + smiddle + ":" + code; + } + + public void update() { + code++; + end = null; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ValidPacket.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ValidPacket.java index 31895ff31..eb1e819ec 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ValidPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/ValidPacket.java @@ -1,147 +1,147 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.localhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; - -/** - * Validation Message class for packet - * - * 2 strings and one byte: sheader,smiddle,send - * - * @author frederic bregier - */ -public class ValidPacket extends AbstractLocalPacket { - private final String sheader; - - private String smiddle; - - private final byte send; - - /** - * @param headerLength - * @param middleLength - * @param endLength - * @param buf - * @return the new ValidPacket from buffer - */ - public static ValidPacket createFromBuffer(int headerLength, - int middleLength, int endLength, ChannelBuffer buf) { - final byte[] bheader = new byte[headerLength - 1]; - final byte[] bmiddle = new byte[middleLength]; - final byte bend; - if (headerLength - 1 > 0) { - buf.readBytes(bheader); - } - if (middleLength > 0) { - buf.readBytes(bmiddle); - } - bend = buf.readByte(); - return new ValidPacket(new String(bheader), new String(bmiddle), bend); - } - - /** - * @param header - * @param middle - * @param end - */ - public ValidPacket(String header, String middle, byte end) { - sheader = header; - smiddle = middle; - send = end; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() - */ - @Override - public void createEnd() throws OpenR66ProtocolPacketException { - end = ChannelBuffers.buffer(1); - end.writeByte(send); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() - */ - @Override - public void createHeader() throws OpenR66ProtocolPacketException { - if (sheader != null) { - header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() - */ - @Override - public void createMiddle() throws OpenR66ProtocolPacketException { - if (smiddle != null) { - middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() - */ - @Override - public String toString() { - return "ValidPacket: " + sheader + ":" + smiddle + ":" + send; - } - - @Override - public byte getType() { - return LocalPacketFactory.VALIDPACKET; - } - - /** - * @return the sheader - */ - public String getSheader() { - return sheader; - } - - /** - * @return the smiddle - */ - public String getSmiddle() { - return smiddle; - } - - /** - * - * @param smiddle - */ - public void setSmiddle(String smiddle) { - this.smiddle = smiddle; - middle = null; - } - - /** - * @return the type - */ - public byte getTypeValid() { - return send; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.localhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; + +/** + * Validation Message class for packet + * + * 2 strings and one byte: sheader,smiddle,send + * + * @author frederic bregier + */ +public class ValidPacket extends AbstractLocalPacket { + private final String sheader; + + private String smiddle; + + private final byte send; + + /** + * @param headerLength + * @param middleLength + * @param endLength + * @param buf + * @return the new ValidPacket from buffer + */ + public static ValidPacket createFromBuffer(int headerLength, + int middleLength, int endLength, ChannelBuffer buf) { + final byte[] bheader = new byte[headerLength - 1]; + final byte[] bmiddle = new byte[middleLength]; + final byte bend; + if (headerLength - 1 > 0) { + buf.readBytes(bheader); + } + if (middleLength > 0) { + buf.readBytes(bmiddle); + } + bend = buf.readByte(); + return new ValidPacket(new String(bheader), new String(bmiddle), bend); + } + + /** + * @param header + * @param middle + * @param end + */ + public ValidPacket(String header, String middle, byte end) { + sheader = header; + smiddle = middle; + send = end; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createEnd() + */ + @Override + public void createEnd() throws OpenR66ProtocolPacketException { + end = ChannelBuffers.buffer(1); + end.writeByte(send); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createHeader() + */ + @Override + public void createHeader() throws OpenR66ProtocolPacketException { + if (sheader != null) { + header = ChannelBuffers.wrappedBuffer(sheader.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#createMiddle() + */ + @Override + public void createMiddle() throws OpenR66ProtocolPacketException { + if (smiddle != null) { + middle = ChannelBuffers.wrappedBuffer(smiddle.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket#toString() + */ + @Override + public String toString() { + return "ValidPacket: " + sheader + ":" + smiddle + ":" + send; + } + + @Override + public byte getType() { + return LocalPacketFactory.VALIDPACKET; + } + + /** + * @return the sheader + */ + public String getSheader() { + return sheader; + } + + /** + * @return the smiddle + */ + public String getSmiddle() { + return smiddle; + } + + /** + * + * @param smiddle + */ + public void setSmiddle(String smiddle) { + this.smiddle = smiddle; + middle = null; + } + + /** + * @return the type + */ + public byte getTypeValid() { + return send; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/package-info.java b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/package-info.java index a6b883919..8df9aa2c5 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/packet/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/packet/package-info.java @@ -1,6 +1,6 @@ -/** - * Classes implementing Packet for Local Handlers - * - */ -package org.waarp.openr66.protocol.localhandler.packet; - +/** + * Classes implementing Packet for Local Handlers + * + */ +package org.waarp.openr66.protocol.localhandler.packet; + diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/ChannelTrafficHandler.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/ChannelTrafficHandler.java index 170ddc159..2bb714d2a 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/ChannelTrafficHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/ChannelTrafficHandler.java @@ -1,65 +1,65 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.jboss.netty.util.ObjectSizeEstimator; -import org.jboss.netty.util.Timer; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; - -/** - * @author Frederic Bregier - * - */ -public class ChannelTrafficHandler extends ChannelTrafficShapingHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ChannelTrafficHandler.class); - - /** - * @param objectSizeEstimator - * @param timer - * @param writeLimit - * @param readLimit - * @param checkInterval - */ - public ChannelTrafficHandler(ObjectSizeEstimator objectSizeEstimator, - Timer timer, long writeLimit, long readLimit, - long checkInterval) { - super(objectSizeEstimator, timer, writeLimit, readLimit, - checkInterval); - } - - /* - * (non-Javadoc) - * @see - * org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler#doAccounting(org.jboss.netty - * .handler.traffic.TrafficCounter) - */ - @SuppressWarnings("unused") - @Override - protected void doAccounting(TrafficCounter counter) { - if (false) - logger.debug(this.toString() + "\n {}", counter); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.jboss.netty.util.ObjectSizeEstimator; +import org.jboss.netty.util.Timer; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; + +/** + * @author Frederic Bregier + * + */ +public class ChannelTrafficHandler extends ChannelTrafficShapingHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ChannelTrafficHandler.class); + + /** + * @param objectSizeEstimator + * @param timer + * @param writeLimit + * @param readLimit + * @param checkInterval + */ + public ChannelTrafficHandler(ObjectSizeEstimator objectSizeEstimator, + Timer timer, long writeLimit, long readLimit, + long checkInterval) { + super(objectSizeEstimator, timer, writeLimit, readLimit, + checkInterval); + } + + /* + * (non-Javadoc) + * @see + * org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler#doAccounting(org.jboss.netty + * .handler.traffic.TrafficCounter) + */ + @SuppressWarnings("unused") + @Override + protected void doAccounting(TrafficCounter counter) { + if (false) + logger.debug(this.toString() + "\n {}", counter); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/ClientNetworkChannels.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/ClientNetworkChannels.java index df04f1c4b..8f00f60f5 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/ClientNetworkChannels.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/ClientNetworkChannels.java @@ -1,73 +1,73 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import java.util.HashSet; - -/** - * Client NetworkChannel attached to one HostId. - * - * - * - * This class is used to keep information for one HostID when it connects as client to the current - * Host. As one Id can be shared or one can use direct send, so having a connection by request, this - * class is useful when one wants to know who is connected and how many times. - * - * - * @author Frederic Bregier - * - */ -public class ClientNetworkChannels { - - private final String hostId; - private final HashSet networkChannels = new HashSet(); - - public ClientNetworkChannels(String hostId) { - this.hostId = hostId; - } - - public void add(NetworkChannel networkChannel) { - networkChannels.add(networkChannel); - } - - public void remove(NetworkChannel networkChannel) { - networkChannels.remove(networkChannel); - } - - public boolean isEmpty() { - return networkChannels.isEmpty(); - } - - public int size() { - return networkChannels.size(); - } - - public boolean shutdownAll() { - boolean status = false; - for (NetworkChannel networkChannel : networkChannels) { - NetworkTransaction.shuttingdownNetworkChannel(networkChannel.channel); - status = true; - } - networkChannels.clear(); - return status; - } - - public String getHostId() { - return hostId; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import java.util.HashSet; + +/** + * Client NetworkChannel attached to one HostId. + * + * + * + * This class is used to keep information for one HostID when it connects as client to the current + * Host. As one Id can be shared or one can use direct send, so having a connection by request, this + * class is useful when one wants to know who is connected and how many times. + * + * + * @author Frederic Bregier + * + */ +public class ClientNetworkChannels { + + private final String hostId; + private final HashSet networkChannels = new HashSet(); + + public ClientNetworkChannels(String hostId) { + this.hostId = hostId; + } + + public void add(NetworkChannel networkChannel) { + networkChannels.add(networkChannel); + } + + public void remove(NetworkChannel networkChannel) { + networkChannels.remove(networkChannel); + } + + public boolean isEmpty() { + return networkChannels.isEmpty(); + } + + public int size() { + return networkChannels.size(); + } + + public boolean shutdownAll() { + boolean status = false; + for (NetworkChannel networkChannel : networkChannels) { + NetworkTransaction.shuttingdownNetworkChannel(networkChannel.channel); + status = true; + } + networkChannels.clear(); + return status; + } + + public String getHostId() { + return hostId; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/GlobalTrafficHandler.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/GlobalTrafficHandler.java index 96f0204e2..eb6496f31 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/GlobalTrafficHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/GlobalTrafficHandler.java @@ -1,67 +1,67 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.jboss.netty.util.ObjectSizeEstimator; -import org.jboss.netty.util.Timer; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; - -/** - * Global function - * - * @author Frederic Bregier - * - */ -public class GlobalTrafficHandler extends GlobalTrafficShapingHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(GlobalTrafficHandler.class); - - /** - * @param objectSizeEstimator - * @param timer - * @param writeLimit - * @param readLimit - * @param checkInterval - */ - public GlobalTrafficHandler(ObjectSizeEstimator objectSizeEstimator, - Timer timer, long writeLimit, long readLimit, - long checkInterval) { - super(objectSizeEstimator, timer, writeLimit, readLimit, - checkInterval); - } - - /* - * (non-Javadoc) - * @see - * org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler#doAccounting(org.jboss.netty - * .handler.traffic.TrafficCounter) - */ - @SuppressWarnings("unused") - @Override - protected void doAccounting(TrafficCounter counter) { - if (false) - logger.debug(this.toString() + "\n {}", counter); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.jboss.netty.util.ObjectSizeEstimator; +import org.jboss.netty.util.Timer; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; + +/** + * Global function + * + * @author Frederic Bregier + * + */ +public class GlobalTrafficHandler extends GlobalTrafficShapingHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(GlobalTrafficHandler.class); + + /** + * @param objectSizeEstimator + * @param timer + * @param writeLimit + * @param readLimit + * @param checkInterval + */ + public GlobalTrafficHandler(ObjectSizeEstimator objectSizeEstimator, + Timer timer, long writeLimit, long readLimit, + long checkInterval) { + super(objectSizeEstimator, timer, writeLimit, readLimit, + checkInterval); + } + + /* + * (non-Javadoc) + * @see + * org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler#doAccounting(org.jboss.netty + * .handler.traffic.TrafficCounter) + */ + @SuppressWarnings("unused") + @Override + protected void doAccounting(TrafficCounter counter) { + if (false) + logger.debug(this.toString() + "\n {}", counter); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkChannel.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkChannel.java index 795ec4d9b..b7010f864 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkChannel.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkChannel.java @@ -1,114 +1,114 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.Channels; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; - -/** - * NetworkChannel object to keep Network channel open while some local channels are attached to it. - * - * @author Frederic Bregier - * - */ -public class NetworkChannel { - /** - * Number of active Local Channel referencing this Network Channel - */ - public volatile AtomicInteger count = new AtomicInteger(1); - /** - * Does this Network Channel is in shutdown - */ - public volatile boolean isShuttingDown = false; - /** - * Associated LocalChannel - */ - public ConcurrentLinkedQueue localChannels = - new ConcurrentLinkedQueue(); - /** - * Network Channel - */ - public final Channel channel; - /** - * Last Time in ms this channel was used by a LocalChannel - */ - public long lastTimeUsed; - - public NetworkChannel(Channel networkChannel) { - this.channel = networkChannel; - } - - synchronized public void add(Channel localChannel) - throws OpenR66ProtocolRemoteShutdownException { - if (isShuttingDown) { - throw new OpenR66ProtocolRemoteShutdownException("Current NetworkChannel is closed"); - } - lastTimeUsed = System.currentTimeMillis(); - localChannels.add(localChannel); - } - - synchronized public void remove(Channel localChannel) { - if (localChannel.isConnected()) { - Channels.close(localChannel); - } - localChannels.remove(localChannel); - } - - synchronized public void shutdownAllLocalChannels() { - isShuttingDown = true; - count.set(0); - Channel localChannel = localChannels.poll(); - while (localChannel != null) { - Channels.close(localChannel); - localChannel = localChannels.poll(); - } - } - - @Override - public String toString() { - return "NC: " + channel.isConnected() + " " + - channel.getRemoteAddress() + " Count: " + count; - } - - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof NetworkChannel) { - NetworkChannel obj2 = (NetworkChannel) obj; - return (obj2.channel.getId() == this.channel.getId()); - } - return false; - } - - /* - * (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return this.channel.getId(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.Channels; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; + +/** + * NetworkChannel object to keep Network channel open while some local channels are attached to it. + * + * @author Frederic Bregier + * + */ +public class NetworkChannel { + /** + * Number of active Local Channel referencing this Network Channel + */ + public volatile AtomicInteger count = new AtomicInteger(1); + /** + * Does this Network Channel is in shutdown + */ + public volatile boolean isShuttingDown = false; + /** + * Associated LocalChannel + */ + public ConcurrentLinkedQueue localChannels = + new ConcurrentLinkedQueue(); + /** + * Network Channel + */ + public final Channel channel; + /** + * Last Time in ms this channel was used by a LocalChannel + */ + public long lastTimeUsed; + + public NetworkChannel(Channel networkChannel) { + this.channel = networkChannel; + } + + synchronized public void add(Channel localChannel) + throws OpenR66ProtocolRemoteShutdownException { + if (isShuttingDown) { + throw new OpenR66ProtocolRemoteShutdownException("Current NetworkChannel is closed"); + } + lastTimeUsed = System.currentTimeMillis(); + localChannels.add(localChannel); + } + + synchronized public void remove(Channel localChannel) { + if (localChannel.isConnected()) { + Channels.close(localChannel); + } + localChannels.remove(localChannel); + } + + synchronized public void shutdownAllLocalChannels() { + isShuttingDown = true; + count.set(0); + Channel localChannel = localChannels.poll(); + while (localChannel != null) { + Channels.close(localChannel); + localChannel = localChannels.poll(); + } + } + + @Override + public String toString() { + return "NC: " + channel.isConnected() + " " + + channel.getRemoteAddress() + " Count: " + count; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof NetworkChannel) { + NetworkChannel obj2 = (NetworkChannel) obj; + return (obj2.channel.getId() == this.channel.getId()); + } + return false; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return this.channel.getId(); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerHandler.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerHandler.java index 2e33938e4..dd71b4298 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerHandler.java @@ -1,415 +1,415 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import java.net.BindException; -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler; -import org.jboss.netty.handler.timeout.IdleStateEvent; -import org.jboss.netty.handler.timeout.ReadTimeoutException; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; -import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.KeepAlivePacket; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; -import org.waarp.openr66.protocol.utils.ChannelCloseTimer; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Network Server Handler (Requester side) - * - * @author frederic bregier - */ -public class NetworkServerHandler extends IdleStateAwareChannelHandler { - // extends SimpleChannelHandler { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(NetworkServerHandler.class); - - /** - * The underlying Network Channel - */ - private volatile Channel networkChannel; - /** - * The associated Remote Address - */ - private volatile SocketAddress remoteAddress; - /** - * The Database connection attached to this NetworkChannel shared among all associated - * LocalChannels - */ - protected volatile DbSession dbSession; - /** - * Does this Handler is for SSL - */ - protected volatile boolean isSSL = false; - /** - * Is this Handler a server side - */ - protected boolean isServer = false; - /** - * To handle the keep alive - */ - protected volatile boolean keepAlivedSent = false; - - /** - * - * @param isServer - */ - public NetworkServerHandler(boolean isServer) { - this.isServer = isServer; - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. - * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { - if (NetworkTransaction.getNbLocalChannel(e.getChannel()) > 0) { - logger.info("Network Channel Closed: {} LocalChannels Left: {}", - e.getChannel().getId(), - NetworkTransaction.getNbLocalChannel(e.getChannel())); - // close if necessary the local channel - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e1) { - } - Configuration.configuration.getLocalTransaction() - .closeLocalChannelsFromNetworkChannel(e.getChannel()); - } - if (remoteAddress == null) { - remoteAddress = e.getChannel().getRemoteAddress(); - } - NetworkTransaction.removeForceNetworkChannel(remoteAddress); - // Now force the close of the database after a wait - if (dbSession != null && dbSession.internalId != DbConstant.admin.session.internalId) { - dbSession.disconnect(); - dbSession = null; - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) - throws OpenR66ProtocolNetworkException { - this.networkChannel = e.getChannel(); - this.remoteAddress = this.networkChannel.getRemoteAddress(); - try { - if (DbConstant.admin.isConnected) { - this.dbSession = new DbSession(DbConstant.admin, false); - } - } catch (WaarpDatabaseNoConnectionException e1) { - // Cannot connect so use default connection - logger.warn("Use default database connection"); - this.dbSession = DbConstant.admin.session; - } - logger.debug("Network Channel Connected: {} ", e.getChannel().getId()); - } - - /* - * (non-Javadoc) - * @see - * org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler#channelIdle(org.jboss.netty. - * channel.ChannelHandlerContext, org.jboss.netty.handler.timeout.IdleStateEvent) - */ - @Override - public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) - throws Exception { - if (Configuration.configuration.isShutdown) - return; - if (keepAlivedSent) { - logger.error("Not getting KAlive: closing channel"); - if (Configuration.configuration.r66Mib != null) { - Configuration.configuration.r66Mib.notifyWarning( - "KeepAlive get no answer", "Closing network connection"); - } - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - } else { - keepAlivedSent = true; - KeepAlivePacket keepAlivePacket = new KeepAlivePacket(); - NetworkPacket response = - new NetworkPacket(ChannelUtils.NOCHANNEL, - ChannelUtils.NOCHANNEL, keepAlivePacket); - logger.info("Write KAlive"); - Channels.write(e.getChannel(), response); - } - } - - public void setKeepAlivedSent() { - keepAlivedSent = false; - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) - */ - @Override - public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { - final NetworkPacket packet = (NetworkPacket) e.getMessage(); - if (packet.getCode() == LocalPacketFactory.NOOPPACKET) { - // Do nothing - return; - } else if (packet.getCode() == LocalPacketFactory.CONNECTERRORPACKET) { - logger.debug("NetworkRecv: {}", packet); - // Special code to STOP here - if (packet.getLocalId() == ChannelUtils.NOCHANNEL) { - // No way to know what is wrong: close all connections with - // remote host - logger - .error("Will close NETWORK channel, Cannot continue connection with remote Host: " - + - packet.toString() + - " : " + - e.getChannel().getRemoteAddress()); - WaarpSslUtility.closingSslChannel(e.getChannel()); - return; - } - } else if (packet.getCode() == LocalPacketFactory.KEEPALIVEPACKET) { - keepAlivedSent = false; - try { - KeepAlivePacket keepAlivePacket = (KeepAlivePacket) - LocalPacketCodec.decodeNetworkPacket(packet.getBuffer()); - if (keepAlivePacket.isToValidate()) { - keepAlivePacket.validate(); - NetworkPacket response = - new NetworkPacket(ChannelUtils.NOCHANNEL, - ChannelUtils.NOCHANNEL, keepAlivePacket); - logger.info("Answer KAlive"); - Channels.write(e.getChannel(), response); - } else { - logger.info("Get KAlive"); - } - } catch (OpenR66ProtocolPacketException e1) { - } - return; - } - LocalChannelReference localChannelReference = null; - if (packet.getLocalId() == ChannelUtils.NOCHANNEL) { - logger.debug("NetworkRecv Create: {} {}", packet, - e.getChannel().getId()); - try { - localChannelReference = - NetworkTransaction.createConnectionFromNetworkChannelStartup( - e.getChannel(), packet); - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Cannot create LocalChannel for: " + packet + " due to " - + e1.getMessage()); - final ConnectionErrorPacket error = new ConnectionErrorPacket( - "Cannot connect to localChannel since cannot create it", null); - writeError(e.getChannel(), packet.getRemoteId(), packet - .getLocalId(), error); - NetworkTransaction.removeNetworkChannel(e.getChannel(), null, null); - return; - } catch (OpenR66ProtocolRemoteShutdownException e1) { - logger.warn("Will Close Local from Network Channel"); - Configuration.configuration.getLocalTransaction() - .closeLocalChannelsFromNetworkChannel(e.getChannel()); - WaarpSslUtility.closingSslChannel(e.getChannel()); - // NetworkTransaction.removeForceNetworkChannel(e.getChannel()); - // ignore since no more valid - return; - } - } else { - if (packet.getCode() == LocalPacketFactory.ENDREQUESTPACKET) { - // Not a local error but a remote one - try { - localChannelReference = Configuration.configuration - .getLocalTransaction().getClient(packet.getRemoteId(), - packet.getLocalId()); - } catch (OpenR66ProtocolSystemException e1) { - // do not send anything since the packet is external - try { - logger.debug("Cannot get LocalChannel while an end of request comes: {}", - LocalPacketCodec.decodeNetworkPacket(packet.getBuffer())); - } catch (OpenR66ProtocolPacketException e2) { - logger.debug("Cannot get LocalChannel while an end of request comes: {}", - packet.toString()); - } - return; - } - // OK continue and send to the local channel - } else if (packet.getCode() == LocalPacketFactory.CONNECTERRORPACKET) { - // Not a local error but a remote one - try { - localChannelReference = Configuration.configuration - .getLocalTransaction().getClient(packet.getRemoteId(), - packet.getLocalId()); - } catch (OpenR66ProtocolSystemException e1) { - // do not send anything since the packet is external - try { - logger.debug("Cannot get LocalChannel while an external error comes: {}", - LocalPacketCodec.decodeNetworkPacket(packet.getBuffer())); - } catch (OpenR66ProtocolPacketException e2) { - logger.debug("Cannot get LocalChannel while an external error comes: {}", - packet.toString()); - } - return; - } - // OK continue and send to the local channel - } else { - try { - localChannelReference = Configuration.configuration - .getLocalTransaction().getClient(packet.getRemoteId(), - packet.getLocalId()); - } catch (OpenR66ProtocolSystemException e1) { - if (remoteAddress == null) { - remoteAddress = e.getChannel().getRemoteAddress(); - } - if (NetworkTransaction.isShuttingdownNetworkChannel(remoteAddress)) { - // ignore - return; - } - logger.debug("Cannot get LocalChannel: " + packet + " due to " + - e1.getMessage()); - final ConnectionErrorPacket error = new ConnectionErrorPacket( - "Cannot get localChannel since cannot retrieve it", null); - writeError(e.getChannel(), packet.getRemoteId(), packet - .getLocalId(), error); - return; - } - } - } - Channels.write(localChannelReference.getLocalChannel(), packet - .getBuffer()); - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss - * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) - */ - @Override - public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { - logger.debug("Network Channel Exception: {}", e.getChannel().getId(), e - .getCause()); - if (e.getCause() instanceof ReadTimeoutException) { - ReadTimeoutException exception = (ReadTimeoutException) e.getCause(); - // No read for too long - logger.error("ReadTimeout so Will close NETWORK channel {}", exception.getMessage()); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - return; - } - if (e.getCause() instanceof BindException) { - // received when not yet connected - logger.debug("BindException"); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - return; - } - OpenR66Exception exception = OpenR66ExceptionTrappedFactory - .getExceptionFromTrappedException(e.getChannel(), e); - if (exception != null) { - if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { - if (NetworkTransaction.getNbLocalChannel(e.getChannel()) > 0) { - logger.debug( - "Network Channel Exception: {} {}", e.getChannel().getId(), - exception.getMessage()); - } - logger.debug("Will close NETWORK channel"); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - return; - } else if (exception instanceof OpenR66ProtocolNoConnectionException) { - logger.debug("Connection impossible with NETWORK channel {}", - exception.getMessage()); - Channels.close(e.getChannel()); - return; - } else { - logger.debug( - "Network Channel Exception: {} {}", e.getChannel().getId(), - exception.getMessage()); - } - final ConnectionErrorPacket errorPacket = new ConnectionErrorPacket( - exception.getMessage(), null); - writeError(e.getChannel(), ChannelUtils.NOCHANNEL, - ChannelUtils.NOCHANNEL, errorPacket); - logger.debug("Will close NETWORK channel: {}", exception.getMessage()); - ChannelCloseTimer.closeFutureChannel(e.getChannel()); - } else { - // Nothing to do - return; - } - } - - /** - * Write error back to remote client - * - * @param channel - * @param remoteId - * @param localId - * @param error - */ - void writeError(Channel channel, Integer remoteId, Integer localId, - AbstractLocalPacket error) { - NetworkPacket networkPacket = null; - try { - networkPacket = new NetworkPacket(localId, remoteId, error); - } catch (OpenR66ProtocolPacketException e) { - } - try { - Channels.write(channel, networkPacket).await(); - } catch (InterruptedException e) { - } - } - - /** - * @return the dbSession - */ - public DbSession getDbSession() { - return dbSession; - } - - /** - * - * @return True if this Handler is for SSL - */ - public boolean isSsl() { - return isSSL; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import java.net.BindException; +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler; +import org.jboss.netty.handler.timeout.IdleStateEvent; +import org.jboss.netty.handler.timeout.ReadTimeoutException; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; +import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.KeepAlivePacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; +import org.waarp.openr66.protocol.utils.ChannelCloseTimer; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Network Server Handler (Requester side) + * + * @author frederic bregier + */ +public class NetworkServerHandler extends IdleStateAwareChannelHandler { + // extends SimpleChannelHandler { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(NetworkServerHandler.class); + + /** + * The underlying Network Channel + */ + private volatile Channel networkChannel; + /** + * The associated Remote Address + */ + private volatile SocketAddress remoteAddress; + /** + * The Database connection attached to this NetworkChannel shared among all associated + * LocalChannels + */ + protected volatile DbSession dbSession; + /** + * Does this Handler is for SSL + */ + protected volatile boolean isSSL = false; + /** + * Is this Handler a server side + */ + protected boolean isServer = false; + /** + * To handle the keep alive + */ + protected volatile boolean keepAlivedSent = false; + + /** + * + * @param isServer + */ + public NetworkServerHandler(boolean isServer) { + this.isServer = isServer; + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelClosed(org.jboss. + * netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { + if (NetworkTransaction.getNbLocalChannel(e.getChannel()) > 0) { + logger.info("Network Channel Closed: {} LocalChannels Left: {}", + e.getChannel().getId(), + NetworkTransaction.getNbLocalChannel(e.getChannel())); + // close if necessary the local channel + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e1) { + } + Configuration.configuration.getLocalTransaction() + .closeLocalChannelsFromNetworkChannel(e.getChannel()); + } + if (remoteAddress == null) { + remoteAddress = e.getChannel().getRemoteAddress(); + } + NetworkTransaction.removeForceNetworkChannel(remoteAddress); + // Now force the close of the database after a wait + if (dbSession != null && dbSession.internalId != DbConstant.admin.session.internalId) { + dbSession.disconnect(); + dbSession = null; + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelConnected(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) + throws OpenR66ProtocolNetworkException { + this.networkChannel = e.getChannel(); + this.remoteAddress = this.networkChannel.getRemoteAddress(); + try { + if (DbConstant.admin.isConnected) { + this.dbSession = new DbSession(DbConstant.admin, false); + } + } catch (WaarpDatabaseNoConnectionException e1) { + // Cannot connect so use default connection + logger.warn("Use default database connection"); + this.dbSession = DbConstant.admin.session; + } + logger.debug("Network Channel Connected: {} ", e.getChannel().getId()); + } + + /* + * (non-Javadoc) + * @see + * org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler#channelIdle(org.jboss.netty. + * channel.ChannelHandlerContext, org.jboss.netty.handler.timeout.IdleStateEvent) + */ + @Override + public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) + throws Exception { + if (Configuration.configuration.isShutdown) + return; + if (keepAlivedSent) { + logger.error("Not getting KAlive: closing channel"); + if (Configuration.configuration.r66Mib != null) { + Configuration.configuration.r66Mib.notifyWarning( + "KeepAlive get no answer", "Closing network connection"); + } + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + } else { + keepAlivedSent = true; + KeepAlivePacket keepAlivePacket = new KeepAlivePacket(); + NetworkPacket response = + new NetworkPacket(ChannelUtils.NOCHANNEL, + ChannelUtils.NOCHANNEL, keepAlivePacket); + logger.info("Write KAlive"); + Channels.write(e.getChannel(), response); + } + } + + public void setKeepAlivedSent() { + keepAlivedSent = false; + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) + */ + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { + final NetworkPacket packet = (NetworkPacket) e.getMessage(); + if (packet.getCode() == LocalPacketFactory.NOOPPACKET) { + // Do nothing + return; + } else if (packet.getCode() == LocalPacketFactory.CONNECTERRORPACKET) { + logger.debug("NetworkRecv: {}", packet); + // Special code to STOP here + if (packet.getLocalId() == ChannelUtils.NOCHANNEL) { + // No way to know what is wrong: close all connections with + // remote host + logger + .error("Will close NETWORK channel, Cannot continue connection with remote Host: " + + + packet.toString() + + " : " + + e.getChannel().getRemoteAddress()); + WaarpSslUtility.closingSslChannel(e.getChannel()); + return; + } + } else if (packet.getCode() == LocalPacketFactory.KEEPALIVEPACKET) { + keepAlivedSent = false; + try { + KeepAlivePacket keepAlivePacket = (KeepAlivePacket) + LocalPacketCodec.decodeNetworkPacket(packet.getBuffer()); + if (keepAlivePacket.isToValidate()) { + keepAlivePacket.validate(); + NetworkPacket response = + new NetworkPacket(ChannelUtils.NOCHANNEL, + ChannelUtils.NOCHANNEL, keepAlivePacket); + logger.info("Answer KAlive"); + Channels.write(e.getChannel(), response); + } else { + logger.info("Get KAlive"); + } + } catch (OpenR66ProtocolPacketException e1) { + } + return; + } + LocalChannelReference localChannelReference = null; + if (packet.getLocalId() == ChannelUtils.NOCHANNEL) { + logger.debug("NetworkRecv Create: {} {}", packet, + e.getChannel().getId()); + try { + localChannelReference = + NetworkTransaction.createConnectionFromNetworkChannelStartup( + e.getChannel(), packet); + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Cannot create LocalChannel for: " + packet + " due to " + + e1.getMessage()); + final ConnectionErrorPacket error = new ConnectionErrorPacket( + "Cannot connect to localChannel since cannot create it", null); + writeError(e.getChannel(), packet.getRemoteId(), packet + .getLocalId(), error); + NetworkTransaction.removeNetworkChannel(e.getChannel(), null, null); + return; + } catch (OpenR66ProtocolRemoteShutdownException e1) { + logger.warn("Will Close Local from Network Channel"); + Configuration.configuration.getLocalTransaction() + .closeLocalChannelsFromNetworkChannel(e.getChannel()); + WaarpSslUtility.closingSslChannel(e.getChannel()); + // NetworkTransaction.removeForceNetworkChannel(e.getChannel()); + // ignore since no more valid + return; + } + } else { + if (packet.getCode() == LocalPacketFactory.ENDREQUESTPACKET) { + // Not a local error but a remote one + try { + localChannelReference = Configuration.configuration + .getLocalTransaction().getClient(packet.getRemoteId(), + packet.getLocalId()); + } catch (OpenR66ProtocolSystemException e1) { + // do not send anything since the packet is external + try { + logger.debug("Cannot get LocalChannel while an end of request comes: {}", + LocalPacketCodec.decodeNetworkPacket(packet.getBuffer())); + } catch (OpenR66ProtocolPacketException e2) { + logger.debug("Cannot get LocalChannel while an end of request comes: {}", + packet.toString()); + } + return; + } + // OK continue and send to the local channel + } else if (packet.getCode() == LocalPacketFactory.CONNECTERRORPACKET) { + // Not a local error but a remote one + try { + localChannelReference = Configuration.configuration + .getLocalTransaction().getClient(packet.getRemoteId(), + packet.getLocalId()); + } catch (OpenR66ProtocolSystemException e1) { + // do not send anything since the packet is external + try { + logger.debug("Cannot get LocalChannel while an external error comes: {}", + LocalPacketCodec.decodeNetworkPacket(packet.getBuffer())); + } catch (OpenR66ProtocolPacketException e2) { + logger.debug("Cannot get LocalChannel while an external error comes: {}", + packet.toString()); + } + return; + } + // OK continue and send to the local channel + } else { + try { + localChannelReference = Configuration.configuration + .getLocalTransaction().getClient(packet.getRemoteId(), + packet.getLocalId()); + } catch (OpenR66ProtocolSystemException e1) { + if (remoteAddress == null) { + remoteAddress = e.getChannel().getRemoteAddress(); + } + if (NetworkTransaction.isShuttingdownNetworkChannel(remoteAddress)) { + // ignore + return; + } + logger.debug("Cannot get LocalChannel: " + packet + " due to " + + e1.getMessage()); + final ConnectionErrorPacket error = new ConnectionErrorPacket( + "Cannot get localChannel since cannot retrieve it", null); + writeError(e.getChannel(), packet.getRemoteId(), packet + .getLocalId(), error); + return; + } + } + } + Channels.write(localChannelReference.getLocalChannel(), packet + .getBuffer()); + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss + * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { + logger.debug("Network Channel Exception: {}", e.getChannel().getId(), e + .getCause()); + if (e.getCause() instanceof ReadTimeoutException) { + ReadTimeoutException exception = (ReadTimeoutException) e.getCause(); + // No read for too long + logger.error("ReadTimeout so Will close NETWORK channel {}", exception.getMessage()); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + return; + } + if (e.getCause() instanceof BindException) { + // received when not yet connected + logger.debug("BindException"); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + return; + } + OpenR66Exception exception = OpenR66ExceptionTrappedFactory + .getExceptionFromTrappedException(e.getChannel(), e); + if (exception != null) { + if (exception instanceof OpenR66ProtocolBusinessNoWriteBackException) { + if (NetworkTransaction.getNbLocalChannel(e.getChannel()) > 0) { + logger.debug( + "Network Channel Exception: {} {}", e.getChannel().getId(), + exception.getMessage()); + } + logger.debug("Will close NETWORK channel"); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + return; + } else if (exception instanceof OpenR66ProtocolNoConnectionException) { + logger.debug("Connection impossible with NETWORK channel {}", + exception.getMessage()); + Channels.close(e.getChannel()); + return; + } else { + logger.debug( + "Network Channel Exception: {} {}", e.getChannel().getId(), + exception.getMessage()); + } + final ConnectionErrorPacket errorPacket = new ConnectionErrorPacket( + exception.getMessage(), null); + writeError(e.getChannel(), ChannelUtils.NOCHANNEL, + ChannelUtils.NOCHANNEL, errorPacket); + logger.debug("Will close NETWORK channel: {}", exception.getMessage()); + ChannelCloseTimer.closeFutureChannel(e.getChannel()); + } else { + // Nothing to do + return; + } + } + + /** + * Write error back to remote client + * + * @param channel + * @param remoteId + * @param localId + * @param error + */ + void writeError(Channel channel, Integer remoteId, Integer localId, + AbstractLocalPacket error) { + NetworkPacket networkPacket = null; + try { + networkPacket = new NetworkPacket(localId, remoteId, error); + } catch (OpenR66ProtocolPacketException e) { + } + try { + Channels.write(channel, networkPacket).await(); + } catch (InterruptedException e) { + } + } + + /** + * @return the dbSession + */ + public DbSession getDbSession() { + return dbSession; + } + + /** + * + * @return True if this Handler is for SSL + */ + public boolean isSsl() { + return isSSL; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerPipelineFactory.java index f747b335e..d7d0e41fa 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkServerPipelineFactory.java @@ -1,87 +1,87 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import java.util.concurrent.TimeUnit; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.jboss.netty.handler.timeout.IdleStateHandler; -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jboss.netty.util.HashedWheelTimer; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec; - -/** - * NetworkServer pipeline (Requester side) - * - * @author Frederic Bregier - */ -public class NetworkServerPipelineFactory implements ChannelPipelineFactory { - /** - * Global HashedWheelTimer - */ - public HashedWheelTimer timer = (HashedWheelTimer) Configuration.configuration - .getTimerClose(); - - public static final String TIMEOUT = "timeout"; - public static final String READTIMEOUT = "readTimeout"; - public static final String LIMIT = "LIMIT"; - public static final String LIMITCHANNEL = "LIMITCHANNEL"; - - protected boolean server = false; - - public NetworkServerPipelineFactory(boolean server) { - this.server = server; - } - - public ChannelPipeline getPipeline() { - final ChannelPipeline pipeline = Channels.pipeline(); - pipeline.addLast("codec", new NetworkPacketCodec()); - GlobalTrafficShapingHandler handler = - Configuration.configuration.getGlobalTrafficShapingHandler(); - if (handler != null) { - pipeline.addLast(LIMIT, handler); - } - ChannelTrafficShapingHandler trafficChannel = null; - try { - trafficChannel = - Configuration.configuration - .newChannelTrafficShapingHandler(); - if (trafficChannel != null) { - pipeline.addLast(LIMITCHANNEL, trafficChannel); - } - } catch (OpenR66ProtocolNoDataException e) { - } - pipeline.addLast("pipelineExecutor", new ExecutionHandler( - Configuration.configuration.getServerPipelineExecutor())); - - pipeline.addLast(TIMEOUT, - new IdleStateHandler(timer, - 0, 0, - Configuration.configuration.TIMEOUTCON, - TimeUnit.MILLISECONDS)); - pipeline.addLast("handler", new NetworkServerHandler(this.server)); - return pipeline; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import java.util.concurrent.TimeUnit; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.jboss.netty.handler.timeout.IdleStateHandler; +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.jboss.netty.util.HashedWheelTimer; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec; + +/** + * NetworkServer pipeline (Requester side) + * + * @author Frederic Bregier + */ +public class NetworkServerPipelineFactory implements ChannelPipelineFactory { + /** + * Global HashedWheelTimer + */ + public HashedWheelTimer timer = (HashedWheelTimer) Configuration.configuration + .getTimerClose(); + + public static final String TIMEOUT = "timeout"; + public static final String READTIMEOUT = "readTimeout"; + public static final String LIMIT = "LIMIT"; + public static final String LIMITCHANNEL = "LIMITCHANNEL"; + + protected boolean server = false; + + public NetworkServerPipelineFactory(boolean server) { + this.server = server; + } + + public ChannelPipeline getPipeline() { + final ChannelPipeline pipeline = Channels.pipeline(); + pipeline.addLast("codec", new NetworkPacketCodec()); + GlobalTrafficShapingHandler handler = + Configuration.configuration.getGlobalTrafficShapingHandler(); + if (handler != null) { + pipeline.addLast(LIMIT, handler); + } + ChannelTrafficShapingHandler trafficChannel = null; + try { + trafficChannel = + Configuration.configuration + .newChannelTrafficShapingHandler(); + if (trafficChannel != null) { + pipeline.addLast(LIMITCHANNEL, trafficChannel); + } + } catch (OpenR66ProtocolNoDataException e) { + } + pipeline.addLast("pipelineExecutor", new ExecutionHandler( + Configuration.configuration.getServerPipelineExecutor())); + + pipeline.addLast(TIMEOUT, + new IdleStateHandler(timer, + 0, 0, + Configuration.configuration.TIMEOUTCON, + TimeUnit.MILLISECONDS)); + pipeline.addLast("handler", new NetworkServerHandler(this.server)); + return pipeline; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkTransaction.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkTransaction.java index 323078dcb..331fb8d30 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkTransaction.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/NetworkTransaction.java @@ -1,1126 +1,1126 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTR; - -import java.net.ConnectException; -import java.net.SocketAddress; -import java.util.Collections; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - -import org.jboss.netty.bootstrap.ClientBootstrap; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.ChannelPipelineException; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.group.ChannelGroup; -import org.jboss.netty.channel.group.DefaultChannelGroup; -import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; -import org.jboss.netty.util.Timeout; -import org.jboss.netty.util.TimerTask; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.RetrieveRunner; -import org.waarp.openr66.protocol.localhandler.packet.AuthentPacket; -import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; -import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerHandler; -import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; - -/** - * This class handles Network Transaction connections - * - * @author frederic bregier - */ -public class NetworkTransaction { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(NetworkTransaction.class); - - /** - * Hashmap for Currently Shutdown remote host - */ - private static final ConcurrentHashMap networkChannelShutdownOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); - - /** - * Hashmap for currently active remote host - */ - private static final ConcurrentHashMap networkChannelOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); - /** - * Hashmap for lock based on remote address - */ - private static final ConcurrentHashMap reentrantLockOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); - /** - * Remote Client NetworkChannels - */ - private static final ConcurrentHashMap remoteClients = new ConcurrentHashMap(); - /** - * Lock for Client NetworkChannels operations - */ - private static final ReentrantLock lockClient = new ReentrantLock(); - /** - * Hashmap for currently active Retrieve Runner (sender) - */ - private static final ConcurrentHashMap retrieveRunnerConcurrentHashMap = - new ConcurrentHashMap(); - - /** - * Lock for NetworkChannel operations - */ - private static final ReentrantLock lock = new ReentrantLock(); - - /** - * ExecutorService for RetrieveOperation - */ - private static final ExecutorService retrieveExecutor = Executors - .newCachedThreadPool(); - - /** - * ExecutorService Server Boss - */ - private final ExecutorService execServerBoss = Executors - .newCachedThreadPool(); - - /** - * ExecutorService Server Worker - */ - private final ExecutorService execServerWorker = Executors - .newCachedThreadPool(); - - private final ChannelFactory channelClientFactory = new NioClientSocketChannelFactory( - execServerBoss, - execServerWorker, - Configuration.configuration.CLIENT_THREAD); - - private final ClientBootstrap clientBootstrap = new ClientBootstrap( - channelClientFactory); - private final ClientBootstrap clientSslBootstrap = new ClientBootstrap( - channelClientFactory); - private final ChannelGroup networkChannelGroup = new DefaultChannelGroup( - "NetworkChannels"); - private final NetworkServerPipelineFactory networkServerPipelineFactory; - private final NetworkSslServerPipelineFactory networkSslServerPipelineFactory; - - public NetworkTransaction() { - networkServerPipelineFactory = new NetworkServerPipelineFactory(false); - clientBootstrap.setPipelineFactory(networkServerPipelineFactory); - clientBootstrap.setOption("tcpNoDelay", true); - clientBootstrap.setOption("reuseAddress", true); - clientBootstrap.setOption("connectTimeoutMillis", - Configuration.configuration.TIMEOUTCON); - if (Configuration.configuration.useSSL && Configuration.configuration.HOST_SSLID != null) { - networkSslServerPipelineFactory = - new NetworkSslServerPipelineFactory(true, execServerWorker); - clientSslBootstrap.setPipelineFactory(networkSslServerPipelineFactory); - clientSslBootstrap.setOption("tcpNoDelay", true); - clientSslBootstrap.setOption("reuseAddress", true); - clientSslBootstrap.setOption("connectTimeoutMillis", - Configuration.configuration.TIMEOUTCON); - } else { - networkSslServerPipelineFactory = null; - logger.warn("No SSL support configured"); - } - } - - private static ReentrantLock getChannelLock(SocketAddress socketAddress) { - lock.lock(); - try { - if (socketAddress == null) { - // should not - logger.info("SocketAddress empty here !"); - return lock; - } - Integer hash = socketAddress.hashCode(); - ReentrantLock socketLock = reentrantLockOnSocketAddressConcurrentHashMap.get(hash); - if (socketLock == null) { - socketLock = new ReentrantLock(true); - reentrantLockOnSocketAddressConcurrentHashMap.put(hash, socketLock); - } - return socketLock; - } finally { - lock.unlock(); - } - } - - private static void removeChannelLock(SocketAddress socketAddress) { - lock.lock(); - try { - if (socketAddress == null) { - // should not - logger.info("SocketAddress empty here !"); - return; - } - Integer hash = socketAddress.hashCode(); - reentrantLockOnSocketAddressConcurrentHashMap.remove(hash); - } finally { - lock.unlock(); - } - } - - /** - * Create a connection to the specified socketAddress with multiple retries - * - * @param socketAddress - * @param isSSL - * @param futureRequest - * @return the LocalChannelReference - */ - public LocalChannelReference createConnectionWithRetry(SocketAddress socketAddress, - boolean isSSL, R66Future futureRequest) { - LocalChannelReference localChannelReference = null; - OpenR66Exception lastException = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - localChannelReference = - createConnection(socketAddress, isSSL, futureRequest); - break; - } catch (OpenR66ProtocolRemoteShutdownException e1) { - lastException = e1; - localChannelReference = null; - break; - } catch (OpenR66ProtocolNoConnectionException e1) { - lastException = e1; - localChannelReference = null; - break; - } catch (OpenR66ProtocolNetworkException e1) { - // Can retry - lastException = e1; - localChannelReference = null; - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e) { - break; - } - } - } - if (localChannelReference == null) { - logger.debug("Cannot connect : {}", lastException.getMessage()); - } else if (lastException != null) { - logger.debug("Connection retried since {}", lastException.getMessage()); - } - return localChannelReference; - } - - /** - * Create a connection to the specified socketAddress - * - * @param socketAddress - * @param isSSL - * @param futureRequest - * @return the LocalChannelReference - * @throws OpenR66ProtocolNetworkException - * @throws OpenR66ProtocolRemoteShutdownException - * @throws OpenR66ProtocolNoConnectionException - */ - public LocalChannelReference createConnection(SocketAddress socketAddress, boolean isSSL, - R66Future futureRequest) - throws OpenR66ProtocolNetworkException, - OpenR66ProtocolRemoteShutdownException, - OpenR66ProtocolNoConnectionException { - NetworkChannel networkChannel = null; - LocalChannelReference localChannelReference = null; - boolean ok = false; - // check valid limit on server side only (could be the initiator but not a client) - if (!Configuration.configuration.HOST_AUTH.isClient()) { - boolean valid = false; - for (int i = 0; i < Configuration.RETRYNB * 2; i++) { - if (Configuration.configuration.constraintLimitHandler.checkConstraintsSleep(i)) { - logger.debug("Constraints exceeded: " + i); - } else { - logger.debug("Constraints NOT exceeded"); - valid = true; - break; - } - } - if (!valid) { - // Limit is locally exceeded - logger.debug("Overloaded local system"); - throw new OpenR66ProtocolNetworkException( - "Cannot connect to remote server due to local overload"); - } - } - try { - networkChannel = createNewConnection(socketAddress, isSSL); - localChannelReference = createNewClient(networkChannel, futureRequest); - ok = true; - } finally { - if (!ok) { - if (networkChannel != null) { - removeNetworkChannel(networkChannel.channel, null, null); - } - } - } - if (localChannelReference.getFutureValidateStartup().isDone() && - localChannelReference.getFutureValidateStartup().isSuccess()) { - sendValidationConnection(localChannelReference); - } else { - OpenR66ProtocolNetworkException exc = - new OpenR66ProtocolNetworkException("Startup is invalid"); - logger.debug("Startup is Invalid", exc); - R66Result finalValue = new R66Result( - exc, null, true, ErrorCode.ConnectionImpossible, null); - localChannelReference.invalidateRequest(finalValue); - Channels.close(localChannelReference.getLocalChannel()); - throw exc; - } - return localChannelReference; - } - - /** - * - * @param socketServerAddress - * @param isSSL - * @return the NetworkChannel - * @throws OpenR66ProtocolNetworkException - * @throws OpenR66ProtocolRemoteShutdownException - * @throws OpenR66ProtocolNoConnectionException - */ - private NetworkChannel createNewConnection(SocketAddress socketServerAddress, boolean isSSL) - throws OpenR66ProtocolNetworkException, - OpenR66ProtocolRemoteShutdownException, - OpenR66ProtocolNoConnectionException { - ReentrantLock socketLock = getChannelLock(socketServerAddress); - socketLock.lock(); - try { - if (!isAddressValid(socketServerAddress)) { - throw new OpenR66ProtocolRemoteShutdownException( - "Cannot connect to remote server since it is shutting down"); - } - NetworkChannel networkChannel; - try { - networkChannel = getRemoteChannel(socketServerAddress); - } catch (OpenR66ProtocolNoDataException e1) { - networkChannel = null; - } - if (networkChannel != null) { - networkChannel.count.incrementAndGet(); - logger.info("Already Connected: {}", networkChannel); - return networkChannel; - } - ChannelFuture channelFuture = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - if (isSSL) { - if (Configuration.configuration.HOST_SSLID != null) { - channelFuture = clientSslBootstrap.connect(socketServerAddress); - } else { - throw new OpenR66ProtocolNoConnectionException("No SSL support"); - } - } else { - channelFuture = clientBootstrap.connect(socketServerAddress); - } - } catch (ChannelPipelineException e) { - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to remote server due to a channel exception"); - } - try { - channelFuture.await(); - } catch (InterruptedException e1) { - } - if (channelFuture.isSuccess()) { - final Channel channel = channelFuture.getChannel(); - if (isSSL) { - if (!NetworkSslServerHandler.isSslConnectedChannel(channel)) { - logger.debug("KO CONNECT since SSL handshake is over"); - Channels.close(channel); - throw new OpenR66ProtocolNoConnectionException( - "Cannot finish connect to remote server"); - } - } - networkChannelGroup.add(channel); - return putRemoteChannel(channel); - } else { - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e) { - } - if (!channelFuture.isDone()) { - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to remote server due to interruption"); - } - if (channelFuture.getCause() instanceof ConnectException) { - logger.debug("KO CONNECT:" + - channelFuture.getCause().getMessage()); - throw new OpenR66ProtocolNoConnectionException( - "Cannot connect to remote server", channelFuture - .getCause()); - } else { - logger.debug("KO CONNECT but retry", channelFuture - .getCause()); - } - } - } - throw new OpenR66ProtocolNetworkException( - "Cannot connect to remote server", channelFuture.getCause()); - } finally { - socketLock.unlock(); - } - } - - /** - * - * @param channel - * @param futureRequest - * @return the LocalChannelReference - * @throws OpenR66ProtocolNetworkException - * @throws OpenR66ProtocolRemoteShutdownException - */ - private LocalChannelReference createNewClient(NetworkChannel networkChannel, - R66Future futureRequest) - throws OpenR66ProtocolNetworkException, - OpenR66ProtocolRemoteShutdownException { - if (!networkChannel.channel.isConnected()) { - throw new OpenR66ProtocolNetworkException( - "Network channel no more connected"); - } - LocalChannelReference localChannelReference = null; - try { - localChannelReference = Configuration.configuration - .getLocalTransaction().createNewClient(networkChannel.channel, - ChannelUtils.NOCHANNEL, futureRequest); - } catch (OpenR66ProtocolSystemException e) { - // check if the channel has other attached local channels - // NO since done in caller (createConnection) - /* - * logger.info("Try to Close Network"); removeNetworkChannel(networkChannel.channel, - * null); - */ - throw new OpenR66ProtocolNetworkException( - "Cannot connect to local channel", e); - } - return localChannelReference; - } - - /** - * Create the LocalChannelReference when a remote local channel starts its connection - * - * @param channel - * @param packet - * @return the LocalChannelReference - * @throws OpenR66ProtocolRemoteShutdownException - * @throws OpenR66ProtocolSystemException - */ - public static LocalChannelReference createConnectionFromNetworkChannelStartup(Channel channel, - NetworkPacket packet) - throws OpenR66ProtocolRemoteShutdownException, OpenR66ProtocolSystemException { - NetworkTransaction.addNetworkChannel(channel); - LocalChannelReference localChannelReference = Configuration.configuration - .getLocalTransaction().createNewClient(channel, - packet.getRemoteId(), null); - return localChannelReference; - } - - /** - * Send a validation of connection with Authentication - * - * @param localChannelReference - * @throws OpenR66ProtocolNetworkException - * @throws OpenR66ProtocolRemoteShutdownException - */ - private void sendValidationConnection( - LocalChannelReference localChannelReference) - throws OpenR66ProtocolNetworkException, - OpenR66ProtocolRemoteShutdownException { - AuthentPacket authent; - try { - authent = new AuthentPacket( - Configuration.configuration.getHostId( - localChannelReference.getNetworkServerHandler().isSsl()), - FilesystemBasedDigest.passwdCrypt( - Configuration.configuration.HOST_AUTH.getHostkey()), - localChannelReference.getLocalId()); - } catch (OpenR66ProtocolNoSslException e1) { - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException("No SSL support", e1), - localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); - logger.error("Authent is Invalid due to no SSL: {}", e1.getMessage()); - if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { - ConnectionErrorPacket error = new ConnectionErrorPacket( - "Cannot connect to localChannel since no SSL is supported", null); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e) { - } - } - localChannelReference.invalidateRequest(finalValue); - Channels.close(localChannelReference.getLocalChannel()); - throw new OpenR66ProtocolNetworkException(e1); - } - logger.debug("Will send request of connection validation"); - localChannelReference.sessionNewState(AUTHENTR); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, authent, true); - } catch (OpenR66ProtocolPacketException e) { - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException("Wrong Authent Protocol", e), - localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); - logger.error("Authent is Invalid due to protocol: {}", e.getMessage()); - localChannelReference.invalidateRequest(finalValue); - if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { - ConnectionErrorPacket error = new ConnectionErrorPacket( - "Cannot connect to localChannel since Authent Protocol is invalid", null); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e1) { - } - } - Channels.close(localChannelReference.getLocalChannel()); - throw new OpenR66ProtocolNetworkException("Bad packet", e); - } - R66Future future = localChannelReference.getFutureValidateConnection(); - if (future.isFailed()) { - logger.debug("Will close NETWORK channel since Future cancelled: {}", - future); - R66Result finalValue = new R66Result( - new OpenR66ProtocolSystemException( - "Out of time or Connection invalid during Authentication"), - localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); - logger.warn("Authent is Invalid due to: {} {}", finalValue.exception.getMessage(), - future.toString()); - localChannelReference.invalidateRequest(finalValue); - if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { - ConnectionErrorPacket error = new ConnectionErrorPacket( - "Cannot connect to localChannel with Out of Time", null); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); - } catch (OpenR66ProtocolPacketException e) { - } - } - Channels.close(localChannelReference.getLocalChannel()); - throw new OpenR66ProtocolNetworkException( - "Cannot validate connection: " + future.getResult(), future - .getCause()); - } - } - - public static ExecutorService getRetrieveExecutor() { - return retrieveExecutor; - } - - public static ConcurrentHashMap getRetrieveRunnerConcurrentHashMap() { - return retrieveRunnerConcurrentHashMap; - } - - /** - * Start retrieve operation - * - * @param session - * @param channel - */ - public static void runRetrieve(R66Session session, Channel channel) { - RetrieveRunner retrieveRunner = new RetrieveRunner(session, channel); - retrieveRunnerConcurrentHashMap.put(session.getLocalChannelReference().getLocalId(), - retrieveRunner); - retrieveRunner.setDaemon(true); - retrieveExecutor.execute(retrieveRunner); - } - - /** - * Stop a retrieve operation - * - * @param localChannelReference - */ - public static void stopRetrieve(LocalChannelReference localChannelReference) { - RetrieveRunner retrieveRunner = - retrieveRunnerConcurrentHashMap.remove(localChannelReference.getLocalId()); - if (retrieveRunner != null) { - retrieveRunner.stopRunner(); - } - } - - /** - * Normal end of a Retrieve Operation - * - * @param localChannelReference - */ - public static void normalEndRetrieve(LocalChannelReference localChannelReference) { - retrieveRunnerConcurrentHashMap.remove(localChannelReference.getLocalId()); - } - - /** - * Stop all Retrieve Executors - */ - public static void closeRetrieveExecutors() { - retrieveExecutor.shutdownNow(); - } - - /** - * Close all Network Ttransaction - */ - public void closeAll() { - logger.debug("close All Network Channels"); - try { - Thread.sleep(Configuration.RETRYINMS * 2); - } catch (InterruptedException e) { - } - if (!Configuration.configuration.isServer) { - R66ShutdownHook.shutdownHook.launchFinalExit(); - } - closeRetrieveExecutors(); - networkChannelGroup.close().awaitUninterruptibly(); - clientBootstrap.releaseExternalResources(); - clientSslBootstrap.releaseExternalResources(); - channelClientFactory.releaseExternalResources(); - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e) { - } - DbAdmin.closeAllConnection(); - Configuration.configuration.clientStop(); - logger.debug("Last action before exit"); - ChannelUtils.stopLogger(); - } - - /** - * - * @param channel - * @throws OpenR66ProtocolRemoteShutdownException - */ - public static void addNetworkChannel(Channel channel) - throws OpenR66ProtocolRemoteShutdownException { - if (!isAddressValid(channel.getRemoteAddress())) { - throw new OpenR66ProtocolRemoteShutdownException( - "Channel is already in shutdown"); - } - try { - putRemoteChannel(channel); - } catch (OpenR66ProtocolNoConnectionException e) { - throw new OpenR66ProtocolRemoteShutdownException( - "Channel is already in shutdown"); - } - } - - /** - * Add a LocalChannel to a NetworkChannel - * - * @param networkChannel - * @param localChannel - * @throws OpenR66ProtocolRemoteShutdownException - */ - public static void addLocalChannelToNetworkChannel(Channel networkChannel, - Channel localChannel) throws OpenR66ProtocolRemoteShutdownException { - SocketAddress address = networkChannel.getRemoteAddress(); - if (address != null) { - NetworkChannel networkChannelObject = networkChannelOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannelObject != null) { - networkChannelObject.add(localChannel); - } - } - } - - /** - * Shutdown one Network Channel - * - * @param channel - */ - public static void shuttingdownNetworkChannel(Channel channel) { - SocketAddress address = channel.getRemoteAddress(); - shuttingdownNetworkChannel(address, channel); - } - - /** - * Shutdown one Network Channel according to its SocketAddress - * - * @param address - * @param channel - * (can be null) - * @return True if the shutdown is starting, False if cannot be done (can be already done - * before) - */ - public static boolean shuttingdownNetworkChannel(SocketAddress address, Channel channel) { - if (address != null) { - ReentrantLock socketLock = getChannelLock(address); - socketLock.lock(); - try { - NetworkChannel networkChannel = - networkChannelShutdownOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannel != null) { - // already done - logger.debug("Already set as shutdown"); - return false; - } - networkChannel = networkChannelOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannel != null) { - logger.debug("Set as shutdown"); - } else { - if (channel != null) { - logger.debug("Newly Set as shutdown"); - networkChannel = new NetworkChannel(channel); - } - } - if (networkChannel != null) { - networkChannelShutdownOnSocketAddressConcurrentHashMap.put(address - .hashCode(), networkChannel); - if (networkChannel.isShuttingDown) { - return false; - } - networkChannel.shutdownAllLocalChannels(); - R66ShutdownNetworkChannelTimerTask timerTask = new R66ShutdownNetworkChannelTimerTask( - address.hashCode()); - Configuration.configuration.getTimerClose().newTimeout(timerTask, - Configuration.configuration.TIMEOUTCON * 3, TimeUnit.MILLISECONDS); - return true; - } - } finally { - socketLock.unlock(); - } - } - return false; - } - - /** - * - * @param address - * @return True if this channel is currently in shutdown - */ - public static boolean isShuttingdownNetworkChannel(SocketAddress address) { - ReentrantLock socketLock = getChannelLock(address); - socketLock.lock(); - try { - return !isAddressValid(address); - } finally { - socketLock.unlock(); - } - } - - /** - * Remove of requester - * - * @param requester - * @param networkChannel - */ - public static void removeClient(String requester, NetworkChannel networkChannel) { - if (networkChannel != null) { - lockClient.lock(); - try { - ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); - if (clientNetworkChannels != null) { - clientNetworkChannels.remove(networkChannel); - if (clientNetworkChannels.isEmpty()) { - remoteClients.remove(requester); - } - } - } finally { - lockClient.unlock(); - } - } - } - - /** - * Get NetworkChannel as client - * - * @param requester - * @return NetworkChannel associated with this host as client (only 1 allow even if more are - * available) - */ - public static boolean shuttingdownNetworkChannels(String requester) { - lockClient.lock(); - try { - ClientNetworkChannels clientNetworkChannels = remoteClients.remove(requester); - if (clientNetworkChannels != null) { - return clientNetworkChannels.shutdownAll(); - } - } finally { - lockClient.unlock(); - } - return false; - } - - /** - * Add a requester channel (so call only by requested host) - * - * @param channel - * (network channel) - * @param requester - */ - public static void addClient(Channel channel, String requester) { - SocketAddress address = channel.getRemoteAddress(); - if (address != null) { - NetworkChannel networkChannel = - networkChannelOnSocketAddressConcurrentHashMap.get(address.hashCode()); - if (networkChannel != null) { - lockClient.lock(); - try { - ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); - if (clientNetworkChannels == null) { - clientNetworkChannels = new ClientNetworkChannels(requester); - remoteClients.put(requester, clientNetworkChannels); - } - clientNetworkChannels.add(networkChannel); - } finally { - lockClient.unlock(); - } - } - } - } - - /** - * - * @param requester - * @return The number of NetworkChannels associated with this requester - */ - public static int getNumberClients(String requester) { - ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); - if (clientNetworkChannels != null) { - return clientNetworkChannels.size(); - } - return 0; - } - - /** - * Force remove of NetworkChannel when it is closed - * - * @param address - * @return the number of still connected Local Channels - */ - public static int removeForceNetworkChannel(SocketAddress address) { - ReentrantLock socketLock = getChannelLock(address); - socketLock.lock(); - try { - if (address != null) { - NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannel != null) { - if (networkChannel.isShuttingDown) { - return networkChannel.count.get(); - } - logger.debug("NC left: {}", networkChannel); - int count = networkChannel.count.get(); - networkChannel.shutdownAllLocalChannels(); - networkChannelOnSocketAddressConcurrentHashMap - .remove(address.hashCode()); - return count; - } else { - logger.debug("Network not registered"); - } - } - return 0; - } finally { - socketLock.unlock(); - removeChannelLock(address); - } - } - - /** - * Class to close the Network Channel if after some delays it has really no Local Channel - * attached - * - * @author Frederic Bregier - * - */ - static class CloseFutureChannel implements TimerTask { - - private static SortedSet inCloseRunning = - Collections - .synchronizedSortedSet(new TreeSet()); - private NetworkChannel networkChannel; - private String requester; - private SocketAddress address; - - /** - * @param networkChannel - * @param requester - * @throws OpenR66RunnerErrorException - */ - CloseFutureChannel(NetworkChannel networkChannel, SocketAddress address, String requester) - throws OpenR66RunnerErrorException { - if (!inCloseRunning.add(networkChannel.channel.getId())) - throw new OpenR66RunnerErrorException("Already scheduled"); - this.networkChannel = networkChannel; - this.requester = requester; - this.address = address; - } - - public void run(Timeout timeout) throws Exception { - ReentrantLock socketLock = getChannelLock(address); - socketLock.lock(); - try { - if (networkChannel.count.get() <= 0) { - long time = networkChannel.lastTimeUsed + - Configuration.configuration.TIMEOUTCON * 2 - - System.currentTimeMillis(); - if (time > Configuration.RETRYINMS) { - // will re execute this request later on - Configuration.configuration.getTimerClose().newTimeout(this, time, - TimeUnit.MILLISECONDS); - return; - } - if (requester != null) - NetworkTransaction.removeClient(requester, networkChannel); - networkChannelOnSocketAddressConcurrentHashMap - .remove(address.hashCode()); - logger.info("Will close NETWORK channel"); - WaarpSslUtility.closingSslChannel(networkChannel.channel); - } - inCloseRunning.remove(networkChannel.channel.getId()); - } finally { - socketLock.unlock(); - } - } - - } - - /** - * - * @param channel - * networkChannel - * @param localChannel - * localChannel - * @param requester - * Requester since call from LocalChannel close (might be null) - * @return the number of local channel still connected to this channel - */ - public static int removeNetworkChannel(Channel channel, Channel localChannel, - String requester) { - SocketAddress address = channel.getRemoteAddress(); - ReentrantLock socketLock = getChannelLock(address); - socketLock.lock(); - try { - if (address != null) { - NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannel != null) { - int count = networkChannel.count.decrementAndGet(); - logger.info("Close con: " + networkChannel); - if (localChannel != null) { - networkChannel.remove(localChannel); - } - if (count <= 0) { - CloseFutureChannel cfc; - try { - cfc = new CloseFutureChannel(networkChannel, address, requester); - Configuration.configuration.getTimerClose(). - newTimeout(cfc, Configuration.configuration.TIMEOUTCON * 2, - TimeUnit.MILLISECONDS); - } catch (OpenR66RunnerErrorException e) { - } - } - logger.debug("NC left: {}", networkChannel); - return count; - } else { - if (channel.isConnected()) { - logger.debug("Should not be here", - new OpenR66ProtocolSystemException()); - } - } - } - return 0; - } finally { - socketLock.unlock(); - } - } - - /** - * - * @param address - * @param host - * @return True if a connection is still active on this socket or for this host - */ - public static int existConnection(SocketAddress address, String host) { - return (networkChannelOnSocketAddressConcurrentHashMap.containsKey(address.hashCode()) ? 1 - : 0) - + getNumberClients(host); - } - - /** - * - * @param channel - * @return the number of local channel associated with this channel - */ - public static int getNbLocalChannel(Channel channel) { - SocketAddress address = channel.getRemoteAddress(); - if (address != null) { - NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap - .get(address.hashCode()); - if (networkChannel != null) { - return networkChannel.count.get(); - } - } - return -1; - } - - /** - * - * @param address - * @return True if this socket Address is currently valid for connection - */ - private static boolean isAddressValid(SocketAddress address) { - if (R66ShutdownHook.isInShutdown()) { - logger.debug("IS IN SHUTDOWN"); - return false; - } - if (address == null) { - logger.debug("ADDRESS IS NULL"); - return false; - } - try { - NetworkChannel networkChannel = getRemoteChannel(address); - logger.debug("IS IN SHUTDOWN: " + networkChannel.isShuttingDown); - return !networkChannel.isShuttingDown; - } catch (OpenR66ProtocolRemoteShutdownException e) { - logger.debug("ALREADY IN SHUTDOWN"); - return false; - } catch (OpenR66ProtocolNoDataException e) { - logger.debug("NOT FOUND SO NO SHUTDOWN"); - return true; - } - } - - /** - * - * @param channel - * @return the associated NetworkChannel if any (Null if none) - */ - public static NetworkChannel getNetworkChannel(Channel channel) { - SocketAddress address = channel.getRemoteAddress(); - if (address != null) { - return networkChannelOnSocketAddressConcurrentHashMap.get(address - .hashCode()); - } - return null; - } - - /** - * - * @param address - * @return NetworkChannel - * @throws OpenR66ProtocolRemoteShutdownException - * @throws OpenR66ProtocolNoDataException - */ - private static NetworkChannel getRemoteChannel(SocketAddress address) - throws OpenR66ProtocolRemoteShutdownException, - OpenR66ProtocolNoDataException { - if (R66ShutdownHook.isInShutdown()) { - logger.debug("IS IN SHUTDOWN"); - throw new OpenR66ProtocolRemoteShutdownException( - "Local Host already in shutdown"); - } - if (address == null) { - throw new OpenR66ProtocolRemoteShutdownException( - "Remote Host already in shutdown"); - } - int hashCode = address.hashCode(); - NetworkChannel nc = networkChannelShutdownOnSocketAddressConcurrentHashMap - .get(hashCode); - if (nc != null) { - throw new OpenR66ProtocolRemoteShutdownException( - "Remote Host already in shutdown"); - } - nc = networkChannelOnSocketAddressConcurrentHashMap.get(hashCode); - if (nc == null) { - throw new OpenR66ProtocolNoDataException("Channel not found"); - } - return nc; - } - - /** - * - * @param channel - * @return the associated NetworkChannel - * @throws OpenR66ProtocolRemoteShutdownException - * @throws OpenR66ProtocolNoDataException - */ - private static NetworkChannel putRemoteChannel(Channel channel) - throws OpenR66ProtocolRemoteShutdownException, OpenR66ProtocolNoConnectionException { - SocketAddress address = channel.getRemoteAddress(); - if (address != null) { - NetworkChannel networkChannel; - try { - networkChannel = getRemoteChannel(address); - networkChannel.count.incrementAndGet(); - logger.info("NC active: {}", networkChannel); - return networkChannel; - } catch (OpenR66ProtocolRemoteShutdownException e) { - throw e; - } catch (OpenR66ProtocolNoDataException e) { - networkChannel = new NetworkChannel(channel); - logger.debug("NC new active: {}", networkChannel); - networkChannelOnSocketAddressConcurrentHashMap.put(address - .hashCode(), networkChannel); - return networkChannel; - } - } - throw new OpenR66ProtocolNoConnectionException("Address is not correct"); - } - - /** - * Remover of Shutdown Remote Host - * - * @author Frederic Bregier - * - */ - private static class R66ShutdownNetworkChannelTimerTask implements TimerTask { - /** - * href to remove - */ - private final int href; - - /** - * Constructor from type - * - * @param href - */ - public R66ShutdownNetworkChannelTimerTask(int href) { - super(); - this.href = href; - } - - public void run(Timeout timeout) throws Exception { - logger.debug("DEBUG: Will remove shutdown for : " + href); - NetworkChannel networkChannel = - networkChannelShutdownOnSocketAddressConcurrentHashMap.remove(href); - if (networkChannel != null && networkChannel.channel != null - && networkChannel.channel.isConnected()) { - WaarpSslUtility.closingSslChannel(networkChannel.channel); - } - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import static org.waarp.openr66.context.R66FiniteDualStates.AUTHENTR; + +import java.net.ConnectException; +import java.net.SocketAddress; +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelPipelineException; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.group.ChannelGroup; +import org.jboss.netty.channel.group.DefaultChannelGroup; +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.TimerTask; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.RetrieveRunner; +import org.waarp.openr66.protocol.localhandler.packet.AuthentPacket; +import org.waarp.openr66.protocol.localhandler.packet.ConnectionErrorPacket; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; +import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerHandler; +import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerPipelineFactory; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; + +/** + * This class handles Network Transaction connections + * + * @author frederic bregier + */ +public class NetworkTransaction { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(NetworkTransaction.class); + + /** + * Hashmap for Currently Shutdown remote host + */ + private static final ConcurrentHashMap networkChannelShutdownOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); + + /** + * Hashmap for currently active remote host + */ + private static final ConcurrentHashMap networkChannelOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); + /** + * Hashmap for lock based on remote address + */ + private static final ConcurrentHashMap reentrantLockOnSocketAddressConcurrentHashMap = new ConcurrentHashMap(); + /** + * Remote Client NetworkChannels + */ + private static final ConcurrentHashMap remoteClients = new ConcurrentHashMap(); + /** + * Lock for Client NetworkChannels operations + */ + private static final ReentrantLock lockClient = new ReentrantLock(); + /** + * Hashmap for currently active Retrieve Runner (sender) + */ + private static final ConcurrentHashMap retrieveRunnerConcurrentHashMap = + new ConcurrentHashMap(); + + /** + * Lock for NetworkChannel operations + */ + private static final ReentrantLock lock = new ReentrantLock(); + + /** + * ExecutorService for RetrieveOperation + */ + private static final ExecutorService retrieveExecutor = Executors + .newCachedThreadPool(); + + /** + * ExecutorService Server Boss + */ + private final ExecutorService execServerBoss = Executors + .newCachedThreadPool(); + + /** + * ExecutorService Server Worker + */ + private final ExecutorService execServerWorker = Executors + .newCachedThreadPool(); + + private final ChannelFactory channelClientFactory = new NioClientSocketChannelFactory( + execServerBoss, + execServerWorker, + Configuration.configuration.CLIENT_THREAD); + + private final ClientBootstrap clientBootstrap = new ClientBootstrap( + channelClientFactory); + private final ClientBootstrap clientSslBootstrap = new ClientBootstrap( + channelClientFactory); + private final ChannelGroup networkChannelGroup = new DefaultChannelGroup( + "NetworkChannels"); + private final NetworkServerPipelineFactory networkServerPipelineFactory; + private final NetworkSslServerPipelineFactory networkSslServerPipelineFactory; + + public NetworkTransaction() { + networkServerPipelineFactory = new NetworkServerPipelineFactory(false); + clientBootstrap.setPipelineFactory(networkServerPipelineFactory); + clientBootstrap.setOption("tcpNoDelay", true); + clientBootstrap.setOption("reuseAddress", true); + clientBootstrap.setOption("connectTimeoutMillis", + Configuration.configuration.TIMEOUTCON); + if (Configuration.configuration.useSSL && Configuration.configuration.HOST_SSLID != null) { + networkSslServerPipelineFactory = + new NetworkSslServerPipelineFactory(true, execServerWorker); + clientSslBootstrap.setPipelineFactory(networkSslServerPipelineFactory); + clientSslBootstrap.setOption("tcpNoDelay", true); + clientSslBootstrap.setOption("reuseAddress", true); + clientSslBootstrap.setOption("connectTimeoutMillis", + Configuration.configuration.TIMEOUTCON); + } else { + networkSslServerPipelineFactory = null; + logger.warn("No SSL support configured"); + } + } + + private static ReentrantLock getChannelLock(SocketAddress socketAddress) { + lock.lock(); + try { + if (socketAddress == null) { + // should not + logger.info("SocketAddress empty here !"); + return lock; + } + Integer hash = socketAddress.hashCode(); + ReentrantLock socketLock = reentrantLockOnSocketAddressConcurrentHashMap.get(hash); + if (socketLock == null) { + socketLock = new ReentrantLock(true); + reentrantLockOnSocketAddressConcurrentHashMap.put(hash, socketLock); + } + return socketLock; + } finally { + lock.unlock(); + } + } + + private static void removeChannelLock(SocketAddress socketAddress) { + lock.lock(); + try { + if (socketAddress == null) { + // should not + logger.info("SocketAddress empty here !"); + return; + } + Integer hash = socketAddress.hashCode(); + reentrantLockOnSocketAddressConcurrentHashMap.remove(hash); + } finally { + lock.unlock(); + } + } + + /** + * Create a connection to the specified socketAddress with multiple retries + * + * @param socketAddress + * @param isSSL + * @param futureRequest + * @return the LocalChannelReference + */ + public LocalChannelReference createConnectionWithRetry(SocketAddress socketAddress, + boolean isSSL, R66Future futureRequest) { + LocalChannelReference localChannelReference = null; + OpenR66Exception lastException = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + localChannelReference = + createConnection(socketAddress, isSSL, futureRequest); + break; + } catch (OpenR66ProtocolRemoteShutdownException e1) { + lastException = e1; + localChannelReference = null; + break; + } catch (OpenR66ProtocolNoConnectionException e1) { + lastException = e1; + localChannelReference = null; + break; + } catch (OpenR66ProtocolNetworkException e1) { + // Can retry + lastException = e1; + localChannelReference = null; + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e) { + break; + } + } + } + if (localChannelReference == null) { + logger.debug("Cannot connect : {}", lastException.getMessage()); + } else if (lastException != null) { + logger.debug("Connection retried since {}", lastException.getMessage()); + } + return localChannelReference; + } + + /** + * Create a connection to the specified socketAddress + * + * @param socketAddress + * @param isSSL + * @param futureRequest + * @return the LocalChannelReference + * @throws OpenR66ProtocolNetworkException + * @throws OpenR66ProtocolRemoteShutdownException + * @throws OpenR66ProtocolNoConnectionException + */ + public LocalChannelReference createConnection(SocketAddress socketAddress, boolean isSSL, + R66Future futureRequest) + throws OpenR66ProtocolNetworkException, + OpenR66ProtocolRemoteShutdownException, + OpenR66ProtocolNoConnectionException { + NetworkChannel networkChannel = null; + LocalChannelReference localChannelReference = null; + boolean ok = false; + // check valid limit on server side only (could be the initiator but not a client) + if (!Configuration.configuration.HOST_AUTH.isClient()) { + boolean valid = false; + for (int i = 0; i < Configuration.RETRYNB * 2; i++) { + if (Configuration.configuration.constraintLimitHandler.checkConstraintsSleep(i)) { + logger.debug("Constraints exceeded: " + i); + } else { + logger.debug("Constraints NOT exceeded"); + valid = true; + break; + } + } + if (!valid) { + // Limit is locally exceeded + logger.debug("Overloaded local system"); + throw new OpenR66ProtocolNetworkException( + "Cannot connect to remote server due to local overload"); + } + } + try { + networkChannel = createNewConnection(socketAddress, isSSL); + localChannelReference = createNewClient(networkChannel, futureRequest); + ok = true; + } finally { + if (!ok) { + if (networkChannel != null) { + removeNetworkChannel(networkChannel.channel, null, null); + } + } + } + if (localChannelReference.getFutureValidateStartup().isDone() && + localChannelReference.getFutureValidateStartup().isSuccess()) { + sendValidationConnection(localChannelReference); + } else { + OpenR66ProtocolNetworkException exc = + new OpenR66ProtocolNetworkException("Startup is invalid"); + logger.debug("Startup is Invalid", exc); + R66Result finalValue = new R66Result( + exc, null, true, ErrorCode.ConnectionImpossible, null); + localChannelReference.invalidateRequest(finalValue); + Channels.close(localChannelReference.getLocalChannel()); + throw exc; + } + return localChannelReference; + } + + /** + * + * @param socketServerAddress + * @param isSSL + * @return the NetworkChannel + * @throws OpenR66ProtocolNetworkException + * @throws OpenR66ProtocolRemoteShutdownException + * @throws OpenR66ProtocolNoConnectionException + */ + private NetworkChannel createNewConnection(SocketAddress socketServerAddress, boolean isSSL) + throws OpenR66ProtocolNetworkException, + OpenR66ProtocolRemoteShutdownException, + OpenR66ProtocolNoConnectionException { + ReentrantLock socketLock = getChannelLock(socketServerAddress); + socketLock.lock(); + try { + if (!isAddressValid(socketServerAddress)) { + throw new OpenR66ProtocolRemoteShutdownException( + "Cannot connect to remote server since it is shutting down"); + } + NetworkChannel networkChannel; + try { + networkChannel = getRemoteChannel(socketServerAddress); + } catch (OpenR66ProtocolNoDataException e1) { + networkChannel = null; + } + if (networkChannel != null) { + networkChannel.count.incrementAndGet(); + logger.info("Already Connected: {}", networkChannel); + return networkChannel; + } + ChannelFuture channelFuture = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + if (isSSL) { + if (Configuration.configuration.HOST_SSLID != null) { + channelFuture = clientSslBootstrap.connect(socketServerAddress); + } else { + throw new OpenR66ProtocolNoConnectionException("No SSL support"); + } + } else { + channelFuture = clientBootstrap.connect(socketServerAddress); + } + } catch (ChannelPipelineException e) { + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to remote server due to a channel exception"); + } + try { + channelFuture.await(); + } catch (InterruptedException e1) { + } + if (channelFuture.isSuccess()) { + final Channel channel = channelFuture.getChannel(); + if (isSSL) { + if (!NetworkSslServerHandler.isSslConnectedChannel(channel)) { + logger.debug("KO CONNECT since SSL handshake is over"); + Channels.close(channel); + throw new OpenR66ProtocolNoConnectionException( + "Cannot finish connect to remote server"); + } + } + networkChannelGroup.add(channel); + return putRemoteChannel(channel); + } else { + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e) { + } + if (!channelFuture.isDone()) { + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to remote server due to interruption"); + } + if (channelFuture.getCause() instanceof ConnectException) { + logger.debug("KO CONNECT:" + + channelFuture.getCause().getMessage()); + throw new OpenR66ProtocolNoConnectionException( + "Cannot connect to remote server", channelFuture + .getCause()); + } else { + logger.debug("KO CONNECT but retry", channelFuture + .getCause()); + } + } + } + throw new OpenR66ProtocolNetworkException( + "Cannot connect to remote server", channelFuture.getCause()); + } finally { + socketLock.unlock(); + } + } + + /** + * + * @param channel + * @param futureRequest + * @return the LocalChannelReference + * @throws OpenR66ProtocolNetworkException + * @throws OpenR66ProtocolRemoteShutdownException + */ + private LocalChannelReference createNewClient(NetworkChannel networkChannel, + R66Future futureRequest) + throws OpenR66ProtocolNetworkException, + OpenR66ProtocolRemoteShutdownException { + if (!networkChannel.channel.isConnected()) { + throw new OpenR66ProtocolNetworkException( + "Network channel no more connected"); + } + LocalChannelReference localChannelReference = null; + try { + localChannelReference = Configuration.configuration + .getLocalTransaction().createNewClient(networkChannel.channel, + ChannelUtils.NOCHANNEL, futureRequest); + } catch (OpenR66ProtocolSystemException e) { + // check if the channel has other attached local channels + // NO since done in caller (createConnection) + /* + * logger.info("Try to Close Network"); removeNetworkChannel(networkChannel.channel, + * null); + */ + throw new OpenR66ProtocolNetworkException( + "Cannot connect to local channel", e); + } + return localChannelReference; + } + + /** + * Create the LocalChannelReference when a remote local channel starts its connection + * + * @param channel + * @param packet + * @return the LocalChannelReference + * @throws OpenR66ProtocolRemoteShutdownException + * @throws OpenR66ProtocolSystemException + */ + public static LocalChannelReference createConnectionFromNetworkChannelStartup(Channel channel, + NetworkPacket packet) + throws OpenR66ProtocolRemoteShutdownException, OpenR66ProtocolSystemException { + NetworkTransaction.addNetworkChannel(channel); + LocalChannelReference localChannelReference = Configuration.configuration + .getLocalTransaction().createNewClient(channel, + packet.getRemoteId(), null); + return localChannelReference; + } + + /** + * Send a validation of connection with Authentication + * + * @param localChannelReference + * @throws OpenR66ProtocolNetworkException + * @throws OpenR66ProtocolRemoteShutdownException + */ + private void sendValidationConnection( + LocalChannelReference localChannelReference) + throws OpenR66ProtocolNetworkException, + OpenR66ProtocolRemoteShutdownException { + AuthentPacket authent; + try { + authent = new AuthentPacket( + Configuration.configuration.getHostId( + localChannelReference.getNetworkServerHandler().isSsl()), + FilesystemBasedDigest.passwdCrypt( + Configuration.configuration.HOST_AUTH.getHostkey()), + localChannelReference.getLocalId()); + } catch (OpenR66ProtocolNoSslException e1) { + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException("No SSL support", e1), + localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); + logger.error("Authent is Invalid due to no SSL: {}", e1.getMessage()); + if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { + ConnectionErrorPacket error = new ConnectionErrorPacket( + "Cannot connect to localChannel since no SSL is supported", null); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e) { + } + } + localChannelReference.invalidateRequest(finalValue); + Channels.close(localChannelReference.getLocalChannel()); + throw new OpenR66ProtocolNetworkException(e1); + } + logger.debug("Will send request of connection validation"); + localChannelReference.sessionNewState(AUTHENTR); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, authent, true); + } catch (OpenR66ProtocolPacketException e) { + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException("Wrong Authent Protocol", e), + localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); + logger.error("Authent is Invalid due to protocol: {}", e.getMessage()); + localChannelReference.invalidateRequest(finalValue); + if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { + ConnectionErrorPacket error = new ConnectionErrorPacket( + "Cannot connect to localChannel since Authent Protocol is invalid", null); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e1) { + } + } + Channels.close(localChannelReference.getLocalChannel()); + throw new OpenR66ProtocolNetworkException("Bad packet", e); + } + R66Future future = localChannelReference.getFutureValidateConnection(); + if (future.isFailed()) { + logger.debug("Will close NETWORK channel since Future cancelled: {}", + future); + R66Result finalValue = new R66Result( + new OpenR66ProtocolSystemException( + "Out of time or Connection invalid during Authentication"), + localChannelReference.getSession(), true, ErrorCode.ConnectionImpossible, null); + logger.warn("Authent is Invalid due to: {} {}", finalValue.exception.getMessage(), + future.toString()); + localChannelReference.invalidateRequest(finalValue); + if (localChannelReference.getRemoteId() != ChannelUtils.NOCHANNEL) { + ConnectionErrorPacket error = new ConnectionErrorPacket( + "Cannot connect to localChannel with Out of Time", null); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, error, true); + } catch (OpenR66ProtocolPacketException e) { + } + } + Channels.close(localChannelReference.getLocalChannel()); + throw new OpenR66ProtocolNetworkException( + "Cannot validate connection: " + future.getResult(), future + .getCause()); + } + } + + public static ExecutorService getRetrieveExecutor() { + return retrieveExecutor; + } + + public static ConcurrentHashMap getRetrieveRunnerConcurrentHashMap() { + return retrieveRunnerConcurrentHashMap; + } + + /** + * Start retrieve operation + * + * @param session + * @param channel + */ + public static void runRetrieve(R66Session session, Channel channel) { + RetrieveRunner retrieveRunner = new RetrieveRunner(session, channel); + retrieveRunnerConcurrentHashMap.put(session.getLocalChannelReference().getLocalId(), + retrieveRunner); + retrieveRunner.setDaemon(true); + retrieveExecutor.execute(retrieveRunner); + } + + /** + * Stop a retrieve operation + * + * @param localChannelReference + */ + public static void stopRetrieve(LocalChannelReference localChannelReference) { + RetrieveRunner retrieveRunner = + retrieveRunnerConcurrentHashMap.remove(localChannelReference.getLocalId()); + if (retrieveRunner != null) { + retrieveRunner.stopRunner(); + } + } + + /** + * Normal end of a Retrieve Operation + * + * @param localChannelReference + */ + public static void normalEndRetrieve(LocalChannelReference localChannelReference) { + retrieveRunnerConcurrentHashMap.remove(localChannelReference.getLocalId()); + } + + /** + * Stop all Retrieve Executors + */ + public static void closeRetrieveExecutors() { + retrieveExecutor.shutdownNow(); + } + + /** + * Close all Network Ttransaction + */ + public void closeAll() { + logger.debug("close All Network Channels"); + try { + Thread.sleep(Configuration.RETRYINMS * 2); + } catch (InterruptedException e) { + } + if (!Configuration.configuration.isServer) { + R66ShutdownHook.shutdownHook.launchFinalExit(); + } + closeRetrieveExecutors(); + networkChannelGroup.close().awaitUninterruptibly(); + clientBootstrap.releaseExternalResources(); + clientSslBootstrap.releaseExternalResources(); + channelClientFactory.releaseExternalResources(); + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e) { + } + DbAdmin.closeAllConnection(); + Configuration.configuration.clientStop(); + logger.debug("Last action before exit"); + ChannelUtils.stopLogger(); + } + + /** + * + * @param channel + * @throws OpenR66ProtocolRemoteShutdownException + */ + public static void addNetworkChannel(Channel channel) + throws OpenR66ProtocolRemoteShutdownException { + if (!isAddressValid(channel.getRemoteAddress())) { + throw new OpenR66ProtocolRemoteShutdownException( + "Channel is already in shutdown"); + } + try { + putRemoteChannel(channel); + } catch (OpenR66ProtocolNoConnectionException e) { + throw new OpenR66ProtocolRemoteShutdownException( + "Channel is already in shutdown"); + } + } + + /** + * Add a LocalChannel to a NetworkChannel + * + * @param networkChannel + * @param localChannel + * @throws OpenR66ProtocolRemoteShutdownException + */ + public static void addLocalChannelToNetworkChannel(Channel networkChannel, + Channel localChannel) throws OpenR66ProtocolRemoteShutdownException { + SocketAddress address = networkChannel.getRemoteAddress(); + if (address != null) { + NetworkChannel networkChannelObject = networkChannelOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannelObject != null) { + networkChannelObject.add(localChannel); + } + } + } + + /** + * Shutdown one Network Channel + * + * @param channel + */ + public static void shuttingdownNetworkChannel(Channel channel) { + SocketAddress address = channel.getRemoteAddress(); + shuttingdownNetworkChannel(address, channel); + } + + /** + * Shutdown one Network Channel according to its SocketAddress + * + * @param address + * @param channel + * (can be null) + * @return True if the shutdown is starting, False if cannot be done (can be already done + * before) + */ + public static boolean shuttingdownNetworkChannel(SocketAddress address, Channel channel) { + if (address != null) { + ReentrantLock socketLock = getChannelLock(address); + socketLock.lock(); + try { + NetworkChannel networkChannel = + networkChannelShutdownOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannel != null) { + // already done + logger.debug("Already set as shutdown"); + return false; + } + networkChannel = networkChannelOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannel != null) { + logger.debug("Set as shutdown"); + } else { + if (channel != null) { + logger.debug("Newly Set as shutdown"); + networkChannel = new NetworkChannel(channel); + } + } + if (networkChannel != null) { + networkChannelShutdownOnSocketAddressConcurrentHashMap.put(address + .hashCode(), networkChannel); + if (networkChannel.isShuttingDown) { + return false; + } + networkChannel.shutdownAllLocalChannels(); + R66ShutdownNetworkChannelTimerTask timerTask = new R66ShutdownNetworkChannelTimerTask( + address.hashCode()); + Configuration.configuration.getTimerClose().newTimeout(timerTask, + Configuration.configuration.TIMEOUTCON * 3, TimeUnit.MILLISECONDS); + return true; + } + } finally { + socketLock.unlock(); + } + } + return false; + } + + /** + * + * @param address + * @return True if this channel is currently in shutdown + */ + public static boolean isShuttingdownNetworkChannel(SocketAddress address) { + ReentrantLock socketLock = getChannelLock(address); + socketLock.lock(); + try { + return !isAddressValid(address); + } finally { + socketLock.unlock(); + } + } + + /** + * Remove of requester + * + * @param requester + * @param networkChannel + */ + public static void removeClient(String requester, NetworkChannel networkChannel) { + if (networkChannel != null) { + lockClient.lock(); + try { + ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); + if (clientNetworkChannels != null) { + clientNetworkChannels.remove(networkChannel); + if (clientNetworkChannels.isEmpty()) { + remoteClients.remove(requester); + } + } + } finally { + lockClient.unlock(); + } + } + } + + /** + * Get NetworkChannel as client + * + * @param requester + * @return NetworkChannel associated with this host as client (only 1 allow even if more are + * available) + */ + public static boolean shuttingdownNetworkChannels(String requester) { + lockClient.lock(); + try { + ClientNetworkChannels clientNetworkChannels = remoteClients.remove(requester); + if (clientNetworkChannels != null) { + return clientNetworkChannels.shutdownAll(); + } + } finally { + lockClient.unlock(); + } + return false; + } + + /** + * Add a requester channel (so call only by requested host) + * + * @param channel + * (network channel) + * @param requester + */ + public static void addClient(Channel channel, String requester) { + SocketAddress address = channel.getRemoteAddress(); + if (address != null) { + NetworkChannel networkChannel = + networkChannelOnSocketAddressConcurrentHashMap.get(address.hashCode()); + if (networkChannel != null) { + lockClient.lock(); + try { + ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); + if (clientNetworkChannels == null) { + clientNetworkChannels = new ClientNetworkChannels(requester); + remoteClients.put(requester, clientNetworkChannels); + } + clientNetworkChannels.add(networkChannel); + } finally { + lockClient.unlock(); + } + } + } + } + + /** + * + * @param requester + * @return The number of NetworkChannels associated with this requester + */ + public static int getNumberClients(String requester) { + ClientNetworkChannels clientNetworkChannels = remoteClients.get(requester); + if (clientNetworkChannels != null) { + return clientNetworkChannels.size(); + } + return 0; + } + + /** + * Force remove of NetworkChannel when it is closed + * + * @param address + * @return the number of still connected Local Channels + */ + public static int removeForceNetworkChannel(SocketAddress address) { + ReentrantLock socketLock = getChannelLock(address); + socketLock.lock(); + try { + if (address != null) { + NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannel != null) { + if (networkChannel.isShuttingDown) { + return networkChannel.count.get(); + } + logger.debug("NC left: {}", networkChannel); + int count = networkChannel.count.get(); + networkChannel.shutdownAllLocalChannels(); + networkChannelOnSocketAddressConcurrentHashMap + .remove(address.hashCode()); + return count; + } else { + logger.debug("Network not registered"); + } + } + return 0; + } finally { + socketLock.unlock(); + removeChannelLock(address); + } + } + + /** + * Class to close the Network Channel if after some delays it has really no Local Channel + * attached + * + * @author Frederic Bregier + * + */ + static class CloseFutureChannel implements TimerTask { + + private static SortedSet inCloseRunning = + Collections + .synchronizedSortedSet(new TreeSet()); + private NetworkChannel networkChannel; + private String requester; + private SocketAddress address; + + /** + * @param networkChannel + * @param requester + * @throws OpenR66RunnerErrorException + */ + CloseFutureChannel(NetworkChannel networkChannel, SocketAddress address, String requester) + throws OpenR66RunnerErrorException { + if (!inCloseRunning.add(networkChannel.channel.getId())) + throw new OpenR66RunnerErrorException("Already scheduled"); + this.networkChannel = networkChannel; + this.requester = requester; + this.address = address; + } + + public void run(Timeout timeout) throws Exception { + ReentrantLock socketLock = getChannelLock(address); + socketLock.lock(); + try { + if (networkChannel.count.get() <= 0) { + long time = networkChannel.lastTimeUsed + + Configuration.configuration.TIMEOUTCON * 2 - + System.currentTimeMillis(); + if (time > Configuration.RETRYINMS) { + // will re execute this request later on + Configuration.configuration.getTimerClose().newTimeout(this, time, + TimeUnit.MILLISECONDS); + return; + } + if (requester != null) + NetworkTransaction.removeClient(requester, networkChannel); + networkChannelOnSocketAddressConcurrentHashMap + .remove(address.hashCode()); + logger.info("Will close NETWORK channel"); + WaarpSslUtility.closingSslChannel(networkChannel.channel); + } + inCloseRunning.remove(networkChannel.channel.getId()); + } finally { + socketLock.unlock(); + } + } + + } + + /** + * + * @param channel + * networkChannel + * @param localChannel + * localChannel + * @param requester + * Requester since call from LocalChannel close (might be null) + * @return the number of local channel still connected to this channel + */ + public static int removeNetworkChannel(Channel channel, Channel localChannel, + String requester) { + SocketAddress address = channel.getRemoteAddress(); + ReentrantLock socketLock = getChannelLock(address); + socketLock.lock(); + try { + if (address != null) { + NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannel != null) { + int count = networkChannel.count.decrementAndGet(); + logger.info("Close con: " + networkChannel); + if (localChannel != null) { + networkChannel.remove(localChannel); + } + if (count <= 0) { + CloseFutureChannel cfc; + try { + cfc = new CloseFutureChannel(networkChannel, address, requester); + Configuration.configuration.getTimerClose(). + newTimeout(cfc, Configuration.configuration.TIMEOUTCON * 2, + TimeUnit.MILLISECONDS); + } catch (OpenR66RunnerErrorException e) { + } + } + logger.debug("NC left: {}", networkChannel); + return count; + } else { + if (channel.isConnected()) { + logger.debug("Should not be here", + new OpenR66ProtocolSystemException()); + } + } + } + return 0; + } finally { + socketLock.unlock(); + } + } + + /** + * + * @param address + * @param host + * @return True if a connection is still active on this socket or for this host + */ + public static int existConnection(SocketAddress address, String host) { + return (networkChannelOnSocketAddressConcurrentHashMap.containsKey(address.hashCode()) ? 1 + : 0) + + getNumberClients(host); + } + + /** + * + * @param channel + * @return the number of local channel associated with this channel + */ + public static int getNbLocalChannel(Channel channel) { + SocketAddress address = channel.getRemoteAddress(); + if (address != null) { + NetworkChannel networkChannel = networkChannelOnSocketAddressConcurrentHashMap + .get(address.hashCode()); + if (networkChannel != null) { + return networkChannel.count.get(); + } + } + return -1; + } + + /** + * + * @param address + * @return True if this socket Address is currently valid for connection + */ + private static boolean isAddressValid(SocketAddress address) { + if (R66ShutdownHook.isInShutdown()) { + logger.debug("IS IN SHUTDOWN"); + return false; + } + if (address == null) { + logger.debug("ADDRESS IS NULL"); + return false; + } + try { + NetworkChannel networkChannel = getRemoteChannel(address); + logger.debug("IS IN SHUTDOWN: " + networkChannel.isShuttingDown); + return !networkChannel.isShuttingDown; + } catch (OpenR66ProtocolRemoteShutdownException e) { + logger.debug("ALREADY IN SHUTDOWN"); + return false; + } catch (OpenR66ProtocolNoDataException e) { + logger.debug("NOT FOUND SO NO SHUTDOWN"); + return true; + } + } + + /** + * + * @param channel + * @return the associated NetworkChannel if any (Null if none) + */ + public static NetworkChannel getNetworkChannel(Channel channel) { + SocketAddress address = channel.getRemoteAddress(); + if (address != null) { + return networkChannelOnSocketAddressConcurrentHashMap.get(address + .hashCode()); + } + return null; + } + + /** + * + * @param address + * @return NetworkChannel + * @throws OpenR66ProtocolRemoteShutdownException + * @throws OpenR66ProtocolNoDataException + */ + private static NetworkChannel getRemoteChannel(SocketAddress address) + throws OpenR66ProtocolRemoteShutdownException, + OpenR66ProtocolNoDataException { + if (R66ShutdownHook.isInShutdown()) { + logger.debug("IS IN SHUTDOWN"); + throw new OpenR66ProtocolRemoteShutdownException( + "Local Host already in shutdown"); + } + if (address == null) { + throw new OpenR66ProtocolRemoteShutdownException( + "Remote Host already in shutdown"); + } + int hashCode = address.hashCode(); + NetworkChannel nc = networkChannelShutdownOnSocketAddressConcurrentHashMap + .get(hashCode); + if (nc != null) { + throw new OpenR66ProtocolRemoteShutdownException( + "Remote Host already in shutdown"); + } + nc = networkChannelOnSocketAddressConcurrentHashMap.get(hashCode); + if (nc == null) { + throw new OpenR66ProtocolNoDataException("Channel not found"); + } + return nc; + } + + /** + * + * @param channel + * @return the associated NetworkChannel + * @throws OpenR66ProtocolRemoteShutdownException + * @throws OpenR66ProtocolNoDataException + */ + private static NetworkChannel putRemoteChannel(Channel channel) + throws OpenR66ProtocolRemoteShutdownException, OpenR66ProtocolNoConnectionException { + SocketAddress address = channel.getRemoteAddress(); + if (address != null) { + NetworkChannel networkChannel; + try { + networkChannel = getRemoteChannel(address); + networkChannel.count.incrementAndGet(); + logger.info("NC active: {}", networkChannel); + return networkChannel; + } catch (OpenR66ProtocolRemoteShutdownException e) { + throw e; + } catch (OpenR66ProtocolNoDataException e) { + networkChannel = new NetworkChannel(channel); + logger.debug("NC new active: {}", networkChannel); + networkChannelOnSocketAddressConcurrentHashMap.put(address + .hashCode(), networkChannel); + return networkChannel; + } + } + throw new OpenR66ProtocolNoConnectionException("Address is not correct"); + } + + /** + * Remover of Shutdown Remote Host + * + * @author Frederic Bregier + * + */ + private static class R66ShutdownNetworkChannelTimerTask implements TimerTask { + /** + * href to remove + */ + private final int href; + + /** + * Constructor from type + * + * @param href + */ + public R66ShutdownNetworkChannelTimerTask(int href) { + super(); + this.href = href; + } + + public void run(Timeout timeout) throws Exception { + logger.debug("DEBUG: Will remove shutdown for : " + href); + NetworkChannel networkChannel = + networkChannelShutdownOnSocketAddressConcurrentHashMap.remove(href); + if (networkChannel != null && networkChannel.channel != null + && networkChannel.channel.isConnected()) { + WaarpSslUtility.closingSslChannel(networkChannel.channel); + } + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/R66ConstraintLimitHandler.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/R66ConstraintLimitHandler.java index 8ac1d14cf..e178c757b 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/R66ConstraintLimitHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/R66ConstraintLimitHandler.java @@ -1,152 +1,152 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler; - -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.waarp.common.cpu.WaarpConstraintLimitHandler; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * R66 Constraint Limit Handler - * - * Constraint Limit (CPU and connection - network and local -) handler, only for server side - * (requested or requester). - * - * @author Frederic Bregier - * - */ -public class R66ConstraintLimitHandler extends WaarpConstraintLimitHandler { - public R66ConstraintLimitHandler() { - super(); - } - - /** - * @param useJdKCpuLimit - * True to use JDK Cpu native or False for JavaSysMon - * @param lowcpuLimit - * for proactive cpu limitation (throttling bandwidth) (0<= x < 1 & highcpulimit) - * @param highcpuLimit - * for proactive cpu limitation (throttling bandwidth) (0<= x <= 1) 0 meaning no - * throttle activated - * @param percentageDecrease - * for proactive cpu limitation, throttling bandwidth reduction (0 < x < 1) as 0.25 - * for 25% of reduction - * @param handler - * the GlobalTrafficShapingHandler associated (null to have no proactive cpu - * limitation) - * @param delay - * the delay between 2 tests for proactive cpu limitation - * @param limitLowBandwidth - * the minimal bandwidth (read or write) to apply when decreasing bandwidth (low - * limit = 4096) - */ - public R66ConstraintLimitHandler(boolean useJdKCpuLimit, - double lowcpuLimit, double highcpuLimit, double percentageDecrease, - GlobalTrafficShapingHandler handler, long delay, - long limitLowBandwidth) { - super(Configuration.WAITFORNETOP, Configuration.configuration.TIMEOUTCON, - useJdKCpuLimit, - lowcpuLimit, highcpuLimit, - percentageDecrease, handler, delay, limitLowBandwidth); - } - - /** - * @param useCpuLimit - * True to enable cpuLimit on connection check - * @param useJdKCpuLimit - * True to use JDK Cpu native or False for JavaSysMon - * @param cpulimit - * high cpu limit (0<= x < 1) to refuse new connections - * @param channellimit - * number of connection limit (0<= x) - */ - public R66ConstraintLimitHandler(boolean useCpuLimit, - boolean useJdKCpuLimit, double cpulimit, int channellimit) { - super(Configuration.WAITFORNETOP, Configuration.configuration != null ? - Configuration.configuration.TIMEOUTCON : 30000, - useCpuLimit, useJdKCpuLimit, cpulimit, channellimit); - } - - /** - * @param useCpuLimit - * True to enable cpuLimit on connection check - * @param useJdKCpuLimit - * True to use JDK Cpu native or False for JavaSysMon - * @param cpulimit - * high cpu limit (0<= x < 1) to refuse new connections - * @param channellimit - * number of connection limit (0<= x) - * @param lowcpuLimit - * for proactive cpu limitation (throttling bandwidth) (0<= x < 1 & highcpulimit) - * @param highcpuLimit - * for proactive cpu limitation (throttling bandwidth) (0<= x <= 1) 0 meaning no - * throttle activated - * @param percentageDecrease - * for proactive cpu limitation, throttling bandwidth reduction (0 < x < 1) as 0.25 - * for 25% of reduction - * @param handler - * the GlobalTrafficShapingHandler associated (null to have no proactive cpu - * limitation) - * @param delay - * the delay between 2 tests for proactive cpu limitation - * @param limitLowBandwidth - * the minimal bandwidth (read or write) to apply when decreasing bandwidth (low - * limit = 4096) - */ - public R66ConstraintLimitHandler( - boolean useCpuLimit, boolean useJdKCpuLimit, double cpulimit, - int channellimit, double lowcpuLimit, double highcpuLimit, - double percentageDecrease, GlobalTrafficShapingHandler handler, - long delay, long limitLowBandwidth) { - super(Configuration.WAITFORNETOP, Configuration.configuration.TIMEOUTCON, - useCpuLimit, useJdKCpuLimit, - cpulimit, channellimit, lowcpuLimit, highcpuLimit, - percentageDecrease, handler, delay, limitLowBandwidth); - } - - /* - * (non-Javadoc) - * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getNumberLocalChannel() - */ - @Override - protected int getNumberLocalChannel() { - if (Configuration.configuration.getLocalTransaction() != null) { - return Configuration.configuration.getLocalTransaction().getNumberLocalChannel(); - } - return 0; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getReadLimit() - */ - @Override - protected long getReadLimit() { - return Configuration.configuration.serverGlobalReadLimit; - } - - /* - * (non-Javadoc) - * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getWriteLimit() - */ - @Override - protected long getWriteLimit() { - return Configuration.configuration.serverGlobalWriteLimit; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler; + +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.waarp.common.cpu.WaarpConstraintLimitHandler; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * R66 Constraint Limit Handler + * + * Constraint Limit (CPU and connection - network and local -) handler, only for server side + * (requested or requester). + * + * @author Frederic Bregier + * + */ +public class R66ConstraintLimitHandler extends WaarpConstraintLimitHandler { + public R66ConstraintLimitHandler() { + super(); + } + + /** + * @param useJdKCpuLimit + * True to use JDK Cpu native or False for JavaSysMon + * @param lowcpuLimit + * for proactive cpu limitation (throttling bandwidth) (0<= x < 1 & highcpulimit) + * @param highcpuLimit + * for proactive cpu limitation (throttling bandwidth) (0<= x <= 1) 0 meaning no + * throttle activated + * @param percentageDecrease + * for proactive cpu limitation, throttling bandwidth reduction (0 < x < 1) as 0.25 + * for 25% of reduction + * @param handler + * the GlobalTrafficShapingHandler associated (null to have no proactive cpu + * limitation) + * @param delay + * the delay between 2 tests for proactive cpu limitation + * @param limitLowBandwidth + * the minimal bandwidth (read or write) to apply when decreasing bandwidth (low + * limit = 4096) + */ + public R66ConstraintLimitHandler(boolean useJdKCpuLimit, + double lowcpuLimit, double highcpuLimit, double percentageDecrease, + GlobalTrafficShapingHandler handler, long delay, + long limitLowBandwidth) { + super(Configuration.WAITFORNETOP, Configuration.configuration.TIMEOUTCON, + useJdKCpuLimit, + lowcpuLimit, highcpuLimit, + percentageDecrease, handler, delay, limitLowBandwidth); + } + + /** + * @param useCpuLimit + * True to enable cpuLimit on connection check + * @param useJdKCpuLimit + * True to use JDK Cpu native or False for JavaSysMon + * @param cpulimit + * high cpu limit (0<= x < 1) to refuse new connections + * @param channellimit + * number of connection limit (0<= x) + */ + public R66ConstraintLimitHandler(boolean useCpuLimit, + boolean useJdKCpuLimit, double cpulimit, int channellimit) { + super(Configuration.WAITFORNETOP, Configuration.configuration != null ? + Configuration.configuration.TIMEOUTCON : 30000, + useCpuLimit, useJdKCpuLimit, cpulimit, channellimit); + } + + /** + * @param useCpuLimit + * True to enable cpuLimit on connection check + * @param useJdKCpuLimit + * True to use JDK Cpu native or False for JavaSysMon + * @param cpulimit + * high cpu limit (0<= x < 1) to refuse new connections + * @param channellimit + * number of connection limit (0<= x) + * @param lowcpuLimit + * for proactive cpu limitation (throttling bandwidth) (0<= x < 1 & highcpulimit) + * @param highcpuLimit + * for proactive cpu limitation (throttling bandwidth) (0<= x <= 1) 0 meaning no + * throttle activated + * @param percentageDecrease + * for proactive cpu limitation, throttling bandwidth reduction (0 < x < 1) as 0.25 + * for 25% of reduction + * @param handler + * the GlobalTrafficShapingHandler associated (null to have no proactive cpu + * limitation) + * @param delay + * the delay between 2 tests for proactive cpu limitation + * @param limitLowBandwidth + * the minimal bandwidth (read or write) to apply when decreasing bandwidth (low + * limit = 4096) + */ + public R66ConstraintLimitHandler( + boolean useCpuLimit, boolean useJdKCpuLimit, double cpulimit, + int channellimit, double lowcpuLimit, double highcpuLimit, + double percentageDecrease, GlobalTrafficShapingHandler handler, + long delay, long limitLowBandwidth) { + super(Configuration.WAITFORNETOP, Configuration.configuration.TIMEOUTCON, + useCpuLimit, useJdKCpuLimit, + cpulimit, channellimit, lowcpuLimit, highcpuLimit, + percentageDecrease, handler, delay, limitLowBandwidth); + } + + /* + * (non-Javadoc) + * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getNumberLocalChannel() + */ + @Override + protected int getNumberLocalChannel() { + if (Configuration.configuration.getLocalTransaction() != null) { + return Configuration.configuration.getLocalTransaction().getNumberLocalChannel(); + } + return 0; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getReadLimit() + */ + @Override + protected long getReadLimit() { + return Configuration.configuration.serverGlobalReadLimit; + } + + /* + * (non-Javadoc) + * @see org.waarp.common.cpu.WaarpConstraintLimitHandler#getWriteLimit() + */ + @Override + protected long getWriteLimit() { + return Configuration.configuration.serverGlobalWriteLimit; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/package-info.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/package-info.java index b203bf6a7..2e1fcb2ad 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/package-info.java @@ -1,8 +1,8 @@ -/** - * Classes implementing Network Handler (multiplexing local handlers) - * - * @apiviz.landmark - * @apiviz.uses {@link org.waarp.openr66.protocol.networkhandler.packet} - */ -package org.waarp.openr66.protocol.networkhandler; - +/** + * Classes implementing Network Handler (multiplexing local handlers) + * + * @apiviz.landmark + * @apiviz.uses {@link org.waarp.openr66.protocol.networkhandler.packet} + */ +package org.waarp.openr66.protocol.networkhandler; + diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacket.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacket.java index 5bf98c664..1fd9d06f5 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacket.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacket.java @@ -1,115 +1,115 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; - -/** - * Network Packet A Packet is composed of one global length field, two Id (4 bytes x 2) and a - * buffer. The first Id is the localId on receive operation and the remoteId on send operation. The - * second Id is the reverse. - * - * @author Frederic Bregier - */ -public class NetworkPacket { - private final ChannelBuffer buffer; - - private final int remoteId; - - private final int localId; - - private final byte code; - - /** - * @param localId - * @param remoteId - * @param code - * @param buffer - */ - public NetworkPacket(int localId, int remoteId, byte code, - ChannelBuffer buffer) { - this.remoteId = remoteId; - this.localId = localId; - this.code = code; - this.buffer = buffer; - } - - /** - * @param localId - * @param remoteId - * @param packet - * @throws OpenR66ProtocolPacketException - */ - public NetworkPacket(int localId, int remoteId, AbstractLocalPacket packet) - throws OpenR66ProtocolPacketException { - this.remoteId = remoteId; - this.localId = localId; - code = packet.getType(); - buffer = packet.getLocalPacket(); - } - - /** - * @return the buffer - */ - public ChannelBuffer getBuffer() { - return buffer; - } - - /** - * @return the remoteId - */ - public int getRemoteId() { - return remoteId; - } - - /** - * @return the localId - */ - public int getLocalId() { - return localId; - } - - /** - * @return the code - */ - public byte getCode() { - return code; - } - - /** - * @return The corresponding ChannelBuffer - */ - public ChannelBuffer getNetworkPacket() { - final ChannelBuffer buf = ChannelBuffers.dynamicBuffer(13); - buf.writeInt(buffer.readableBytes() + 9); - buf.writeInt(remoteId); - buf.writeInt(localId); - buf.writeByte(code); - return ChannelBuffers.wrappedBuffer(buf, buffer); - } - - @Override - public String toString() { - return "RId: " + remoteId + " LId: " + localId + " Code: " + code + - " Length: " + buffer.readableBytes(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; + +/** + * Network Packet A Packet is composed of one global length field, two Id (4 bytes x 2) and a + * buffer. The first Id is the localId on receive operation and the remoteId on send operation. The + * second Id is the reverse. + * + * @author Frederic Bregier + */ +public class NetworkPacket { + private final ChannelBuffer buffer; + + private final int remoteId; + + private final int localId; + + private final byte code; + + /** + * @param localId + * @param remoteId + * @param code + * @param buffer + */ + public NetworkPacket(int localId, int remoteId, byte code, + ChannelBuffer buffer) { + this.remoteId = remoteId; + this.localId = localId; + this.code = code; + this.buffer = buffer; + } + + /** + * @param localId + * @param remoteId + * @param packet + * @throws OpenR66ProtocolPacketException + */ + public NetworkPacket(int localId, int remoteId, AbstractLocalPacket packet) + throws OpenR66ProtocolPacketException { + this.remoteId = remoteId; + this.localId = localId; + code = packet.getType(); + buffer = packet.getLocalPacket(); + } + + /** + * @return the buffer + */ + public ChannelBuffer getBuffer() { + return buffer; + } + + /** + * @return the remoteId + */ + public int getRemoteId() { + return remoteId; + } + + /** + * @return the localId + */ + public int getLocalId() { + return localId; + } + + /** + * @return the code + */ + public byte getCode() { + return code; + } + + /** + * @return The corresponding ChannelBuffer + */ + public ChannelBuffer getNetworkPacket() { + final ChannelBuffer buf = ChannelBuffers.dynamicBuffer(13); + buf.writeInt(buffer.readableBytes() + 9); + buf.writeInt(remoteId); + buf.writeInt(localId); + buf.writeByte(code); + return ChannelBuffers.wrappedBuffer(buf, buffer); + } + + @Override + public String toString() { + return "RId: " + remoteId + " LId: " + localId + " Code: " + code + + " Length: " + buffer.readableBytes(); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketCodec.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketCodec.java index 699cd7ee0..b5ff43c05 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketCodec.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketCodec.java @@ -1,110 +1,110 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler.packet; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelDownstreamHandler; -import org.jboss.netty.channel.ChannelEvent; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.handler.codec.frame.FrameDecoder; -import org.waarp.common.exception.InvalidArgumentException; -import org.waarp.openr66.protocol.localhandler.packet.KeepAlivePacket; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.NoOpPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Packet Decoder - * - * @author Frederic Bregier - */ -public class NetworkPacketCodec extends FrameDecoder implements - ChannelDownstreamHandler { - /* - * (non-Javadoc) - * @see org.jboss.netty.handler.codec.frame.FrameDecoder#decode(org.jboss.netty - * .channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, - * org.jboss.netty.buffer.ChannelBuffer) - */ - @Override - protected Object decode(ChannelHandlerContext ctx, Channel channel, - ChannelBuffer buf) throws Exception { - // Make sure if the length field was received. - if (buf.readableBytes() < 4) { - // The length field was not received yet - return null. - // This method will be invoked again when more packets are - // received and appended to the buffer. - return null; - } - // Mark the current buffer position - buf.markReaderIndex(); - // Read the length field - final int length = buf.readInt(); - if (buf.readableBytes() < length) { - buf.resetReaderIndex(); - return null; - } - // Now we can read the two Ids - final int localId = buf.readInt(); - final int remoteId = buf.readInt(); - final byte code = buf.readByte(); - int readerInder = buf.readerIndex(); - ChannelBuffer buffer = buf.slice(readerInder, length - 9); - buf.skipBytes(length - 9); - NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer); - if (code == LocalPacketFactory.KEEPALIVEPACKET) { - KeepAlivePacket keepAlivePacket = (KeepAlivePacket) - LocalPacketCodec.decodeNetworkPacket(networkPacket.getBuffer()); - if (keepAlivePacket.isToValidate()) { - keepAlivePacket.validate(); - NetworkPacket response = - new NetworkPacket(ChannelUtils.NOCHANNEL, - ChannelUtils.NOCHANNEL, keepAlivePacket); - Channels.write(channel, response); - } - // Replaced by a NoOp packet - networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket()); - NetworkServerHandler nsh = (NetworkServerHandler) ctx.getPipeline().getLast(); - nsh.setKeepAlivedSent(); - } - return networkPacket; - } - - public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) - throws Exception { - if (e instanceof MessageEvent) { - final MessageEvent evt = (MessageEvent) e; - Object msg = evt.getMessage(); - if (!(msg instanceof NetworkPacket)) { - throw new InvalidArgumentException("Incorrect write object: " + - msg.getClass().getName()); - } - final NetworkPacket packet = (NetworkPacket) msg; - final ChannelBuffer finalBuf = packet.getNetworkPacket(); - Channels.write(ctx, evt.getFuture(), finalBuf); - } else { - ctx.sendDownstream(e); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler.packet; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelDownstreamHandler; +import org.jboss.netty.channel.ChannelEvent; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.handler.codec.frame.FrameDecoder; +import org.waarp.common.exception.InvalidArgumentException; +import org.waarp.openr66.protocol.localhandler.packet.KeepAlivePacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketCodec; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.NoOpPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Packet Decoder + * + * @author Frederic Bregier + */ +public class NetworkPacketCodec extends FrameDecoder implements + ChannelDownstreamHandler { + /* + * (non-Javadoc) + * @see org.jboss.netty.handler.codec.frame.FrameDecoder#decode(org.jboss.netty + * .channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, + * org.jboss.netty.buffer.ChannelBuffer) + */ + @Override + protected Object decode(ChannelHandlerContext ctx, Channel channel, + ChannelBuffer buf) throws Exception { + // Make sure if the length field was received. + if (buf.readableBytes() < 4) { + // The length field was not received yet - return null. + // This method will be invoked again when more packets are + // received and appended to the buffer. + return null; + } + // Mark the current buffer position + buf.markReaderIndex(); + // Read the length field + final int length = buf.readInt(); + if (buf.readableBytes() < length) { + buf.resetReaderIndex(); + return null; + } + // Now we can read the two Ids + final int localId = buf.readInt(); + final int remoteId = buf.readInt(); + final byte code = buf.readByte(); + int readerInder = buf.readerIndex(); + ChannelBuffer buffer = buf.slice(readerInder, length - 9); + buf.skipBytes(length - 9); + NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer); + if (code == LocalPacketFactory.KEEPALIVEPACKET) { + KeepAlivePacket keepAlivePacket = (KeepAlivePacket) + LocalPacketCodec.decodeNetworkPacket(networkPacket.getBuffer()); + if (keepAlivePacket.isToValidate()) { + keepAlivePacket.validate(); + NetworkPacket response = + new NetworkPacket(ChannelUtils.NOCHANNEL, + ChannelUtils.NOCHANNEL, keepAlivePacket); + Channels.write(channel, response); + } + // Replaced by a NoOp packet + networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket()); + NetworkServerHandler nsh = (NetworkServerHandler) ctx.getPipeline().getLast(); + nsh.setKeepAlivedSent(); + } + return networkPacket; + } + + public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) + throws Exception { + if (e instanceof MessageEvent) { + final MessageEvent evt = (MessageEvent) e; + Object msg = evt.getMessage(); + if (!(msg instanceof NetworkPacket)) { + throw new InvalidArgumentException("Incorrect write object: " + + msg.getClass().getName()); + } + final NetworkPacket packet = (NetworkPacket) msg; + final ChannelBuffer finalBuf = packet.getNetworkPacket(); + Channels.write(ctx, evt.getFuture(), finalBuf); + } else { + ctx.sendDownstream(e); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketSizeEstimator.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketSizeEstimator.java index 69ae2df30..5522fa3d0 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketSizeEstimator.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/NetworkPacketSizeEstimator.java @@ -1,45 +1,45 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler.packet; - -import org.jboss.netty.util.DefaultObjectSizeEstimator; -import org.jboss.netty.util.ObjectSizeEstimator; - -/** - * Network Packet size estimator - * - * @author Frederic Bregier - * - */ -public class NetworkPacketSizeEstimator implements ObjectSizeEstimator { - private DefaultObjectSizeEstimator internal = new DefaultObjectSizeEstimator(); - - /* - * (non-Javadoc) - * @see org.jboss.netty.handler.execution.ObjectSizeEstimator#estimateSize(java .lang.Object) - */ - public int estimateSize(Object o) { - if (!(o instanceof NetworkPacket)) { - // Type unimplemented - return internal.estimateSize(o); - } - NetworkPacket packet = (NetworkPacket) o; - int size = packet.getBuffer().readableBytes() + 13; - return size; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler.packet; + +import org.jboss.netty.util.DefaultObjectSizeEstimator; +import org.jboss.netty.util.ObjectSizeEstimator; + +/** + * Network Packet size estimator + * + * @author Frederic Bregier + * + */ +public class NetworkPacketSizeEstimator implements ObjectSizeEstimator { + private DefaultObjectSizeEstimator internal = new DefaultObjectSizeEstimator(); + + /* + * (non-Javadoc) + * @see org.jboss.netty.handler.execution.ObjectSizeEstimator#estimateSize(java .lang.Object) + */ + public int estimateSize(Object o) { + if (!(o instanceof NetworkPacket)) { + // Type unimplemented + return internal.estimateSize(o); + } + NetworkPacket packet = (NetworkPacket) o; + int size = packet.getBuffer().readableBytes() + 13; + return size; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/package-info.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/package-info.java index 7b101fe3f..58272a82c 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/packet/package-info.java @@ -1,6 +1,6 @@ -/** - * Classes implementing Packet for Network Handler - * - */ -package org.waarp.openr66.protocol.networkhandler.packet; - +/** + * Classes implementing Packet for Network Handler + * + */ +package org.waarp.openr66.protocol.networkhandler.packet; + diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerHandler.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerHandler.java index ce1c9a27d..1d52ad12c 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerHandler.java @@ -1,133 +1,133 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler.ssl; - - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelHandler; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.ChannelStateEvent; -import org.jboss.netty.handler.ssl.SslHandler; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.common.future.WaarpFuture; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; - -/** - * @author Frederic Bregier - * - */ -public class NetworkSslServerHandler extends NetworkServerHandler { - /** - * @param isServer - */ - public NetworkSslServerHandler(boolean isServer) { - super(isServer); - } - - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(NetworkSslServerHandler.class); - - /** - * - * @param channel - * @return True if the SSL handshake is over and OK, else False - */ - public static boolean isSslConnectedChannel(Channel channel) { - - WaarpFuture futureSSL = WaarpSslUtility.getFutureSslHandshake(channel); - if (futureSSL == null) { - for (int i = 0; i < Configuration.RETRYNB; i++) { - futureSSL = WaarpSslUtility.getFutureSslHandshake(channel); - if (futureSSL != null) - break; - try { - Thread.sleep(Configuration.RETRYINMS); - } catch (InterruptedException e) { - } - } - } - if (futureSSL == null) { - logger.debug("No wait For SSL found"); - return false; - } else { - try { - futureSSL.await(Configuration.configuration.TIMEOUTCON); - } catch (InterruptedException e) { - } - if (futureSSL.isDone()) { - logger.debug("Wait For SSL: " + futureSSL.isSuccess()); - return futureSSL.isSuccess(); - } - logger.error("Out of time for wait For SSL"); - return false; - } - } - - /* - * (non-Javadoc) - * @see org.jboss.netty.channel.SimpleChannelHandler#channelOpen(org.jboss.netty.channel. - * ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) - throws Exception { - Channel channel = e.getChannel(); - logger.debug("Add channel to ssl"); - WaarpSslUtility.addSslOpenedChannel(channel); - isSSL = true; - super.channelOpen(ctx, e); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.protocol.networkhandler.NetworkServerHandler#channelConnected - * (org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) - */ - @Override - public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) - throws OpenR66ProtocolNetworkException { - // Get the SslHandler in the current pipeline. - // We added it in NetworkSslServerPipelineFactory. - final ChannelHandler handler = ctx.getPipeline().getFirst(); - if (handler instanceof SslHandler) { - final SslHandler sslHandler = (SslHandler) handler; - if (sslHandler.isIssueHandshake()) { - // client side - WaarpSslUtility.setStatusSslConnectedChannel(ctx.getChannel(), true); - } else { - // server side - // Get the SslHandler and begin handshake ASAP. - // Get notified when SSL handshake is done. - if (! WaarpSslUtility.runHandshake(ctx.getChannel())) { - Configuration.configuration.r66Mib.notifyError( - "SSL Connection Error", "During Handshake"); - } - } - } else { - logger.error("SSL Not found"); - } - super.channelConnected(ctx, e); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler.ssl; + + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelHandler; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.handler.ssl.SslHandler; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.common.future.WaarpFuture; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.networkhandler.NetworkServerHandler; + +/** + * @author Frederic Bregier + * + */ +public class NetworkSslServerHandler extends NetworkServerHandler { + /** + * @param isServer + */ + public NetworkSslServerHandler(boolean isServer) { + super(isServer); + } + + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(NetworkSslServerHandler.class); + + /** + * + * @param channel + * @return True if the SSL handshake is over and OK, else False + */ + public static boolean isSslConnectedChannel(Channel channel) { + + WaarpFuture futureSSL = WaarpSslUtility.getFutureSslHandshake(channel); + if (futureSSL == null) { + for (int i = 0; i < Configuration.RETRYNB; i++) { + futureSSL = WaarpSslUtility.getFutureSslHandshake(channel); + if (futureSSL != null) + break; + try { + Thread.sleep(Configuration.RETRYINMS); + } catch (InterruptedException e) { + } + } + } + if (futureSSL == null) { + logger.debug("No wait For SSL found"); + return false; + } else { + try { + futureSSL.await(Configuration.configuration.TIMEOUTCON); + } catch (InterruptedException e) { + } + if (futureSSL.isDone()) { + logger.debug("Wait For SSL: " + futureSSL.isSuccess()); + return futureSSL.isSuccess(); + } + logger.error("Out of time for wait For SSL"); + return false; + } + } + + /* + * (non-Javadoc) + * @see org.jboss.netty.channel.SimpleChannelHandler#channelOpen(org.jboss.netty.channel. + * ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + Channel channel = e.getChannel(); + logger.debug("Add channel to ssl"); + WaarpSslUtility.addSslOpenedChannel(channel); + isSSL = true; + super.channelOpen(ctx, e); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.protocol.networkhandler.NetworkServerHandler#channelConnected + * (org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) + */ + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) + throws OpenR66ProtocolNetworkException { + // Get the SslHandler in the current pipeline. + // We added it in NetworkSslServerPipelineFactory. + final ChannelHandler handler = ctx.getPipeline().getFirst(); + if (handler instanceof SslHandler) { + final SslHandler sslHandler = (SslHandler) handler; + if (sslHandler.isIssueHandshake()) { + // client side + WaarpSslUtility.setStatusSslConnectedChannel(ctx.getChannel(), true); + } else { + // server side + // Get the SslHandler and begin handshake ASAP. + // Get notified when SSL handshake is done. + if (! WaarpSslUtility.runHandshake(ctx.getChannel())) { + Configuration.configuration.r66Mib.notifyError( + "SSL Connection Error", "During Handshake"); + } + } + } else { + logger.error("SSL Not found"); + } + super.channelConnected(ctx, e); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerPipelineFactory.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerPipelineFactory.java index 8818adb1f..ddca74b7f 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerPipelineFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/NetworkSslServerPipelineFactory.java @@ -1,109 +1,109 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.networkhandler.ssl; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; - -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.handler.execution.ExecutionHandler; -import org.jboss.netty.handler.ssl.SslHandler; -import org.jboss.netty.handler.timeout.IdleStateHandler; -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jboss.netty.util.HashedWheelTimer; -import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; -import org.waarp.common.crypto.ssl.WaarpSslContextFactory; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; -import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec; - -/** - * @author Frederic Bregier - * - */ -public class NetworkSslServerPipelineFactory implements ChannelPipelineFactory { - protected final boolean isClient; - public static WaarpSslContextFactory waarpSslContextFactory; - public static WaarpSecureKeyStore WaarpSecureKeyStore; - protected final ExecutorService executorService; - /** - * Global HashedWheelTimer - */ - public HashedWheelTimer timer = (HashedWheelTimer) Configuration.configuration - .getTimerClose(); - - /** - * - * @param isClient - * True if this Factory is to be used in Client mode - */ - public NetworkSslServerPipelineFactory(boolean isClient, ExecutorService executor) { - super(); - this.isClient = isClient; - this.executorService = executor; - } - - public ChannelPipeline getPipeline() { - final ChannelPipeline pipeline = Channels.pipeline(); - // Add SSL handler first to encrypt and decrypt everything. - SslHandler sslHandler = null; - if (isClient) { - // Not server: no clientAuthent, no renegotiation - sslHandler = - waarpSslContextFactory.initPipelineFactory(false, - false, false, executorService); - sslHandler.setIssueHandshake(true); - } else { - // Server: no renegotiation still, but possible clientAuthent - sslHandler = - waarpSslContextFactory.initPipelineFactory(true, - waarpSslContextFactory.needClientAuthentication(), - true, executorService); - } - pipeline.addLast("ssl", sslHandler); - - pipeline.addLast("codec", new NetworkPacketCodec()); - GlobalTrafficShapingHandler handler = Configuration.configuration - .getGlobalTrafficShapingHandler(); - if (handler != null) { - pipeline.addLast(NetworkServerPipelineFactory.LIMIT, handler); - } - ChannelTrafficShapingHandler trafficChannel = null; - try { - trafficChannel = - Configuration.configuration - .newChannelTrafficShapingHandler(); - pipeline.addLast(NetworkServerPipelineFactory.LIMITCHANNEL, trafficChannel); - } catch (OpenR66ProtocolNoDataException e) { - } - pipeline.addLast("pipelineExecutor", new ExecutionHandler( - Configuration.configuration.getServerPipelineExecutor())); - - pipeline.addLast(NetworkServerPipelineFactory.TIMEOUT, - new IdleStateHandler(timer, - 0, 0, - Configuration.configuration.TIMEOUTCON, - TimeUnit.MILLISECONDS)); - pipeline.addLast("handler", new NetworkSslServerHandler(!this.isClient)); - return pipeline; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.networkhandler.ssl; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.handler.execution.ExecutionHandler; +import org.jboss.netty.handler.ssl.SslHandler; +import org.jboss.netty.handler.timeout.IdleStateHandler; +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.jboss.netty.util.HashedWheelTimer; +import org.waarp.common.crypto.ssl.WaarpSecureKeyStore; +import org.waarp.common.crypto.ssl.WaarpSslContextFactory; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoDataException; +import org.waarp.openr66.protocol.networkhandler.NetworkServerPipelineFactory; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacketCodec; + +/** + * @author Frederic Bregier + * + */ +public class NetworkSslServerPipelineFactory implements ChannelPipelineFactory { + protected final boolean isClient; + public static WaarpSslContextFactory waarpSslContextFactory; + public static WaarpSecureKeyStore WaarpSecureKeyStore; + protected final ExecutorService executorService; + /** + * Global HashedWheelTimer + */ + public HashedWheelTimer timer = (HashedWheelTimer) Configuration.configuration + .getTimerClose(); + + /** + * + * @param isClient + * True if this Factory is to be used in Client mode + */ + public NetworkSslServerPipelineFactory(boolean isClient, ExecutorService executor) { + super(); + this.isClient = isClient; + this.executorService = executor; + } + + public ChannelPipeline getPipeline() { + final ChannelPipeline pipeline = Channels.pipeline(); + // Add SSL handler first to encrypt and decrypt everything. + SslHandler sslHandler = null; + if (isClient) { + // Not server: no clientAuthent, no renegotiation + sslHandler = + waarpSslContextFactory.initPipelineFactory(false, + false, false, executorService); + sslHandler.setIssueHandshake(true); + } else { + // Server: no renegotiation still, but possible clientAuthent + sslHandler = + waarpSslContextFactory.initPipelineFactory(true, + waarpSslContextFactory.needClientAuthentication(), + true, executorService); + } + pipeline.addLast("ssl", sslHandler); + + pipeline.addLast("codec", new NetworkPacketCodec()); + GlobalTrafficShapingHandler handler = Configuration.configuration + .getGlobalTrafficShapingHandler(); + if (handler != null) { + pipeline.addLast(NetworkServerPipelineFactory.LIMIT, handler); + } + ChannelTrafficShapingHandler trafficChannel = null; + try { + trafficChannel = + Configuration.configuration + .newChannelTrafficShapingHandler(); + pipeline.addLast(NetworkServerPipelineFactory.LIMITCHANNEL, trafficChannel); + } catch (OpenR66ProtocolNoDataException e) { + } + pipeline.addLast("pipelineExecutor", new ExecutionHandler( + Configuration.configuration.getServerPipelineExecutor())); + + pipeline.addLast(NetworkServerPipelineFactory.TIMEOUT, + new IdleStateHandler(timer, + 0, 0, + Configuration.configuration.TIMEOUTCON, + TimeUnit.MILLISECONDS)); + pipeline.addLast("handler", new NetworkSslServerHandler(!this.isClient)); + return pipeline; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/package-info.java b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/package-info.java index ad8a728e6..7f0c7dcd7 100644 --- a/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/networkhandler/ssl/package-info.java @@ -1,8 +1,8 @@ -/** - * Classes implementing Network SSL Handler (multiplexing local handlers) - * - * @apiviz.landmark - * @apiviz.uses {@link org.waarp.openr66.protocol.networkhandler.packet} - */ -package org.waarp.openr66.protocol.networkhandler.ssl; - +/** + * Classes implementing Network SSL Handler (multiplexing local handlers) + * + * @apiviz.landmark + * @apiviz.uses {@link org.waarp.openr66.protocol.networkhandler.packet} + */ +package org.waarp.openr66.protocol.networkhandler.ssl; + diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/R66Counter32.java b/src/main/java/org/waarp/openr66/protocol/snmp/R66Counter32.java index bb66badad..444fb9479 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/R66Counter32.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/R66Counter32.java @@ -1,68 +1,68 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.snmp; - -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.snmp.interf.WaarpCounter32; - -/** - * R66 Counter32 SNMP implementation - * - * @author Frederic Bregier - * - */ -public class R66Counter32 extends WaarpCounter32 { - - private int type = 1; - private int entry = 0; - /** - * - */ - private static final long serialVersionUID = -5850987508703222927L; - - public R66Counter32(int type, int entry) { - this.type = type; - this.entry = entry; - setInternalValue(); - } - - public R66Counter32(int type, int entry, long value) { - this.type = type; - this.entry = entry; - setInternalValue(value); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() - */ - @Override - protected void setInternalValue() { - Configuration.configuration.monitoring.run(type, entry); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) - */ - @Override - protected void setInternalValue(long value) { - setValue(value); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.snmp; + +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.snmp.interf.WaarpCounter32; + +/** + * R66 Counter32 SNMP implementation + * + * @author Frederic Bregier + * + */ +public class R66Counter32 extends WaarpCounter32 { + + private int type = 1; + private int entry = 0; + /** + * + */ + private static final long serialVersionUID = -5850987508703222927L; + + public R66Counter32(int type, int entry) { + this.type = type; + this.entry = entry; + setInternalValue(); + } + + public R66Counter32(int type, int entry, long value) { + this.type = type; + this.entry = entry; + setInternalValue(value); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() + */ + @Override + protected void setInternalValue() { + Configuration.configuration.monitoring.run(type, entry); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) + */ + @Override + protected void setInternalValue(long value) { + setValue(value); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/R66Gauge32.java b/src/main/java/org/waarp/openr66/protocol/snmp/R66Gauge32.java index 4bb9735f3..bb36b519f 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/R66Gauge32.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/R66Gauge32.java @@ -1,68 +1,68 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.snmp; - -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.snmp.interf.WaarpGauge32; - -/** - * R66 Gauge32 SNMP implementation - * - * @author Frederic Bregier - * - */ -public class R66Gauge32 extends WaarpGauge32 { - - private int type = 1; - private int entry = 0; - /** - * - */ - private static final long serialVersionUID = -5850987508703222927L; - - public R66Gauge32(int type, int entry) { - this.type = type; - this.entry = entry; - setInternalValue(); - } - - public R66Gauge32(int type, int entry, long value) { - this.type = type; - this.entry = entry; - setInternalValue(value); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() - */ - @Override - protected void setInternalValue() { - Configuration.configuration.monitoring.run(type, entry); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) - */ - @Override - protected void setInternalValue(long value) { - setValue(value); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.snmp; + +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.snmp.interf.WaarpGauge32; + +/** + * R66 Gauge32 SNMP implementation + * + * @author Frederic Bregier + * + */ +public class R66Gauge32 extends WaarpGauge32 { + + private int type = 1; + private int entry = 0; + /** + * + */ + private static final long serialVersionUID = -5850987508703222927L; + + public R66Gauge32(int type, int entry) { + this.type = type; + this.entry = entry; + setInternalValue(); + } + + public R66Gauge32(int type, int entry, long value) { + this.type = type; + this.entry = entry; + setInternalValue(value); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() + */ + @Override + protected void setInternalValue() { + Configuration.configuration.monitoring.run(type, entry); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) + */ + @Override + protected void setInternalValue(long value) { + setValue(value); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/R66PrivateMib.java b/src/main/java/org/waarp/openr66/protocol/snmp/R66PrivateMib.java index d7f505968..46a4e5205 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/R66PrivateMib.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/R66PrivateMib.java @@ -1,359 +1,359 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.snmp; - -import org.snmp4j.agent.DuplicateRegistrationException; -import org.snmp4j.agent.MOScope; -import org.snmp4j.mp.SnmpConstants; -import org.snmp4j.smi.Gauge32; -import org.snmp4j.smi.OctetString; -import org.snmp4j.smi.TimeTicks; -import org.snmp4j.smi.VariableBinding; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; -import org.waarp.openr66.protocol.utils.Version; -import org.waarp.snmp.r66.WaarpPrivateMib; -import org.waarp.snmp.utils.MemoryGauge32; -import org.waarp.snmp.utils.MemoryGauge32.MemoryType; -import org.waarp.snmp.utils.WaarpMORow; -import org.waarp.snmp.utils.WaarpMOScalar; -import org.waarp.snmp.utils.WaarpUptime; - -/** - * Waarp OpenR66 Private MIB implementation - * - * @author Frederic Bregier - * - */ -public class R66PrivateMib extends WaarpPrivateMib { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66PrivateMib.class); - - /** - * @param sysdesc - * @param port - * @param smiPrivateCodeFinal - * @param typeWaarpObject - * @param scontactName - * @param stextualName - * @param saddress - * @param iservice - */ - public R66PrivateMib(String sysdesc, int port, int smiPrivateCodeFinal, - int typeWaarpObject, String scontactName, String stextualName, - String saddress, int iservice) { - super(sysdesc, port, smiPrivateCodeFinal, typeWaarpObject, - scontactName, stextualName, saddress, iservice); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.WaarpPrivateMib#agentRegisterWaarpMib() - */ - @Override - protected void agentRegisterWaarpMib() - throws DuplicateRegistrationException { - logger.debug("registerGGMib"); - // register Static info - rowInfo = new WaarpMORow(this, rootOIDWaarpInfo, WaarpDefinition, - MibLevel.staticInfo.ordinal()); - rowInfo.setValue(WaarpDefinitionIndex.applName.ordinal(), - "Waarp OpenR66"); - rowInfo.setValue(WaarpDefinitionIndex.applServerName.ordinal(), - Configuration.configuration.HOST_ID); - rowInfo.setValue(WaarpDefinitionIndex.applVersion.ordinal(), - Version.ID); - rowInfo.setValue(WaarpDefinitionIndex.applDescription.ordinal(), - "Waarp OpenR66: File Transfer Monitor"); - rowInfo.setValue(WaarpDefinitionIndex.applURL.ordinal(), - "http://waarp.github.com/Waarp"); - rowInfo.setValue(WaarpDefinitionIndex.applApplicationProtocol.ordinal(), - applicationProtocol); - - rowInfo.registerMOs(agent.getServer(), null); - // register General info - rowGlobal = new WaarpMORow(this, rootOIDWaarpGlobal, WaarpGlobalValues, - MibLevel.globalInfo.ordinal()); - WaarpMOScalar memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryTotal.ordinal()]; - memoryScalar.setValue(new MemoryGauge32(MemoryType.TotalMemory)); - memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryFree.ordinal()]; - memoryScalar.setValue(new MemoryGauge32(MemoryType.FreeMemory)); - memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryUsed.ordinal()]; - memoryScalar.setValue(new MemoryGauge32(MemoryType.UsedMemory)); - rowGlobal.registerMOs(agent.getServer(), null); - // setup UpTime to SysUpTime and change status - scalarUptime = rowGlobal.row[WaarpGlobalValuesIndex.applUptime.ordinal()]; - scalarUptime.setValue(new WaarpUptime(upTime)); - changeStatus(OperStatus.restarting); - changeStatus(OperStatus.up); - // register Detailed info - rowDetailed = new WaarpMORow(this, rootOIDWaarpDetailed, WaarpDetailedValues, - MibLevel.detailedInfo.ordinal()); - rowDetailed.registerMOs(agent.getServer(), null); - // register Error info - rowError = new WaarpMORow(this, rootOIDWaarpError, WaarpErrorValues, - MibLevel.errorInfo.ordinal()); - rowError.registerMOs(agent.getServer(), null); - } - - /** - * Send a notification (trap or inform) for Shutdown event - * - * @param message - * @param message2 - */ - public void notifyStartStop(String message, String message2) { - if (!TrapLevel.StartStop.isLevelValid(agent.trapLevel)) - return; - notify(NotificationElements.TrapShutdown, message, message2); - } - - /** - * Send a notification (trap or inform) for Error event - * - * @param message - * @param message2 - */ - public void notifyError(String message, String message2) { - if (!TrapLevel.Alert.isLevelValid(agent.trapLevel)) - return; - notify(NotificationElements.TrapError, message, message2); - } - - /** - * Send a notification (trap or inform) for Server Overloaded event - * - * @param message - * @param message2 - */ - public void notifyOverloaded(String message, String message2) { - if (!TrapLevel.Warning.isLevelValid(agent.trapLevel)) - return; - notify(NotificationElements.TrapOverloaded, message, message2); - } - - /** - * Send a notification (trap or inform) for Warning event - * - * @param message - * @param message2 - */ - public void notifyWarning(String message, String message2) { - if (!TrapLevel.Warning.isLevelValid(agent.trapLevel)) - return; - notify(NotificationElements.TrapWarning, message, message2); - } - - /** - * Send a notification (trap or inform) - * - * @param message - * @param runner - */ - public void notifyInternalTask(String message, DbTaskRunner runner) { - long delay = (runner.getStart().getTime() - - agent.getUptimeSystemTime()) / 10; - if (delay < 0) - delay = 0; - agent.getNotificationOriginator() - .notify(new OctetString("public"), - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif), - new VariableBinding[] { - new VariableBinding( - NotificationElements.InfoTask.getOID( - rootOIDWaarpNotif, 1), - new OctetString( - NotificationElements.InfoTask - .name())), - new VariableBinding( - NotificationElements.InfoTask.getOID( - rootOIDWaarpNotif, 1), - new OctetString(message)), - // Start of Task - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.globalStepInfo - .getOID()), - new Gauge32(runner.getGloballaststep())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.stepInfo - .getOID()), - new Gauge32(runner.getStep() + 1)), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.rankFileInfo - .getOID()), - new Gauge32(runner.getRank())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.stepStatusInfo - .getOID()), - new OctetString(runner.getStatus().mesg)), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.filenameInfo - .getOID()), - new OctetString(runner.getFilename())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.originalNameInfo - .getOID()), - new OctetString(runner.getOriginalFilename())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.idRuleInfo - .getOID()), - new OctetString(runner.getRuleId())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.modeTransInfo - .getOID()), - new OctetString(TRANSFERMODE.values()[runner.getMode()] - .name())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.retrieveModeInfo - .getOID()), - new OctetString(runner.isSender() ? "Sender" : "Receiver")), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.startTransInfo - .getOID()), - new TimeTicks(delay)), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.infoStatusInfo - .getOID()), - new OctetString(runner.getErrorInfo().mesg)), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.requesterInfo - .getOID()), - new OctetString(runner.getRequester())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.requestedInfo - .getOID()), - new OctetString(runner.getRequested())), - new VariableBinding( - NotificationElements.InfoTask - .getOID(rootOIDWaarpNotif, - NotificationTasks.specialIdInfo - .getOID()), - new OctetString("" + runner.getSpecialId())), - // End of Task - new VariableBinding(SnmpConstants.sysDescr, - snmpv2.getDescr()), - new VariableBinding(SnmpConstants.sysObjectID, - snmpv2.getObjectID()), - new VariableBinding(SnmpConstants.sysContact, - snmpv2.getContact()), - new VariableBinding(SnmpConstants.sysName, - snmpv2.getName()), - new VariableBinding(SnmpConstants.sysLocation, - snmpv2.getLocation()) }); - } - - /** - * Send a notification (trap or inform) for Warning/Error event on a single Transfer Task - * - * @param message - * @param runner - */ - public void notifyInfoTask(String message, DbTaskRunner runner) { - if (!TrapLevel.All.isLevelValid(agent.trapLevel)) - return; - if (logger.isDebugEnabled()) - logger.debug("Notify: " + NotificationElements.InfoTask + ":" + message + - ":" + runner.toShortString()); - notifyInternalTask(message, runner); - } - /** - * Send a notification (trap or inform) for all events on a single Transfer Task - * - * @param message - * @param runner - */ - public void notifyTask(String message, DbTaskRunner runner) { - if (!TrapLevel.AllEvents.isLevelValid(agent.trapLevel)) - return; - if (logger.isDebugEnabled()) - logger.debug("Notify: " + NotificationElements.InfoTask + ":" + message + - ":" + runner.toShortString()); - notifyInternalTask(message, runner); - } - - /** - * Trap/Notification - * - * @param element - * @param message - * @param message2 - */ - private void notify(NotificationElements element, String message, String message2) { - if (logger.isDebugEnabled()) - logger.debug("Notify: " + element + ":" + message + ":" + message2); - agent.getNotificationOriginator().notify( - new OctetString("public"), - element.getOID(rootOIDWaarpNotif), - new VariableBinding[] { - new VariableBinding( - element.getOID(rootOIDWaarpNotif, 1), - new OctetString(element.name())), - new VariableBinding( - element.getOID(rootOIDWaarpNotif, 1), - new OctetString(message)), - new VariableBinding( - element.getOID(rootOIDWaarpNotif, 1), - new OctetString(message2)), - new VariableBinding(SnmpConstants.sysDescr, snmpv2.getDescr()), - new VariableBinding(SnmpConstants.sysObjectID, snmpv2.getObjectID()), - new VariableBinding(SnmpConstants.sysContact, snmpv2.getContact()), - new VariableBinding(SnmpConstants.sysName, snmpv2.getName()), - new VariableBinding(SnmpConstants.sysLocation, snmpv2.getLocation()) - }); - } - - public void updateServices(WaarpMOScalar scalar) { - } - - public void updateServices(MOScope range) { - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.snmp; + +import org.snmp4j.agent.DuplicateRegistrationException; +import org.snmp4j.agent.MOScope; +import org.snmp4j.mp.SnmpConstants; +import org.snmp4j.smi.Gauge32; +import org.snmp4j.smi.OctetString; +import org.snmp4j.smi.TimeTicks; +import org.snmp4j.smi.VariableBinding; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; +import org.waarp.openr66.protocol.utils.Version; +import org.waarp.snmp.r66.WaarpPrivateMib; +import org.waarp.snmp.utils.MemoryGauge32; +import org.waarp.snmp.utils.MemoryGauge32.MemoryType; +import org.waarp.snmp.utils.WaarpMORow; +import org.waarp.snmp.utils.WaarpMOScalar; +import org.waarp.snmp.utils.WaarpUptime; + +/** + * Waarp OpenR66 Private MIB implementation + * + * @author Frederic Bregier + * + */ +public class R66PrivateMib extends WaarpPrivateMib { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66PrivateMib.class); + + /** + * @param sysdesc + * @param port + * @param smiPrivateCodeFinal + * @param typeWaarpObject + * @param scontactName + * @param stextualName + * @param saddress + * @param iservice + */ + public R66PrivateMib(String sysdesc, int port, int smiPrivateCodeFinal, + int typeWaarpObject, String scontactName, String stextualName, + String saddress, int iservice) { + super(sysdesc, port, smiPrivateCodeFinal, typeWaarpObject, + scontactName, stextualName, saddress, iservice); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.WaarpPrivateMib#agentRegisterWaarpMib() + */ + @Override + protected void agentRegisterWaarpMib() + throws DuplicateRegistrationException { + logger.debug("registerGGMib"); + // register Static info + rowInfo = new WaarpMORow(this, rootOIDWaarpInfo, WaarpDefinition, + MibLevel.staticInfo.ordinal()); + rowInfo.setValue(WaarpDefinitionIndex.applName.ordinal(), + "Waarp OpenR66"); + rowInfo.setValue(WaarpDefinitionIndex.applServerName.ordinal(), + Configuration.configuration.HOST_ID); + rowInfo.setValue(WaarpDefinitionIndex.applVersion.ordinal(), + Version.ID); + rowInfo.setValue(WaarpDefinitionIndex.applDescription.ordinal(), + "Waarp OpenR66: File Transfer Monitor"); + rowInfo.setValue(WaarpDefinitionIndex.applURL.ordinal(), + "http://waarp.github.com/Waarp"); + rowInfo.setValue(WaarpDefinitionIndex.applApplicationProtocol.ordinal(), + applicationProtocol); + + rowInfo.registerMOs(agent.getServer(), null); + // register General info + rowGlobal = new WaarpMORow(this, rootOIDWaarpGlobal, WaarpGlobalValues, + MibLevel.globalInfo.ordinal()); + WaarpMOScalar memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryTotal.ordinal()]; + memoryScalar.setValue(new MemoryGauge32(MemoryType.TotalMemory)); + memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryFree.ordinal()]; + memoryScalar.setValue(new MemoryGauge32(MemoryType.FreeMemory)); + memoryScalar = rowGlobal.row[WaarpGlobalValuesIndex.memoryUsed.ordinal()]; + memoryScalar.setValue(new MemoryGauge32(MemoryType.UsedMemory)); + rowGlobal.registerMOs(agent.getServer(), null); + // setup UpTime to SysUpTime and change status + scalarUptime = rowGlobal.row[WaarpGlobalValuesIndex.applUptime.ordinal()]; + scalarUptime.setValue(new WaarpUptime(upTime)); + changeStatus(OperStatus.restarting); + changeStatus(OperStatus.up); + // register Detailed info + rowDetailed = new WaarpMORow(this, rootOIDWaarpDetailed, WaarpDetailedValues, + MibLevel.detailedInfo.ordinal()); + rowDetailed.registerMOs(agent.getServer(), null); + // register Error info + rowError = new WaarpMORow(this, rootOIDWaarpError, WaarpErrorValues, + MibLevel.errorInfo.ordinal()); + rowError.registerMOs(agent.getServer(), null); + } + + /** + * Send a notification (trap or inform) for Shutdown event + * + * @param message + * @param message2 + */ + public void notifyStartStop(String message, String message2) { + if (!TrapLevel.StartStop.isLevelValid(agent.trapLevel)) + return; + notify(NotificationElements.TrapShutdown, message, message2); + } + + /** + * Send a notification (trap or inform) for Error event + * + * @param message + * @param message2 + */ + public void notifyError(String message, String message2) { + if (!TrapLevel.Alert.isLevelValid(agent.trapLevel)) + return; + notify(NotificationElements.TrapError, message, message2); + } + + /** + * Send a notification (trap or inform) for Server Overloaded event + * + * @param message + * @param message2 + */ + public void notifyOverloaded(String message, String message2) { + if (!TrapLevel.Warning.isLevelValid(agent.trapLevel)) + return; + notify(NotificationElements.TrapOverloaded, message, message2); + } + + /** + * Send a notification (trap or inform) for Warning event + * + * @param message + * @param message2 + */ + public void notifyWarning(String message, String message2) { + if (!TrapLevel.Warning.isLevelValid(agent.trapLevel)) + return; + notify(NotificationElements.TrapWarning, message, message2); + } + + /** + * Send a notification (trap or inform) + * + * @param message + * @param runner + */ + public void notifyInternalTask(String message, DbTaskRunner runner) { + long delay = (runner.getStart().getTime() - + agent.getUptimeSystemTime()) / 10; + if (delay < 0) + delay = 0; + agent.getNotificationOriginator() + .notify(new OctetString("public"), + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif), + new VariableBinding[] { + new VariableBinding( + NotificationElements.InfoTask.getOID( + rootOIDWaarpNotif, 1), + new OctetString( + NotificationElements.InfoTask + .name())), + new VariableBinding( + NotificationElements.InfoTask.getOID( + rootOIDWaarpNotif, 1), + new OctetString(message)), + // Start of Task + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.globalStepInfo + .getOID()), + new Gauge32(runner.getGloballaststep())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.stepInfo + .getOID()), + new Gauge32(runner.getStep() + 1)), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.rankFileInfo + .getOID()), + new Gauge32(runner.getRank())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.stepStatusInfo + .getOID()), + new OctetString(runner.getStatus().mesg)), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.filenameInfo + .getOID()), + new OctetString(runner.getFilename())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.originalNameInfo + .getOID()), + new OctetString(runner.getOriginalFilename())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.idRuleInfo + .getOID()), + new OctetString(runner.getRuleId())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.modeTransInfo + .getOID()), + new OctetString(TRANSFERMODE.values()[runner.getMode()] + .name())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.retrieveModeInfo + .getOID()), + new OctetString(runner.isSender() ? "Sender" : "Receiver")), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.startTransInfo + .getOID()), + new TimeTicks(delay)), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.infoStatusInfo + .getOID()), + new OctetString(runner.getErrorInfo().mesg)), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.requesterInfo + .getOID()), + new OctetString(runner.getRequester())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.requestedInfo + .getOID()), + new OctetString(runner.getRequested())), + new VariableBinding( + NotificationElements.InfoTask + .getOID(rootOIDWaarpNotif, + NotificationTasks.specialIdInfo + .getOID()), + new OctetString("" + runner.getSpecialId())), + // End of Task + new VariableBinding(SnmpConstants.sysDescr, + snmpv2.getDescr()), + new VariableBinding(SnmpConstants.sysObjectID, + snmpv2.getObjectID()), + new VariableBinding(SnmpConstants.sysContact, + snmpv2.getContact()), + new VariableBinding(SnmpConstants.sysName, + snmpv2.getName()), + new VariableBinding(SnmpConstants.sysLocation, + snmpv2.getLocation()) }); + } + + /** + * Send a notification (trap or inform) for Warning/Error event on a single Transfer Task + * + * @param message + * @param runner + */ + public void notifyInfoTask(String message, DbTaskRunner runner) { + if (!TrapLevel.All.isLevelValid(agent.trapLevel)) + return; + if (logger.isDebugEnabled()) + logger.debug("Notify: " + NotificationElements.InfoTask + ":" + message + + ":" + runner.toShortString()); + notifyInternalTask(message, runner); + } + /** + * Send a notification (trap or inform) for all events on a single Transfer Task + * + * @param message + * @param runner + */ + public void notifyTask(String message, DbTaskRunner runner) { + if (!TrapLevel.AllEvents.isLevelValid(agent.trapLevel)) + return; + if (logger.isDebugEnabled()) + logger.debug("Notify: " + NotificationElements.InfoTask + ":" + message + + ":" + runner.toShortString()); + notifyInternalTask(message, runner); + } + + /** + * Trap/Notification + * + * @param element + * @param message + * @param message2 + */ + private void notify(NotificationElements element, String message, String message2) { + if (logger.isDebugEnabled()) + logger.debug("Notify: " + element + ":" + message + ":" + message2); + agent.getNotificationOriginator().notify( + new OctetString("public"), + element.getOID(rootOIDWaarpNotif), + new VariableBinding[] { + new VariableBinding( + element.getOID(rootOIDWaarpNotif, 1), + new OctetString(element.name())), + new VariableBinding( + element.getOID(rootOIDWaarpNotif, 1), + new OctetString(message)), + new VariableBinding( + element.getOID(rootOIDWaarpNotif, 1), + new OctetString(message2)), + new VariableBinding(SnmpConstants.sysDescr, snmpv2.getDescr()), + new VariableBinding(SnmpConstants.sysObjectID, snmpv2.getObjectID()), + new VariableBinding(SnmpConstants.sysContact, snmpv2.getContact()), + new VariableBinding(SnmpConstants.sysName, snmpv2.getName()), + new VariableBinding(SnmpConstants.sysLocation, snmpv2.getLocation()) + }); + } + + public void updateServices(WaarpMOScalar scalar) { + } + + public void updateServices(MOScope range) { + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/R66TimeTicks.java b/src/main/java/org/waarp/openr66/protocol/snmp/R66TimeTicks.java index 3d188f197..38d8312be 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/R66TimeTicks.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/R66TimeTicks.java @@ -1,68 +1,68 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.snmp; - -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.snmp.interf.WaarpTimeTicks; - -/** - * R66 TimeTicks SNMP implementation - * - * @author Frederic Bregier - * - */ -public class R66TimeTicks extends WaarpTimeTicks { - - private int type = 1; - private int entry = 0; - /** - * - */ - private static final long serialVersionUID = -5850987508703222927L; - - public R66TimeTicks(int type, int entry) { - this.type = type; - this.entry = entry; - setInternalValue(); - } - - public R66TimeTicks(int type, int entry, long value) { - this.type = type; - this.entry = entry; - setInternalValue(value); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() - */ - @Override - protected void setInternalValue() { - Configuration.configuration.monitoring.run(type, entry); - } - - /* - * (non-Javadoc) - * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) - */ - @Override - protected void setInternalValue(long value) { - setValue(value); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.snmp; + +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.snmp.interf.WaarpTimeTicks; + +/** + * R66 TimeTicks SNMP implementation + * + * @author Frederic Bregier + * + */ +public class R66TimeTicks extends WaarpTimeTicks { + + private int type = 1; + private int entry = 0; + /** + * + */ + private static final long serialVersionUID = -5850987508703222927L; + + public R66TimeTicks(int type, int entry) { + this.type = type; + this.entry = entry; + setInternalValue(); + } + + public R66TimeTicks(int type, int entry, long value) { + this.type = type; + this.entry = entry; + setInternalValue(value); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue() + */ + @Override + protected void setInternalValue() { + Configuration.configuration.monitoring.run(type, entry); + } + + /* + * (non-Javadoc) + * @see org.waarp.snmp.interf.WaarpGauge32#setInternalValue(long) + */ + @Override + protected void setInternalValue(long value) { + setValue(value); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/R66VariableFactory.java b/src/main/java/org/waarp/openr66/protocol/snmp/R66VariableFactory.java index b8bd73b99..a8020cd61 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/R66VariableFactory.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/R66VariableFactory.java @@ -1,82 +1,82 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.snmp; - -import org.snmp4j.smi.Counter64; -import org.snmp4j.smi.Integer32; -import org.snmp4j.smi.IpAddress; -import org.snmp4j.smi.Null; -import org.snmp4j.smi.OID; -import org.snmp4j.smi.OctetString; -import org.snmp4j.smi.Opaque; -import org.snmp4j.smi.SMIConstants; -import org.snmp4j.smi.Variable; -import org.waarp.snmp.interf.WaarpInterfaceVariableFactory; - -/** - * R66 implementation of VariableFactory for SNMP support - * - * @author Frederic Bregier - * - */ -public class R66VariableFactory implements WaarpInterfaceVariableFactory { - - public Variable getVariable(OID oid, int type, int mibLevel, int entry) { - Variable var; - switch (type) { - case SMIConstants.SYNTAX_INTEGER: - // case SMIConstants.SYNTAX_INTEGER32: - var = new Integer32(); - break; - case SMIConstants.SYNTAX_OCTET_STRING: - // case SMIConstants.SYNTAX_BITS: - var = new OctetString(); - break; - case SMIConstants.SYNTAX_NULL: - var = new Null(); - break; - case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: - var = new OID(); - break; - case SMIConstants.SYNTAX_IPADDRESS: - var = new IpAddress(); - break; - case SMIConstants.SYNTAX_COUNTER32: - var = new R66Counter32(mibLevel, entry); - break; - case SMIConstants.SYNTAX_GAUGE32: - // case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: - var = new R66Gauge32(mibLevel, entry); - break; - case SMIConstants.SYNTAX_TIMETICKS: - var = new R66TimeTicks(mibLevel, entry); - break; - case SMIConstants.SYNTAX_OPAQUE: - var = new Opaque(); - break; - case SMIConstants.SYNTAX_COUNTER64: - var = new Counter64(); - break; - default: - throw new IllegalArgumentException("Unmanaged Type: " + - type); - } - return var; - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.snmp; + +import org.snmp4j.smi.Counter64; +import org.snmp4j.smi.Integer32; +import org.snmp4j.smi.IpAddress; +import org.snmp4j.smi.Null; +import org.snmp4j.smi.OID; +import org.snmp4j.smi.OctetString; +import org.snmp4j.smi.Opaque; +import org.snmp4j.smi.SMIConstants; +import org.snmp4j.smi.Variable; +import org.waarp.snmp.interf.WaarpInterfaceVariableFactory; + +/** + * R66 implementation of VariableFactory for SNMP support + * + * @author Frederic Bregier + * + */ +public class R66VariableFactory implements WaarpInterfaceVariableFactory { + + public Variable getVariable(OID oid, int type, int mibLevel, int entry) { + Variable var; + switch (type) { + case SMIConstants.SYNTAX_INTEGER: + // case SMIConstants.SYNTAX_INTEGER32: + var = new Integer32(); + break; + case SMIConstants.SYNTAX_OCTET_STRING: + // case SMIConstants.SYNTAX_BITS: + var = new OctetString(); + break; + case SMIConstants.SYNTAX_NULL: + var = new Null(); + break; + case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: + var = new OID(); + break; + case SMIConstants.SYNTAX_IPADDRESS: + var = new IpAddress(); + break; + case SMIConstants.SYNTAX_COUNTER32: + var = new R66Counter32(mibLevel, entry); + break; + case SMIConstants.SYNTAX_GAUGE32: + // case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: + var = new R66Gauge32(mibLevel, entry); + break; + case SMIConstants.SYNTAX_TIMETICKS: + var = new R66TimeTicks(mibLevel, entry); + break; + case SMIConstants.SYNTAX_OPAQUE: + var = new Opaque(); + break; + case SMIConstants.SYNTAX_COUNTER64: + var = new Counter64(); + break; + default: + throw new IllegalArgumentException("Unmanaged Type: " + + type); + } + return var; + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/snmp/package-info.java b/src/main/java/org/waarp/openr66/protocol/snmp/package-info.java index 8d1da7aa5..0857d1a29 100644 --- a/src/main/java/org/waarp/openr66/protocol/snmp/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/snmp/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing SNMP elements for OpenR66 - * - * @apiviz.landmark - */ -package org.waarp.openr66.protocol.snmp; - +/** + * Classes implementing SNMP elements for OpenR66 + * + * @apiviz.landmark + */ +package org.waarp.openr66.protocol.snmp; + diff --git a/src/main/java/org/waarp/openr66/protocol/utils/ChannelCloseTimer.java b/src/main/java/org/waarp/openr66/protocol/utils/ChannelCloseTimer.java index c5e12c868..a9dc87e9e 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/ChannelCloseTimer.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/ChannelCloseTimer.java @@ -1,56 +1,56 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import java.util.concurrent.TimeUnit; - -import org.jboss.netty.channel.Channel; -import org.jboss.netty.util.Timeout; -import org.jboss.netty.util.TimerTask; -import org.waarp.common.crypto.ssl.WaarpSslUtility; -import org.waarp.openr66.protocol.configuration.Configuration; - -/** - * TimerTask to Close a Channel in the future - * - * @author Frederic Bregier - * - */ -public class ChannelCloseTimer implements TimerTask { - - private Channel channel; - - public ChannelCloseTimer(Channel channel) { - this.channel = channel; - } - - public void run(Timeout timeout) throws Exception { - WaarpSslUtility.closingSslChannel(channel); - } - - /** - * Close in the future this channel - * - * @param channel - */ - public static void closeFutureChannel(Channel channel) { - Configuration.configuration.getTimerClose().newTimeout( - new ChannelCloseTimer(channel), - Configuration.WAITFORNETOP, TimeUnit.MILLISECONDS); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import java.util.concurrent.TimeUnit; + +import org.jboss.netty.channel.Channel; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.TimerTask; +import org.waarp.common.crypto.ssl.WaarpSslUtility; +import org.waarp.openr66.protocol.configuration.Configuration; + +/** + * TimerTask to Close a Channel in the future + * + * @author Frederic Bregier + * + */ +public class ChannelCloseTimer implements TimerTask { + + private Channel channel; + + public ChannelCloseTimer(Channel channel) { + this.channel = channel; + } + + public void run(Timeout timeout) throws Exception { + WaarpSslUtility.closingSslChannel(channel); + } + + /** + * Close in the future this channel + * + * @param channel + */ + public static void closeFutureChannel(Channel channel) { + Configuration.configuration.getTimerClose().newTimeout( + new ChannelCloseTimer(channel), + Configuration.WAITFORNETOP, TimeUnit.MILLISECONDS); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/ChannelUtils.java b/src/main/java/org/waarp/openr66/protocol/utils/ChannelUtils.java index c30c7bf31..156b8221f 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/ChannelUtils.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/ChannelUtils.java @@ -1,459 +1,459 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.group.ChannelGroupFuture; -import org.jboss.netty.channel.group.ChannelGroupFutureListener; -import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; -import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; -import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jboss.netty.handler.traffic.TrafficCounter; -import org.slf4j.LoggerFactory; -import org.waarp.common.database.DbAdmin; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.task.localexec.LocalExecClient; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; -import org.waarp.openr66.protocol.localhandler.packet.DataPacket; -import org.waarp.openr66.protocol.localhandler.packet.EndTransferPacket; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; - -import ch.qos.logback.classic.LoggerContext; - -/** - * Channel Utils - * - * @author Frederic Bregier - */ -public class ChannelUtils extends Thread { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ChannelUtils.class); - - public static final Integer NOCHANNEL = Integer.MIN_VALUE; - - /** - * Get the Remote InetAddress - * - * @param channel - * @return the remote InetAddress - */ - public static InetAddress getRemoteInetAddress(Channel channel) { - InetSocketAddress socketAddress = (InetSocketAddress) channel - .getRemoteAddress(); - if (socketAddress == null) { - socketAddress = new InetSocketAddress(20); - } - return socketAddress.getAddress(); - } - - /** - * Get the Local InetAddress - * - * @param channel - * @return the local InetAddress - */ - public static InetAddress getLocalInetAddress(Channel channel) { - final InetSocketAddress socketAddress = (InetSocketAddress) channel - .getLocalAddress(); - return socketAddress.getAddress(); - } - - /** - * Get the Remote InetSocketAddress - * - * @param channel - * @return the remote InetSocketAddress - */ - public static InetSocketAddress getRemoteInetSocketAddress(Channel channel) { - return (InetSocketAddress) channel.getRemoteAddress(); - } - - /** - * Get the Local InetSocketAddress - * - * @param channel - * @return the local InetSocketAddress - */ - public static InetSocketAddress getLocalInetSocketAddress(Channel channel) { - return (InetSocketAddress) channel.getLocalAddress(); - } - - /** - * Finalize resources attached to handlers - * - * @author Frederic Bregier - */ - private static class R66ChannelGroupFutureListener implements - ChannelGroupFutureListener { - OrderedMemoryAwareThreadPoolExecutor pool; - String name; - ChannelFactory channelFactory; - - public R66ChannelGroupFutureListener( - String name, - OrderedMemoryAwareThreadPoolExecutor pool, - ChannelFactory channelFactory) { - this.name = name; - this.pool = pool; - this.channelFactory = channelFactory; - } - - public void operationComplete(ChannelGroupFuture future) - throws Exception { - logger.info("Start with shutdown external resources for " + name); - if (pool != null) { - pool.shutdownNow(); - } - if (channelFactory != null) { - channelFactory.releaseExternalResources(); - } - logger.info("Done with shutdown " + name); - } - } - - /** - * Terminate all registered channels - * - * @return the number of previously registered network channels - */ - private static int terminateCommandChannels() { - if (Configuration.configuration.getServerChannelGroup() == null) { - return 0; - } - final int result = Configuration.configuration.getServerChannelGroup() - .size(); - logger.info("ServerChannelGroup: " + result); - Configuration.configuration.getServerChannelGroup().close() - .addListener( - new R66ChannelGroupFutureListener( - "ServerChannelGroup", - Configuration.configuration - .getServerPipelineExecutor(), - Configuration.configuration - .getServerChannelFactory())); - return result; - } - - /** - * Terminate all registered Http channels - * - * @return the number of previously registered http network channels - */ - private static int terminateHttpChannels() { - if (Configuration.configuration.getHttpChannelGroup() == null) { - return 0; - } - final int result = Configuration.configuration.getHttpChannelGroup() - .size(); - logger.debug("HttpChannelGroup: " + result); - Configuration.configuration.getHttpChannelGroup().close() - .addListener( - new R66ChannelGroupFutureListener( - "HttpChannelGroup", - null, - Configuration.configuration - .getHttpChannelFactory())); - Configuration.configuration.getHttpsChannelFactory().releaseExternalResources(); - return result; - } - - /** - * Return the current number of network connections - * - * @param configuration - * @return the current number of network connections - */ - public static int nbCommandChannels(Configuration configuration) { - return configuration.getServerChannelGroup().size(); - } - - /** - * To be used only with LocalChannel (NetworkChannel could be using SSL) - * @param channel - */ - public static void close(Channel channel) { - try { - Thread.sleep(Configuration.WAITFORNETOP); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - Channels.close(channel); - } - - /** - * - * @param localChannelReference - * @param block - * @return the ChannelFuture of this write operation - * @throws OpenR66ProtocolPacketException - */ - public static ChannelFuture writeBackDataBlock( - LocalChannelReference localChannelReference, DataBlock block) - throws OpenR66ProtocolPacketException { - ChannelBuffer md5 = ChannelBuffers.EMPTY_BUFFER; - DbTaskRunner runner = localChannelReference.getSession().getRunner(); - if (RequestPacket.isMD5Mode(runner.getMode())) { - md5 = FileUtils.getHash(block.getBlock()); - } - localChannelReference.sessionNewState(R66FiniteDualStates.DATAS); - DataPacket data = new DataPacket(runner.getRank(), block.getBlock() - .copy(), md5); - ChannelFuture future = writeAbstractLocalPacket(localChannelReference, data, false); - runner.incrementRank(); - return future; - } - - /** - * Write the EndTransfer - * - * @param localChannelReference - * @throws OpenR66ProtocolPacketException - */ - public static void writeEndTransfer( - LocalChannelReference localChannelReference) - throws OpenR66ProtocolPacketException { - EndTransferPacket packet = new EndTransferPacket( - LocalPacketFactory.REQUESTPACKET); - localChannelReference.sessionNewState(R66FiniteDualStates.ENDTRANSFERS); - writeAbstractLocalPacket(localChannelReference, packet, false); - } - /** - * Write the EndTransfer plus Global Hash - * - * @param localChannelReference - * @param hash - * @throws OpenR66ProtocolPacketException - */ - public static void writeEndTransfer( - LocalChannelReference localChannelReference, String hash) - throws OpenR66ProtocolPacketException { - EndTransferPacket packet = new EndTransferPacket( - LocalPacketFactory.REQUESTPACKET, hash); - localChannelReference.sessionNewState(R66FiniteDualStates.ENDTRANSFERS); - writeAbstractLocalPacket(localChannelReference, packet, false); - } - - /** - * Write an AbstractLocalPacket to the network Channel - * - * @param localChannelReference - * @param packet - * @param wait - * @return the ChannelFuture on write operation - * @throws OpenR66ProtocolPacketException - */ - public static ChannelFuture writeAbstractLocalPacket( - LocalChannelReference localChannelReference, AbstractLocalPacket packet, - boolean wait) - throws OpenR66ProtocolPacketException { - NetworkPacket networkPacket; - try { - networkPacket = new NetworkPacket(localChannelReference - .getLocalId(), localChannelReference.getRemoteId(), packet); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Cannot construct message from " + packet.toString(), - e); - throw e; - } - if (wait) { - ChannelFuture future = Channels.write(localChannelReference.getNetworkChannel(), - networkPacket); - try { - return future.await(); - } catch (InterruptedException e) { - return future; - } - } else { - return Channels.write(localChannelReference.getNetworkChannel(), networkPacket); - } - } - - /** - * Write an AbstractLocalPacket to the Local Channel - * - * @param localChannelReference - * @param packet - * @return the ChannelFuture on write operation - * @throws OpenR66ProtocolPacketException - */ - public static ChannelFuture writeAbstractLocalPacketToLocal( - LocalChannelReference localChannelReference, AbstractLocalPacket packet) - throws OpenR66ProtocolPacketException { - return Channels.write(localChannelReference.getLocalChannel(), packet); - } - - /** - * Compute Wait for Traffic in Write (ugly turn around) - * - * @param localChannelReference - * @param size - * @return the wait in ms - */ - public static final long willBeWaitingWriting(LocalChannelReference localChannelReference, - int size) { - ChannelTrafficShapingHandler cts = localChannelReference.getChannelTrafficShapingHandler(); - return willBeWaitingWriting(cts, size); - } - - /** - * Compute Wait for Traffic in Write (ugly turn around) - * - * @param cts - * @param size - * @return the wait in ms - */ - public static final long willBeWaitingWriting(ChannelTrafficShapingHandler cts, int size) { - long currentTime = System.currentTimeMillis(); - if (cts != null && Configuration.configuration.serverChannelWriteLimit > 0) { - TrafficCounter tc = cts.getTrafficCounter(); - if (tc != null) { - long wait = waitTraffic(Configuration.configuration.serverChannelWriteLimit, - tc.getCurrentWrittenBytes() + size, - tc.getLastTime(), currentTime); - if (wait > 0) { - return wait; - } - } - } - if (Configuration.configuration.serverGlobalWriteLimit > 0) { - GlobalTrafficShapingHandler gts = Configuration.configuration - .getGlobalTrafficShapingHandler(); - if (gts != null) { - TrafficCounter tc = gts.getTrafficCounter(); - if (tc != null) { - long wait = waitTraffic(Configuration.configuration.serverGlobalWriteLimit, - tc.getCurrentWrittenBytes() + size, - tc.getLastTime(), currentTime); - if (wait > 0) { - return wait; - } - } - } - } - return 0; - } - - private static final long waitTraffic(long limit, long bytes, long lastTime, - long curtime) { - long interval = curtime - lastTime; - if (interval == 0) { - // Time is too short, so just lets continue - return 0; - } - return ((bytes * 1000 / limit - interval) / 10) * 10; - } - - /** - * Exit global ChannelFactory - */ - public static void exit() { - if (Configuration.configuration.constraintLimitHandler != null) { - Configuration.configuration.constraintLimitHandler.release(); - } - // First try to StopAll - TransferUtils.stopSelectedTransfers(DbConstant.admin.session, 0, - null, null, null, null, null, null, null, null, null, true, true, true); - Configuration.configuration.isShutdown = true; - Configuration.configuration.prepareServerStop(); - final long delay = Configuration.configuration.TIMEOUTCON; - // Inform others that shutdown - if (Configuration.configuration.getLocalTransaction() != null) { - Configuration.configuration.getLocalTransaction() - .shutdownLocalChannels(); - } - logger.warn("Exit: Give a delay of " + delay + " ms"); - try { - Thread.sleep(delay); - } catch (final InterruptedException e) { - } - NetworkTransaction.closeRetrieveExecutors(); - if (Configuration.configuration.getLocalTransaction() != null) { - Configuration.configuration.getLocalTransaction().debugPrintActiveLocalChannels(); - } - if (Configuration.configuration.getGlobalTrafficShapingHandler() != null) { - Configuration.configuration.getGlobalTrafficShapingHandler() - .releaseExternalResources(); - } - logger.info("Exit Shutdown Http"); - terminateHttpChannels(); - logger.info("Exit Shutdown Local"); - if (Configuration.configuration.getLocalTransaction() != null) { - Configuration.configuration.getLocalTransaction().closeAll(); - } - logger.info("Exit Shutdown Command"); - terminateCommandChannels(); - logger.info("Exit Shutdown LocalExec"); - if (Configuration.configuration.useLocalExec) { - LocalExecClient.releaseResources(); - } - logger.info("Exit Shutdown Db Connection"); - DbAdmin.closeAllConnection(); - logger.info("Exit Shutdown ServerStop"); - Configuration.configuration.serverStop(); - logger.warn("Exit end of Shutdown"); - System.err.println("Exit end of Shutdown"); - //Thread.currentThread().interrupt(); - } - - public static void stopLogger() { - if (WaarpInternalLoggerFactory.getDefaultFactory() instanceof WaarpSlf4JLoggerFactory) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.stop(); - } - } - - /** - * This function is the top function to be called when the server is to be shutdown. - */ - @Override - public void run() { - R66ShutdownHook.terminate(false); - } - - /** - * Start Shutdown - */ - public static void startShutdown() { - Thread thread = new Thread(new ChannelUtils(), "R66 Shutdown Thread"); - thread.setDaemon(true); - thread.start(); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.group.ChannelGroupFuture; +import org.jboss.netty.channel.group.ChannelGroupFutureListener; +import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; +import org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler; +import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler; +import org.jboss.netty.handler.traffic.TrafficCounter; +import org.slf4j.LoggerFactory; +import org.waarp.common.database.DbAdmin; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.task.localexec.LocalExecClient; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; +import org.waarp.openr66.protocol.localhandler.packet.DataPacket; +import org.waarp.openr66.protocol.localhandler.packet.EndTransferPacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket; + +import ch.qos.logback.classic.LoggerContext; + +/** + * Channel Utils + * + * @author Frederic Bregier + */ +public class ChannelUtils extends Thread { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ChannelUtils.class); + + public static final Integer NOCHANNEL = Integer.MIN_VALUE; + + /** + * Get the Remote InetAddress + * + * @param channel + * @return the remote InetAddress + */ + public static InetAddress getRemoteInetAddress(Channel channel) { + InetSocketAddress socketAddress = (InetSocketAddress) channel + .getRemoteAddress(); + if (socketAddress == null) { + socketAddress = new InetSocketAddress(20); + } + return socketAddress.getAddress(); + } + + /** + * Get the Local InetAddress + * + * @param channel + * @return the local InetAddress + */ + public static InetAddress getLocalInetAddress(Channel channel) { + final InetSocketAddress socketAddress = (InetSocketAddress) channel + .getLocalAddress(); + return socketAddress.getAddress(); + } + + /** + * Get the Remote InetSocketAddress + * + * @param channel + * @return the remote InetSocketAddress + */ + public static InetSocketAddress getRemoteInetSocketAddress(Channel channel) { + return (InetSocketAddress) channel.getRemoteAddress(); + } + + /** + * Get the Local InetSocketAddress + * + * @param channel + * @return the local InetSocketAddress + */ + public static InetSocketAddress getLocalInetSocketAddress(Channel channel) { + return (InetSocketAddress) channel.getLocalAddress(); + } + + /** + * Finalize resources attached to handlers + * + * @author Frederic Bregier + */ + private static class R66ChannelGroupFutureListener implements + ChannelGroupFutureListener { + OrderedMemoryAwareThreadPoolExecutor pool; + String name; + ChannelFactory channelFactory; + + public R66ChannelGroupFutureListener( + String name, + OrderedMemoryAwareThreadPoolExecutor pool, + ChannelFactory channelFactory) { + this.name = name; + this.pool = pool; + this.channelFactory = channelFactory; + } + + public void operationComplete(ChannelGroupFuture future) + throws Exception { + logger.info("Start with shutdown external resources for " + name); + if (pool != null) { + pool.shutdownNow(); + } + if (channelFactory != null) { + channelFactory.releaseExternalResources(); + } + logger.info("Done with shutdown " + name); + } + } + + /** + * Terminate all registered channels + * + * @return the number of previously registered network channels + */ + private static int terminateCommandChannels() { + if (Configuration.configuration.getServerChannelGroup() == null) { + return 0; + } + final int result = Configuration.configuration.getServerChannelGroup() + .size(); + logger.info("ServerChannelGroup: " + result); + Configuration.configuration.getServerChannelGroup().close() + .addListener( + new R66ChannelGroupFutureListener( + "ServerChannelGroup", + Configuration.configuration + .getServerPipelineExecutor(), + Configuration.configuration + .getServerChannelFactory())); + return result; + } + + /** + * Terminate all registered Http channels + * + * @return the number of previously registered http network channels + */ + private static int terminateHttpChannels() { + if (Configuration.configuration.getHttpChannelGroup() == null) { + return 0; + } + final int result = Configuration.configuration.getHttpChannelGroup() + .size(); + logger.debug("HttpChannelGroup: " + result); + Configuration.configuration.getHttpChannelGroup().close() + .addListener( + new R66ChannelGroupFutureListener( + "HttpChannelGroup", + null, + Configuration.configuration + .getHttpChannelFactory())); + Configuration.configuration.getHttpsChannelFactory().releaseExternalResources(); + return result; + } + + /** + * Return the current number of network connections + * + * @param configuration + * @return the current number of network connections + */ + public static int nbCommandChannels(Configuration configuration) { + return configuration.getServerChannelGroup().size(); + } + + /** + * To be used only with LocalChannel (NetworkChannel could be using SSL) + * @param channel + */ + public static void close(Channel channel) { + try { + Thread.sleep(Configuration.WAITFORNETOP); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + Channels.close(channel); + } + + /** + * + * @param localChannelReference + * @param block + * @return the ChannelFuture of this write operation + * @throws OpenR66ProtocolPacketException + */ + public static ChannelFuture writeBackDataBlock( + LocalChannelReference localChannelReference, DataBlock block) + throws OpenR66ProtocolPacketException { + ChannelBuffer md5 = ChannelBuffers.EMPTY_BUFFER; + DbTaskRunner runner = localChannelReference.getSession().getRunner(); + if (RequestPacket.isMD5Mode(runner.getMode())) { + md5 = FileUtils.getHash(block.getBlock()); + } + localChannelReference.sessionNewState(R66FiniteDualStates.DATAS); + DataPacket data = new DataPacket(runner.getRank(), block.getBlock() + .copy(), md5); + ChannelFuture future = writeAbstractLocalPacket(localChannelReference, data, false); + runner.incrementRank(); + return future; + } + + /** + * Write the EndTransfer + * + * @param localChannelReference + * @throws OpenR66ProtocolPacketException + */ + public static void writeEndTransfer( + LocalChannelReference localChannelReference) + throws OpenR66ProtocolPacketException { + EndTransferPacket packet = new EndTransferPacket( + LocalPacketFactory.REQUESTPACKET); + localChannelReference.sessionNewState(R66FiniteDualStates.ENDTRANSFERS); + writeAbstractLocalPacket(localChannelReference, packet, false); + } + /** + * Write the EndTransfer plus Global Hash + * + * @param localChannelReference + * @param hash + * @throws OpenR66ProtocolPacketException + */ + public static void writeEndTransfer( + LocalChannelReference localChannelReference, String hash) + throws OpenR66ProtocolPacketException { + EndTransferPacket packet = new EndTransferPacket( + LocalPacketFactory.REQUESTPACKET, hash); + localChannelReference.sessionNewState(R66FiniteDualStates.ENDTRANSFERS); + writeAbstractLocalPacket(localChannelReference, packet, false); + } + + /** + * Write an AbstractLocalPacket to the network Channel + * + * @param localChannelReference + * @param packet + * @param wait + * @return the ChannelFuture on write operation + * @throws OpenR66ProtocolPacketException + */ + public static ChannelFuture writeAbstractLocalPacket( + LocalChannelReference localChannelReference, AbstractLocalPacket packet, + boolean wait) + throws OpenR66ProtocolPacketException { + NetworkPacket networkPacket; + try { + networkPacket = new NetworkPacket(localChannelReference + .getLocalId(), localChannelReference.getRemoteId(), packet); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Cannot construct message from " + packet.toString(), + e); + throw e; + } + if (wait) { + ChannelFuture future = Channels.write(localChannelReference.getNetworkChannel(), + networkPacket); + try { + return future.await(); + } catch (InterruptedException e) { + return future; + } + } else { + return Channels.write(localChannelReference.getNetworkChannel(), networkPacket); + } + } + + /** + * Write an AbstractLocalPacket to the Local Channel + * + * @param localChannelReference + * @param packet + * @return the ChannelFuture on write operation + * @throws OpenR66ProtocolPacketException + */ + public static ChannelFuture writeAbstractLocalPacketToLocal( + LocalChannelReference localChannelReference, AbstractLocalPacket packet) + throws OpenR66ProtocolPacketException { + return Channels.write(localChannelReference.getLocalChannel(), packet); + } + + /** + * Compute Wait for Traffic in Write (ugly turn around) + * + * @param localChannelReference + * @param size + * @return the wait in ms + */ + public static final long willBeWaitingWriting(LocalChannelReference localChannelReference, + int size) { + ChannelTrafficShapingHandler cts = localChannelReference.getChannelTrafficShapingHandler(); + return willBeWaitingWriting(cts, size); + } + + /** + * Compute Wait for Traffic in Write (ugly turn around) + * + * @param cts + * @param size + * @return the wait in ms + */ + public static final long willBeWaitingWriting(ChannelTrafficShapingHandler cts, int size) { + long currentTime = System.currentTimeMillis(); + if (cts != null && Configuration.configuration.serverChannelWriteLimit > 0) { + TrafficCounter tc = cts.getTrafficCounter(); + if (tc != null) { + long wait = waitTraffic(Configuration.configuration.serverChannelWriteLimit, + tc.getCurrentWrittenBytes() + size, + tc.getLastTime(), currentTime); + if (wait > 0) { + return wait; + } + } + } + if (Configuration.configuration.serverGlobalWriteLimit > 0) { + GlobalTrafficShapingHandler gts = Configuration.configuration + .getGlobalTrafficShapingHandler(); + if (gts != null) { + TrafficCounter tc = gts.getTrafficCounter(); + if (tc != null) { + long wait = waitTraffic(Configuration.configuration.serverGlobalWriteLimit, + tc.getCurrentWrittenBytes() + size, + tc.getLastTime(), currentTime); + if (wait > 0) { + return wait; + } + } + } + } + return 0; + } + + private static final long waitTraffic(long limit, long bytes, long lastTime, + long curtime) { + long interval = curtime - lastTime; + if (interval == 0) { + // Time is too short, so just lets continue + return 0; + } + return ((bytes * 1000 / limit - interval) / 10) * 10; + } + + /** + * Exit global ChannelFactory + */ + public static void exit() { + if (Configuration.configuration.constraintLimitHandler != null) { + Configuration.configuration.constraintLimitHandler.release(); + } + // First try to StopAll + TransferUtils.stopSelectedTransfers(DbConstant.admin.session, 0, + null, null, null, null, null, null, null, null, null, true, true, true); + Configuration.configuration.isShutdown = true; + Configuration.configuration.prepareServerStop(); + final long delay = Configuration.configuration.TIMEOUTCON; + // Inform others that shutdown + if (Configuration.configuration.getLocalTransaction() != null) { + Configuration.configuration.getLocalTransaction() + .shutdownLocalChannels(); + } + logger.warn("Exit: Give a delay of " + delay + " ms"); + try { + Thread.sleep(delay); + } catch (final InterruptedException e) { + } + NetworkTransaction.closeRetrieveExecutors(); + if (Configuration.configuration.getLocalTransaction() != null) { + Configuration.configuration.getLocalTransaction().debugPrintActiveLocalChannels(); + } + if (Configuration.configuration.getGlobalTrafficShapingHandler() != null) { + Configuration.configuration.getGlobalTrafficShapingHandler() + .releaseExternalResources(); + } + logger.info("Exit Shutdown Http"); + terminateHttpChannels(); + logger.info("Exit Shutdown Local"); + if (Configuration.configuration.getLocalTransaction() != null) { + Configuration.configuration.getLocalTransaction().closeAll(); + } + logger.info("Exit Shutdown Command"); + terminateCommandChannels(); + logger.info("Exit Shutdown LocalExec"); + if (Configuration.configuration.useLocalExec) { + LocalExecClient.releaseResources(); + } + logger.info("Exit Shutdown Db Connection"); + DbAdmin.closeAllConnection(); + logger.info("Exit Shutdown ServerStop"); + Configuration.configuration.serverStop(); + logger.warn("Exit end of Shutdown"); + System.err.println("Exit end of Shutdown"); + //Thread.currentThread().interrupt(); + } + + public static void stopLogger() { + if (WaarpInternalLoggerFactory.getDefaultFactory() instanceof WaarpSlf4JLoggerFactory) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.stop(); + } + } + + /** + * This function is the top function to be called when the server is to be shutdown. + */ + @Override + public void run() { + R66ShutdownHook.terminate(false); + } + + /** + * Start Shutdown + */ + public static void startShutdown() { + Thread thread = new Thread(new ChannelUtils(), "R66 Shutdown Thread"); + thread.setDaemon(true); + thread.start(); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java b/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java index 0a861beea..2b5cabc36 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java @@ -1,544 +1,544 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.nio.channels.FileChannel; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.file.DirInterface; -import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; - -/** - * File Utils - * - * @author Frederic Bregier - * - */ -public class FileUtils { - /** - * - * @param base - * in absolute - * @param path - * path in absolute or relative - * @return a new String for a file from the base and the path (according to relative or absolute - * path) - * @throws OpenR66ProtocolSystemException - */ - public static String consolidatePath(String base, String path) - throws OpenR66ProtocolSystemException { - if (base == null || base.length() == 0 || path == null || - path.length() == 0) { - throw new OpenR66ProtocolSystemException( - "base and path must not be empty"); - } - // First check if the path is relative or absolute - String extDir = null; - if (path.charAt(0) == DirInterface.SEPARATORCHAR) { - extDir = Configuration.configuration.baseDirectory + - DirInterface.SEPARATOR + path; - } else { - extDir = Configuration.configuration.baseDirectory + - DirInterface.SEPARATOR + base + DirInterface.SEPARATOR + - path; - } - return extDir; - } - - /** - * Copy one file to another one - * - * @param from - * @param to - * @param move - * True if the copy is in fact a move operation - * @param append - * True if the copy is in append - * @throws OpenR66ProtocolSystemException - */ - public static void copy(File from, File to, boolean move, boolean append) - throws OpenR66ProtocolSystemException { - if (from == null || to == null) { - throw new OpenR66ProtocolSystemException( - "Source or Destination is null"); - } - File directoryTo = to.getParentFile(); - if (createDir(directoryTo)) { - if (move && from.renameTo(to)) { - return; - } - FileChannel fileChannelIn = getFileChannel(from, false, false); - if (fileChannelIn == null) { - throw new OpenR66ProtocolSystemException( - "Cannot read source file"); - // return false; - } - FileChannel fileChannelOut = getFileChannel(to, true, append); - if (fileChannelOut == null) { - try { - fileChannelIn.close(); - } catch (IOException e) { - } - throw new OpenR66ProtocolSystemException( - "Cannot write destination file"); - } - if (write(fileChannelIn, fileChannelOut) > 0) { - if (move) { - // do not test the delete - from.delete(); - } - return; - } - throw new OpenR66ProtocolSystemException("Cannot copy"); - } - throw new OpenR66ProtocolSystemException( - "Cannot access to parent dir of destination"); - } - - /** - * Copy a group of files to a directory - * - * @param from - * @param directoryTo - * @param move - * True if the copy is in fact a move operation - * @return the group of copy files or null (partially or totally) if an error occurs - * @throws OpenR66ProtocolSystemException - */ - public static File[] copy(File[] from, File directoryTo, boolean move) - throws OpenR66ProtocolSystemException { - if (from == null || directoryTo == null) { - return null; - } - File[] to = null; - if (createDir(directoryTo)) { - to = new File[from.length]; - for (int i = 0; i < from.length; i++) { - try { - to[i] = copyToDir(from[i], directoryTo, move); - } catch (OpenR66ProtocolSystemException e) { - throw e; - } - } - } - return to; - } - - /** - * Copy one file to a directory - * - * @param from - * @param directoryTo - * @param move - * True if the copy is in fact a move operation - * @return The copied file or null if an error occurs - * @throws OpenR66ProtocolSystemException - */ - public static File copyToDir(File from, File directoryTo, boolean move) - throws OpenR66ProtocolSystemException { - if (from == null || directoryTo == null) { - throw new OpenR66ProtocolSystemException( - "Source or Destination is null"); - } - if (createDir(directoryTo)) { - File to = new File(directoryTo, from.getName()); - if (move && from.renameTo(to)) { - return to; - } - FileChannel fileChannelIn = getFileChannel(from, false, false); - if (fileChannelIn == null) { - throw new OpenR66ProtocolSystemException( - "Cannot read source file"); - } - FileChannel fileChannelOut = getFileChannel(to, true, false); - if (fileChannelOut == null) { - try { - fileChannelIn.close(); - } catch (IOException e) { - } - throw new OpenR66ProtocolSystemException( - "Cannot write destination file"); - } - if (write(fileChannelIn, fileChannelOut) > 0) { - if (move) { - // do not test the delete - from.delete(); - } - return to; - } - throw new OpenR66ProtocolSystemException( - "Cannot write destination file"); - } - throw new OpenR66ProtocolSystemException( - "Cannot access to parent dir of destination"); - } - - /** - * Create the directory associated with the File as path - * - * @param directory - * @return True if created, False else. - */ - public static boolean createDir(File directory) { - if (directory == null) { - return false; - } - if (directory.isDirectory()) { - return true; - } - return directory.mkdirs(); - } - - /** - * Delete physically the file - * - * @param file - * @return True if OK, else if not (or if the file never exists). - */ - public static boolean delete(File file) { - if (!file.exists()) { - return true; - } - return file.delete(); - } - - /** - * Delete the directory associated with the File as path if empty - * - * @param directory - * @return True if deleted, False else. - */ - public static boolean deleteDir(File directory) { - if (directory == null) { - return true; - } - if (!directory.exists()) { - return true; - } - if (!directory.isDirectory()) { - return false; - } - return directory.delete(); - } - - /** - * Delete physically the file but when the JVM exits (useful for temporary file) - * - * @param file - */ - public static void deleteOnExit(File file) { - if (!file.exists()) { - return; - } - file.deleteOnExit(); - } - - /** - * Delete the directory and its subdirs associated with the File as path if empty - * - * @param directory - * @return True if deleted, False else. - */ - public static boolean deleteRecursiveDir(File directory) { - if (directory == null) { - return true; - } - boolean retour = true; - if (!directory.exists()) { - return true; - } - if (!directory.isDirectory()) { - return false; - } - File[] list = directory.listFiles(); - if (list == null || list.length == 0) { - list = null; - retour = directory.delete(); - return retour; - } - int len = list.length; - for (int i = 0; i < len; i++) { - if (list[i].isDirectory()) { - if (!deleteRecursiveFileDir(list[i])) { - retour = false; - } - } else { - retour = false; - } - } - list = null; - if (retour) { - retour = directory.delete(); - } - return retour; - } - - /** - * Delete the directory and its subdirs associated with the File dir if empty - * - * @param dir - * @return True if deleted, False else. - */ - private static boolean deleteRecursiveFileDir(File dir) { - if (dir == null) { - return true; - } - boolean retour = true; - if (!dir.exists()) { - return true; - } - File[] list = dir.listFiles(); - if (list == null || list.length == 0) { - list = null; - return dir.delete(); - } - int len = list.length; - for (int i = 0; i < len; i++) { - if (list[i].isDirectory()) { - if (!deleteRecursiveFileDir(list[i])) { - retour = false; - } - } else { - retour = false; - list = null; - return retour; - } - } - list = null; - if (retour) { - retour = dir.delete(); - } - return retour; - } - - /** - * @param _FileName - * @param _Path - * @return true if the file exist in the specified path - */ - public static boolean FileExist(String _FileName, String _Path) { - boolean exist = false; - String fileString = _Path + File.separator + _FileName; - File file = new File(fileString); - if (file.exists()) { - exist = true; - } - return exist; - } - - /** - * Returns the FileChannel in Out MODE (if isOut is True) or in In MODE (if isOut is False) - * associated with the file. In out MODE, it can be in append MODE. - * - * @param isOut - * @param append - * @return the FileChannel (OUT or IN) - * @throws OpenR66ProtocolSystemException - */ - private static FileChannel getFileChannel(File file, boolean isOut, - boolean append) throws OpenR66ProtocolSystemException { - FileChannel fileChannel = null; - try { - if (isOut) { - @SuppressWarnings("resource") - FileOutputStream fileOutputStream = new FileOutputStream(file - .getPath(), append); - fileChannel = fileOutputStream.getChannel(); - if (append) { - // Bug in JVM since it does not respect the API (position - // should be set as length) - try { - fileChannel.position(file.length()); - } catch (IOException e) { - } - } - } else { - if (!file.exists()) { - throw new OpenR66ProtocolSystemException( - "File does not exist"); - } - @SuppressWarnings("resource") - FileInputStream fileInputStream = new FileInputStream(file - .getPath()); - fileChannel = fileInputStream.getChannel(); - } - } catch (FileNotFoundException e) { - throw new OpenR66ProtocolSystemException("File not found", e); - } - return fileChannel; - } - - /** - * Get the list of files from a given directory - * - * @param directory - * @return the list of files (as an array) - */ - public static File[] getFiles(File directory) { - if (directory == null || !directory.isDirectory()) { - return null; - } - return directory.listFiles(); - } - - /** - * Get the list of files from a given directory and a filter - * - * @param directory - * @param filter - * @return the list of files (as an array) - */ - public static File[] getFiles(File directory, FilenameFilter filter) { - if (directory == null || !directory.isDirectory()) { - return null; - } - return directory.listFiles(filter); - } - - /** - * Calculates and returns the hash of the contents of the given file. - * - * @param f - * FileInterface to hash - * @return the hash from the given file - * @throws OpenR66ProtocolSystemException - **/ - public static String getHash(File f) throws OpenR66ProtocolSystemException { - try { - return FilesystemBasedDigest.getHex(FilesystemBasedDigest.getHash(f, - FilesystemBasedFileParameterImpl.useNio, Configuration.configuration.digest)); - } catch (IOException e) { - throw new OpenR66ProtocolSystemException(e); - } - } - - /** - * - * @param buffer - * @return the hash from the given Buffer - */ - public static ChannelBuffer getHash(ChannelBuffer buffer) { - byte[] newkey; - try { - newkey = FilesystemBasedDigest.getHash(buffer, Configuration.configuration.digest); - } catch (IOException e) { - return ChannelBuffers.EMPTY_BUFFER; - } - return ChannelBuffers.wrappedBuffer(newkey); - } - - /** - * Compute global hash (if possible) - * @param digest - * @param block - */ - public static void computeGlobalHash(FilesystemBasedDigest digest, ChannelBuffer buffer) { - if (digest == null) { - return; - } - byte[] bytes = null; - int start = 0; - int length = buffer.readableBytes(); - if (buffer.hasArray()) { - start = buffer.arrayOffset(); - bytes = buffer.array(); - if (bytes.length > start + length) { - byte[] temp = new byte[length]; - System.arraycopy(bytes, start, temp, 0, length); - start = 0; - bytes = temp; - } - } else { - bytes = new byte[length]; - buffer.getBytes(buffer.readerIndex(), bytes); - } - digest.Update(bytes, start, length); - } - - /** - * Write one fileChannel to another one. Close the fileChannels - * - * @param fileChannelIn - * source of file - * @param fileChannelOut - * destination of file - * @return The size of copy if is OK - * @throws AtlasIoException - */ - private static long write(FileChannel fileChannelIn, - FileChannel fileChannelOut) throws OpenR66ProtocolSystemException { - if (fileChannelIn == null) { - if (fileChannelOut != null) { - try { - fileChannelOut.close(); - } catch (IOException e) { - } - } - throw new OpenR66ProtocolSystemException("FileChannelIn is null"); - } - if (fileChannelOut == null) { - try { - fileChannelIn.close(); - } catch (IOException e) { - } - throw new OpenR66ProtocolSystemException("FileChannelOut is null"); - } - long size = 0; - long transfert = 0; - try { - transfert = fileChannelOut.position(); - size = fileChannelIn.size(); - int chunkSize = 8192; - while (transfert < size) { - if (chunkSize < size - transfert) { - chunkSize = (int) (size - transfert); - } - transfert += fileChannelOut.transferFrom(fileChannelIn, transfert, chunkSize); - } - } catch (IOException e) { - try { - fileChannelOut.close(); - fileChannelIn.close(); - } catch (IOException e1) { - } - throw new OpenR66ProtocolSystemException( - "An error during copy occurs", e); - } - try { - fileChannelOut.close(); - fileChannelIn.close(); - } catch (IOException e) {// Close error can be ignored - } - boolean retour = size == transfert; - if (!retour) { - throw new OpenR66ProtocolSystemException("Copy is not complete: " + - transfert + " bytes instead of " + size + " original bytes"); - } - return size; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.channels.FileChannel; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.file.DirInterface; +import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; + +/** + * File Utils + * + * @author Frederic Bregier + * + */ +public class FileUtils { + /** + * + * @param base + * in absolute + * @param path + * path in absolute or relative + * @return a new String for a file from the base and the path (according to relative or absolute + * path) + * @throws OpenR66ProtocolSystemException + */ + public static String consolidatePath(String base, String path) + throws OpenR66ProtocolSystemException { + if (base == null || base.length() == 0 || path == null || + path.length() == 0) { + throw new OpenR66ProtocolSystemException( + "base and path must not be empty"); + } + // First check if the path is relative or absolute + String extDir = null; + if (path.charAt(0) == DirInterface.SEPARATORCHAR) { + extDir = Configuration.configuration.baseDirectory + + DirInterface.SEPARATOR + path; + } else { + extDir = Configuration.configuration.baseDirectory + + DirInterface.SEPARATOR + base + DirInterface.SEPARATOR + + path; + } + return extDir; + } + + /** + * Copy one file to another one + * + * @param from + * @param to + * @param move + * True if the copy is in fact a move operation + * @param append + * True if the copy is in append + * @throws OpenR66ProtocolSystemException + */ + public static void copy(File from, File to, boolean move, boolean append) + throws OpenR66ProtocolSystemException { + if (from == null || to == null) { + throw new OpenR66ProtocolSystemException( + "Source or Destination is null"); + } + File directoryTo = to.getParentFile(); + if (createDir(directoryTo)) { + if (move && from.renameTo(to)) { + return; + } + FileChannel fileChannelIn = getFileChannel(from, false, false); + if (fileChannelIn == null) { + throw new OpenR66ProtocolSystemException( + "Cannot read source file"); + // return false; + } + FileChannel fileChannelOut = getFileChannel(to, true, append); + if (fileChannelOut == null) { + try { + fileChannelIn.close(); + } catch (IOException e) { + } + throw new OpenR66ProtocolSystemException( + "Cannot write destination file"); + } + if (write(fileChannelIn, fileChannelOut) > 0) { + if (move) { + // do not test the delete + from.delete(); + } + return; + } + throw new OpenR66ProtocolSystemException("Cannot copy"); + } + throw new OpenR66ProtocolSystemException( + "Cannot access to parent dir of destination"); + } + + /** + * Copy a group of files to a directory + * + * @param from + * @param directoryTo + * @param move + * True if the copy is in fact a move operation + * @return the group of copy files or null (partially or totally) if an error occurs + * @throws OpenR66ProtocolSystemException + */ + public static File[] copy(File[] from, File directoryTo, boolean move) + throws OpenR66ProtocolSystemException { + if (from == null || directoryTo == null) { + return null; + } + File[] to = null; + if (createDir(directoryTo)) { + to = new File[from.length]; + for (int i = 0; i < from.length; i++) { + try { + to[i] = copyToDir(from[i], directoryTo, move); + } catch (OpenR66ProtocolSystemException e) { + throw e; + } + } + } + return to; + } + + /** + * Copy one file to a directory + * + * @param from + * @param directoryTo + * @param move + * True if the copy is in fact a move operation + * @return The copied file or null if an error occurs + * @throws OpenR66ProtocolSystemException + */ + public static File copyToDir(File from, File directoryTo, boolean move) + throws OpenR66ProtocolSystemException { + if (from == null || directoryTo == null) { + throw new OpenR66ProtocolSystemException( + "Source or Destination is null"); + } + if (createDir(directoryTo)) { + File to = new File(directoryTo, from.getName()); + if (move && from.renameTo(to)) { + return to; + } + FileChannel fileChannelIn = getFileChannel(from, false, false); + if (fileChannelIn == null) { + throw new OpenR66ProtocolSystemException( + "Cannot read source file"); + } + FileChannel fileChannelOut = getFileChannel(to, true, false); + if (fileChannelOut == null) { + try { + fileChannelIn.close(); + } catch (IOException e) { + } + throw new OpenR66ProtocolSystemException( + "Cannot write destination file"); + } + if (write(fileChannelIn, fileChannelOut) > 0) { + if (move) { + // do not test the delete + from.delete(); + } + return to; + } + throw new OpenR66ProtocolSystemException( + "Cannot write destination file"); + } + throw new OpenR66ProtocolSystemException( + "Cannot access to parent dir of destination"); + } + + /** + * Create the directory associated with the File as path + * + * @param directory + * @return True if created, False else. + */ + public static boolean createDir(File directory) { + if (directory == null) { + return false; + } + if (directory.isDirectory()) { + return true; + } + return directory.mkdirs(); + } + + /** + * Delete physically the file + * + * @param file + * @return True if OK, else if not (or if the file never exists). + */ + public static boolean delete(File file) { + if (!file.exists()) { + return true; + } + return file.delete(); + } + + /** + * Delete the directory associated with the File as path if empty + * + * @param directory + * @return True if deleted, False else. + */ + public static boolean deleteDir(File directory) { + if (directory == null) { + return true; + } + if (!directory.exists()) { + return true; + } + if (!directory.isDirectory()) { + return false; + } + return directory.delete(); + } + + /** + * Delete physically the file but when the JVM exits (useful for temporary file) + * + * @param file + */ + public static void deleteOnExit(File file) { + if (!file.exists()) { + return; + } + file.deleteOnExit(); + } + + /** + * Delete the directory and its subdirs associated with the File as path if empty + * + * @param directory + * @return True if deleted, False else. + */ + public static boolean deleteRecursiveDir(File directory) { + if (directory == null) { + return true; + } + boolean retour = true; + if (!directory.exists()) { + return true; + } + if (!directory.isDirectory()) { + return false; + } + File[] list = directory.listFiles(); + if (list == null || list.length == 0) { + list = null; + retour = directory.delete(); + return retour; + } + int len = list.length; + for (int i = 0; i < len; i++) { + if (list[i].isDirectory()) { + if (!deleteRecursiveFileDir(list[i])) { + retour = false; + } + } else { + retour = false; + } + } + list = null; + if (retour) { + retour = directory.delete(); + } + return retour; + } + + /** + * Delete the directory and its subdirs associated with the File dir if empty + * + * @param dir + * @return True if deleted, False else. + */ + private static boolean deleteRecursiveFileDir(File dir) { + if (dir == null) { + return true; + } + boolean retour = true; + if (!dir.exists()) { + return true; + } + File[] list = dir.listFiles(); + if (list == null || list.length == 0) { + list = null; + return dir.delete(); + } + int len = list.length; + for (int i = 0; i < len; i++) { + if (list[i].isDirectory()) { + if (!deleteRecursiveFileDir(list[i])) { + retour = false; + } + } else { + retour = false; + list = null; + return retour; + } + } + list = null; + if (retour) { + retour = dir.delete(); + } + return retour; + } + + /** + * @param _FileName + * @param _Path + * @return true if the file exist in the specified path + */ + public static boolean FileExist(String _FileName, String _Path) { + boolean exist = false; + String fileString = _Path + File.separator + _FileName; + File file = new File(fileString); + if (file.exists()) { + exist = true; + } + return exist; + } + + /** + * Returns the FileChannel in Out MODE (if isOut is True) or in In MODE (if isOut is False) + * associated with the file. In out MODE, it can be in append MODE. + * + * @param isOut + * @param append + * @return the FileChannel (OUT or IN) + * @throws OpenR66ProtocolSystemException + */ + private static FileChannel getFileChannel(File file, boolean isOut, + boolean append) throws OpenR66ProtocolSystemException { + FileChannel fileChannel = null; + try { + if (isOut) { + @SuppressWarnings("resource") + FileOutputStream fileOutputStream = new FileOutputStream(file + .getPath(), append); + fileChannel = fileOutputStream.getChannel(); + if (append) { + // Bug in JVM since it does not respect the API (position + // should be set as length) + try { + fileChannel.position(file.length()); + } catch (IOException e) { + } + } + } else { + if (!file.exists()) { + throw new OpenR66ProtocolSystemException( + "File does not exist"); + } + @SuppressWarnings("resource") + FileInputStream fileInputStream = new FileInputStream(file + .getPath()); + fileChannel = fileInputStream.getChannel(); + } + } catch (FileNotFoundException e) { + throw new OpenR66ProtocolSystemException("File not found", e); + } + return fileChannel; + } + + /** + * Get the list of files from a given directory + * + * @param directory + * @return the list of files (as an array) + */ + public static File[] getFiles(File directory) { + if (directory == null || !directory.isDirectory()) { + return null; + } + return directory.listFiles(); + } + + /** + * Get the list of files from a given directory and a filter + * + * @param directory + * @param filter + * @return the list of files (as an array) + */ + public static File[] getFiles(File directory, FilenameFilter filter) { + if (directory == null || !directory.isDirectory()) { + return null; + } + return directory.listFiles(filter); + } + + /** + * Calculates and returns the hash of the contents of the given file. + * + * @param f + * FileInterface to hash + * @return the hash from the given file + * @throws OpenR66ProtocolSystemException + **/ + public static String getHash(File f) throws OpenR66ProtocolSystemException { + try { + return FilesystemBasedDigest.getHex(FilesystemBasedDigest.getHash(f, + FilesystemBasedFileParameterImpl.useNio, Configuration.configuration.digest)); + } catch (IOException e) { + throw new OpenR66ProtocolSystemException(e); + } + } + + /** + * + * @param buffer + * @return the hash from the given Buffer + */ + public static ChannelBuffer getHash(ChannelBuffer buffer) { + byte[] newkey; + try { + newkey = FilesystemBasedDigest.getHash(buffer, Configuration.configuration.digest); + } catch (IOException e) { + return ChannelBuffers.EMPTY_BUFFER; + } + return ChannelBuffers.wrappedBuffer(newkey); + } + + /** + * Compute global hash (if possible) + * @param digest + * @param block + */ + public static void computeGlobalHash(FilesystemBasedDigest digest, ChannelBuffer buffer) { + if (digest == null) { + return; + } + byte[] bytes = null; + int start = 0; + int length = buffer.readableBytes(); + if (buffer.hasArray()) { + start = buffer.arrayOffset(); + bytes = buffer.array(); + if (bytes.length > start + length) { + byte[] temp = new byte[length]; + System.arraycopy(bytes, start, temp, 0, length); + start = 0; + bytes = temp; + } + } else { + bytes = new byte[length]; + buffer.getBytes(buffer.readerIndex(), bytes); + } + digest.Update(bytes, start, length); + } + + /** + * Write one fileChannel to another one. Close the fileChannels + * + * @param fileChannelIn + * source of file + * @param fileChannelOut + * destination of file + * @return The size of copy if is OK + * @throws AtlasIoException + */ + private static long write(FileChannel fileChannelIn, + FileChannel fileChannelOut) throws OpenR66ProtocolSystemException { + if (fileChannelIn == null) { + if (fileChannelOut != null) { + try { + fileChannelOut.close(); + } catch (IOException e) { + } + } + throw new OpenR66ProtocolSystemException("FileChannelIn is null"); + } + if (fileChannelOut == null) { + try { + fileChannelIn.close(); + } catch (IOException e) { + } + throw new OpenR66ProtocolSystemException("FileChannelOut is null"); + } + long size = 0; + long transfert = 0; + try { + transfert = fileChannelOut.position(); + size = fileChannelIn.size(); + int chunkSize = 8192; + while (transfert < size) { + if (chunkSize < size - transfert) { + chunkSize = (int) (size - transfert); + } + transfert += fileChannelOut.transferFrom(fileChannelIn, transfert, chunkSize); + } + } catch (IOException e) { + try { + fileChannelOut.close(); + fileChannelIn.close(); + } catch (IOException e1) { + } + throw new OpenR66ProtocolSystemException( + "An error during copy occurs", e); + } + try { + fileChannelOut.close(); + fileChannelIn.close(); + } catch (IOException e) {// Close error can be ignored + } + boolean retour = size == transfert; + if (!retour) { + throw new OpenR66ProtocolSystemException("Copy is not complete: " + + transfert + " bytes instead of " + size + " original bytes"); + } + return size; + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/NbAndSpecialId.java b/src/main/java/org/waarp/openr66/protocol/utils/NbAndSpecialId.java index 4ab96fc00..72221fb8a 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/NbAndSpecialId.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/NbAndSpecialId.java @@ -1,32 +1,32 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import org.waarp.openr66.database.DbConstant; - -/** - * Class to retrieve the number of runner and the higher rank. - * - * @author Frederic Bregier - * - */ -public class NbAndSpecialId { - public int nb = 0; - public long higherSpecialId = DbConstant.ILLEGALVALUE; - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import org.waarp.openr66.database.DbConstant; + +/** + * Class to retrieve the number of runner and the higher rank. + * + * @author Frederic Bregier + * + */ +public class NbAndSpecialId { + public int nb = 0; + public long higherSpecialId = DbConstant.ILLEGALVALUE; + +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/R66Future.java b/src/main/java/org/waarp/openr66/protocol/utils/R66Future.java index 266e848d3..2a28f8dc2 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/R66Future.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/R66Future.java @@ -1,73 +1,73 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import org.waarp.common.future.WaarpFuture; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.data.DbTaskRunner; - -/** - * Future implementation - * - * @author Frederic Bregier - * - */ -public class R66Future extends WaarpFuture { - - private R66Result result = null; - /** - * Used in some specific occasion, such as client submission in API mode - */ - public DbTaskRunner runner = null; - public long filesize = 0; - - /** - * - */ - public R66Future() { - } - - /** - * @param cancellable - */ - public R66Future(boolean cancellable) { - super(cancellable); - } - - /** - * @return the result - */ - public R66Result getResult() { - return result; - } - - /** - * @param result - * the result to set - */ - public void setResult(R66Result result) { - this.result = result; - } - - @Override - public String toString() { - return "Future: " + isDone() + " " + isSuccess() + " " + - (getCause() != null ? getCause().getMessage() : "no cause") + - " " + (result != null ? result.toString() : "no result"); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import org.waarp.common.future.WaarpFuture; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.data.DbTaskRunner; + +/** + * Future implementation + * + * @author Frederic Bregier + * + */ +public class R66Future extends WaarpFuture { + + private R66Result result = null; + /** + * Used in some specific occasion, such as client submission in API mode + */ + public DbTaskRunner runner = null; + public long filesize = 0; + + /** + * + */ + public R66Future() { + } + + /** + * @param cancellable + */ + public R66Future(boolean cancellable) { + super(cancellable); + } + + /** + * @return the result + */ + public R66Result getResult() { + return result; + } + + /** + * @param result + * the result to set + */ + public void setResult(R66Result result) { + this.result = result; + } + + @Override + public String toString() { + return "Future: " + isDone() + " " + isSuccess() + " " + + (getCause() != null ? getCause().getMessage() : "no cause") + + " " + (result != null ? result.toString() : "no result"); + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/R66ShutdownHook.java b/src/main/java/org/waarp/openr66/protocol/utils/R66ShutdownHook.java index 79919bc08..c0fee8edb 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/R66ShutdownHook.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/R66ShutdownHook.java @@ -1,43 +1,43 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project 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. - - Waarp 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 Waarp . If not, see . - */ -package org.waarp.openr66.protocol.utils; - -import org.waarp.common.utility.WaarpShutdownHook; - -/** - * @author "Frederic Bregier" - * - */ -public class R66ShutdownHook extends WaarpShutdownHook { - - /** - * @param configuration - */ - public R66ShutdownHook(ShutdownConfiguration configuration) { - super(configuration); - } - - @Override - protected void exit() { - ChannelUtils.exit(); - } - -} +/** + This file is part of Waarp Project. + + Copyright 2009, Frederic Bregier, and individual contributors by the @author + tags. See the COPYRIGHT.txt in the distribution for a full listing of + individual contributors. + + All Waarp Project 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. + + Waarp 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 Waarp . If not, see . + */ +package org.waarp.openr66.protocol.utils; + +import org.waarp.common.utility.WaarpShutdownHook; + +/** + * @author "Frederic Bregier" + * + */ +public class R66ShutdownHook extends WaarpShutdownHook { + + /** + * @param configuration + */ + public R66ShutdownHook(ShutdownConfiguration configuration) { + super(configuration); + } + + @Override + protected void exit() { + ChannelUtils.exit(); + } + +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/TransferUtils.java b/src/main/java/org/waarp/openr66/protocol/utils/TransferUtils.java index 56424d254..41eb2d65f 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/TransferUtils.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/TransferUtils.java @@ -1,316 +1,316 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.utils; - -import java.sql.Timestamp; - -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.RequestTransfer; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.commander.CommanderNoDb; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; - -/** - * Utility class for transfers - * - * @author Frederic Bregier - * - */ -public class TransferUtils { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(TransferUtils.class); - - /** - * Try to restart one Transfer Runner Task - * - * @param taskRunner - * @return the associated Result - * @throws WaarpDatabaseException - */ - @SuppressWarnings("unused") - public static R66Result restartTransfer(DbTaskRunner taskRunner, LocalChannelReference lcr) - throws WaarpDatabaseException { - R66Result finalResult = new R66Result(null, true, ErrorCode.InitOk, taskRunner); - if (lcr != null) { - finalResult.code = ErrorCode.QueryStillRunning; - finalResult.other = "Transfer is still running so not restartable"; - } else { - if (taskRunner.isSendThrough()) { - // XXX FIXME TODO cannot be restarted... Really? - if (false) { - finalResult.code = ErrorCode.PassThroughMode; - finalResult.other = "Transfer cannot be restarted since it is in PassThrough mode"; - return finalResult; - } - } - // Transfer is not running - // but maybe need action on database - try { - if (taskRunner.restart(true)) { - taskRunner.forceSaveStatus(); - finalResult.code = ErrorCode.PreProcessingOk; - finalResult.other = "Transfer is restarted"; - } else { - if (taskRunner.isSelfRequested() && - (taskRunner.getGloballaststep() < TASKSTEP.POSTTASK.ordinal())) { - // send a VALID packet with VALID code to the requester - R66Future result = new R66Future(true); - RequestTransfer requestTransfer = - new RequestTransfer(result, taskRunner.getSpecialId(), - taskRunner.getRequested(), taskRunner.getRequester(), - false, false, true, - Configuration.configuration.getInternalRunner(). - getNetworkTransaction()); - requestTransfer.run(); - result.awaitUninterruptibly(); - R66Result finalValue = result.getResult(); - switch (finalValue.code) { - case QueryStillRunning: - finalResult.code = ErrorCode.QueryStillRunning; - finalResult.other = "Transfer restart requested but already active and running"; - break; - case Running: - finalResult.code = ErrorCode.Running; - finalResult.other = "Transfer restart requested but already running"; - break; - case PreProcessingOk: - finalResult.code = ErrorCode.PreProcessingOk; - finalResult.other = "Transfer restart requested and restarted"; - break; - case CompleteOk: - finalResult.code = ErrorCode.CompleteOk; - finalResult.other = "Transfer restart requested but already finished so try to run Post Action"; - taskRunner.setPostTask(); - TransferUtils.finalizeTaskWithNoSession(taskRunner, lcr); - taskRunner.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); - taskRunner.forceSaveStatus(); - break; - case RemoteError: - finalResult.code = ErrorCode.RemoteError; - finalResult.other = "Transfer restart requested but remote error"; - break; - default: - finalResult.code = ErrorCode.Internal; - finalResult.other = "Transfer restart requested but internal error"; - break; - } - } else { - finalResult.code = ErrorCode.CompleteOk; - finalResult.other = "Transfer is finished so not restartable"; - taskRunner.setPostTask(); - TransferUtils.finalizeTaskWithNoSession(taskRunner, lcr); - taskRunner.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); - taskRunner.forceSaveStatus(); - } - } - } catch (OpenR66RunnerErrorException e) { - finalResult.code = ErrorCode.PreProcessingOk; - finalResult.other = "Transfer is restarted"; - } - } - return finalResult; - } - - private static void stopOneTransfer(DbTaskRunner taskRunner, - StringBuilder builder, R66Session session, String body) { - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(taskRunner.getKey()); - ErrorCode result; - ErrorCode code = ErrorCode.StoppedTransfer; - if (lcr != null) { - int rank = taskRunner.getRank(); - lcr.sessionNewState(R66FiniteDualStates.ERROR); - ErrorPacket perror = new ErrorPacket("Transfer Stopped at " + rank, - code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - // XXX ChannelUtils.writeAbstractLocalPacket(lcr, perror); - // inform local instead of remote - ChannelUtils.writeAbstractLocalPacketToLocal(lcr, perror); - } catch (Exception e) { - } - result = ErrorCode.StoppedTransfer; - } else { - // Transfer is not running - // if in ERROR already just ignore it - if (taskRunner.getUpdatedInfo() == UpdatedInfo.INERROR) { - result = ErrorCode.TransferError; - } else { - // the database saying it is not stopped - result = ErrorCode.TransferError; - if (taskRunner != null) { - if (taskRunner.stopOrCancelRunner(code)) { - result = ErrorCode.StoppedTransfer; - } - } - } - } - ErrorCode last = taskRunner.getErrorInfo(); - taskRunner.setErrorExecutionStatus(result); - if (builder != null) { - builder.append(taskRunner.toSpecializedHtml(session, body, - lcr != null ? "Active" : "NotActive")); - } - taskRunner.setErrorExecutionStatus(last); - } - - /** - * Stop all selected transfers - * - * @param dbSession - * @param limit - * @param builder - * @param session - * @param body - * @param startid - * @param stopid - * @param tstart - * @param tstop - * @param rule - * @param req - * @param pending - * @param transfer - * @param error - * @return the associated StringBuilder if the one given as parameter is not null - */ - public static StringBuilder stopSelectedTransfers(DbSession dbSession, int limit, - StringBuilder builder, R66Session session, String body, - String startid, String stopid, Timestamp tstart, Timestamp tstop, String rule, - String req, boolean pending, boolean transfer, boolean error) { - if (dbSession == null || dbSession.isDisconnected) { - // do it without DB - if (ClientRunner.activeRunners != null) { - for (ClientRunner runner : ClientRunner.activeRunners) { - DbTaskRunner taskRunner = runner.getTaskRunner(); - stopOneTransfer(taskRunner, builder, session, body); - } - } - if (CommanderNoDb.todoList != null) { - CommanderNoDb.todoList.clear(); - } - return builder; - } - DbPreparedStatement preparedStatement = null; - try { - preparedStatement = - DbTaskRunner.getFilterPrepareStatement(dbSession, limit, true, - startid, stopid, tstart, tstop, rule, req, - pending, transfer, error, false, false); - preparedStatement.executeQuery(); - while (preparedStatement.getNext()) { - DbTaskRunner taskRunner = DbTaskRunner.getFromStatement(preparedStatement); - stopOneTransfer(taskRunner, builder, session, body); - } - preparedStatement.realClose(); - return builder; - } catch (WaarpDatabaseException e) { - if (preparedStatement != null) { - preparedStatement.realClose(); - } - logger.error("OpenR66 Error {}", e.getMessage()); - return null; - } - } - - /** - * Finalize a local task since only Post action has to be done - * - * @param taskRunner - * @param localChannelReference - * @throws OpenR66RunnerErrorException - */ - public static void finalizeTaskWithNoSession(DbTaskRunner taskRunner, - LocalChannelReference localChannelReference) - throws OpenR66RunnerErrorException { - R66Session session = new R66Session(); - session.setStatus(50); - String remoteId = taskRunner.isSelfRequested() ? - taskRunner.getRequester() : - taskRunner.getRequested(); - session.getAuth().specialNoSessionAuth(false, remoteId); - session.setNoSessionRunner(taskRunner, localChannelReference); - if (taskRunner.isSender()) { - // Change dir - try { - session.getDir().changeDirectory(taskRunner.getRule().sendPath); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } else { - // Change dir - try { - session.getDir().changeDirectory(taskRunner.getRule().workPath); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } - try { - try { - session.setFileAfterPreRunner(false); - } catch (CommandAbstractException e) { - throw new OpenR66RunnerErrorException(e); - } - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot recreate file: {}", taskRunner.getFilename()); - taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); - taskRunner.setErrorExecutionStatus(ErrorCode.FileNotFound); - try { - taskRunner.update(); - } catch (WaarpDatabaseException e1) { - } - throw new OpenR66RunnerErrorException("Cannot recreate file", e); - } - R66File file = session.getFile(); - R66Result finalValue = new R66Result(null, true, ErrorCode.CompleteOk, taskRunner); - finalValue.file = file; - finalValue.runner = taskRunner; - taskRunner.finishTransferTask(ErrorCode.TransferOk); - try { - taskRunner.finalizeTransfer(localChannelReference, file, finalValue, true); - } catch (OpenR66ProtocolSystemException e) { - logger.error("Cannot validate runner:\n {}", taskRunner.toShortString()); - taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); - taskRunner.setErrorExecutionStatus(ErrorCode.Internal); - try { - taskRunner.update(); - } catch (WaarpDatabaseException e1) { - } - throw new OpenR66RunnerErrorException("Cannot validate runner", e); - } - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.utils; + +import java.sql.Timestamp; + +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.RequestTransfer; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.commander.CommanderNoDb; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; + +/** + * Utility class for transfers + * + * @author Frederic Bregier + * + */ +public class TransferUtils { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(TransferUtils.class); + + /** + * Try to restart one Transfer Runner Task + * + * @param taskRunner + * @return the associated Result + * @throws WaarpDatabaseException + */ + @SuppressWarnings("unused") + public static R66Result restartTransfer(DbTaskRunner taskRunner, LocalChannelReference lcr) + throws WaarpDatabaseException { + R66Result finalResult = new R66Result(null, true, ErrorCode.InitOk, taskRunner); + if (lcr != null) { + finalResult.code = ErrorCode.QueryStillRunning; + finalResult.other = "Transfer is still running so not restartable"; + } else { + if (taskRunner.isSendThrough()) { + // XXX FIXME TODO cannot be restarted... Really? + if (false) { + finalResult.code = ErrorCode.PassThroughMode; + finalResult.other = "Transfer cannot be restarted since it is in PassThrough mode"; + return finalResult; + } + } + // Transfer is not running + // but maybe need action on database + try { + if (taskRunner.restart(true)) { + taskRunner.forceSaveStatus(); + finalResult.code = ErrorCode.PreProcessingOk; + finalResult.other = "Transfer is restarted"; + } else { + if (taskRunner.isSelfRequested() && + (taskRunner.getGloballaststep() < TASKSTEP.POSTTASK.ordinal())) { + // send a VALID packet with VALID code to the requester + R66Future result = new R66Future(true); + RequestTransfer requestTransfer = + new RequestTransfer(result, taskRunner.getSpecialId(), + taskRunner.getRequested(), taskRunner.getRequester(), + false, false, true, + Configuration.configuration.getInternalRunner(). + getNetworkTransaction()); + requestTransfer.run(); + result.awaitUninterruptibly(); + R66Result finalValue = result.getResult(); + switch (finalValue.code) { + case QueryStillRunning: + finalResult.code = ErrorCode.QueryStillRunning; + finalResult.other = "Transfer restart requested but already active and running"; + break; + case Running: + finalResult.code = ErrorCode.Running; + finalResult.other = "Transfer restart requested but already running"; + break; + case PreProcessingOk: + finalResult.code = ErrorCode.PreProcessingOk; + finalResult.other = "Transfer restart requested and restarted"; + break; + case CompleteOk: + finalResult.code = ErrorCode.CompleteOk; + finalResult.other = "Transfer restart requested but already finished so try to run Post Action"; + taskRunner.setPostTask(); + TransferUtils.finalizeTaskWithNoSession(taskRunner, lcr); + taskRunner.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); + taskRunner.forceSaveStatus(); + break; + case RemoteError: + finalResult.code = ErrorCode.RemoteError; + finalResult.other = "Transfer restart requested but remote error"; + break; + default: + finalResult.code = ErrorCode.Internal; + finalResult.other = "Transfer restart requested but internal error"; + break; + } + } else { + finalResult.code = ErrorCode.CompleteOk; + finalResult.other = "Transfer is finished so not restartable"; + taskRunner.setPostTask(); + TransferUtils.finalizeTaskWithNoSession(taskRunner, lcr); + taskRunner.setErrorExecutionStatus(ErrorCode.QueryAlreadyFinished); + taskRunner.forceSaveStatus(); + } + } + } catch (OpenR66RunnerErrorException e) { + finalResult.code = ErrorCode.PreProcessingOk; + finalResult.other = "Transfer is restarted"; + } + } + return finalResult; + } + + private static void stopOneTransfer(DbTaskRunner taskRunner, + StringBuilder builder, R66Session session, String body) { + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(taskRunner.getKey()); + ErrorCode result; + ErrorCode code = ErrorCode.StoppedTransfer; + if (lcr != null) { + int rank = taskRunner.getRank(); + lcr.sessionNewState(R66FiniteDualStates.ERROR); + ErrorPacket perror = new ErrorPacket("Transfer Stopped at " + rank, + code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + // XXX ChannelUtils.writeAbstractLocalPacket(lcr, perror); + // inform local instead of remote + ChannelUtils.writeAbstractLocalPacketToLocal(lcr, perror); + } catch (Exception e) { + } + result = ErrorCode.StoppedTransfer; + } else { + // Transfer is not running + // if in ERROR already just ignore it + if (taskRunner.getUpdatedInfo() == UpdatedInfo.INERROR) { + result = ErrorCode.TransferError; + } else { + // the database saying it is not stopped + result = ErrorCode.TransferError; + if (taskRunner != null) { + if (taskRunner.stopOrCancelRunner(code)) { + result = ErrorCode.StoppedTransfer; + } + } + } + } + ErrorCode last = taskRunner.getErrorInfo(); + taskRunner.setErrorExecutionStatus(result); + if (builder != null) { + builder.append(taskRunner.toSpecializedHtml(session, body, + lcr != null ? "Active" : "NotActive")); + } + taskRunner.setErrorExecutionStatus(last); + } + + /** + * Stop all selected transfers + * + * @param dbSession + * @param limit + * @param builder + * @param session + * @param body + * @param startid + * @param stopid + * @param tstart + * @param tstop + * @param rule + * @param req + * @param pending + * @param transfer + * @param error + * @return the associated StringBuilder if the one given as parameter is not null + */ + public static StringBuilder stopSelectedTransfers(DbSession dbSession, int limit, + StringBuilder builder, R66Session session, String body, + String startid, String stopid, Timestamp tstart, Timestamp tstop, String rule, + String req, boolean pending, boolean transfer, boolean error) { + if (dbSession == null || dbSession.isDisconnected) { + // do it without DB + if (ClientRunner.activeRunners != null) { + for (ClientRunner runner : ClientRunner.activeRunners) { + DbTaskRunner taskRunner = runner.getTaskRunner(); + stopOneTransfer(taskRunner, builder, session, body); + } + } + if (CommanderNoDb.todoList != null) { + CommanderNoDb.todoList.clear(); + } + return builder; + } + DbPreparedStatement preparedStatement = null; + try { + preparedStatement = + DbTaskRunner.getFilterPrepareStatement(dbSession, limit, true, + startid, stopid, tstart, tstop, rule, req, + pending, transfer, error, false, false); + preparedStatement.executeQuery(); + while (preparedStatement.getNext()) { + DbTaskRunner taskRunner = DbTaskRunner.getFromStatement(preparedStatement); + stopOneTransfer(taskRunner, builder, session, body); + } + preparedStatement.realClose(); + return builder; + } catch (WaarpDatabaseException e) { + if (preparedStatement != null) { + preparedStatement.realClose(); + } + logger.error("OpenR66 Error {}", e.getMessage()); + return null; + } + } + + /** + * Finalize a local task since only Post action has to be done + * + * @param taskRunner + * @param localChannelReference + * @throws OpenR66RunnerErrorException + */ + public static void finalizeTaskWithNoSession(DbTaskRunner taskRunner, + LocalChannelReference localChannelReference) + throws OpenR66RunnerErrorException { + R66Session session = new R66Session(); + session.setStatus(50); + String remoteId = taskRunner.isSelfRequested() ? + taskRunner.getRequester() : + taskRunner.getRequested(); + session.getAuth().specialNoSessionAuth(false, remoteId); + session.setNoSessionRunner(taskRunner, localChannelReference); + if (taskRunner.isSender()) { + // Change dir + try { + session.getDir().changeDirectory(taskRunner.getRule().sendPath); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } else { + // Change dir + try { + session.getDir().changeDirectory(taskRunner.getRule().workPath); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } + try { + try { + session.setFileAfterPreRunner(false); + } catch (CommandAbstractException e) { + throw new OpenR66RunnerErrorException(e); + } + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot recreate file: {}", taskRunner.getFilename()); + taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); + taskRunner.setErrorExecutionStatus(ErrorCode.FileNotFound); + try { + taskRunner.update(); + } catch (WaarpDatabaseException e1) { + } + throw new OpenR66RunnerErrorException("Cannot recreate file", e); + } + R66File file = session.getFile(); + R66Result finalValue = new R66Result(null, true, ErrorCode.CompleteOk, taskRunner); + finalValue.file = file; + finalValue.runner = taskRunner; + taskRunner.finishTransferTask(ErrorCode.TransferOk); + try { + taskRunner.finalizeTransfer(localChannelReference, file, finalValue, true); + } catch (OpenR66ProtocolSystemException e) { + logger.error("Cannot validate runner:\n {}", taskRunner.toShortString()); + taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); + taskRunner.setErrorExecutionStatus(ErrorCode.Internal); + try { + taskRunner.update(); + } catch (WaarpDatabaseException e1) { + } + throw new OpenR66RunnerErrorException("Cannot validate runner", e); + } + } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/Version.java b/src/main/java/org/waarp/openr66/protocol/utils/Version.java index a1dea9ce5..3d82adbcb 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/Version.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/Version.java @@ -1,10 +1,10 @@ -// DO NOT MODIFY - WILL BE OVERWRITTEN DURING THE BUILD PROCESS -package org.waarp.openr66.protocol.utils; -/** Provides the version information of Waarp OpenR66. */ -public final class Version { - /** The version identifier. */ - public static final String ID = "2.4.11"; - /** Prints out the version identifier to stdout. */ - public static void main(String[] args) { System.out.println(ID); } - private Version() { super(); } -} +// DO NOT MODIFY - WILL BE OVERWRITTEN DURING THE BUILD PROCESS +package org.waarp.openr66.protocol.utils; +/** Provides the version information of Waarp OpenR66. */ +public final class Version { + /** The version identifier. */ + public static final String ID = "2.4.11"; + /** Prints out the version identifier to stdout. */ + public static void main(String[] args) { System.out.println(ID); } + private Version() { super(); } +} diff --git a/src/main/java/org/waarp/openr66/protocol/utils/package-info.java b/src/main/java/org/waarp/openr66/protocol/utils/package-info.java index 02552f720..c0e429e51 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/package-info.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Utilities - * - * @apiviz.landmark - */ -package org.waarp.openr66.protocol.utils; - +/** + * Classes implementing Utilities + * + * @apiviz.landmark + */ +package org.waarp.openr66.protocol.utils; + diff --git a/src/main/java/org/waarp/openr66/server/ChangeBandwidthLimits.java b/src/main/java/org/waarp/openr66/server/ChangeBandwidthLimits.java index 47c14042f..8c8f6a046 100644 --- a/src/main/java/org/waarp/openr66/server/ChangeBandwidthLimits.java +++ b/src/main/java/org/waarp/openr66/server/ChangeBandwidthLimits.java @@ -1,240 +1,240 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * This command enables the dynamic change of bandwidth limitation. It does not changed the valuesin - * the database but only dynamic values while the server is running and until it is shutdown. - * - * @author Frederic Bregier - * - */ -public class ChangeBandwidthLimits implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final R66Future future; - protected final long writeGlobalLimit; - protected final long readGlobalLimit; - protected final long writeSessionLimit; - protected final long readSessionLimit; - protected final NetworkTransaction networkTransaction; - protected DbHostAuth host; - - public ChangeBandwidthLimits(R66Future future, long wgl, long rgl, long wsl, long rsl, - NetworkTransaction networkTransaction) { - this.future = future; - this.writeGlobalLimit = wgl; - this.readGlobalLimit = rgl; - this.writeSessionLimit = wsl; - this.readSessionLimit = rsl; - this.networkTransaction = networkTransaction; - this.host = Configuration.configuration.HOST_SSLAUTH; - } - - - public void setHost(DbHostAuth host) { - this.host = host; - } - - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ChangeBandwidthLimits.class); - } - ValidPacket valid = null; - if (writeGlobalLimit < 0 && readGlobalLimit < 0 && writeSessionLimit < 0 && readSessionLimit < 0) { - // will ask current values instead - valid = new ValidPacket("-1", - "-1", LocalPacketFactory.BANDWIDTHPACKET); - } else { - valid = new ValidPacket(writeGlobalLimit + " " + readGlobalLimit, - writeSessionLimit + " " + readSessionLimit, LocalPacketFactory.BANDWIDTHPACKET); - } - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - host = null; - logger.error("Cannot Connect"); - future.setResult(new R66Result( - new OpenR66ProtocolNoConnectionException("Cannot connect to server"), - null, true, ErrorCode.Internal, null)); - future.setFailure(future.getResult().exception); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - host = null; - valid = null; - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return; - } - host = null; - future.awaitUninterruptibly(); - logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - } - - protected static long swriteGlobalLimit = -1; - protected static long sreadGlobalLimit = -1; - protected static long swriteSessionLimit = -1; - protected static long sreadSessionLimit = -1; - - protected static boolean getParams(String[] args) { - if (args.length < 3) { - logger.error("Need the configuration file as first argument then at least one of\n" + - " -wglob limitGlobalWrite\n" + - " -rglob limitGlobalRead\n" + - " -wsess limitSessionWrite\n" + - " -rsess limitSessionWrite"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger.error("Need the configuration file as first argument then at least one of\n" + - " -wglob limitGlobalWrite\n" + - " -rglob limitGlobalRead\n" + - " -wsess limitSessionWrite\n" + - " -rsess limitSessionWrite"); - return false; - } - for (int i = 1; i < args.length; i++) { - try { - if (args[i].equalsIgnoreCase("-wglob")) { - i++; - swriteGlobalLimit = Long.parseLong(args[i]); - } else if (args[i].equalsIgnoreCase("-rglob")) { - i++; - sreadGlobalLimit = Long.parseLong(args[i]); - } else if (args[i].equalsIgnoreCase("-wsess")) { - i++; - swriteSessionLimit = Long.parseLong(args[i]); - } else if (args[i].equalsIgnoreCase("-rsess")) { - i++; - sreadSessionLimit = Long.parseLong(args[i]); - } - } catch (NumberFormatException e) { - } - } - if (swriteGlobalLimit == -1 && sreadGlobalLimit == -1 && - swriteSessionLimit == -1 && sreadSessionLimit == -1) { - logger.error("Need the configuration file as first argument then at least one of\n" + - " -wglob limitGlobalWrite\n" + - " -rglob limitGlobalRead\n" + - " -wsess limitSessionWrite\n" + - " -rsess limitSessionWrite"); - return false; - } - return true; - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ChangeBandwidthLimits.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - ChangeBandwidthLimits transaction = new ChangeBandwidthLimits(future, - swriteGlobalLimit, sreadGlobalLimit, swriteSessionLimit, sreadSessionLimit, - networkTransaction); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.code == ErrorCode.Warning) { - logger.warn("WARNED on bandwidth:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } else { - logger.warn("SUCCESS on Bandwidth:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } - } else { - if (result.code == ErrorCode.Warning) { - logger.warn("Bandwidth is\n WARNED", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Bandwidth in\n FAILURE", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * This command enables the dynamic change of bandwidth limitation. It does not changed the valuesin + * the database but only dynamic values while the server is running and until it is shutdown. + * + * @author Frederic Bregier + * + */ +public class ChangeBandwidthLimits implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final R66Future future; + protected final long writeGlobalLimit; + protected final long readGlobalLimit; + protected final long writeSessionLimit; + protected final long readSessionLimit; + protected final NetworkTransaction networkTransaction; + protected DbHostAuth host; + + public ChangeBandwidthLimits(R66Future future, long wgl, long rgl, long wsl, long rsl, + NetworkTransaction networkTransaction) { + this.future = future; + this.writeGlobalLimit = wgl; + this.readGlobalLimit = rgl; + this.writeSessionLimit = wsl; + this.readSessionLimit = rsl; + this.networkTransaction = networkTransaction; + this.host = Configuration.configuration.HOST_SSLAUTH; + } + + + public void setHost(DbHostAuth host) { + this.host = host; + } + + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ChangeBandwidthLimits.class); + } + ValidPacket valid = null; + if (writeGlobalLimit < 0 && readGlobalLimit < 0 && writeSessionLimit < 0 && readSessionLimit < 0) { + // will ask current values instead + valid = new ValidPacket("-1", + "-1", LocalPacketFactory.BANDWIDTHPACKET); + } else { + valid = new ValidPacket(writeGlobalLimit + " " + readGlobalLimit, + writeSessionLimit + " " + readSessionLimit, LocalPacketFactory.BANDWIDTHPACKET); + } + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + host = null; + logger.error("Cannot Connect"); + future.setResult(new R66Result( + new OpenR66ProtocolNoConnectionException("Cannot connect to server"), + null, true, ErrorCode.Internal, null)); + future.setFailure(future.getResult().exception); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + host = null; + valid = null; + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return; + } + host = null; + future.awaitUninterruptibly(); + logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + } + + protected static long swriteGlobalLimit = -1; + protected static long sreadGlobalLimit = -1; + protected static long swriteSessionLimit = -1; + protected static long sreadSessionLimit = -1; + + protected static boolean getParams(String[] args) { + if (args.length < 3) { + logger.error("Need the configuration file as first argument then at least one of\n" + + " -wglob limitGlobalWrite\n" + + " -rglob limitGlobalRead\n" + + " -wsess limitSessionWrite\n" + + " -rsess limitSessionWrite"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger.error("Need the configuration file as first argument then at least one of\n" + + " -wglob limitGlobalWrite\n" + + " -rglob limitGlobalRead\n" + + " -wsess limitSessionWrite\n" + + " -rsess limitSessionWrite"); + return false; + } + for (int i = 1; i < args.length; i++) { + try { + if (args[i].equalsIgnoreCase("-wglob")) { + i++; + swriteGlobalLimit = Long.parseLong(args[i]); + } else if (args[i].equalsIgnoreCase("-rglob")) { + i++; + sreadGlobalLimit = Long.parseLong(args[i]); + } else if (args[i].equalsIgnoreCase("-wsess")) { + i++; + swriteSessionLimit = Long.parseLong(args[i]); + } else if (args[i].equalsIgnoreCase("-rsess")) { + i++; + sreadSessionLimit = Long.parseLong(args[i]); + } + } catch (NumberFormatException e) { + } + } + if (swriteGlobalLimit == -1 && sreadGlobalLimit == -1 && + swriteSessionLimit == -1 && sreadSessionLimit == -1) { + logger.error("Need the configuration file as first argument then at least one of\n" + + " -wglob limitGlobalWrite\n" + + " -rglob limitGlobalRead\n" + + " -wsess limitSessionWrite\n" + + " -rsess limitSessionWrite"); + return false; + } + return true; + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ChangeBandwidthLimits.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + ChangeBandwidthLimits transaction = new ChangeBandwidthLimits(future, + swriteGlobalLimit, sreadGlobalLimit, swriteSessionLimit, sreadSessionLimit, + networkTransaction); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.code == ErrorCode.Warning) { + logger.warn("WARNED on bandwidth:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } else { + logger.warn("SUCCESS on Bandwidth:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } + } else { + if (result.code == ErrorCode.Warning) { + logger.warn("Bandwidth is\n WARNED", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Bandwidth in\n FAILURE", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/server/ConfigExport.java b/src/main/java/org/waarp/openr66/server/ConfigExport.java index 30f2befb2..6f5916ebc 100644 --- a/src/main/java/org/waarp/openr66/server/ConfigExport.java +++ b/src/main/java/org/waarp/openr66/server/ConfigExport.java @@ -1,207 +1,207 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Config Export from a local client without database connection - * - * @author Frederic Bregier - * - */ -public class ConfigExport implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final R66Future future; - protected final boolean host; - protected final boolean rule; - protected final NetworkTransaction networkTransaction; - protected DbHostAuth dbhost; - - public ConfigExport(R66Future future, boolean host, boolean rule, - NetworkTransaction networkTransaction) { - this.future = future; - this.host = host; - this.rule = rule; - this.networkTransaction = networkTransaction; - this.dbhost = Configuration.configuration.HOST_SSLAUTH; - } - - public void setHost(DbHostAuth host) { - this.dbhost = host; - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ConfigExport.class); - } - ValidPacket valid = new ValidPacket(Boolean.toString(host), Boolean.toString(rule), - LocalPacketFactory.CONFEXPORTPACKET); - SocketAddress socketAddress = dbhost.getSocketAddress(); - boolean isSSL = dbhost.isSsl(); - - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - dbhost = null; - logger.error("Cannot Connect"); - future.setResult(new R66Result( - new OpenR66ProtocolNoConnectionException("Cannot connect to server"), - null, true, ErrorCode.Internal, null)); - future.setFailure(future.getResult().exception); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - dbhost = null; - valid = null; - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return; - } - dbhost = null; - future.awaitUninterruptibly(); - logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - } - - protected static boolean shost = false; - protected static boolean srule = false; - - protected static boolean getParams(String[] args) { - if (args.length < 2) { - logger.error("Need at least the configuration file as first argument then at least one from\n" - + - " -hosts\n" + - " -rules"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger.error("Need at least the configuration file as first argument then at least one from\n" - + - " -hosts\n" + - " -rules"); - return false; - } - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-hosts")) { - shost = true; - } else if (args[i].equalsIgnoreCase("-rules")) { - srule = true; - } - } - if ((!shost) && (!srule)) { - logger.error("Need at least one of -hosts - rules"); - return false; - } - return true; - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ConfigExport.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - ConfigExport transaction = new ConfigExport(future, - shost, srule, - networkTransaction); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.code == ErrorCode.Warning) { - logger.warn("WARNED on files:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } else { - logger.warn("SUCCESS on Final files:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } - } else { - if (result.code == ErrorCode.Warning) { - logger.warn("Transfer is\n WARNED", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in\n FAILURE", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Config Export from a local client without database connection + * + * @author Frederic Bregier + * + */ +public class ConfigExport implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final R66Future future; + protected final boolean host; + protected final boolean rule; + protected final NetworkTransaction networkTransaction; + protected DbHostAuth dbhost; + + public ConfigExport(R66Future future, boolean host, boolean rule, + NetworkTransaction networkTransaction) { + this.future = future; + this.host = host; + this.rule = rule; + this.networkTransaction = networkTransaction; + this.dbhost = Configuration.configuration.HOST_SSLAUTH; + } + + public void setHost(DbHostAuth host) { + this.dbhost = host; + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ConfigExport.class); + } + ValidPacket valid = new ValidPacket(Boolean.toString(host), Boolean.toString(rule), + LocalPacketFactory.CONFEXPORTPACKET); + SocketAddress socketAddress = dbhost.getSocketAddress(); + boolean isSSL = dbhost.isSsl(); + + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + dbhost = null; + logger.error("Cannot Connect"); + future.setResult(new R66Result( + new OpenR66ProtocolNoConnectionException("Cannot connect to server"), + null, true, ErrorCode.Internal, null)); + future.setFailure(future.getResult().exception); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + dbhost = null; + valid = null; + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return; + } + dbhost = null; + future.awaitUninterruptibly(); + logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + } + + protected static boolean shost = false; + protected static boolean srule = false; + + protected static boolean getParams(String[] args) { + if (args.length < 2) { + logger.error("Need at least the configuration file as first argument then at least one from\n" + + + " -hosts\n" + + " -rules"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger.error("Need at least the configuration file as first argument then at least one from\n" + + + " -hosts\n" + + " -rules"); + return false; + } + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-hosts")) { + shost = true; + } else if (args[i].equalsIgnoreCase("-rules")) { + srule = true; + } + } + if ((!shost) && (!srule)) { + logger.error("Need at least one of -hosts - rules"); + return false; + } + return true; + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ConfigExport.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + ConfigExport transaction = new ConfigExport(future, + shost, srule, + networkTransaction); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.code == ErrorCode.Warning) { + logger.warn("WARNED on files:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } else { + logger.warn("SUCCESS on Final files:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } + } else { + if (result.code == ErrorCode.Warning) { + logger.warn("Transfer is\n WARNED", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in\n FAILURE", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/server/ConfigImport.java b/src/main/java/org/waarp/openr66/server/ConfigImport.java index febe368b7..9d6b5b321 100644 --- a/src/main/java/org/waarp/openr66/server/ConfigImport.java +++ b/src/main/java/org/waarp/openr66/server/ConfigImport.java @@ -1,231 +1,231 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.net.SocketAddress; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Config Import from a local client without database connection - * - * @author Frederic Bregier - * - */ -public class ConfigImport implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final R66Future future; - protected final String host; - protected final boolean hostPurge; - protected final String rule; - protected final boolean rulePurge; - protected final NetworkTransaction networkTransaction; - protected DbHostAuth dbhost; - - public ConfigImport(R66Future future, boolean hostPurge, boolean rulePurge, - String host, String rule, - NetworkTransaction networkTransaction) { - this.future = future; - this.host = host; - this.rule = rule; - this.hostPurge = hostPurge; - this.rulePurge = rulePurge; - this.networkTransaction = networkTransaction; - this.dbhost = Configuration.configuration.HOST_SSLAUTH; - } - - public void setHost(DbHostAuth host) { - this.dbhost = host; - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ConfigImport.class); - } - ValidPacket valid = new ValidPacket((hostPurge ? "1 " : "0 ") + host, - (rulePurge ? "1 " : "0 ") + rule, - LocalPacketFactory.CONFIMPORTPACKET); - SocketAddress socketAddress = dbhost.getSocketAddress(); - boolean isSSL = dbhost.isSsl(); - - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - dbhost = null; - logger.error("Cannot Connect"); - future.setResult(new R66Result( - new OpenR66ProtocolNoConnectionException("Cannot connect to server"), - null, true, ErrorCode.Internal, null)); - future.setFailure(future.getResult().exception); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - dbhost = null; - valid = null; - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return; - } - dbhost = null; - future.awaitUninterruptibly(); - logger.debug("Request done with " + (future.isSuccess() ? "success" : "error")); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - } - - protected static String shost = null; - protected static String srule = null; - protected static boolean shostpurge = false; - protected static boolean srulepurge = false; - - protected static boolean getParams(String[] args) { - if (args.length < 3) { - logger.error("Need at least the configuration file as first argument then at least one from\n" - + - " -hosts file\n" + - " -rules file\n" + - " -purgehosts\n" + - " -purgerules"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger.error("Need at least the configuration file as first argument then at least one from\n" - + - " -hosts file\n" + - " -rules file\n" + - " -purgehosts\n" + - " -purgerules"); - return false; - } - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-hosts")) { - i++; - if (args.length <= i) { - return false; - } - shost = args[i]; - } else if (args[i].equalsIgnoreCase("-rules")) { - i++; - if (args.length <= i) { - return false; - } - srule = args[i]; - } else if (args[i].equalsIgnoreCase("-purgehosts")) { - shostpurge = true; - } else if (args[i].equalsIgnoreCase("-purgerules")) { - srulepurge = true; - } - } - if ((shost == null) && (srule == null)) { - logger.error("Need at least one of -hosts - rules"); - return false; - } - return true; - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ConfigImport.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - ConfigImport transaction = new ConfigImport(future, - shostpurge, srulepurge, shost, srule, - networkTransaction); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.code == ErrorCode.Warning) { - logger.warn("WARNED on import:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no import") - + "\n delay: " + delay); - } else { - logger.warn("SUCCESS on import:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no import") - + "\n delay: " + delay); - } - } else { - if (result.code == ErrorCode.Warning) { - logger.warn("Transfer is\n WARNED", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in\n FAILURE", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.net.SocketAddress; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Config Import from a local client without database connection + * + * @author Frederic Bregier + * + */ +public class ConfigImport implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final R66Future future; + protected final String host; + protected final boolean hostPurge; + protected final String rule; + protected final boolean rulePurge; + protected final NetworkTransaction networkTransaction; + protected DbHostAuth dbhost; + + public ConfigImport(R66Future future, boolean hostPurge, boolean rulePurge, + String host, String rule, + NetworkTransaction networkTransaction) { + this.future = future; + this.host = host; + this.rule = rule; + this.hostPurge = hostPurge; + this.rulePurge = rulePurge; + this.networkTransaction = networkTransaction; + this.dbhost = Configuration.configuration.HOST_SSLAUTH; + } + + public void setHost(DbHostAuth host) { + this.dbhost = host; + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ConfigImport.class); + } + ValidPacket valid = new ValidPacket((hostPurge ? "1 " : "0 ") + host, + (rulePurge ? "1 " : "0 ") + rule, + LocalPacketFactory.CONFIMPORTPACKET); + SocketAddress socketAddress = dbhost.getSocketAddress(); + boolean isSSL = dbhost.isSsl(); + + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + dbhost = null; + logger.error("Cannot Connect"); + future.setResult(new R66Result( + new OpenR66ProtocolNoConnectionException("Cannot connect to server"), + null, true, ErrorCode.Internal, null)); + future.setFailure(future.getResult().exception); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + dbhost = null; + valid = null; + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return; + } + dbhost = null; + future.awaitUninterruptibly(); + logger.debug("Request done with " + (future.isSuccess() ? "success" : "error")); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + } + + protected static String shost = null; + protected static String srule = null; + protected static boolean shostpurge = false; + protected static boolean srulepurge = false; + + protected static boolean getParams(String[] args) { + if (args.length < 3) { + logger.error("Need at least the configuration file as first argument then at least one from\n" + + + " -hosts file\n" + + " -rules file\n" + + " -purgehosts\n" + + " -purgerules"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger.error("Need at least the configuration file as first argument then at least one from\n" + + + " -hosts file\n" + + " -rules file\n" + + " -purgehosts\n" + + " -purgerules"); + return false; + } + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-hosts")) { + i++; + if (args.length <= i) { + return false; + } + shost = args[i]; + } else if (args[i].equalsIgnoreCase("-rules")) { + i++; + if (args.length <= i) { + return false; + } + srule = args[i]; + } else if (args[i].equalsIgnoreCase("-purgehosts")) { + shostpurge = true; + } else if (args[i].equalsIgnoreCase("-purgerules")) { + srulepurge = true; + } + } + if ((shost == null) && (srule == null)) { + logger.error("Need at least one of -hosts - rules"); + return false; + } + return true; + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ConfigImport.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + ConfigImport transaction = new ConfigImport(future, + shostpurge, srulepurge, shost, srule, + networkTransaction); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.code == ErrorCode.Warning) { + logger.warn("WARNED on import:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no import") + + "\n delay: " + delay); + } else { + logger.warn("SUCCESS on import:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no import") + + "\n delay: " + delay); + } + } else { + if (result.code == ErrorCode.Warning) { + logger.warn("Transfer is\n WARNED", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in\n FAILURE", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/server/LogExport.java b/src/main/java/org/waarp/openr66/server/LogExport.java index 89a89f3fa..754c3a39e 100644 --- a/src/main/java/org/waarp/openr66/server/LogExport.java +++ b/src/main/java/org/waarp/openr66/server/LogExport.java @@ -1,319 +1,319 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.net.SocketAddress; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Log Export from a local client without database connection - * - * @author Frederic Bregier - * - */ -public class LogExport implements Runnable { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - protected final R66Future future; - protected final boolean purgeLog; - protected final Timestamp start; - protected final Timestamp stop; - protected final boolean clean; - protected final NetworkTransaction networkTransaction; - protected DbHostAuth host; - - public LogExport(R66Future future, boolean purgeLog, boolean clean, - Timestamp start, Timestamp stop, - NetworkTransaction networkTransaction) { - this.future = future; - this.purgeLog = purgeLog; - this.clean = clean; - this.start = start; - this.stop = stop; - this.networkTransaction = networkTransaction; - this.host = Configuration.configuration.HOST_SSLAUTH; - } - - public void setHost(DbHostAuth host) { - this.host = host; - } - - /** - * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It - * is the responsibility of the caller to finish all network resources. - */ - public void run() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(LogExport.class); - } - String lstart = (start != null) ? start.toString() : null; - String lstop = (stop != null) ? stop.toString() : null; - byte type = (purgeLog) ? LocalPacketFactory.LOGPURGEPACKET : LocalPacketFactory.LOGPACKET; - ValidPacket valid = new ValidPacket(lstart, lstop, type); - SocketAddress socketAddress = host.getSocketAddress(); - boolean isSSL = host.isSsl(); - - // first clean if ask - if (clean) { - // Update all UpdatedInfo to DONE - // where GlobalLastStep = ALLDONETASK and status = CompleteOk - try { - DbTaskRunner.changeFinishedToDone(DbConstant.admin.session); - } catch (WaarpDatabaseNoConnectionException e) { - logger.warn("Clean cannot be done {}", e.getMessage()); - } - } - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, isSSL, future); - socketAddress = null; - if (localChannelReference == null) { - host = null; - logger.error("Cannot Connect"); - future.setResult(new R66Result( - new OpenR66ProtocolNoConnectionException("Cannot connect to server"), - null, true, ErrorCode.Internal, null)); - future.setFailure(future.getResult().exception); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - host = null; - valid = null; - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, null)); - future.setFailure(e); - return; - } - host = null; - future.awaitUninterruptibly(); - logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); - Channels.close(localChannelReference.getLocalChannel()); - localChannelReference = null; - } - - protected static boolean spurgeLog = false; - protected static Timestamp sstart = null; - protected static Timestamp sstop = null; - protected static boolean sclean = false; - - private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); - - public static Timestamp fixDate(String sdate) { - Timestamp tdate = null; - String date = sdate.replaceAll("/|:|\\.| |-", ""); - if (date.length() > 0) { - if (date.length() < 15) { - int len = date.length(); - date += "000000000000000".substring(len); - } - try { - Date ddate = format.parse(date); - tdate = new Timestamp(ddate.getTime()); - } catch (ParseException e) { - logger.debug("start {}", e.getMessage()); - } - } - return tdate; - } - - public static Timestamp fixDate(String sdate, Timestamp before) { - Timestamp tdate = null; - String date = sdate.replaceAll("/|:|\\.| |-", ""); - if (date.length() > 0) { - if (date.length() < 15) { - int len = date.length(); - date += "000000000000000".substring(len); - } - try { - Date ddate = format.parse(date); - if (before != null) { - Date bef = new Date(before.getTime()); - if (bef.compareTo(ddate) >= 0) { - ddate = new Date(bef.getTime() + 1000 * 3600 * 24 - 1); - } - } - tdate = new Timestamp(ddate.getTime()); - } catch (ParseException e) { - logger.debug("start {}", e.getMessage()); - } - } - return tdate; - } - - public static Timestamp getTodayMidnight() { - GregorianCalendar calendar = new GregorianCalendar(); - calendar.set(GregorianCalendar.HOUR_OF_DAY, 0); - calendar.set(GregorianCalendar.MINUTE, 0); - calendar.set(GregorianCalendar.SECOND, 0); - calendar.set(GregorianCalendar.MILLISECOND, 0); - return new Timestamp(calendar.getTimeInMillis()); - } - - protected static boolean getParams(String[] args) { - if (args.length < 1) { - logger.error("Need at least the configuration file as first argument then optionally\n" - + - " -purge\n" - + - " -clean\n" - + - " -start timestamp in format yyyyMMddHHmmssSSS possibly truncated and where one of ':-. ' can be separators\n" - + - " -stop timestamp in same format than start\n" + - "If not start and no stop are given, stop is Today Midnight (00:00:00)\n" + - "If start is equals or greater than stop, stop is start+24H"); - return false; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger.error("Need at least the configuration file as first argument then optionally\n" - + - " -purge\n" - + - " -clean\n" - + - " -start timestamp in format yyyyMMddHHmmssSSS possibly truncated and where one of ':-. ' can be separators\n" - + - " -stop timestamp in same format than start\n" + - "If not start and no stop are given, stop is Today Midnight (00:00:00)\n" + - "If start is equals or greater than stop, stop is start+24H"); - return false; - } - String ssstart = null; - String ssstop = null; - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-purge")) { - spurgeLog = true; - } else if (args[i].equalsIgnoreCase("-clean")) { - sclean = true; - } else if (args[i].equalsIgnoreCase("-start")) { - i++; - ssstart = args[i]; - } else if (args[i].equalsIgnoreCase("-stop")) { - i++; - ssstop = args[i]; - } - } - if (ssstart != null) { - Timestamp tstart = fixDate(ssstart); - if (tstart != null) { - sstart = tstart; - } - } - if (ssstop != null) { - Timestamp tstop = fixDate(ssstop, sstart); - if (tstop != null) { - sstop = tstop; - } - } - if (ssstart == null && ssstop == null) { - sstop = getTodayMidnight(); - } - return true; - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(LogExport.class); - } - if (!getParams(args)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - LogExport transaction = new LogExport(future, - spurgeLog, sclean, sstart, sstop, - networkTransaction); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.code == ErrorCode.Warning) { - logger.warn("WARNED on file:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } else { - logger.warn("SUCCESS on Final file:\n " + - (result.other != null ? ((ValidPacket) result.other).getSheader() : - "no file") - + "\n delay: " + delay); - } - } else { - if (result.code == ErrorCode.Warning) { - logger.warn("Transfer is\n WARNED", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in\n FAILURE", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.net.SocketAddress; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Log Export from a local client without database connection + * + * @author Frederic Bregier + * + */ +public class LogExport implements Runnable { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + protected final R66Future future; + protected final boolean purgeLog; + protected final Timestamp start; + protected final Timestamp stop; + protected final boolean clean; + protected final NetworkTransaction networkTransaction; + protected DbHostAuth host; + + public LogExport(R66Future future, boolean purgeLog, boolean clean, + Timestamp start, Timestamp stop, + NetworkTransaction networkTransaction) { + this.future = future; + this.purgeLog = purgeLog; + this.clean = clean; + this.start = start; + this.stop = stop; + this.networkTransaction = networkTransaction; + this.host = Configuration.configuration.HOST_SSLAUTH; + } + + public void setHost(DbHostAuth host) { + this.host = host; + } + + /** + * Prior to call this method, the pipeline and NetworkTransaction must have been initialized. It + * is the responsibility of the caller to finish all network resources. + */ + public void run() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(LogExport.class); + } + String lstart = (start != null) ? start.toString() : null; + String lstop = (stop != null) ? stop.toString() : null; + byte type = (purgeLog) ? LocalPacketFactory.LOGPURGEPACKET : LocalPacketFactory.LOGPACKET; + ValidPacket valid = new ValidPacket(lstart, lstop, type); + SocketAddress socketAddress = host.getSocketAddress(); + boolean isSSL = host.isSsl(); + + // first clean if ask + if (clean) { + // Update all UpdatedInfo to DONE + // where GlobalLastStep = ALLDONETASK and status = CompleteOk + try { + DbTaskRunner.changeFinishedToDone(DbConstant.admin.session); + } catch (WaarpDatabaseNoConnectionException e) { + logger.warn("Clean cannot be done {}", e.getMessage()); + } + } + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, isSSL, future); + socketAddress = null; + if (localChannelReference == null) { + host = null; + logger.error("Cannot Connect"); + future.setResult(new R66Result( + new OpenR66ProtocolNoConnectionException("Cannot connect to server"), + null, true, ErrorCode.Internal, null)); + future.setFailure(future.getResult().exception); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.VALIDOTHER); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, false); + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + host = null; + valid = null; + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, null)); + future.setFailure(e); + return; + } + host = null; + future.awaitUninterruptibly(); + logger.info("Request done with " + (future.isSuccess() ? "success" : "error")); + Channels.close(localChannelReference.getLocalChannel()); + localChannelReference = null; + } + + protected static boolean spurgeLog = false; + protected static Timestamp sstart = null; + protected static Timestamp sstop = null; + protected static boolean sclean = false; + + private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + + public static Timestamp fixDate(String sdate) { + Timestamp tdate = null; + String date = sdate.replaceAll("/|:|\\.| |-", ""); + if (date.length() > 0) { + if (date.length() < 15) { + int len = date.length(); + date += "000000000000000".substring(len); + } + try { + Date ddate = format.parse(date); + tdate = new Timestamp(ddate.getTime()); + } catch (ParseException e) { + logger.debug("start {}", e.getMessage()); + } + } + return tdate; + } + + public static Timestamp fixDate(String sdate, Timestamp before) { + Timestamp tdate = null; + String date = sdate.replaceAll("/|:|\\.| |-", ""); + if (date.length() > 0) { + if (date.length() < 15) { + int len = date.length(); + date += "000000000000000".substring(len); + } + try { + Date ddate = format.parse(date); + if (before != null) { + Date bef = new Date(before.getTime()); + if (bef.compareTo(ddate) >= 0) { + ddate = new Date(bef.getTime() + 1000 * 3600 * 24 - 1); + } + } + tdate = new Timestamp(ddate.getTime()); + } catch (ParseException e) { + logger.debug("start {}", e.getMessage()); + } + } + return tdate; + } + + public static Timestamp getTodayMidnight() { + GregorianCalendar calendar = new GregorianCalendar(); + calendar.set(GregorianCalendar.HOUR_OF_DAY, 0); + calendar.set(GregorianCalendar.MINUTE, 0); + calendar.set(GregorianCalendar.SECOND, 0); + calendar.set(GregorianCalendar.MILLISECOND, 0); + return new Timestamp(calendar.getTimeInMillis()); + } + + protected static boolean getParams(String[] args) { + if (args.length < 1) { + logger.error("Need at least the configuration file as first argument then optionally\n" + + + " -purge\n" + + + " -clean\n" + + + " -start timestamp in format yyyyMMddHHmmssSSS possibly truncated and where one of ':-. ' can be separators\n" + + + " -stop timestamp in same format than start\n" + + "If not start and no stop are given, stop is Today Midnight (00:00:00)\n" + + "If start is equals or greater than stop, stop is start+24H"); + return false; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger.error("Need at least the configuration file as first argument then optionally\n" + + + " -purge\n" + + + " -clean\n" + + + " -start timestamp in format yyyyMMddHHmmssSSS possibly truncated and where one of ':-. ' can be separators\n" + + + " -stop timestamp in same format than start\n" + + "If not start and no stop are given, stop is Today Midnight (00:00:00)\n" + + "If start is equals or greater than stop, stop is start+24H"); + return false; + } + String ssstart = null; + String ssstop = null; + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-purge")) { + spurgeLog = true; + } else if (args[i].equalsIgnoreCase("-clean")) { + sclean = true; + } else if (args[i].equalsIgnoreCase("-start")) { + i++; + ssstart = args[i]; + } else if (args[i].equalsIgnoreCase("-stop")) { + i++; + ssstop = args[i]; + } + } + if (ssstart != null) { + Timestamp tstart = fixDate(ssstart); + if (tstart != null) { + sstart = tstart; + } + } + if (ssstop != null) { + Timestamp tstop = fixDate(ssstop, sstart); + if (tstop != null) { + sstop = tstop; + } + } + if (ssstart == null && ssstop == null) { + sstop = getTodayMidnight(); + } + return true; + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(LogExport.class); + } + if (!getParams(args)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + LogExport transaction = new LogExport(future, + spurgeLog, sclean, sstart, sstop, + networkTransaction); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.code == ErrorCode.Warning) { + logger.warn("WARNED on file:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } else { + logger.warn("SUCCESS on Final file:\n " + + (result.other != null ? ((ValidPacket) result.other).getSheader() : + "no file") + + "\n delay: " + delay); + } + } else { + if (result.code == ErrorCode.Warning) { + logger.warn("Transfer is\n WARNED", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in\n FAILURE", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + } + +} diff --git a/src/main/java/org/waarp/openr66/server/R66Server.java b/src/main/java/org/waarp/openr66/server/R66Server.java index ca39cffbb..ed4966aaf 100644 --- a/src/main/java/org/waarp/openr66/server/R66Server.java +++ b/src/main/java/org/waarp/openr66/server/R66Server.java @@ -1,83 +1,83 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; - -/** - * R66Server startup main class - * - * @author Frederic Bregier - */ -public class R66Server { - private static WaarpInternalLogger logger; - - /** - * @param args - * as first argument the configuration file - * @throws OpenR66ProtocolPacketException - */ - public static void main(String[] args) - throws OpenR66ProtocolPacketException { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - logger = WaarpInternalLoggerFactory - .getLogger(R66Server.class); - if (args.length < 1) { - logger - .error("Needs the configuration file as first argument"); - return; - } - if (initialize(args[0])) { - logger.warn("Server OpenR66 starts for " + Configuration.configuration.HOST_ID); - System.err.println("Server OpenR66 starts for " + Configuration.configuration.HOST_ID); - } else { - logger.error("Cannot start Server OpenR66 for " + Configuration.configuration.HOST_ID); - System.err.println("Cannot start Server OpenR66 for " + Configuration.configuration.HOST_ID); - System.exit(1); - } - } - - public static boolean initialize(String config) { - if (logger == null) { - logger = WaarpInternalLoggerFactory - .getLogger(R66Server.class); - } - if (!FileBasedConfiguration - .setConfigurationServerFromXml(Configuration.configuration, config)) { - logger - .error("Needs a correct configuration file as first argument"); - return false; - } - try { - Configuration.configuration.serverStartup(); - } catch (Throwable e) { - logger - .error("Startup of server is in error", e); - R66ShutdownHook.terminate(false); - return false; - } - return true; - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; + +/** + * R66Server startup main class + * + * @author Frederic Bregier + */ +public class R66Server { + private static WaarpInternalLogger logger; + + /** + * @param args + * as first argument the configuration file + * @throws OpenR66ProtocolPacketException + */ + public static void main(String[] args) + throws OpenR66ProtocolPacketException { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + logger = WaarpInternalLoggerFactory + .getLogger(R66Server.class); + if (args.length < 1) { + logger + .error("Needs the configuration file as first argument"); + return; + } + if (initialize(args[0])) { + logger.warn("Server OpenR66 starts for " + Configuration.configuration.HOST_ID); + System.err.println("Server OpenR66 starts for " + Configuration.configuration.HOST_ID); + } else { + logger.error("Cannot start Server OpenR66 for " + Configuration.configuration.HOST_ID); + System.err.println("Cannot start Server OpenR66 for " + Configuration.configuration.HOST_ID); + System.exit(1); + } + } + + public static boolean initialize(String config) { + if (logger == null) { + logger = WaarpInternalLoggerFactory + .getLogger(R66Server.class); + } + if (!FileBasedConfiguration + .setConfigurationServerFromXml(Configuration.configuration, config)) { + logger + .error("Needs a correct configuration file as first argument"); + return false; + } + try { + Configuration.configuration.serverStartup(); + } catch (Throwable e) { + logger + .error("Startup of server is in error", e); + R66ShutdownHook.terminate(false); + return false; + } + return true; + } +} diff --git a/src/main/java/org/waarp/openr66/server/ServerExportConfiguration.java b/src/main/java/org/waarp/openr66/server/ServerExportConfiguration.java index 285c8a801..1bc56d877 100644 --- a/src/main/java/org/waarp/openr66/server/ServerExportConfiguration.java +++ b/src/main/java/org/waarp/openr66/server/ServerExportConfiguration.java @@ -1,150 +1,150 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.io.File; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.configuration.RuleFileBasedConfiguration; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Server local configuration export to files - * - * @author Frederic Bregier - * - */ -public class ServerExportConfiguration { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger; - - /** - * - * @param args - * as configuration file and the directory where to export - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ServerExportConfiguration.class); - } - if (args.length < 2) { - System.err - .println("Need configuration file and the directory where to export"); - System.exit(1); - } - try { - if (!FileBasedConfiguration - .setConfigurationServerMinimalFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - return; - } - String directory = args[1]; - String hostname = Configuration.configuration.HOST_ID; - logger.info("Start of Export"); - File dir = new File(directory); - if (!dir.isDirectory()) { - dir.mkdirs(); - } - try { - RuleFileBasedConfiguration.writeXml(directory, hostname); - } catch (WaarpDatabaseNoConnectionException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (WaarpDatabaseSqlException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (OpenR66ProtocolSystemException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } - String filename = dir.getAbsolutePath() + File.separator + hostname - + "_Runners.run.xml"; - try { - DbTaskRunner.writeXMLWriter(filename); - } catch (WaarpDatabaseNoConnectionException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (WaarpDatabaseSqlException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (OpenR66ProtocolBusinessException e1) { - logger.error("Error", e1); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } - filename = dir.getAbsolutePath() + File.separator + hostname + "_Authentications.xml"; - try { - AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, - filename); - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Error", e); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (WaarpDatabaseSqlException e) { - logger.error("Error", e); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } catch (OpenR66ProtocolSystemException e) { - logger.error("Error", e); - DbConstant.admin.close(); - ChannelUtils.stopLogger(); - System.exit(2); - } - logger.info("End of Export"); - } finally { - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.io.File; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.configuration.RuleFileBasedConfiguration; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Server local configuration export to files + * + * @author Frederic Bregier + * + */ +public class ServerExportConfiguration { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger; + + /** + * + * @param args + * as configuration file and the directory where to export + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ServerExportConfiguration.class); + } + if (args.length < 2) { + System.err + .println("Need configuration file and the directory where to export"); + System.exit(1); + } + try { + if (!FileBasedConfiguration + .setConfigurationServerMinimalFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + return; + } + String directory = args[1]; + String hostname = Configuration.configuration.HOST_ID; + logger.info("Start of Export"); + File dir = new File(directory); + if (!dir.isDirectory()) { + dir.mkdirs(); + } + try { + RuleFileBasedConfiguration.writeXml(directory, hostname); + } catch (WaarpDatabaseNoConnectionException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (WaarpDatabaseSqlException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (OpenR66ProtocolSystemException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } + String filename = dir.getAbsolutePath() + File.separator + hostname + + "_Runners.run.xml"; + try { + DbTaskRunner.writeXMLWriter(filename); + } catch (WaarpDatabaseNoConnectionException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (WaarpDatabaseSqlException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (OpenR66ProtocolBusinessException e1) { + logger.error("Error", e1); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } + filename = dir.getAbsolutePath() + File.separator + hostname + "_Authentications.xml"; + try { + AuthenticationFileBasedConfiguration.writeXML(Configuration.configuration, + filename); + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Error", e); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (WaarpDatabaseSqlException e) { + logger.error("Error", e); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } catch (OpenR66ProtocolSystemException e) { + logger.error("Error", e); + DbConstant.admin.close(); + ChannelUtils.stopLogger(); + System.exit(2); + } + logger.info("End of Export"); + } finally { + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + } + } + +} diff --git a/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java b/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java index 30270db4d..a4cad7364 100644 --- a/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java +++ b/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java @@ -1,284 +1,284 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.configuration.RuleFileBasedConfiguration; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostConfiguration; -import org.waarp.openr66.database.model.DbModelFactory; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Utility class to initiate the database for a server - * - * @author Frederic Bregier - * - */ -public class ServerInitDatabase { - /** - * Internal Logger - */ - static volatile WaarpInternalLogger logger; - - static String sxml = null; - static boolean database = false; - static String sbusiness = null; - static String salias = null; - static String sroles = null; - static String sdirconfig = null; - static String shostauth = null; - static String slimitconfig = null; - - protected static boolean getParams(String[] args) { - if (args.length < 1) { - logger.error("Need at least the configuration file as first argument then optionally\n" - + - " -initdb\n" + - " -loadBusiness xmlfile for Business configuration\n" + - " -loadAlias xmlfile for Alias configuration\n" + - " -loadRoles xmlfile for Roles configuration\n" + - " -dir directory for rules configuration\n" + - " -limit xmlfile containing limit of bandwidth\n" + - " -auth xml file containing the authentication of hosts"); - return false; - } - sxml = args[0]; - for (int i = 1; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-initdb")) { - database = true; - } else if (args[i].equalsIgnoreCase("-loadBusiness")) { - i++; - sbusiness = args[i]; - } else if (args[i].equalsIgnoreCase("-loadAlias")) { - i++; - salias = args[i]; - } else if (args[i].equalsIgnoreCase("-loadRoles")) { - i++; - sroles = args[i]; - } else if (args[i].equalsIgnoreCase("-dir")) { - i++; - sdirconfig = args[i]; - } else if (args[i].equalsIgnoreCase("-limit")) { - i++; - slimitconfig = args[i]; - } else if (args[i].equalsIgnoreCase("-auth")) { - i++; - shostauth = args[i]; - } - } - return true; - } - - /** - * @param args - * as config_database file [rules_directory host_authent limit_configuration] - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ServerInitDatabase.class); - } - if (!getParams(args)) { - logger.error("Need at least the configuration file as first argument then optionally\n" - + - " -initdb\n" + - " -loadBusiness xmlfile for Business configuration\n" + - " -loadAlias xmlfile for Alias configuration\n" + - " -loadRoles xmlfile for Roles configuration\n" + - " -dir directory for rules configuration\n" + - " -limit xmlfile containing limit of bandwidth\n" + - " -auth xml file containing the authentication of hosts"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - } - - try { - if (!FileBasedConfiguration - .setConfigurationInitDatabase(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - return; - } - if (database) { - // Init database - try { - initdb(); - } catch (WaarpDatabaseNoConnectionException e) { - logger.error("Cannot connect to database"); - return; - } - System.out.println("End creation"); - } - if (sdirconfig != null) { - // load Rules - File dirConfig = new File(sdirconfig); - if (dirConfig.isDirectory()) { - loadRules(dirConfig); - } else { - System.err.println("Dir is not a directory: " + sdirconfig); - } - } - if (shostauth != null) { - // Load Host Authentications - if (args.length > 2) { - loadHostAuth(shostauth); - } - } - if (slimitconfig != null) { - // Load configuration - if (args.length > 2) { - FileBasedConfiguration.setConfigurationLoadLimitFromXml( - Configuration.configuration, - slimitconfig); - } - } - - if (sbusiness != null || salias != null || sroles != null) { - if (sbusiness != null) { - File file = new File(sbusiness); - if (file.canRead()) { - try { - String value = FileUtils.readFileToString(file); - if (value != null && ! value.trim().isEmpty()) { - value = value.trim().replaceAll("\r|\n| ", " ").trim(); - value = value.replaceAll("\r|\n| ", " "); - sbusiness = value.trim(); - } else { - sbusiness = null; - } - } catch (IOException e) { - sbusiness = null; - e.printStackTrace(); - } - } else { - sbusiness = null; - } - } - if (salias != null) { - File file = new File(salias); - if (file.canRead()) { - try { - String value = FileUtils.readFileToString(file); - if (value != null && ! value.trim().isEmpty()) { - value = value.trim().replaceAll("\r|\t|\n| ", " ").trim(); - value = value.replaceAll("\r|\n| ", " "); - salias = value.trim(); - } else { - salias = null; - } - } catch (IOException e) { - salias = null; - e.printStackTrace(); - } - } else { - salias = null; - } - } - if (sroles != null) { - File file = new File(sroles); - if (file.canRead()) { - try { - String value = FileUtils.readFileToString(file); - if (value != null && ! value.trim().isEmpty()) { - value = value.trim().replaceAll("\r|\n| ", " ").trim(); - value = value.replaceAll("\r|\n| ", " "); - sroles = value.trim(); - } else { - sroles = null; - } - } catch (IOException e) { - sroles = null; - e.printStackTrace(); - } - } else { - sroles = null; - } - } - DbHostConfiguration hostConfiguration = null; - try { - hostConfiguration = new DbHostConfiguration(DbConstant.admin.session, Configuration.configuration.HOST_ID); - if (salias != null) { - hostConfiguration.setAliases(salias); - } - if (sbusiness != null) { - hostConfiguration.setBusiness(sbusiness); - } - if (sroles != null) { - hostConfiguration.setRoles(sroles); - } - hostConfiguration.update(); - } catch (WaarpDatabaseException e) { - hostConfiguration = new DbHostConfiguration(DbConstant.admin.session, Configuration.configuration.HOST_ID, - sbusiness, sroles, salias, null); - try { - hostConfiguration.insert(); - } catch (WaarpDatabaseException e1) { - e1.printStackTrace(); - } - } - } - System.out.println("Load done"); - } finally { - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - } - } - - public static void initdb() throws WaarpDatabaseNoConnectionException { - // Create tables: configuration, hosts, rules, runner, cptrunner - DbModelFactory.dbModel.createTables(DbConstant.admin.session); - } - - public static void loadRules(File dirConfig) { - try { - RuleFileBasedConfiguration.importRules(dirConfig); - } catch (OpenR66ProtocolSystemException e3) { - e3.printStackTrace(); - } catch (WaarpDatabaseException e) { - e.printStackTrace(); - } - } - - public static void loadHostAuth(String filename) { - AuthenticationFileBasedConfiguration.loadAuthentication(Configuration.configuration, - filename); - } -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.configuration.RuleFileBasedConfiguration; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostConfiguration; +import org.waarp.openr66.database.model.DbModelFactory; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Utility class to initiate the database for a server + * + * @author Frederic Bregier + * + */ +public class ServerInitDatabase { + /** + * Internal Logger + */ + static volatile WaarpInternalLogger logger; + + static String sxml = null; + static boolean database = false; + static String sbusiness = null; + static String salias = null; + static String sroles = null; + static String sdirconfig = null; + static String shostauth = null; + static String slimitconfig = null; + + protected static boolean getParams(String[] args) { + if (args.length < 1) { + logger.error("Need at least the configuration file as first argument then optionally\n" + + + " -initdb\n" + + " -loadBusiness xmlfile for Business configuration\n" + + " -loadAlias xmlfile for Alias configuration\n" + + " -loadRoles xmlfile for Roles configuration\n" + + " -dir directory for rules configuration\n" + + " -limit xmlfile containing limit of bandwidth\n" + + " -auth xml file containing the authentication of hosts"); + return false; + } + sxml = args[0]; + for (int i = 1; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-initdb")) { + database = true; + } else if (args[i].equalsIgnoreCase("-loadBusiness")) { + i++; + sbusiness = args[i]; + } else if (args[i].equalsIgnoreCase("-loadAlias")) { + i++; + salias = args[i]; + } else if (args[i].equalsIgnoreCase("-loadRoles")) { + i++; + sroles = args[i]; + } else if (args[i].equalsIgnoreCase("-dir")) { + i++; + sdirconfig = args[i]; + } else if (args[i].equalsIgnoreCase("-limit")) { + i++; + slimitconfig = args[i]; + } else if (args[i].equalsIgnoreCase("-auth")) { + i++; + shostauth = args[i]; + } + } + return true; + } + + /** + * @param args + * as config_database file [rules_directory host_authent limit_configuration] + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ServerInitDatabase.class); + } + if (!getParams(args)) { + logger.error("Need at least the configuration file as first argument then optionally\n" + + + " -initdb\n" + + " -loadBusiness xmlfile for Business configuration\n" + + " -loadAlias xmlfile for Alias configuration\n" + + " -loadRoles xmlfile for Roles configuration\n" + + " -dir directory for rules configuration\n" + + " -limit xmlfile containing limit of bandwidth\n" + + " -auth xml file containing the authentication of hosts"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + } + + try { + if (!FileBasedConfiguration + .setConfigurationInitDatabase(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + return; + } + if (database) { + // Init database + try { + initdb(); + } catch (WaarpDatabaseNoConnectionException e) { + logger.error("Cannot connect to database"); + return; + } + System.out.println("End creation"); + } + if (sdirconfig != null) { + // load Rules + File dirConfig = new File(sdirconfig); + if (dirConfig.isDirectory()) { + loadRules(dirConfig); + } else { + System.err.println("Dir is not a directory: " + sdirconfig); + } + } + if (shostauth != null) { + // Load Host Authentications + if (args.length > 2) { + loadHostAuth(shostauth); + } + } + if (slimitconfig != null) { + // Load configuration + if (args.length > 2) { + FileBasedConfiguration.setConfigurationLoadLimitFromXml( + Configuration.configuration, + slimitconfig); + } + } + + if (sbusiness != null || salias != null || sroles != null) { + if (sbusiness != null) { + File file = new File(sbusiness); + if (file.canRead()) { + try { + String value = FileUtils.readFileToString(file); + if (value != null && ! value.trim().isEmpty()) { + value = value.trim().replaceAll("\r|\n| ", " ").trim(); + value = value.replaceAll("\r|\n| ", " "); + sbusiness = value.trim(); + } else { + sbusiness = null; + } + } catch (IOException e) { + sbusiness = null; + e.printStackTrace(); + } + } else { + sbusiness = null; + } + } + if (salias != null) { + File file = new File(salias); + if (file.canRead()) { + try { + String value = FileUtils.readFileToString(file); + if (value != null && ! value.trim().isEmpty()) { + value = value.trim().replaceAll("\r|\t|\n| ", " ").trim(); + value = value.replaceAll("\r|\n| ", " "); + salias = value.trim(); + } else { + salias = null; + } + } catch (IOException e) { + salias = null; + e.printStackTrace(); + } + } else { + salias = null; + } + } + if (sroles != null) { + File file = new File(sroles); + if (file.canRead()) { + try { + String value = FileUtils.readFileToString(file); + if (value != null && ! value.trim().isEmpty()) { + value = value.trim().replaceAll("\r|\n| ", " ").trim(); + value = value.replaceAll("\r|\n| ", " "); + sroles = value.trim(); + } else { + sroles = null; + } + } catch (IOException e) { + sroles = null; + e.printStackTrace(); + } + } else { + sroles = null; + } + } + DbHostConfiguration hostConfiguration = null; + try { + hostConfiguration = new DbHostConfiguration(DbConstant.admin.session, Configuration.configuration.HOST_ID); + if (salias != null) { + hostConfiguration.setAliases(salias); + } + if (sbusiness != null) { + hostConfiguration.setBusiness(sbusiness); + } + if (sroles != null) { + hostConfiguration.setRoles(sroles); + } + hostConfiguration.update(); + } catch (WaarpDatabaseException e) { + hostConfiguration = new DbHostConfiguration(DbConstant.admin.session, Configuration.configuration.HOST_ID, + sbusiness, sroles, salias, null); + try { + hostConfiguration.insert(); + } catch (WaarpDatabaseException e1) { + e1.printStackTrace(); + } + } + } + System.out.println("Load done"); + } finally { + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + } + } + + public static void initdb() throws WaarpDatabaseNoConnectionException { + // Create tables: configuration, hosts, rules, runner, cptrunner + DbModelFactory.dbModel.createTables(DbConstant.admin.session); + } + + public static void loadRules(File dirConfig) { + try { + RuleFileBasedConfiguration.importRules(dirConfig); + } catch (OpenR66ProtocolSystemException e3) { + e3.printStackTrace(); + } catch (WaarpDatabaseException e) { + e.printStackTrace(); + } + } + + public static void loadHostAuth(String filename) { + AuthenticationFileBasedConfiguration.loadAuthentication(Configuration.configuration, + filename); + } +} diff --git a/src/main/java/org/waarp/openr66/server/ServerShutdown.java b/src/main/java/org/waarp/openr66/server/ServerShutdown.java index 16f5fedc4..2462e9427 100644 --- a/src/main/java/org/waarp/openr66/server/ServerShutdown.java +++ b/src/main/java/org/waarp/openr66/server/ServerShutdown.java @@ -1,135 +1,135 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.server; - -import java.net.SocketAddress; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.digest.FilesystemBasedDigest; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; -import org.waarp.openr66.protocol.localhandler.packet.ShutdownPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; - -/** - * Local client to shutdown the server (using network) - * - * @author Frederic Bregier - */ -public class ServerShutdown { - - /** - * @param args - * the configuration file as first argument - * @throws OpenR66ProtocolPacketException - */ - public static void main(String[] args) - throws OpenR66ProtocolPacketException { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(ServerShutdown.class); - if (args.length < 1) { - logger - .error("Needs the configuration file as first argument and optionally [-nossl]"); - ChannelUtils.stopLogger(); - System.exit(1); - return; - } - if (!FileBasedConfiguration - .setConfigurationServerShutdownFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument and optionally [-nossl]"); - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - return; - } - boolean useSsl = true; - if (args.length > 1) { - if (args[1].equalsIgnoreCase("-nossl")) { - useSsl = false; - } - } - DbHostAuth host = null; - if (useSsl) { - host = Configuration.configuration.HOST_SSLAUTH; - } else { - host = Configuration.configuration.HOST_AUTH; - } - if (host == null) { - logger.error("Host id not found while SSL mode is : "+useSsl); - if (DbConstant.admin != null) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(1); - return; - } - Configuration.configuration.pipelineInit(); - byte[] key; - key = FilesystemBasedDigest.passwdCrypt(Configuration.configuration.getSERVERADMINKEY()); - final ShutdownPacket packet = new ShutdownPacket( - key); - final NetworkTransaction networkTransaction = new NetworkTransaction(); - final SocketAddress socketServerAddress = host.getSocketAddress(); - LocalChannelReference localChannelReference = null; - localChannelReference = networkTransaction - .createConnectionWithRetry(socketServerAddress, useSsl, null); - if (localChannelReference == null) { - logger.error("Cannot connect to " + host.getSocketAddress()); - networkTransaction.closeAll(); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.SHUTDOWN); - ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); - localChannelReference.getFutureRequest().awaitUninterruptibly(); - if (localChannelReference.getFutureRequest().isSuccess()) { - logger.warn("Shutdown OK"); - } else { - R66Result result = localChannelReference.getFutureRequest() - .getResult(); - if (result.other instanceof ValidPacket - && - ((ValidPacket) result.other).getTypeValid() == LocalPacketFactory.SHUTDOWNPACKET) { - logger.warn("Shutdown command OK"); - } else if (result.code == ErrorCode.Shutdown) { - logger.warn("Shutdown command done"); - } else { - logger.error("Cannot Shutdown: " + result.toString(), localChannelReference - .getFutureRequest().getCause()); - } - } - networkTransaction.closeAll(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.server; + +import java.net.SocketAddress; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.ShutdownPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; + +/** + * Local client to shutdown the server (using network) + * + * @author Frederic Bregier + */ +public class ServerShutdown { + + /** + * @param args + * the configuration file as first argument + * @throws OpenR66ProtocolPacketException + */ + public static void main(String[] args) + throws OpenR66ProtocolPacketException { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(ServerShutdown.class); + if (args.length < 1) { + logger + .error("Needs the configuration file as first argument and optionally [-nossl]"); + ChannelUtils.stopLogger(); + System.exit(1); + return; + } + if (!FileBasedConfiguration + .setConfigurationServerShutdownFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument and optionally [-nossl]"); + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + return; + } + boolean useSsl = true; + if (args.length > 1) { + if (args[1].equalsIgnoreCase("-nossl")) { + useSsl = false; + } + } + DbHostAuth host = null; + if (useSsl) { + host = Configuration.configuration.HOST_SSLAUTH; + } else { + host = Configuration.configuration.HOST_AUTH; + } + if (host == null) { + logger.error("Host id not found while SSL mode is : "+useSsl); + if (DbConstant.admin != null) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(1); + return; + } + Configuration.configuration.pipelineInit(); + byte[] key; + key = FilesystemBasedDigest.passwdCrypt(Configuration.configuration.getSERVERADMINKEY()); + final ShutdownPacket packet = new ShutdownPacket( + key); + final NetworkTransaction networkTransaction = new NetworkTransaction(); + final SocketAddress socketServerAddress = host.getSocketAddress(); + LocalChannelReference localChannelReference = null; + localChannelReference = networkTransaction + .createConnectionWithRetry(socketServerAddress, useSsl, null); + if (localChannelReference == null) { + logger.error("Cannot connect to " + host.getSocketAddress()); + networkTransaction.closeAll(); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.SHUTDOWN); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, false); + localChannelReference.getFutureRequest().awaitUninterruptibly(); + if (localChannelReference.getFutureRequest().isSuccess()) { + logger.warn("Shutdown OK"); + } else { + R66Result result = localChannelReference.getFutureRequest() + .getResult(); + if (result.other instanceof ValidPacket + && + ((ValidPacket) result.other).getTypeValid() == LocalPacketFactory.SHUTDOWNPACKET) { + logger.warn("Shutdown command OK"); + } else if (result.code == ErrorCode.Shutdown) { + logger.warn("Shutdown command done"); + } else { + logger.error("Cannot Shutdown: " + result.toString(), localChannelReference + .getFutureRequest().getCause()); + } + } + networkTransaction.closeAll(); + } + +} diff --git a/src/main/java/org/waarp/openr66/server/package-info.java b/src/main/java/org/waarp/openr66/server/package-info.java index d167e5290..1940c7e5a 100644 --- a/src/main/java/org/waarp/openr66/server/package-info.java +++ b/src/main/java/org/waarp/openr66/server/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Server startup main class or utility classes - * - * @apiviz.landmark - */ -package org.waarp.openr66.server; - +/** + * Classes implementing Server startup main class or utility classes + * + * @apiviz.landmark + */ +package org.waarp.openr66.server; + diff --git a/src/main/java/org/waarp/openr66/service/R66Engine.java b/src/main/java/org/waarp/openr66/service/R66Engine.java index e674871ee..b26fa2926 100644 --- a/src/main/java/org/waarp/openr66/service/R66Engine.java +++ b/src/main/java/org/waarp/openr66/service/R66Engine.java @@ -1,88 +1,88 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project 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. - - Waarp 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 Waarp . If not, see . - */ -package org.waarp.openr66.service; - -import org.waarp.common.future.WaarpFuture; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.service.EngineAbstract; -import org.waarp.common.utility.SystemPropertyUtil; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.utils.R66ShutdownHook; -import org.waarp.openr66.server.R66Server; - -/** - * Engine used to start and stop the real R66 service - * @author Frederic Bregier - * - */ -public class R66Engine extends EngineAbstract { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66Engine.class); - - public static WaarpFuture closeFuture = new WaarpFuture(true); - - public static final String CONFIGFILE = "org.waarp.r66.config.file"; - - @Override - public void run() { - String config = SystemPropertyUtil.get(CONFIGFILE); - if (config == null) { - logger.error("Cannot find "+CONFIGFILE+" parameter"); - closeFuture.cancel(); - shutdown(); - return; - } - Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture; - try { - if (! R66Server.initialize(config)) { - throw new Exception("Initialization in error"); - } - } catch (Throwable e) { - logger.error("Cannot start R66", e); - closeFuture.cancel(); - shutdown(); - return; - } - logger.warn("Service started with "+config); - } - - @Override - public void shutdown() { - R66ShutdownHook.terminate(false); - closeFuture.setSuccess(); - logger.info("Service stopped"); - } - - @Override - public boolean isShutdown() { - return closeFuture.isDone(); - } - - @Override - public boolean waitShutdown() throws InterruptedException { - closeFuture.await(); - return closeFuture.isSuccess(); - } -} +/** + This file is part of Waarp Project. + + Copyright 2009, Frederic Bregier, and individual contributors by the @author + tags. See the COPYRIGHT.txt in the distribution for a full listing of + individual contributors. + + All Waarp Project 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. + + Waarp 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 Waarp . If not, see . + */ +package org.waarp.openr66.service; + +import org.waarp.common.future.WaarpFuture; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.service.EngineAbstract; +import org.waarp.common.utility.SystemPropertyUtil; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.utils.R66ShutdownHook; +import org.waarp.openr66.server.R66Server; + +/** + * Engine used to start and stop the real R66 service + * @author Frederic Bregier + * + */ +public class R66Engine extends EngineAbstract { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66Engine.class); + + public static WaarpFuture closeFuture = new WaarpFuture(true); + + public static final String CONFIGFILE = "org.waarp.r66.config.file"; + + @Override + public void run() { + String config = SystemPropertyUtil.get(CONFIGFILE); + if (config == null) { + logger.error("Cannot find "+CONFIGFILE+" parameter"); + closeFuture.cancel(); + shutdown(); + return; + } + Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture; + try { + if (! R66Server.initialize(config)) { + throw new Exception("Initialization in error"); + } + } catch (Throwable e) { + logger.error("Cannot start R66", e); + closeFuture.cancel(); + shutdown(); + return; + } + logger.warn("Service started with "+config); + } + + @Override + public void shutdown() { + R66ShutdownHook.terminate(false); + closeFuture.setSuccess(); + logger.info("Service stopped"); + } + + @Override + public boolean isShutdown() { + return closeFuture.isDone(); + } + + @Override + public boolean waitShutdown() throws InterruptedException { + closeFuture.await(); + return closeFuture.isSuccess(); + } +} diff --git a/src/main/java/org/waarp/openr66/service/R66ServiceLauncher.java b/src/main/java/org/waarp/openr66/service/R66ServiceLauncher.java index a253e5dd1..ee03c85fb 100644 --- a/src/main/java/org/waarp/openr66/service/R66ServiceLauncher.java +++ b/src/main/java/org/waarp/openr66/service/R66ServiceLauncher.java @@ -1,56 +1,56 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project 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. - - Waarp 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 Waarp . If not, see . - */ -package org.waarp.openr66.service; - -import org.waarp.common.service.EngineAbstract; -import org.waarp.common.service.ServiceLauncher; - -/** - * @author Frederic Bregier - * - */ -public class R66ServiceLauncher extends ServiceLauncher { - - public static void main(String[] args) { - _main(args); - } - public static void windowsService(String args[]) throws Exception { - _windowsService(args); - } - public static void windowsStart(String args[]) throws Exception { - _windowsStart(args); - } - public static void windowsStop(String args[]) { - _windowsStop(args); - } - /** - * - */ - public R66ServiceLauncher() { - super(); - } - - @Override - protected EngineAbstract getNewEngineAbstract() { - return new R66Engine(); - } - -} +/** + This file is part of Waarp Project. + + Copyright 2009, Frederic Bregier, and individual contributors by the @author + tags. See the COPYRIGHT.txt in the distribution for a full listing of + individual contributors. + + All Waarp Project 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. + + Waarp 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 Waarp . If not, see . + */ +package org.waarp.openr66.service; + +import org.waarp.common.service.EngineAbstract; +import org.waarp.common.service.ServiceLauncher; + +/** + * @author Frederic Bregier + * + */ +public class R66ServiceLauncher extends ServiceLauncher { + + public static void main(String[] args) { + _main(args); + } + public static void windowsService(String args[]) throws Exception { + _windowsService(args); + } + public static void windowsStart(String args[]) throws Exception { + _windowsStart(args); + } + public static void windowsStop(String args[]) { + _windowsStop(args); + } + /** + * + */ + public R66ServiceLauncher() { + super(); + } + + @Override + protected EngineAbstract getNewEngineAbstract() { + return new R66Engine(); + } + +} diff --git a/src/main/java/org/waarp/openr66/service/package-info.java b/src/main/java/org/waarp/openr66/service/package-info.java index ce668b5ab..d40d6bf7c 100644 --- a/src/main/java/org/waarp/openr66/service/package-info.java +++ b/src/main/java/org/waarp/openr66/service/package-info.java @@ -1,23 +1,23 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -/** - * Interface for Apache Daemon tool to run as a Service - * @author Frederic Bregier - * - */ +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +/** + * Interface for Apache Daemon tool to run as a Service + * @author Frederic Bregier + * + */ package org.waarp.openr66.service; \ No newline at end of file diff --git a/src/main/java/org/waarp/openr66/service/service.bat b/src/main/java/org/waarp/openr66/service/service.bat index 638b710a3..8f80b2df1 100644 --- a/src/main/java/org/waarp/openr66/service/service.bat +++ b/src/main/java/org/waarp/openr66/service/service.bat @@ -1,135 +1,135 @@ -@echo off - -rem -- DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) - -rem -- Organization: -rem -- EXEC_PATH is root (pid will be there) -rem -- EXEC_PATH\..\logs\ will be the log place -rem -- EXEC_PATH\windows\ is where prunsrv.exe is placed -rem -- DAEMON_ROOT is where all you jars are (even commons-daemon) -rem -- DAEMON_NAME will be the service name -rem -- SERVICE_DESCRIPTION will be the service description -rem -- MAIN_DAEMON_CLASS will be the start/stop class used - -rem -- Root path where the executables are -set EXEC_PATH=C:\Waarp\Run - -rem -- Change this by the path where all jars are -set DAEMON_ROOT=C:\Waarp\Classpath - -rem -- Service description -set SERVICE_DESCRIPTION="Waarp R66 Server" - -rem -- Service name -set SERVICE_NAME=WaarpR66 - -rem -- Service CLASSPATH -set SERVICE_CLASSPATH=%DAEMON_ROOT%\commons-codec-1.6.jar;%DAEMON_ROOT%\commons-compress-1.4.1.jar;%DAEMON_ROOT%\commons-exec-1.1.jar;%DAEMON_ROOT%\commons-io-2.4.jar;%DAEMON_ROOT%\dom4j-1.6.1.jar;%DAEMON_ROOT%\h2-1.3.167.jar;%DAEMON_ROOT%\javasysmon-0.3.3.jar;%DAEMON_ROOT%\jaxen-1.1.3.jar;%DAEMON_ROOT%\log4j-1.2.14.jar;%DAEMON_ROOT%\logback-access-1.0.6.jar;%DAEMON_ROOT%\logback-classic-1.0.6.jar;%DAEMON_ROOT%\logback-core-1.0.6.jar;%DAEMON_ROOT%\netty-3.5.5.Final.jar;%DAEMON_ROOT%\slf4j-api-1.6.6.jar;%DAEMON_ROOT%\snmp4j-2.1.0.jar;%DAEMON_ROOT%\snmp4j-agent-2.0.6.jar;%DAEMON_ROOT%\WaarpCommon-1.2.6.jar;%DAEMON_ROOT%\WaarpDigest-1.1.5.jar;%DAEMON_ROOT%\WaarpExec-1.1.3.jar;%DAEMON_ROOT%\WaarpPassword-1.1.1.jar;%DAEMON_ROOT%\WaarpR66-2.4.7-beta.jar;%DAEMON_ROOT%\WaarpR66Gui-2.1.2.jar;%DAEMON_ROOT%\WaarpSnmp-1.1.1.jar;%DAEMON_ROOT%\WaarpThrift-1.0.0.jar;%DAEMON_ROOT%\WaarpXmlEditor-1.0.0.jar;%DAEMON_ROOT%\xercesImpl.jar;%DAEMON_ROOT%\xml-apis.jar;%DAEMON_ROOT%\xmleditor.jar;%DAEMON_ROOT%\commons-daemon-1.0.10.jar;%DAEMON_ROOT%\libthrift-0.8.0.jar - -rem -- Service main class -set MAIN_SERVICE_CLASS=org.waarp.openr66.service.R66ServiceLauncher - -rem -- Path for log files -set LOG_PATH=%EXEC_PATH%\..\logs - -rem -- STDERR log file: IMPORTANT SINCE LOG will be there according to logback.xml -set ERR_LOG_FILE=%LOG_PATH%\stderr.txt - -rem -- STDOUT log file: IMPORTANT SINCE LOG will be there according to logback.xml -set OUT_LOG_FILE=%LOG_PATH%\stdout.txt - -rem -- Startup mode (manual or auto) -set SERVICE_STARTUP=auto - -rem -- JVM option (auto or full path to jvm.dll, if possible pointing to server version) -rem example: set JVMMODE=--JVM=C:\Java\jdk1.7.0_05\jre\bin\server\jvm.dll -set JVMMODE=--Jvm=auto - -rem -- Java memory options -set JAVAxMS=64m -set JAVAxMX=512m - -rem -- Logback configuration file: ATTENTION recommendation is to configure output to STDOUT or STDERR -set LOGBACK_CONF=%EXEC_PATH%\..\conf\logback.xml - -rem -- R66 configuration file -set R66_CONF=%EXEC_PATH%\..\conf\config-serverA2-2.xml - -rem -- prunsrv.exe location -set PRUNSRVEXEC=%EXEC_PATH%\windows\prunsrv.exe - -rem -- Loglevel of Daemon between debug, info, warn, error -set LOGLEVEL=info - -rem --------------------------------------------------------------------------- -rem -- Various Java options -set JAVA_OPTS=%JVMMODE% --JvmMs=%JAVAxMS% --JvmMx=%JAVAxMX% ++JvmOptions=-Dlogback.configurationFile=%LOGBACK_CONF% ++JvmOptions=-Dorg.waarp.r66.config.file=%R66_CONF% - -set SERVICE_OPTIONS=%JAVA_OPTS% --Description=%SERVICE_DESCRIPTION% --Classpath=%SERVICE_CLASSPATH% --StartMode=jvm --StartClass=%MAIN_SERVICE_CLASS% --StartMethod=windowsStart --StopMode=jvm --StopClass=%MAIN_SERVICE_CLASS% --StopMethod=windowsStop --LogPath=%LOG_PATH% --StdOutput=%OUT_LOG_FILE% --StdError=%ERR_LOG_FILE% --Startup=%SERVICE_STARTUP% --PidFile=service.pid --LogLevel=%LOGLEVEL% - -set RESTART=0 - -:GETOPTS -if /I "%1" == "start" ( goto START ) -if /I "%1" == "stop" ( goto STOP ) -if /I "%1" == "console" ( goto CONSOLE ) -if /I "%1" == "restart" ( goto RESTART ) -if /I "%1" == "install" ( goto INSTALL ) -if /I "%1" == "remove" ( goto REMOVE ) - -goto HELP - -rem -- START ------------------------------------------------------------------ -:START - -echo Start service %SERVICE_NAME% -%PRUNSRVEXEC% //RS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- INSTALL ---------------------------------------------------------------- -:INSTALL - -echo Install service %SERVICE_NAME% -%PRUNSRVEXEC% //IS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- STOP ------------------------------------------------------------------- -:STOP - -echo Stop service %SERVICE_NAME% -%PRUNSRVEXEC% //SS/%SERVICE_NAME% %SERVICE_OPTIONS% - -if "%RESTART%" == "1" ( goto START ) -goto FIN - -rem -- REMOVE ----------------------------------------------------------------- -:REMOVE - -echo Remove service %SERVICE_NAME% -%PRUNSRVEXEC% //DS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- CONSOLE ---------------------------------------------------------------- -:CONSOLE - -%PRUNSRVEXEC% //TS/%SERVICE_NAME% %SERVICE_OPTIONS% - -goto FIN - -rem -- RESTART ---------------------------------------------------------------- -:RESTART - -set RESTART=1 - -goto STOP - -rem -- HELP ------------------------------------------------------------------- -:HELP - -echo "service.bat install|remove|start|stop|restart" -goto FIN - -:FIN +@echo off + +rem -- DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) + +rem -- Organization: +rem -- EXEC_PATH is root (pid will be there) +rem -- EXEC_PATH\..\logs\ will be the log place +rem -- EXEC_PATH\windows\ is where prunsrv.exe is placed +rem -- DAEMON_ROOT is where all you jars are (even commons-daemon) +rem -- DAEMON_NAME will be the service name +rem -- SERVICE_DESCRIPTION will be the service description +rem -- MAIN_DAEMON_CLASS will be the start/stop class used + +rem -- Root path where the executables are +set EXEC_PATH=C:\Waarp\Run + +rem -- Change this by the path where all jars are +set DAEMON_ROOT=C:\Waarp\Classpath + +rem -- Service description +set SERVICE_DESCRIPTION="Waarp R66 Server" + +rem -- Service name +set SERVICE_NAME=WaarpR66 + +rem -- Service CLASSPATH +set SERVICE_CLASSPATH=%DAEMON_ROOT%\commons-codec-1.6.jar;%DAEMON_ROOT%\commons-compress-1.4.1.jar;%DAEMON_ROOT%\commons-exec-1.1.jar;%DAEMON_ROOT%\commons-io-2.4.jar;%DAEMON_ROOT%\dom4j-1.6.1.jar;%DAEMON_ROOT%\h2-1.3.167.jar;%DAEMON_ROOT%\javasysmon-0.3.3.jar;%DAEMON_ROOT%\jaxen-1.1.3.jar;%DAEMON_ROOT%\log4j-1.2.14.jar;%DAEMON_ROOT%\logback-access-1.0.6.jar;%DAEMON_ROOT%\logback-classic-1.0.6.jar;%DAEMON_ROOT%\logback-core-1.0.6.jar;%DAEMON_ROOT%\netty-3.5.5.Final.jar;%DAEMON_ROOT%\slf4j-api-1.6.6.jar;%DAEMON_ROOT%\snmp4j-2.1.0.jar;%DAEMON_ROOT%\snmp4j-agent-2.0.6.jar;%DAEMON_ROOT%\WaarpCommon-1.2.6.jar;%DAEMON_ROOT%\WaarpDigest-1.1.5.jar;%DAEMON_ROOT%\WaarpExec-1.1.3.jar;%DAEMON_ROOT%\WaarpPassword-1.1.1.jar;%DAEMON_ROOT%\WaarpR66-2.4.7-beta.jar;%DAEMON_ROOT%\WaarpR66Gui-2.1.2.jar;%DAEMON_ROOT%\WaarpSnmp-1.1.1.jar;%DAEMON_ROOT%\WaarpThrift-1.0.0.jar;%DAEMON_ROOT%\WaarpXmlEditor-1.0.0.jar;%DAEMON_ROOT%\xercesImpl.jar;%DAEMON_ROOT%\xml-apis.jar;%DAEMON_ROOT%\xmleditor.jar;%DAEMON_ROOT%\commons-daemon-1.0.10.jar;%DAEMON_ROOT%\libthrift-0.8.0.jar + +rem -- Service main class +set MAIN_SERVICE_CLASS=org.waarp.openr66.service.R66ServiceLauncher + +rem -- Path for log files +set LOG_PATH=%EXEC_PATH%\..\logs + +rem -- STDERR log file: IMPORTANT SINCE LOG will be there according to logback.xml +set ERR_LOG_FILE=%LOG_PATH%\stderr.txt + +rem -- STDOUT log file: IMPORTANT SINCE LOG will be there according to logback.xml +set OUT_LOG_FILE=%LOG_PATH%\stdout.txt + +rem -- Startup mode (manual or auto) +set SERVICE_STARTUP=auto + +rem -- JVM option (auto or full path to jvm.dll, if possible pointing to server version) +rem example: set JVMMODE=--JVM=C:\Java\jdk1.7.0_05\jre\bin\server\jvm.dll +set JVMMODE=--Jvm=auto + +rem -- Java memory options +set JAVAxMS=64m +set JAVAxMX=512m + +rem -- Logback configuration file: ATTENTION recommendation is to configure output to STDOUT or STDERR +set LOGBACK_CONF=%EXEC_PATH%\..\conf\logback.xml + +rem -- R66 configuration file +set R66_CONF=%EXEC_PATH%\..\conf\config-serverA2-2.xml + +rem -- prunsrv.exe location +set PRUNSRVEXEC=%EXEC_PATH%\windows\prunsrv.exe + +rem -- Loglevel of Daemon between debug, info, warn, error +set LOGLEVEL=info + +rem --------------------------------------------------------------------------- +rem -- Various Java options +set JAVA_OPTS=%JVMMODE% --JvmMs=%JAVAxMS% --JvmMx=%JAVAxMX% ++JvmOptions=-Dlogback.configurationFile=%LOGBACK_CONF% ++JvmOptions=-Dorg.waarp.r66.config.file=%R66_CONF% + +set SERVICE_OPTIONS=%JAVA_OPTS% --Description=%SERVICE_DESCRIPTION% --Classpath=%SERVICE_CLASSPATH% --StartMode=jvm --StartClass=%MAIN_SERVICE_CLASS% --StartMethod=windowsStart --StopMode=jvm --StopClass=%MAIN_SERVICE_CLASS% --StopMethod=windowsStop --LogPath=%LOG_PATH% --StdOutput=%OUT_LOG_FILE% --StdError=%ERR_LOG_FILE% --Startup=%SERVICE_STARTUP% --PidFile=service.pid --LogLevel=%LOGLEVEL% + +set RESTART=0 + +:GETOPTS +if /I "%1" == "start" ( goto START ) +if /I "%1" == "stop" ( goto STOP ) +if /I "%1" == "console" ( goto CONSOLE ) +if /I "%1" == "restart" ( goto RESTART ) +if /I "%1" == "install" ( goto INSTALL ) +if /I "%1" == "remove" ( goto REMOVE ) + +goto HELP + +rem -- START ------------------------------------------------------------------ +:START + +echo Start service %SERVICE_NAME% +%PRUNSRVEXEC% //RS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- INSTALL ---------------------------------------------------------------- +:INSTALL + +echo Install service %SERVICE_NAME% +%PRUNSRVEXEC% //IS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- STOP ------------------------------------------------------------------- +:STOP + +echo Stop service %SERVICE_NAME% +%PRUNSRVEXEC% //SS/%SERVICE_NAME% %SERVICE_OPTIONS% + +if "%RESTART%" == "1" ( goto START ) +goto FIN + +rem -- REMOVE ----------------------------------------------------------------- +:REMOVE + +echo Remove service %SERVICE_NAME% +%PRUNSRVEXEC% //DS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- CONSOLE ---------------------------------------------------------------- +:CONSOLE + +%PRUNSRVEXEC% //TS/%SERVICE_NAME% %SERVICE_OPTIONS% + +goto FIN + +rem -- RESTART ---------------------------------------------------------------- +:RESTART + +set RESTART=1 + +goto STOP + +rem -- HELP ------------------------------------------------------------------- +:HELP + +echo "service.bat install|remove|start|stop|restart" +goto FIN + +:FIN diff --git a/src/main/java/org/waarp/openr66/service/service.sh b/src/main/java/org/waarp/openr66/service/service.sh index 29e3b1a59..07f908c6b 100644 --- a/src/main/java/org/waarp/openr66/service/service.sh +++ b/src/main/java/org/waarp/openr66/service/service.sh @@ -1,117 +1,117 @@ -#!/bin/bash - -# DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) - -# Organization: -# EXEC_PATH is root (pid will be there) -# EXEC_PATH/../logs/ will be the log place -# EXEC_PATH/../bin/ is where jsvc is placed -# DAEMON_ROOT is where all you jars are (even commons-daemon) -# DAEMON_NAME will be the service name -# MAIN_DAEMON_CLASS will be the start/stop class used - -# Change this to adapt the path where the pid should be -export EXEC_PATH=/waarp/run -# could be also `dirname $0` - -# Change this by the path where all jars are -export DAEMON_ROOT=/waarp/classpath - -# Change this by the name of your daemon -export DAEMON_NAME="WaarpDaemon" - -# Change this to match your classpath -export DAEMON_CLASSPATH=${DAEMON_ROOT}/commons-daemon-1.0.10.jar:%DAEMON_ROOT%\commons-codec-1.6.jar:%DAEMON_ROOT%\commons-compress-1.4.1.jar:%DAEMON_ROOT%\commons-exec-1.1.jar:%DAEMON_ROOT%\commons-io-2.4.jar:%DAEMON_ROOT%\dom4j-1.6.1.jar:%DAEMON_ROOT%\h2-1.3.167.jar:%DAEMON_ROOT%\javasysmon-0.3.3.jar:%DAEMON_ROOT%\jaxen-1.1.3.jar:%DAEMON_ROOT%\log4j-1.2.14.jar:%DAEMON_ROOT%\logback-access-1.0.6.jar:%DAEMON_ROOT%\logback-classic-1.0.6.jar:%DAEMON_ROOT%\logback-core-1.0.6.jar:%DAEMON_ROOT%\netty-3.5.5.Final.jar:%DAEMON_ROOT%\slf4j-api-1.6.6.jar:%DAEMON_ROOT%\snmp4j-2.1.0.jar:%DAEMON_ROOT%\snmp4j-agent-2.0.6.jar:%DAEMON_ROOT%\WaarpCommon-1.2.6.jar:%DAEMON_ROOT%\WaarpDigest-1.1.5.jar:%DAEMON_ROOT%\WaarpExec-1.1.3.jar:%DAEMON_ROOT%\WaarpPassword-1.1.1.jar:%DAEMON_ROOT%\WaarpR66-2.4.7-beta.jar:%DAEMON_ROOT%\WaarpR66Gui-2.1.2.jar:%DAEMON_ROOT%\WaarpSnmp-1.1.1.jar:%DAEMON_ROOT%\WaarpThrift-1.0.0.jar:%DAEMON_ROOT%\WaarpXmlEditor-1.0.0.jar:%DAEMON_ROOT%\xercesImpl.jar:%DAEMON_ROOT%\xml-apis.jar:%DAEMON_ROOT%\xmleditor.jar:%DAEMON_ROOT%\libthrift-0.8.0.jar - -# Change this to specify the PID file path and name -export PID_FILE=${EXEC_PATH}/service.pid - -# Change this to match you Daemon class -export MAIN_DAEMON_CLASS=org.waarp.xxx.service.ServiceLauncher - -# Change this to specify the stdout file -export STDOUT_FILE=${EXEC_PATH}/../logs/stdout.txt - -# Change this to specify the stderr file -export STDERR_FILE=${EXEC_PATH}/../logs/stderr.txt - -# Java memory options -export JAVAxMS=-Xms64m -export JAVAxMX=-Xmx512m - -# JVM server option -export JAVASERVER=-jvm=server -#export JAVASERVER=-jvm=client - -# Logback configuration file -export LOGBACK_CONF=-Dlogback.configurationFile=/waarp/conf/logback.xml - -# Add -debug if you want to run in debug mode -export JSVC_OPTIONS=${JAVAxMS} ${JAVAxMX} ${JAVASERVER} ${LOGBACK_CONF} - -# ----------------------------------------------------------------------------- - -export OS_TYPE=`uname` -if [ "x${OS_TYPE}" == "xDarwin" ]; then - export EXEC="arch -arch i386 "${EXEC_PATH}"/jsvc" -else - export EXEC=${EXEC_PATH}"/jsvc" -fi - -running() { - if [ -f ${PID_FILE} ]; then - echo ${DAEMON_NAME}" already running." - exit 0 - fi -} - -start() { - running - ${EXEC} \ - -cp ${DAEMON_CLASSPATH} \ - -outfile ${STDOUT_FILE} \ - -errfile ${STDERR_FILE} \ - -pidfile ${PID_FILE} \ - ${JSVC_OPTIONS} \ - ${MAIN_DAEMON_CLASS} -} - -stop() { - ${EXEC} \ - -cp ${DAEMON_CLASSPATH} \ - -outfile ${STDOUT_FILE} \ - -errfile ${STDERR_FILE} \ - -pidfile ${PID_FILE} \ - ${JSVC_OPTIONS} \ - -stop \ - ${MAIN_DAEMON_CLASS} -} - -case "$1" in - 'start') - echo "Starting "${DAEMON_NAME}"..." - start - ;; - 'stop') - echo "Stopping "${DAEMON_NAME}"..." - stop - ;; - 'status') - if [ -f ${PID_FILE} ]; then - PID=`cat ${PID_FILE}` - echo ${DAEMON_NAME}" is running PID: "${PID} - else - echo ${DAEMON_NAME}" is not running!" - fi - ;; - 'restart') - $0 stop - sleep 5 - $0 start - ;; - *) - echo $0 "start|stop|status|restart" - exit 1 - ;; -esac -exit 0 +#!/bin/bash + +# DO NOT CHANGE THIS ! OR YOU REALLY KNOW WHAT YOU ARE DOING ;) + +# Organization: +# EXEC_PATH is root (pid will be there) +# EXEC_PATH/../logs/ will be the log place +# EXEC_PATH/../bin/ is where jsvc is placed +# DAEMON_ROOT is where all you jars are (even commons-daemon) +# DAEMON_NAME will be the service name +# MAIN_DAEMON_CLASS will be the start/stop class used + +# Change this to adapt the path where the pid should be +export EXEC_PATH=/waarp/run +# could be also `dirname $0` + +# Change this by the path where all jars are +export DAEMON_ROOT=/waarp/classpath + +# Change this by the name of your daemon +export DAEMON_NAME="WaarpDaemon" + +# Change this to match your classpath +export DAEMON_CLASSPATH=${DAEMON_ROOT}/commons-daemon-1.0.10.jar:%DAEMON_ROOT%\commons-codec-1.6.jar:%DAEMON_ROOT%\commons-compress-1.4.1.jar:%DAEMON_ROOT%\commons-exec-1.1.jar:%DAEMON_ROOT%\commons-io-2.4.jar:%DAEMON_ROOT%\dom4j-1.6.1.jar:%DAEMON_ROOT%\h2-1.3.167.jar:%DAEMON_ROOT%\javasysmon-0.3.3.jar:%DAEMON_ROOT%\jaxen-1.1.3.jar:%DAEMON_ROOT%\log4j-1.2.14.jar:%DAEMON_ROOT%\logback-access-1.0.6.jar:%DAEMON_ROOT%\logback-classic-1.0.6.jar:%DAEMON_ROOT%\logback-core-1.0.6.jar:%DAEMON_ROOT%\netty-3.5.5.Final.jar:%DAEMON_ROOT%\slf4j-api-1.6.6.jar:%DAEMON_ROOT%\snmp4j-2.1.0.jar:%DAEMON_ROOT%\snmp4j-agent-2.0.6.jar:%DAEMON_ROOT%\WaarpCommon-1.2.6.jar:%DAEMON_ROOT%\WaarpDigest-1.1.5.jar:%DAEMON_ROOT%\WaarpExec-1.1.3.jar:%DAEMON_ROOT%\WaarpPassword-1.1.1.jar:%DAEMON_ROOT%\WaarpR66-2.4.7-beta.jar:%DAEMON_ROOT%\WaarpR66Gui-2.1.2.jar:%DAEMON_ROOT%\WaarpSnmp-1.1.1.jar:%DAEMON_ROOT%\WaarpThrift-1.0.0.jar:%DAEMON_ROOT%\WaarpXmlEditor-1.0.0.jar:%DAEMON_ROOT%\xercesImpl.jar:%DAEMON_ROOT%\xml-apis.jar:%DAEMON_ROOT%\xmleditor.jar:%DAEMON_ROOT%\libthrift-0.8.0.jar + +# Change this to specify the PID file path and name +export PID_FILE=${EXEC_PATH}/service.pid + +# Change this to match you Daemon class +export MAIN_DAEMON_CLASS=org.waarp.xxx.service.ServiceLauncher + +# Change this to specify the stdout file +export STDOUT_FILE=${EXEC_PATH}/../logs/stdout.txt + +# Change this to specify the stderr file +export STDERR_FILE=${EXEC_PATH}/../logs/stderr.txt + +# Java memory options +export JAVAxMS=-Xms64m +export JAVAxMX=-Xmx512m + +# JVM server option +export JAVASERVER=-jvm=server +#export JAVASERVER=-jvm=client + +# Logback configuration file +export LOGBACK_CONF=-Dlogback.configurationFile=/waarp/conf/logback.xml + +# Add -debug if you want to run in debug mode +export JSVC_OPTIONS=${JAVAxMS} ${JAVAxMX} ${JAVASERVER} ${LOGBACK_CONF} + +# ----------------------------------------------------------------------------- + +export OS_TYPE=`uname` +if [ "x${OS_TYPE}" == "xDarwin" ]; then + export EXEC="arch -arch i386 "${EXEC_PATH}"/jsvc" +else + export EXEC=${EXEC_PATH}"/jsvc" +fi + +running() { + if [ -f ${PID_FILE} ]; then + echo ${DAEMON_NAME}" already running." + exit 0 + fi +} + +start() { + running + ${EXEC} \ + -cp ${DAEMON_CLASSPATH} \ + -outfile ${STDOUT_FILE} \ + -errfile ${STDERR_FILE} \ + -pidfile ${PID_FILE} \ + ${JSVC_OPTIONS} \ + ${MAIN_DAEMON_CLASS} +} + +stop() { + ${EXEC} \ + -cp ${DAEMON_CLASSPATH} \ + -outfile ${STDOUT_FILE} \ + -errfile ${STDERR_FILE} \ + -pidfile ${PID_FILE} \ + ${JSVC_OPTIONS} \ + -stop \ + ${MAIN_DAEMON_CLASS} +} + +case "$1" in + 'start') + echo "Starting "${DAEMON_NAME}"..." + start + ;; + 'stop') + echo "Stopping "${DAEMON_NAME}"..." + stop + ;; + 'status') + if [ -f ${PID_FILE} ]; then + PID=`cat ${PID_FILE}` + echo ${DAEMON_NAME}" is running PID: "${PID} + else + echo ${DAEMON_NAME}" is not running!" + fi + ;; + 'restart') + $0 stop + sleep 5 + $0 start + ;; + *) + echo $0 "start|stop|status|restart" + exit 1 + ;; +esac +exit 0 diff --git a/src/main/java/org/waarp/openr66/thrift/R66EmbeddedServiceImpl.java b/src/main/java/org/waarp/openr66/thrift/R66EmbeddedServiceImpl.java index 5572754cd..bead2ef85 100644 --- a/src/main/java/org/waarp/openr66/thrift/R66EmbeddedServiceImpl.java +++ b/src/main/java/org/waarp/openr66/thrift/R66EmbeddedServiceImpl.java @@ -1,436 +1,436 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project 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. - - Waarp 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 Waarp . If not, see . - */ -package org.waarp.openr66.thrift; - -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.thrift.TException; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.database.data.AbstractDbData; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.TransferUtils; -import org.waarp.thrift.r66.Action; -import org.waarp.thrift.r66.ErrorCode; -import org.waarp.thrift.r66.R66Request; -import org.waarp.thrift.r66.R66Result; -import org.waarp.thrift.r66.R66Service; -import org.waarp.thrift.r66.RequestMode; - -/** - * Embedded service attached with the Thrift service - * @author Frederic Bregier - * - */ -public class R66EmbeddedServiceImpl implements R66Service.Iface { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66EmbeddedServiceImpl.class); - - private DbTaskRunner initRequest(R66Request request) { - Timestamp ttimestart = null; - if (request.isSetStart()) { - Date date; - try { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - date = dateFormat.parse(request.getStart()); - ttimestart = new Timestamp(date.getTime()); - } catch (ParseException e) { - } - } else if (request.isSetDelay()) { - if (request.getDelay().charAt(0) == '+') { - ttimestart = new Timestamp(System.currentTimeMillis() + - Long.parseLong(request.getDelay().substring(1))); - } else { - ttimestart = new Timestamp(Long.parseLong(request.getDelay())); - } - } - DbRule rule; - try { - rule = new DbRule(DbConstant.admin.session, request.getRule()); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot get Rule: " + request.getRule(), e); - return null; - } - int mode = rule.mode; - if (request.isMd5()) { - mode = RequestPacket.getModeMD5(mode); - } - DbTaskRunner taskRunner = null; - long tid = DbConstant.ILLEGALVALUE; - if (request.isSetTid()) { - tid = request.getTid(); - } - if (tid != DbConstant.ILLEGALVALUE) { - try { - taskRunner = new DbTaskRunner(DbConstant.admin.session, tid, - request.getDestuid()); - // requested - taskRunner.setSenderByRequestToValidate(true); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot get task", e); - return null; - } - } else { - RequestPacket requestPacket = new RequestPacket(request.getRule(), - mode, request.getFile(), request.getBlocksize(), 0, - tid, request.getInfo(), -1); - // Not isRecv since it is the requester, so send => isRetrieve is true - boolean isRetrieve = !RequestPacket.isRecvMode(requestPacket.getMode()); - try { - taskRunner = - new DbTaskRunner(DbConstant.admin.session, rule, isRetrieve, requestPacket, - request.getDestuid(), ttimestart); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot get task", e); - return null; - } - } - return taskRunner; - } - - public R66Result transferRequestQuery(R66Request request) throws TException { - DbTaskRunner runner = initRequest(request); - if (runner != null) { - runner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.TOSUBMIT); - boolean isSender = runner.isSender(); - if (! runner.forceSaveStatus()) { - logger.warn("Cannot prepare task"); - return new R66Result(request.getMode(), ErrorCode.CommandNotFound, - "ERROR: Cannot prepare transfer"); - } - R66Result result = new R66Result(request.getMode(), ErrorCode.InitOk, - "Transfer Scheduled"); - if (request.getMode() == RequestMode.SYNCTRANSFER) { - // now need to wait but first, reload the runner - try { - runner.select(); - while (! runner.isFinished()) { - try { - Thread.sleep(1000); - runner.select(); - } catch (InterruptedException e) { - break; - } - } - runner.setSender(isSender); - } catch (WaarpDatabaseException e1) { - } - setResultFromRunner(runner, result); - if (runner.isAllDone()) { - result.setCode(ErrorCode.CompleteOk); - result.setResultinfo("Transfer Done"); - } else { - result.setCode(ErrorCode.valueOf(runner.getErrorInfo().name())); - result.setResultinfo(runner.getErrorInfo().mesg); - } - } else { - try { - runner.select(); - } catch (WaarpDatabaseException e) { - } - runner.setSender(isSender); - setResultFromRunner(runner, result); - } - return result; - } else { - logger.warn("ERROR: Transfer NOT scheduled"); - R66Result result = new R66Result(request.getMode(), ErrorCode.Internal, - "ERROR: Transfer NOT scheduled"); - return result; - } - } - - private void setResultFromRunner(DbTaskRunner runner, R66Result result) { - result.setDestuid(runner.getRequested()); - result.setFromuid(runner.getRequester()); - result.setTid(runner.getSpecialId()); - result.setRule(runner.getRuleId()); - result.setBlocksize(runner.getBlocksize()); - result.setFile(runner.getFilename()); - result.setOriginalfilename(runner.getOriginalFilename()); - result.setIsmoved(runner.isFileMoved()); - result.setModetransfer(runner.getMode()); - result.setRetrievemode(runner.isSender()); - result.setStep(runner.getStep()); - result.setGloballaststep(runner.getGloballaststep()); - result.setRank(runner.getRank()); - result.setStart(runner.getStart().toString()); - result.setStop(runner.getStop().toString()); - result.setResultinfo(runner.getFileInformation()); - } - - private void setResultFromLCR(LocalChannelReference lcr, R66Result result) { - R66Session session = lcr.getSession(); - DbTaskRunner runner = null; - if (session != null) { - runner = session.getRunner(); - } else { - ClientRunner run = lcr.getClientRunner(); - if (run != null) { - runner = run.getTaskRunner(); - } - } - if (runner != null) { - setResultFromRunner(runner, result); - } - } - - private int stopOrCancelRunner(long id, String reqd, String reqr, org.waarp.openr66.context.ErrorCode code) { - try { - DbTaskRunner taskRunner = - new DbTaskRunner(DbConstant.admin.session, null, - null, id, reqr, reqd); - return taskRunner.stopOrCancelRunner(code) ? 1 : 0; - } catch (WaarpDatabaseException e) { - } - logger.warn("Cannot accomplished action on task: "+id+" "+code.name()); - return -1; - } - - private R66Result stopOrCancel(R66Request request, LocalChannelReference lcr, - org.waarp.openr66.context.ErrorCode r66code) { - // stop the current transfer - R66Result resulttest; - if (lcr != null) { - int rank = 0; - if (r66code == org.waarp.openr66.context.ErrorCode.StoppedTransfer && lcr.getSession() != null) { - DbTaskRunner taskRunner = lcr.getSession().getRunner(); - if (taskRunner != null) { - rank = taskRunner.getRank(); - } - } - ErrorPacket error = new ErrorPacket(r66code.name() + " " + rank, - r66code.getCode(), ErrorPacket.FORWARDCLOSECODE); - try { - // inform local instead of remote - ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); - } catch (Exception e) { - } - resulttest = new R66Result(request.getMode(), ErrorCode.CompleteOk, - r66code.name()); - setResultFromLCR(lcr, resulttest); - } else { - // Transfer is not running - // but maybe need action on database - int test = stopOrCancelRunner(request.getTid(), request.getDestuid(), request.getFromuid(), r66code); - if (test > 0) { - resulttest = new R66Result(request.getMode(), ErrorCode.CompleteOk, - r66code.name()); - } else if (test == 0) { - resulttest = new R66Result(request.getMode(), ErrorCode.TransferOk, - r66code.name()); - } else { - resulttest = new R66Result(request.getMode(), ErrorCode.CommandNotFound, - "Error: cannot accomplished task on transfer"); - } - } - return resulttest; - } - - private R66Result restart(R66Request request, LocalChannelReference lcr) { - // Try to validate a restarting transfer - // validLimit on requested side - if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { - logger.warn("Limit exceeded while asking to relaunch a task " - + request.toString()); - return new R66Result(request.getMode(), ErrorCode.ServerOverloaded, - "Limit exceeded while asking to relaunch a task"); - } - // Try to validate a restarting transfer - // header = ?; middle = requested+blank+requester+blank+specialId - DbTaskRunner taskRunner = null; - try { - taskRunner = new DbTaskRunner(DbConstant.admin.session, null, - null, request.getTid(), request.getFromuid(), request.getDestuid()); - org.waarp.openr66.context.R66Result resulttest = TransferUtils.restartTransfer(taskRunner, lcr); - return new R66Result(request.getMode(), ErrorCode.valueOf(resulttest.code.name()), - resulttest.getMessage()); - } catch (WaarpDatabaseException e1) { - logger.warn("Exception while trying to restart transfer", e1); - return new R66Result(request.getMode(), ErrorCode.Internal, - "Exception while trying to restart transfer"); - } - } - - public R66Result infoTransferQuery(R66Request request) throws TException { - RequestMode mode = request.getMode(); - if (mode != RequestMode.INFOREQUEST) { - // error - logger.warn("Mode is uncompatible with infoTransferQuery"); - return new R66Result(request.getMode(), ErrorCode.Unimplemented, - "Mode is uncompatible with infoTransferQuery"); - } - // now check if enough arguments are provided - if ((!request.isSetTid()) || (!request.isSetDestuid() && !request.isSetFromuid()) || - (!request.isSetAction())) { - // error - logger.warn("Not enough arguments"); - return new R66Result(request.getMode(), ErrorCode.RemoteError, - "Not enough arguments"); - } - // requested+blank+requester+blank+specialId - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(request.getDestuid()+" "+request.getFromuid()+" "+request.getTid()); - org.waarp.openr66.context.ErrorCode r66code; - switch (request.getAction()) { - case Detail: { - R66Result result = new R66Result(request.getMode(), ErrorCode.CompleteOk, - "Existence test OK"); - result.setAction(Action.Exist); - result.setDestuid(request.getDestuid()); - result.setFromuid(request.getFromuid()); - result.setTid(request.getTid()); - if (lcr != null) { - setResultFromLCR(lcr, result); - } else { - try { - DbTaskRunner runner = new DbTaskRunner(DbConstant.admin.session, null, - null, request.getTid(), request.getFromuid(), - request.getDestuid()); - if (runner != null) { - setResultFromRunner(runner, result); - } - } catch (WaarpDatabaseException e) { - result.setCode(ErrorCode.FileNotFound); - } - } - return result; - } - case Restart: - return restart(request, lcr); - case Cancel: - r66code = org.waarp.openr66.context.ErrorCode.CanceledTransfer; - return stopOrCancel(request, lcr, r66code); - case Stop: - r66code = org.waarp.openr66.context.ErrorCode.StoppedTransfer; - return stopOrCancel(request, lcr, r66code); - default: - logger.warn("Uncompatible with "+request.getAction().name()); - return new R66Result(request.getMode(), ErrorCode.Unimplemented, - "Uncompatible with "+request.getAction().name()); - } - } - - public boolean isStillRunning(String fromuid, String touid, long tid) throws TException { - // now check if enough arguments are provided - if (fromuid == null || touid == null || tid == DbConstant.ILLEGALVALUE) { - // error - logger.warn("Not enough arguments"); - return false; - } - // header = ?; middle = requested+blank+requester+blank+specialId - LocalChannelReference lcr = - Configuration.configuration.getLocalTransaction(). - getFromRequest(touid+" "+fromuid+" "+tid); - return (lcr != null); - } - - public List infoListQuery(R66Request request) throws TException { - List list = new ArrayList(); - RequestMode mode = request.getMode(); - if (mode != RequestMode.INFOFILE) { - // error - logger.warn("Not correct mode for infoListQuery"); - list.add("Not correct mode for infoListQuery"); - return list; - } - // now check if enough arguments are provided - if ((!request.isSetRule()) || (!request.isSetAction())) { - // error - logger.warn("Not enough arguments"); - list.add("Not enough arguments"); - return list; - } - R66Session session = new R66Session(); - session.getAuth().specialNoSessionAuth(false, Configuration.configuration.HOST_ID); - DbRule rule; - try { - rule = new DbRule(DbConstant.admin.session, request.getRule()); - } catch (WaarpDatabaseException e) { - logger.warn("Rule is unknown: " + request.getRule()); - list.add("Rule is unknown: " + request.getRule()); - return list; - } - try { - if (RequestPacket.isRecvMode(rule.mode)) { - session.getDir().changeDirectory(rule.workPath); - } else { - session.getDir().changeDirectory(rule.sendPath); - } - - if (request.getAction() == Action.List || - request.getAction() == Action.Mlsx) { - // ls or mls from current directory - if (request.getAction() == Action.List) { - list = session.getDir().list(request.getFile()); - } else { - list = session.getDir().listFull(request.getFile(), false); - } - return list; - } else { - // ls pr mls from current directory and filename - if (! request.isSetFile()) { - logger.warn("File missing"); - list.add("File missing"); - return list; - } - R66File file = (R66File) session.getDir().setFile(request.getFile(), false); - String sresult = null; - if (request.getAction() == Action.Exist) { - sresult = "" + file.exists(); - list.add(sresult); - } else if (request.getAction() == Action.Detail) { - sresult = session.getDir().fileFull(request.getFile(), false); - String[] slist = sresult.split("\n"); - sresult = slist[1]; - list.add(sresult); - } - return list; - } - } catch (CommandAbstractException e) { - logger.warn("Error occurs during: " + request.toString(), e); - list.add("Error occurs during: " + request.toString()); - return list; - } - } - -} +/** + This file is part of Waarp Project. + + Copyright 2009, Frederic Bregier, and individual contributors by the @author + tags. See the COPYRIGHT.txt in the distribution for a full listing of + individual contributors. + + All Waarp Project 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. + + Waarp 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 Waarp . If not, see . + */ +package org.waarp.openr66.thrift; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.thrift.TException; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.database.data.AbstractDbData; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.ErrorPacket; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.TransferUtils; +import org.waarp.thrift.r66.Action; +import org.waarp.thrift.r66.ErrorCode; +import org.waarp.thrift.r66.R66Request; +import org.waarp.thrift.r66.R66Result; +import org.waarp.thrift.r66.R66Service; +import org.waarp.thrift.r66.RequestMode; + +/** + * Embedded service attached with the Thrift service + * @author Frederic Bregier + * + */ +public class R66EmbeddedServiceImpl implements R66Service.Iface { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66EmbeddedServiceImpl.class); + + private DbTaskRunner initRequest(R66Request request) { + Timestamp ttimestart = null; + if (request.isSetStart()) { + Date date; + try { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + date = dateFormat.parse(request.getStart()); + ttimestart = new Timestamp(date.getTime()); + } catch (ParseException e) { + } + } else if (request.isSetDelay()) { + if (request.getDelay().charAt(0) == '+') { + ttimestart = new Timestamp(System.currentTimeMillis() + + Long.parseLong(request.getDelay().substring(1))); + } else { + ttimestart = new Timestamp(Long.parseLong(request.getDelay())); + } + } + DbRule rule; + try { + rule = new DbRule(DbConstant.admin.session, request.getRule()); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot get Rule: " + request.getRule(), e); + return null; + } + int mode = rule.mode; + if (request.isMd5()) { + mode = RequestPacket.getModeMD5(mode); + } + DbTaskRunner taskRunner = null; + long tid = DbConstant.ILLEGALVALUE; + if (request.isSetTid()) { + tid = request.getTid(); + } + if (tid != DbConstant.ILLEGALVALUE) { + try { + taskRunner = new DbTaskRunner(DbConstant.admin.session, tid, + request.getDestuid()); + // requested + taskRunner.setSenderByRequestToValidate(true); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot get task", e); + return null; + } + } else { + RequestPacket requestPacket = new RequestPacket(request.getRule(), + mode, request.getFile(), request.getBlocksize(), 0, + tid, request.getInfo(), -1); + // Not isRecv since it is the requester, so send => isRetrieve is true + boolean isRetrieve = !RequestPacket.isRecvMode(requestPacket.getMode()); + try { + taskRunner = + new DbTaskRunner(DbConstant.admin.session, rule, isRetrieve, requestPacket, + request.getDestuid(), ttimestart); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot get task", e); + return null; + } + } + return taskRunner; + } + + public R66Result transferRequestQuery(R66Request request) throws TException { + DbTaskRunner runner = initRequest(request); + if (runner != null) { + runner.changeUpdatedInfo(AbstractDbData.UpdatedInfo.TOSUBMIT); + boolean isSender = runner.isSender(); + if (! runner.forceSaveStatus()) { + logger.warn("Cannot prepare task"); + return new R66Result(request.getMode(), ErrorCode.CommandNotFound, + "ERROR: Cannot prepare transfer"); + } + R66Result result = new R66Result(request.getMode(), ErrorCode.InitOk, + "Transfer Scheduled"); + if (request.getMode() == RequestMode.SYNCTRANSFER) { + // now need to wait but first, reload the runner + try { + runner.select(); + while (! runner.isFinished()) { + try { + Thread.sleep(1000); + runner.select(); + } catch (InterruptedException e) { + break; + } + } + runner.setSender(isSender); + } catch (WaarpDatabaseException e1) { + } + setResultFromRunner(runner, result); + if (runner.isAllDone()) { + result.setCode(ErrorCode.CompleteOk); + result.setResultinfo("Transfer Done"); + } else { + result.setCode(ErrorCode.valueOf(runner.getErrorInfo().name())); + result.setResultinfo(runner.getErrorInfo().mesg); + } + } else { + try { + runner.select(); + } catch (WaarpDatabaseException e) { + } + runner.setSender(isSender); + setResultFromRunner(runner, result); + } + return result; + } else { + logger.warn("ERROR: Transfer NOT scheduled"); + R66Result result = new R66Result(request.getMode(), ErrorCode.Internal, + "ERROR: Transfer NOT scheduled"); + return result; + } + } + + private void setResultFromRunner(DbTaskRunner runner, R66Result result) { + result.setDestuid(runner.getRequested()); + result.setFromuid(runner.getRequester()); + result.setTid(runner.getSpecialId()); + result.setRule(runner.getRuleId()); + result.setBlocksize(runner.getBlocksize()); + result.setFile(runner.getFilename()); + result.setOriginalfilename(runner.getOriginalFilename()); + result.setIsmoved(runner.isFileMoved()); + result.setModetransfer(runner.getMode()); + result.setRetrievemode(runner.isSender()); + result.setStep(runner.getStep()); + result.setGloballaststep(runner.getGloballaststep()); + result.setRank(runner.getRank()); + result.setStart(runner.getStart().toString()); + result.setStop(runner.getStop().toString()); + result.setResultinfo(runner.getFileInformation()); + } + + private void setResultFromLCR(LocalChannelReference lcr, R66Result result) { + R66Session session = lcr.getSession(); + DbTaskRunner runner = null; + if (session != null) { + runner = session.getRunner(); + } else { + ClientRunner run = lcr.getClientRunner(); + if (run != null) { + runner = run.getTaskRunner(); + } + } + if (runner != null) { + setResultFromRunner(runner, result); + } + } + + private int stopOrCancelRunner(long id, String reqd, String reqr, org.waarp.openr66.context.ErrorCode code) { + try { + DbTaskRunner taskRunner = + new DbTaskRunner(DbConstant.admin.session, null, + null, id, reqr, reqd); + return taskRunner.stopOrCancelRunner(code) ? 1 : 0; + } catch (WaarpDatabaseException e) { + } + logger.warn("Cannot accomplished action on task: "+id+" "+code.name()); + return -1; + } + + private R66Result stopOrCancel(R66Request request, LocalChannelReference lcr, + org.waarp.openr66.context.ErrorCode r66code) { + // stop the current transfer + R66Result resulttest; + if (lcr != null) { + int rank = 0; + if (r66code == org.waarp.openr66.context.ErrorCode.StoppedTransfer && lcr.getSession() != null) { + DbTaskRunner taskRunner = lcr.getSession().getRunner(); + if (taskRunner != null) { + rank = taskRunner.getRank(); + } + } + ErrorPacket error = new ErrorPacket(r66code.name() + " " + rank, + r66code.getCode(), ErrorPacket.FORWARDCLOSECODE); + try { + // inform local instead of remote + ChannelUtils.writeAbstractLocalPacketToLocal(lcr, error); + } catch (Exception e) { + } + resulttest = new R66Result(request.getMode(), ErrorCode.CompleteOk, + r66code.name()); + setResultFromLCR(lcr, resulttest); + } else { + // Transfer is not running + // but maybe need action on database + int test = stopOrCancelRunner(request.getTid(), request.getDestuid(), request.getFromuid(), r66code); + if (test > 0) { + resulttest = new R66Result(request.getMode(), ErrorCode.CompleteOk, + r66code.name()); + } else if (test == 0) { + resulttest = new R66Result(request.getMode(), ErrorCode.TransferOk, + r66code.name()); + } else { + resulttest = new R66Result(request.getMode(), ErrorCode.CommandNotFound, + "Error: cannot accomplished task on transfer"); + } + } + return resulttest; + } + + private R66Result restart(R66Request request, LocalChannelReference lcr) { + // Try to validate a restarting transfer + // validLimit on requested side + if (Configuration.configuration.constraintLimitHandler.checkConstraints()) { + logger.warn("Limit exceeded while asking to relaunch a task " + + request.toString()); + return new R66Result(request.getMode(), ErrorCode.ServerOverloaded, + "Limit exceeded while asking to relaunch a task"); + } + // Try to validate a restarting transfer + // header = ?; middle = requested+blank+requester+blank+specialId + DbTaskRunner taskRunner = null; + try { + taskRunner = new DbTaskRunner(DbConstant.admin.session, null, + null, request.getTid(), request.getFromuid(), request.getDestuid()); + org.waarp.openr66.context.R66Result resulttest = TransferUtils.restartTransfer(taskRunner, lcr); + return new R66Result(request.getMode(), ErrorCode.valueOf(resulttest.code.name()), + resulttest.getMessage()); + } catch (WaarpDatabaseException e1) { + logger.warn("Exception while trying to restart transfer", e1); + return new R66Result(request.getMode(), ErrorCode.Internal, + "Exception while trying to restart transfer"); + } + } + + public R66Result infoTransferQuery(R66Request request) throws TException { + RequestMode mode = request.getMode(); + if (mode != RequestMode.INFOREQUEST) { + // error + logger.warn("Mode is uncompatible with infoTransferQuery"); + return new R66Result(request.getMode(), ErrorCode.Unimplemented, + "Mode is uncompatible with infoTransferQuery"); + } + // now check if enough arguments are provided + if ((!request.isSetTid()) || (!request.isSetDestuid() && !request.isSetFromuid()) || + (!request.isSetAction())) { + // error + logger.warn("Not enough arguments"); + return new R66Result(request.getMode(), ErrorCode.RemoteError, + "Not enough arguments"); + } + // requested+blank+requester+blank+specialId + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(request.getDestuid()+" "+request.getFromuid()+" "+request.getTid()); + org.waarp.openr66.context.ErrorCode r66code; + switch (request.getAction()) { + case Detail: { + R66Result result = new R66Result(request.getMode(), ErrorCode.CompleteOk, + "Existence test OK"); + result.setAction(Action.Exist); + result.setDestuid(request.getDestuid()); + result.setFromuid(request.getFromuid()); + result.setTid(request.getTid()); + if (lcr != null) { + setResultFromLCR(lcr, result); + } else { + try { + DbTaskRunner runner = new DbTaskRunner(DbConstant.admin.session, null, + null, request.getTid(), request.getFromuid(), + request.getDestuid()); + if (runner != null) { + setResultFromRunner(runner, result); + } + } catch (WaarpDatabaseException e) { + result.setCode(ErrorCode.FileNotFound); + } + } + return result; + } + case Restart: + return restart(request, lcr); + case Cancel: + r66code = org.waarp.openr66.context.ErrorCode.CanceledTransfer; + return stopOrCancel(request, lcr, r66code); + case Stop: + r66code = org.waarp.openr66.context.ErrorCode.StoppedTransfer; + return stopOrCancel(request, lcr, r66code); + default: + logger.warn("Uncompatible with "+request.getAction().name()); + return new R66Result(request.getMode(), ErrorCode.Unimplemented, + "Uncompatible with "+request.getAction().name()); + } + } + + public boolean isStillRunning(String fromuid, String touid, long tid) throws TException { + // now check if enough arguments are provided + if (fromuid == null || touid == null || tid == DbConstant.ILLEGALVALUE) { + // error + logger.warn("Not enough arguments"); + return false; + } + // header = ?; middle = requested+blank+requester+blank+specialId + LocalChannelReference lcr = + Configuration.configuration.getLocalTransaction(). + getFromRequest(touid+" "+fromuid+" "+tid); + return (lcr != null); + } + + public List infoListQuery(R66Request request) throws TException { + List list = new ArrayList(); + RequestMode mode = request.getMode(); + if (mode != RequestMode.INFOFILE) { + // error + logger.warn("Not correct mode for infoListQuery"); + list.add("Not correct mode for infoListQuery"); + return list; + } + // now check if enough arguments are provided + if ((!request.isSetRule()) || (!request.isSetAction())) { + // error + logger.warn("Not enough arguments"); + list.add("Not enough arguments"); + return list; + } + R66Session session = new R66Session(); + session.getAuth().specialNoSessionAuth(false, Configuration.configuration.HOST_ID); + DbRule rule; + try { + rule = new DbRule(DbConstant.admin.session, request.getRule()); + } catch (WaarpDatabaseException e) { + logger.warn("Rule is unknown: " + request.getRule()); + list.add("Rule is unknown: " + request.getRule()); + return list; + } + try { + if (RequestPacket.isRecvMode(rule.mode)) { + session.getDir().changeDirectory(rule.workPath); + } else { + session.getDir().changeDirectory(rule.sendPath); + } + + if (request.getAction() == Action.List || + request.getAction() == Action.Mlsx) { + // ls or mls from current directory + if (request.getAction() == Action.List) { + list = session.getDir().list(request.getFile()); + } else { + list = session.getDir().listFull(request.getFile(), false); + } + return list; + } else { + // ls pr mls from current directory and filename + if (! request.isSetFile()) { + logger.warn("File missing"); + list.add("File missing"); + return list; + } + R66File file = (R66File) session.getDir().setFile(request.getFile(), false); + String sresult = null; + if (request.getAction() == Action.Exist) { + sresult = "" + file.exists(); + list.add(sresult); + } else if (request.getAction() == Action.Detail) { + sresult = session.getDir().fileFull(request.getFile(), false); + String[] slist = sresult.split("\n"); + sresult = slist[1]; + list.add(sresult); + } + return list; + } + } catch (CommandAbstractException e) { + logger.warn("Error occurs during: " + request.toString(), e); + list.add("Error occurs during: " + request.toString()); + return list; + } + } + +} diff --git a/src/main/java/org/waarp/openr66/thrift/R66ThriftServerService.java b/src/main/java/org/waarp/openr66/thrift/R66ThriftServerService.java index 12d6c29f9..5c3567e5d 100644 --- a/src/main/java/org/waarp/openr66/thrift/R66ThriftServerService.java +++ b/src/main/java/org/waarp/openr66/thrift/R66ThriftServerService.java @@ -1,114 +1,114 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project 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. - - Waarp 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 Waarp . If not, see . - */ -package org.waarp.openr66.thrift; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TServerTransport; -import org.apache.thrift.transport.TTransportException; -import org.waarp.common.future.WaarpFuture; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.thrift.r66.R66Service; - -/** - * Main Thrift server service - * @author Frederic Bregier - * - */ -public class R66ThriftServerService implements Runnable { - /** - * Internal Logger - */ - private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory - .getLogger(R66ThriftServerService.class); - - protected int port = 4266; - protected TServerTransport serverTransport = null; - protected TServer server = null; - protected WaarpFuture serviceReady; - - public R66ThriftServerService(WaarpFuture serviceReady, int port) { - this.serviceReady = serviceReady; - this.port = port; - } - - public boolean awaitInitialization() { - if (serviceReady != null) { - try { - serviceReady.await(); - } catch (InterruptedException e) { - } - return serviceReady.isSuccess(); - } - return true; - } - - public void run() { - try { - logger.warn("Will start Thrift service on port: " + port); - byte [] local = {127,0,0,1}; - InetAddress addr; - try { - addr = InetAddress.getByAddress(local); - } catch (UnknownHostException e) { - try { - addr = InetAddress.getLocalHost(); - } catch (UnknownHostException e1) { - logger.error("Cannot start the Thrift service", e1); - serviceReady.setFailure(e); - releaseResources(); - return; - } - } - InetSocketAddress address = new InetSocketAddress(addr, port); - serverTransport = new TServerSocket(address); - R66Service.Processor processor = - new R66Service.Processor( - new R66EmbeddedServiceImpl()); - server = new TThreadPoolServer( - new TThreadPoolServer.Args(serverTransport).processor(processor)); - serviceReady.setSuccess(); - server.serve(); - } catch (TTransportException e) { - logger.error("An error occurs during initialization of Thrift support", e); - serviceReady.setFailure(e); - releaseResources(); - } - } - - public void releaseResources() { - if (server != null) { - logger.debug("Stop Thrift Server"); - server.stop(); - } - if (serverTransport != null) { - logger.debug("Stop Thrift Transport"); - serverTransport.close(); - } - logger.debug("Thrift stopped"); - } -} +/** + This file is part of Waarp Project. + + Copyright 2009, Frederic Bregier, and individual contributors by the @author + tags. See the COPYRIGHT.txt in the distribution for a full listing of + individual contributors. + + All Waarp Project 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. + + Waarp 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 Waarp . If not, see . + */ +package org.waarp.openr66.thrift; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TThreadPoolServer; +import org.apache.thrift.transport.TServerSocket; +import org.apache.thrift.transport.TServerTransport; +import org.apache.thrift.transport.TTransportException; +import org.waarp.common.future.WaarpFuture; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.thrift.r66.R66Service; + +/** + * Main Thrift server service + * @author Frederic Bregier + * + */ +public class R66ThriftServerService implements Runnable { + /** + * Internal Logger + */ + private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory + .getLogger(R66ThriftServerService.class); + + protected int port = 4266; + protected TServerTransport serverTransport = null; + protected TServer server = null; + protected WaarpFuture serviceReady; + + public R66ThriftServerService(WaarpFuture serviceReady, int port) { + this.serviceReady = serviceReady; + this.port = port; + } + + public boolean awaitInitialization() { + if (serviceReady != null) { + try { + serviceReady.await(); + } catch (InterruptedException e) { + } + return serviceReady.isSuccess(); + } + return true; + } + + public void run() { + try { + logger.warn("Will start Thrift service on port: " + port); + byte [] local = {127,0,0,1}; + InetAddress addr; + try { + addr = InetAddress.getByAddress(local); + } catch (UnknownHostException e) { + try { + addr = InetAddress.getLocalHost(); + } catch (UnknownHostException e1) { + logger.error("Cannot start the Thrift service", e1); + serviceReady.setFailure(e); + releaseResources(); + return; + } + } + InetSocketAddress address = new InetSocketAddress(addr, port); + serverTransport = new TServerSocket(address); + R66Service.Processor processor = + new R66Service.Processor( + new R66EmbeddedServiceImpl()); + server = new TThreadPoolServer( + new TThreadPoolServer.Args(serverTransport).processor(processor)); + serviceReady.setSuccess(); + server.serve(); + } catch (TTransportException e) { + logger.error("An error occurs during initialization of Thrift support", e); + serviceReady.setFailure(e); + releaseResources(); + } + } + + public void releaseResources() { + if (server != null) { + logger.debug("Stop Thrift Server"); + server.stop(); + } + if (serverTransport != null) { + logger.debug("Stop Thrift Transport"); + serverTransport.close(); + } + logger.debug("Thrift stopped"); + } +} diff --git a/src/main/java/org/waarp/openr66/thrift/package-info.java b/src/main/java/org/waarp/openr66/thrift/package-info.java index 8cbf74189..809280da2 100644 --- a/src/main/java/org/waarp/openr66/thrift/package-info.java +++ b/src/main/java/org/waarp/openr66/thrift/package-info.java @@ -1,25 +1,25 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -/** - * Thrift Package that can be activated to allow Thrift clients interactions - * @author Frederic Bregier - * - * @apiviz.landmark - * - */ +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +/** + * Thrift Package that can be activated to allow Thrift clients interactions + * @author Frederic Bregier + * + * @apiviz.landmark + * + */ package org.waarp.openr66.thrift; \ No newline at end of file diff --git a/src/main/xample/OpenR66-Authent.xsd b/src/main/xample/OpenR66-Authent.xsd index 14e8e0203..df67c7b70 100644 --- a/src/main/xample/OpenR66-Authent.xsd +++ b/src/main/xample/OpenR66-Authent.xsd @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - Used to initialize remote Hosts table at setup or with client with no database support - - - - - - - - - Host ID of remote Host - - - - - - - Address of remote host (IP or DNS entry) - - - - - - - Port associated with the Address of the remote Host - - - - - - - True if this Address Entry is for SSL mode - - - - - - - True if this Address Entry allows Admin access through R66 Protocol. -Note from version 2.4.9, it could be override if roles are specified on general configuration file. - - - - - - - - True if this Address Entry is for a Client - - - - - - - - GoldenGate Password File containing the password for this host - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + Used to initialize remote Hosts table at setup or with client with no database support + + + + + + + + + Host ID of remote Host + + + + + + + Address of remote host (IP or DNS entry) + + + + + + + Port associated with the Address of the remote Host + + + + + + + True if this Address Entry is for SSL mode + + + + + + + True if this Address Entry allows Admin access through R66 Protocol. +Note from version 2.4.9, it could be override if roles are specified on general configuration file. + + + + + + + + True if this Address Entry is for a Client + + + + + + + + GoldenGate Password File containing the password for this host + + + + + + + + + + + + + diff --git a/src/main/xample/OpenR66-Client.xsd b/src/main/xample/OpenR66-Client.xsd index 1b0631316..1086b3b24 100644 --- a/src/main/xample/OpenR66-Client.xsd +++ b/src/main/xample/OpenR66-Client.xsd @@ -1,52 +1,52 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/xample/OpenR66-ClientNoDB.xsd b/src/main/xample/OpenR66-ClientNoDB.xsd index 404bf66ba..83caf7502 100644 --- a/src/main/xample/OpenR66-ClientNoDB.xsd +++ b/src/main/xample/OpenR66-ClientNoDB.xsd @@ -1,63 +1,63 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/xample/OpenR66-Limit.xsd b/src/main/xample/OpenR66-Limit.xsd index d86993237..3fb29603e 100644 --- a/src/main/xample/OpenR66-Limit.xsd +++ b/src/main/xample/OpenR66-Limit.xsd @@ -1,89 +1,89 @@ - - - - - - - - - - - - - - - - - - - - - Host ID in NON SSL mode - - - - - - - - - - - - - - - Bandwidth for one session (64Mb) - - - - - - - Global Bandwidth (512Mb) - - - - - - - Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - - - - - - Limit by batch of active transfers (10000) - - - - - - - Delay between 2 execution of the Commander (5s) - - - - - - - Delay between 2 attemps in case of error (30s) - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + Host ID in NON SSL mode + + + + + + + + + + + + + + + Bandwidth for one session (64Mb) + + + + + + + Global Bandwidth (512Mb) + + + + + + + Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + + + + + + Limit by batch of active transfers (10000) + + + + + + + Delay between 2 execution of the Commander (5s) + + + + + + + Delay between 2 attemps in case of error (30s) + + + + + + + + + + + diff --git a/src/main/xample/OpenR66-Rule.xsd b/src/main/xample/OpenR66-Rule.xsd index a95df18c9..005857c40 100644 --- a/src/main/xample/OpenR66-Rule.xsd +++ b/src/main/xample/OpenR66-Rule.xsd @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/src/main/xample/OpenR66-Rules.xsd b/src/main/xample/OpenR66-Rules.xsd index 480e8747d..17078488c 100644 --- a/src/main/xample/OpenR66-Rules.xsd +++ b/src/main/xample/OpenR66-Rules.xsd @@ -1,17 +1,17 @@ - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/src/main/xample/OpenR66-Server.xsd b/src/main/xample/OpenR66-Server.xsd index 737169898..dea65ba00 100644 --- a/src/main/xample/OpenR66-Server.xsd +++ b/src/main/xample/OpenR66-Server.xsd @@ -1,96 +1,96 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/xample/OpenR66-SubmitClient.xsd b/src/main/xample/OpenR66-SubmitClient.xsd index 070e27190..55d71c19c 100644 --- a/src/main/xample/OpenR66-SubmitClient.xsd +++ b/src/main/xample/OpenR66-SubmitClient.xsd @@ -1,55 +1,55 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/xample/R66-AliasTypes.xsd b/src/main/xample/R66-AliasTypes.xsd index e3583e208..6c086deb5 100644 --- a/src/main/xample/R66-AliasTypes.xsd +++ b/src/main/xample/R66-AliasTypes.xsd @@ -1,60 +1,60 @@ - - - - - - - - - - - - -This will allow alias usage for host ids (from version 2.4.12). - - - - - - - - - - -The real host id that will have aliases (locally) - - - - - - - - - -The set of aliases assign to this host separated by '|' or blank space - - - - - - - - - + + + + + + + + + + + + +This will allow alias usage for host ids (from version 2.4.12). + + + + + + + + + + +The real host id that will have aliases (locally) + + + + + + + + + +The set of aliases assign to this host separated by '|' or blank space + + + + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-BusinessTypes.xsd b/src/main/xample/R66-BusinessTypes.xsd index 60fcfecf7..6938f9d0c 100644 --- a/src/main/xample/R66-BusinessTypes.xsd +++ b/src/main/xample/R66-BusinessTypes.xsd @@ -1,32 +1,32 @@ - - - - - - - - - - - - - - - -The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) - - - - - - + + + + + + + + + + + + + + + +The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-DbTypes.xsd b/src/main/xample/R66-DbTypes.xsd index f2500880d..eccc0c477 100644 --- a/src/main/xample/R66-DbTypes.xsd +++ b/src/main/xample/R66-DbTypes.xsd @@ -1,38 +1,38 @@ - - - - - - - - - - - - - - - - - - -When a server with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - - - - - - - + + + + + + + + + + + + + + + + + + +When a server with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-DirectoryTypes.xsd b/src/main/xample/R66-DirectoryTypes.xsd index 4f34050f8..bed014356 100644 --- a/src/main/xample/R66-DirectoryTypes.xsd +++ b/src/main/xample/R66-DirectoryTypes.xsd @@ -1,105 +1,105 @@ - - - - - - - - - - - - - - - -Home Directory for the OpenR66 Server (relative path to this Home) - - - - - - - - - -Default Receive Directory - - - - - - - - - -Default Send Directory - - - - - - - - - -Default Archive Directory - - - - - - - - - -Default Working Directory - - - - - - - - - -Configuration Directory - - - - - - + + + + + + + + + + + + + + + +Home Directory for the OpenR66 Server (relative path to this Home) + + + + + + + + + +Default Receive Directory + + + + + + + + + +Default Send Directory + + + + + + + + + +Default Archive Directory + + + + + + + + + +Default Working Directory + + + + + + + + + +Configuration Directory + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-GlobalTypes.xsd b/src/main/xample/R66-GlobalTypes.xsd index 0160fa437..af2274a7e 100644 --- a/src/main/xample/R66-GlobalTypes.xsd +++ b/src/main/xample/R66-GlobalTypes.xsd @@ -1,225 +1,225 @@ - - - - - - - - True - False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |2Any files: *.* - - - Any file path - - - - - - - - |1Directory: * - - - Any directory path - - - - - - - - - jks|jeks|0JKS Keystore files: *.jks, *.jeks - - - - JKS Keystore files: *.jks, *.jeks - - - - - - - - - xml|0XML files: *.xml - - - XML files: *.xml - - - - - - - - - des|blf|0Des Blowfish Key files: *.des, *.blf - - - - Des Blowfish Key files: *.des, *.blf - - - - - - - - - - so|dll|0SO or DLL files: *.so, *.dll - - - - SO or DLL files: *.so, *.dll - - - - - - - - ggp|0GoldenGate Password files: *.ggp - - - - GoldenGate Password files: *.ggp - - - - - - - - - - - JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - - - - - - - Password for the KeyStore - - - - - - - - Password for the Server Certificate within the - KeyStore - - - - - - - - - - - - - JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - - - - - - - Password for the Trust KeyStore - - - - - - - - - - - - - JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - - - - - - - Password for the HTTP KeyStore - - - - - - - - - Password for the HTTP Server Certificate within - the HTTP KeyStore - - - - - - + + + + + + + + True + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + |2Any files: *.* + + + Any file path + + + + + + + + |1Directory: * + + + Any directory path + + + + + + + + + jks|jeks|0JKS Keystore files: *.jks, *.jeks + + + + JKS Keystore files: *.jks, *.jeks + + + + + + + + + xml|0XML files: *.xml + + + XML files: *.xml + + + + + + + + + des|blf|0Des Blowfish Key files: *.des, *.blf + + + + Des Blowfish Key files: *.des, *.blf + + + + + + + + + + so|dll|0SO or DLL files: *.so, *.dll + + + + SO or DLL files: *.so, *.dll + + + + + + + + ggp|0GoldenGate Password files: *.ggp + + + + GoldenGate Password files: *.ggp + + + + + + + + + + + JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + + + + + + + Password for the KeyStore + + + + + + + + Password for the Server Certificate within the + KeyStore + + + + + + + + + + + + + JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + + + + + + + Password for the Trust KeyStore + + + + + + + + + + + + + JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + + + + + + + Password for the HTTP KeyStore + + + + + + + + + Password for the HTTP Server Certificate within + the HTTP KeyStore + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-IdentityTypes.xsd b/src/main/xample/R66-IdentityTypes.xsd index df741556e..1faf91245 100644 --- a/src/main/xample/R66-IdentityTypes.xsd +++ b/src/main/xample/R66-IdentityTypes.xsd @@ -1,36 +1,36 @@ - - - - - - - - - - - - - - - - - -Authentication File containing Authentications for partners - - - - - - - - + + + + + + + + + + + + + + + + + +Authentication File containing Authentications for partners + + + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-LimitTypes.xsd b/src/main/xample/R66-LimitTypes.xsd index ba956c76a..1a012a1fa 100644 --- a/src/main/xample/R66-LimitTypes.xsd +++ b/src/main/xample/R66-LimitTypes.xsd @@ -1,452 +1,452 @@ - - - - - - - - - - - - - - - -Number of Threads on Server side (=Number of Cores) - - - - - - - - - -Number of Threads on Client side (=10xServer) - - - - - - - - - -Memory Limit for R66 Server Java Process - - - - - - - - - -Bandwidth for one session (64Mb) - - - - - - - - - -Global Bandwidth (512Mb) - - - - - - - - - -Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - - - - - - - - -Limit by batch of active transfers (10000) - - - - - - - - - -Delay between 2 execution of the Commander (5s) - - - - - - - - - -Delay between 2 attemps in case of error (30s) - - - - - - - - - -Delay before a Time Out occurs (30s) - - - - - - - - - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - - - - - - - - - - - - - -Gap to use when restarting a transfer as gap x blocksize - - - - - - - - - -Usage of NIO support for the files. According to the JDK, it can enhance the performances - - - - - - - - - -Usage of CPU Limitation when new request starts - - - - - - - - - -Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - - - - - - - - -Limit of CPU usage in percentage from 0 to 1 - - - - - - - - - -Limit of concurrent connections usage from 0 - - - - - - - - - -Low Limit of CPU usage in percentage from 0 to 1 - - - - - - - - - -High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated - - - - - - - - - -Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 - - - - - - - - - -Delay in ms, minimal as 500ms, best around 1000ms - - - - - - - - - - - - - - - -Low Limit of Bandwidth when decreasing from 4096 - - - - - - - - - -Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - - - - - - - - -If set to less or = 0, will not use Thrift support, if set greater than 0 (preferably greater than 1024) will enable Thrift support on the TCP port specified by this number - - - - - - - - - -New protocol extension using checkversion to check the compatibility - - - - - - - - - -Global digest by transfer enable - - - - - - + + + + + + + + + + + + + + + +Number of Threads on Server side (=Number of Cores) + + + + + + + + + +Number of Threads on Client side (=10xServer) + + + + + + + + + +Memory Limit for R66 Server Java Process + + + + + + + + + +Bandwidth for one session (64Mb) + + + + + + + + + +Global Bandwidth (512Mb) + + + + + + + + + +Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + + + + + + + + +Limit by batch of active transfers (10000) + + + + + + + + + +Delay between 2 execution of the Commander (5s) + + + + + + + + + +Delay between 2 attemps in case of error (30s) + + + + + + + + + +Delay before a Time Out occurs (30s) + + + + + + + + + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + + + + + + + + + + + + + +Gap to use when restarting a transfer as gap x blocksize + + + + + + + + + +Usage of NIO support for the files. According to the JDK, it can enhance the performances + + + + + + + + + +Usage of CPU Limitation when new request starts + + + + + + + + + +Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + + + + + + + + +Limit of CPU usage in percentage from 0 to 1 + + + + + + + + + +Limit of concurrent connections usage from 0 + + + + + + + + + +Low Limit of CPU usage in percentage from 0 to 1 + + + + + + + + + +High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated + + + + + + + + + +Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 + + + + + + + + + +Delay in ms, minimal as 500ms, best around 1000ms + + + + + + + + + + + + + + + +Low Limit of Bandwidth when decreasing from 4096 + + + + + + + + + +Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + + + + + + + + +If set to less or = 0, will not use Thrift support, if set greater than 0 (preferably greater than 1024) will enable Thrift support on the TCP port specified by this number + + + + + + + + + +New protocol extension using checkversion to check the compatibility + + + + + + + + + +Global digest by transfer enable + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-NetworkTypes.xsd b/src/main/xample/R66-NetworkTypes.xsd index f192ec3e5..83210a6d4 100644 --- a/src/main/xample/R66-NetworkTypes.xsd +++ b/src/main/xample/R66-NetworkTypes.xsd @@ -1,72 +1,72 @@ - - - - - - - - - - - - - - - -Port used in NON SSL mode - - - - - - - - - -Port used in SSL mode - - - - - - - - - -Port used for monitoring in HTTP mode - - - - - - - - - -Port used for Administrator access in HTTPS mode - - - - - - + + + + + + + + + + + + + + + +Port used in NON SSL mode + + + + + + + + + +Port used in SSL mode + + + + + + + + + +Port used for monitoring in HTTP mode + + + + + + + + + +Port used for Administrator access in HTTPS mode + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-RolesTypes.xsd b/src/main/xample/R66-RolesTypes.xsd index 3c85ed783..adb81ac87 100644 --- a/src/main/xample/R66-RolesTypes.xsd +++ b/src/main/xample/R66-RolesTypes.xsd @@ -1,65 +1,65 @@ - - - - - - - - - - - - -If specified for one host, this will override database roles for ALL hosts (from version 2.4.9). By default, local server should be added as role = FULLADMIN. - - - - - - - - - - -The host ids (1 by 1) that will override database roles - - - - - - - - - -The role assign to this host between NOACCESS,READONLY,TRANSFER,RULE,HOST,LIMIT,SYSTEM,LOGCONTROL,PARTNER(READONLY,TRANSFER),CONFIGADMIN(PARTNER,RULE,HOST),FULLADMIN(CONFIGADMIN,LIMIT,SYSTEM,LOGCONTROL) - - - - - - - - - - - - - - - + + + + + + + + + + + + +If specified for one host, this will override database roles for ALL hosts (from version 2.4.9). By default, local server should be added as role = FULLADMIN. + + + + + + + + + + +The host ids (1 by 1) that will override database roles + + + + + + + + + +The role assign to this host between NOACCESS,READONLY,TRANSFER,RULE,HOST,LIMIT,SYSTEM,LOGCONTROL,PARTNER(READONLY,TRANSFER),CONFIGADMIN(PARTNER,RULE,HOST),FULLADMIN(CONFIGADMIN,LIMIT,SYSTEM,LOGCONTROL) + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-RuleTypes.xsd b/src/main/xample/R66-RuleTypes.xsd index b3fa688e2..331165692 100644 --- a/src/main/xample/R66-RuleTypes.xsd +++ b/src/main/xample/R66-RuleTypes.xsd @@ -1,270 +1,270 @@ - - - - - - - - - - - - - - - - - - - - -Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP, FTP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." - - - - - - - Maximum delay for execution of the task in ms - - - - - - - - - - - - - - - - - - - - Rule ID - - - - - - - List of Host Ids allowed to use this rule. No Host Id means all allowed. - - - - - - - - Host ID allowed to use this rule - - - - - - - - - - 1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE - - - - - - - - Default Receive Directory - - - - - - - Default Send Directory - - - - - - - Default Archive Directory - - - - - - - Default Working Directory - - - - - - - List of tasks -if any- to execute before transfer on receiver side - - - - - - - - - - - - - List of tasks -if any- to execute after transfer on receiver side - - - - - - - - - - - - - List of tasks -if any- to execute after an error on receiver side - - - - - - - - - - - - - List of tasks -if any- to execute before transfer on sender side - - - - - - - - - - - - - List of tasks -if any- to execute after transfer on sender side - - - - - - - - - - - - - List of tasks -if any- to execute after an error on sender side - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + +Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP, FTP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." + + + + + + + Maximum delay for execution of the task in ms + + + + + + + + + + + + + + + + + + + + Rule ID + + + + + + + List of Host Ids allowed to use this rule. No Host Id means all allowed. + + + + + + + + Host ID allowed to use this rule + + + + + + + + + + 1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE + + + + + + + + Default Receive Directory + + + + + + + Default Send Directory + + + + + + + Default Archive Directory + + + + + + + Default Working Directory + + + + + + + List of tasks -if any- to execute before transfer on receiver side + + + + + + + + + + + + + List of tasks -if any- to execute after transfer on receiver side + + + + + + + + + + + + + List of tasks -if any- to execute after an error on receiver side + + + + + + + + + + + + + List of tasks -if any- to execute before transfer on sender side + + + + + + + + + + + + + List of tasks -if any- to execute after transfer on sender side + + + + + + + + + + + + + List of tasks -if any- to execute after an error on sender side + + + + + + + + + + + diff --git a/src/main/xample/R66-ServerTypes.xsd b/src/main/xample/R66-ServerTypes.xsd index fa91c3edc..e13c62cf8 100644 --- a/src/main/xample/R66-ServerTypes.xsd +++ b/src/main/xample/R66-ServerTypes.xsd @@ -1,245 +1,245 @@ - - - - - - - - - - - - - - - -Username for Administrator access - - - - - - - - - - GoldenGate Password File containing the password for Administrator access - - - - - - - - Password for Administrator access using Crypto Key - - - - - - - - - - -True (Default) if R66 will allow no SSL mode connection - - - - - - - - - -True if R66 will allow SSL mode connection - - - - - - - - - -True if Administrator (HTTPS) will allow HTTP compression - - - - - - - - - -By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemon tends to reach better performances through execution delegation - - - - - - - - - -Address of LocalExec Daemon - - - - - - - - - -Port of LocalExec Daemon - - - - - - - - - -Home Directory for HTTPS file support for Administrator - - - - - - - - - - - -True if R66 will check remote IP address while accepting a new connection - - - - - - - - - -True if R66 will check remote IP address also for remote Client - - - - - - - - - -Monitoring: how long in ms to get back in monitoring - - - - - - - - - -Monitoring: minimal interval in ms before redo real monitoring - - - - - - - - - -Configuration XML File for SNMP service - - - - - - - - - -Set the number of servers that act in the same group as a single instance of a OpenR66 File Transfer Monitor - - - - - - + + + + + + + + + + + + + + + +Username for Administrator access + + + + + + + + + + GoldenGate Password File containing the password for Administrator access + + + + + + + + Password for Administrator access using Crypto Key + + + + + + + + + + +True (Default) if R66 will allow no SSL mode connection + + + + + + + + + +True if R66 will allow SSL mode connection + + + + + + + + + +True if Administrator (HTTPS) will allow HTTP compression + + + + + + + + + +By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemon tends to reach better performances through execution delegation + + + + + + + + + +Address of LocalExec Daemon + + + + + + + + + +Port of LocalExec Daemon + + + + + + + + + +Home Directory for HTTPS file support for Administrator + + + + + + + + + + + +True if R66 will check remote IP address while accepting a new connection + + + + + + + + + +True if R66 will check remote IP address also for remote Client + + + + + + + + + +Monitoring: how long in ms to get back in monitoring + + + + + + + + + +Monitoring: minimal interval in ms before redo real monitoring + + + + + + + + + +Configuration XML File for SNMP service + + + + + + + + + +Set the number of servers that act in the same group as a single instance of a OpenR66 File Transfer Monitor + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-SslTypes.xsd b/src/main/xample/R66-SslTypes.xsd index aae868d05..30212ec73 100644 --- a/src/main/xample/R66-SslTypes.xsd +++ b/src/main/xample/R66-SslTypes.xsd @@ -1,38 +1,38 @@ - - - - - - - - - - - - - - - - - - - -True if R66 will only allow client through SSL authentication - - - - - - + + + + + + + + + + + + + + + + + + + +True if R66 will only allow client through SSL authentication + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-SubDbTypes.xsd b/src/main/xample/R66-SubDbTypes.xsd index 62abcd543..0b121f1ca 100644 --- a/src/main/xample/R66-SubDbTypes.xsd +++ b/src/main/xample/R66-SubDbTypes.xsd @@ -1,80 +1,80 @@ - - - - - - - - - - - - - - - -4 types of database are currently supported: oracle, mysql, postgresql, h2 - - - - - - - - - - - - - - - - - - - - - -Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - - - - - - - - - - - - - - -Database User - - - - - - - - - -Database User's Password - - - - - - + + + + + + + + + + + + + + + +4 types of database are currently supported: oracle, mysql, postgresql, h2 + + + + + + + + + + + + + + + + + + + + + +Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + + + + + + + + + + + + + + +Database User + + + + + + + + + +Database User's Password + + + + + + \ No newline at end of file diff --git a/src/main/xample/R66-SubIdentityTypes.xsd b/src/main/xample/R66-SubIdentityTypes.xsd index a12d9ea42..00e8984e9 100644 --- a/src/main/xample/R66-SubIdentityTypes.xsd +++ b/src/main/xample/R66-SubIdentityTypes.xsd @@ -1,57 +1,57 @@ - - - - - - - - - - - - - - - - -Host ID in NON SSL mode - - - - - - - - - -Host ID in SSL mode - - - - - - - - - -Des CryptoKey File containing the key in Des mode for R66 passwords - - - - - - + + + + + + + + + + + + + + + + +Host ID in NON SSL mode + + + + + + + + + +Host ID in SSL mode + + + + + + + + + +Des CryptoKey File containing the key in Des mode for R66 passwords + + + + + + \ No newline at end of file diff --git a/src/main/xample/SnmpConfiguration.xsd b/src/main/xample/SnmpConfiguration.xsd index 3b557e82c..f1d5e28f0 100644 --- a/src/main/xample/SnmpConfiguration.xsd +++ b/src/main/xample/SnmpConfiguration.xsd @@ -1,212 +1,212 @@ - - - - - - - - - - - - - - - - - - - Local Address to use as listen in format udp:address/port or tcp:address/port - - - - - - - Number of threads to use (4) - - - - - - - Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. - - - - - - - Use Trap (True) or Inform (False) when generating push event - - - - - - - Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning 5 Every events - - - - - - - - - - - - - - - - - Name To use as target - - - - - - - 1 Value between: UdpIpv4 UdpIpv6 UdpIpv4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z - - - - - - - - - - - - - - - - - - - - - - - - - - - - - As address/port as 192.168.0.1/162 - - - - - - - - - - - - - - Maximum delay to wait with an Inform mode event - - - - - - - Number of retries once the Inform is sent and not acknowledged - - - - - - - This entry is conformed with V2C or with V3 of SNMP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + Local Address to use as listen in format udp:address/port or tcp:address/port + + + + + + + Number of threads to use (4) + + + + + + + Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. + + + + + + + Use Trap (True) or Inform (False) when generating push event + + + + + + + Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning 5 Every events + + + + + + + + + + + + + + + + + Name To use as target + + + + + + + 1 Value between: UdpIpv4 UdpIpv6 UdpIpv4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + As address/port as 192.168.0.1/162 + + + + + + + + + + + + + + Maximum delay to wait with an Inform mode event + + + + + + + Number of retries once the Inform is sent and not acknowledged + + + + + + + This entry is conformed with V2C or with V3 of SNMP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/xample/jaxe-OpenR66-Authent-config.xml b/src/main/xample/jaxe-OpenR66-Authent-config.xml index 5425bd982..df3ed2aca 100644 --- a/src/main/xample/jaxe-OpenR66-Authent-config.xml +++ b/src/main/xample/jaxe-OpenR66-Authent-config.xml @@ -1,142 +1,142 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -authent - - -comment - - -entry -Used to initialize remote Hosts table at setup or with client with no database support - - -hostid -Host ID of remote Host - - -address -Address of remote host (IP or DNS entry) - - -port -Port associated with the Address of the remote Host - - -isssl -True if this Address Entry is for SSL mode - - -admin -True if this Address Entry allows Admin access through R66 Protocol. -Note from version 2.4.9, it could be override if roles are specified on general configuration file. - - -isclient -True if this Address Entry is for a Client - - -keyfile -GoldenGate Password File containing the password for this host - - -key - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +authent + + +comment + + +entry +Used to initialize remote Hosts table at setup or with client with no database support + + +hostid +Host ID of remote Host + + +address +Address of remote host (IP or DNS entry) + + +port +Port associated with the Address of the remote Host + + +isssl +True if this Address Entry is for SSL mode + + +admin +True if this Address Entry allows Admin access through R66 Protocol. +Note from version 2.4.9, it could be override if roles are specified on general configuration file. + + +isclient +True if this Address Entry is for a Client + + +keyfile +GoldenGate Password File containing the password for this host + + +key + + + diff --git a/src/main/xample/jaxe-OpenR66-Client-config.xml b/src/main/xample/jaxe-OpenR66-Client-config.xml index c31a294ce..03943b3da 100644 --- a/src/main/xample/jaxe-OpenR66-Client-config.xml +++ b/src/main/xample/jaxe-OpenR66-Client-config.xml @@ -1,466 +1,466 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -hostid - -Host ID in NON SSL mode - - - -sslhostid - -Host ID in SSL mode - - - -cryptokey - -Des CryptoKey File containing the key in Des mode for R66 passwords - - - -authentfile - -Authentication File containing Authentications for partners - - - -trustuseclientauthenticate - -True if R66 will only allow client through SSL authentication - - - -serverhome - -Home Directory for the OpenR66 Server (relative path to this Home) - - - -in - -Default Receive Directory - - - -out - -Default Send Directory - - - -arch - -Default Archive Directory - - - -work - -Default Working Directory - - - -conf - -Configuration Directory - - - -serverthread - -Number of Threads on Server side (=Number of Cores) - - - -clientthread - -Number of Threads on Client side (=10xServer) - - - -memorylimit - -Memory Limit for R66 Server Java Process - - - -sessionlimit - -Bandwidth for one session (64Mb) - - - -globallimit - -Global Bandwidth (512Mb) - - - -delaylimit - -Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - - -runlimit - -Limit by batch of active transfers (10000) - - - -delaycommand - -Delay between 2 execution of the Commander (5s) - - - -delayretry - -Delay between 2 attemps in case of error (30s) - - - -timeoutcon - -Delay before a Time Out occurs (30s) - - - -blocksize - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - -gaprestart - -Gap to use when restarting a transfer as gap x blocksize - - - -usenio - -Usage of NIO support for the files. According to the JDK, it can enhance the performances - - - -usecpulimit - -Usage of CPU Limitation when new request starts - - - -usejdkcpulimit - -Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - - -cpulimit - -Limit of CPU usage in percentage from 0 to 1 - - - -connlimit - -Limit of concurrent connections usage from 0 - - - -lowcpulimit - -Low Limit of CPU usage in percentage from 0 to 1 - - - -highcpulimit - -High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated - - - -percentdecrease - -Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 - - - -delaythrottle - -Delay in ms, minimal as 500ms, best around 1000ms - - - -limitlowbandwidth - -Low Limit of Bandwidth when decreasing from 4096 - - - -digest - -Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 - - - -usefastmd5 - -Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - - -dbdriver - -4 types of database are currently supported: oracle, mysql, postgresql, h2 - - - -dbserver - -Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - - -dbuser - -Database User - - - -dbpasswd - -Database User's Password - - - -businessids - -The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) - - - -config - - -comment - - -identity - - -client - - -taskrunnernodb -When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - -ssl - - -directory - - -limit - - -db - - -business - - -realid - -The real host id that will have aliases (locally) - - - -aliasid - -The set of aliases assign to this host separated by '|' or blank space - - - -aliases - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +hostid + +Host ID in NON SSL mode + + + +sslhostid + +Host ID in SSL mode + + + +cryptokey + +Des CryptoKey File containing the key in Des mode for R66 passwords + + + +authentfile + +Authentication File containing Authentications for partners + + + +trustuseclientauthenticate + +True if R66 will only allow client through SSL authentication + + + +serverhome + +Home Directory for the OpenR66 Server (relative path to this Home) + + + +in + +Default Receive Directory + + + +out + +Default Send Directory + + + +arch + +Default Archive Directory + + + +work + +Default Working Directory + + + +conf + +Configuration Directory + + + +serverthread + +Number of Threads on Server side (=Number of Cores) + + + +clientthread + +Number of Threads on Client side (=10xServer) + + + +memorylimit + +Memory Limit for R66 Server Java Process + + + +sessionlimit + +Bandwidth for one session (64Mb) + + + +globallimit + +Global Bandwidth (512Mb) + + + +delaylimit + +Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + + +runlimit + +Limit by batch of active transfers (10000) + + + +delaycommand + +Delay between 2 execution of the Commander (5s) + + + +delayretry + +Delay between 2 attemps in case of error (30s) + + + +timeoutcon + +Delay before a Time Out occurs (30s) + + + +blocksize + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + +gaprestart + +Gap to use when restarting a transfer as gap x blocksize + + + +usenio + +Usage of NIO support for the files. According to the JDK, it can enhance the performances + + + +usecpulimit + +Usage of CPU Limitation when new request starts + + + +usejdkcpulimit + +Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + + +cpulimit + +Limit of CPU usage in percentage from 0 to 1 + + + +connlimit + +Limit of concurrent connections usage from 0 + + + +lowcpulimit + +Low Limit of CPU usage in percentage from 0 to 1 + + + +highcpulimit + +High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated + + + +percentdecrease + +Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 + + + +delaythrottle + +Delay in ms, minimal as 500ms, best around 1000ms + + + +limitlowbandwidth + +Low Limit of Bandwidth when decreasing from 4096 + + + +digest + +Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 + + + +usefastmd5 + +Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + + +dbdriver + +4 types of database are currently supported: oracle, mysql, postgresql, h2 + + + +dbserver + +Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + + +dbuser + +Database User + + + +dbpasswd + +Database User's Password + + + +businessids + +The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) + + + +config + + +comment + + +identity + + +client + + +taskrunnernodb +When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + +ssl + + +directory + + +limit + + +db + + +business + + +realid + +The real host id that will have aliases (locally) + + + +aliasid + +The set of aliases assign to this host separated by '|' or blank space + + + +aliases + + + diff --git a/src/main/xample/jaxe-OpenR66-ClientNoDB-config.xml b/src/main/xample/jaxe-OpenR66-ClientNoDB-config.xml index 647c5e4ec..3da6e6052 100644 --- a/src/main/xample/jaxe-OpenR66-ClientNoDB-config.xml +++ b/src/main/xample/jaxe-OpenR66-ClientNoDB-config.xml @@ -1,434 +1,434 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -hostid - -Host ID in NON SSL mode - - - -sslhostid - -Host ID in SSL mode - - - -cryptokey - -Des CryptoKey File containing the key in Des mode for R66 passwords - - - -authentfile - -Authentication File containing Authentications for partners - - - -trustuseclientauthenticate - -True if R66 will only allow client through SSL authentication - - - -serverhome - -Home Directory for the OpenR66 Server (relative path to this Home) - - - -in - -Default Receive Directory - - - -out - -Default Send Directory - - - -arch - -Default Archive Directory - - - -work - -Default Working Directory - - - -conf - -Configuration Directory - - - -serverthread - -Number of Threads on Server side (=Number of Cores) - - - -clientthread - -Number of Threads on Client side (=10xServer) - - - -memorylimit - -Memory Limit for R66 Server Java Process - - - -sessionlimit - -Bandwidth for one session (64Mb) - - - -globallimit - -Global Bandwidth (512Mb) - - - -delaylimit - -Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - - -runlimit - -Limit by batch of active transfers (10000) - - - -delaycommand - -Delay between 2 execution of the Commander (5s) - - - -delayretry - -Delay between 2 attemps in case of error (30s) - - - -timeoutcon - -Delay before a Time Out occurs (30s) - - - -blocksize - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - -gaprestart - -Gap to use when restarting a transfer as gap x blocksize - - - -usenio - -Usage of NIO support for the files. According to the JDK, it can enhance the performances - - - -usecpulimit - -Usage of CPU Limitation when new request starts - - - -usejdkcpulimit - -Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - - -cpulimit - -Limit of CPU usage in percentage from 0 to 1 - - - -connlimit - -Limit of concurrent connections usage from 0 - - - -lowcpulimit - -Low Limit of CPU usage in percentage from 0 to 1 - - - -highcpulimit - -High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated - - - -percentdecrease - -Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 - - - -delaythrottle - -Delay in ms, minimal as 500ms, best around 1000ms - - - -limitlowbandwidth - -Low Limit of Bandwidth when decreasing from 4096 - - - -digest - -Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 - - - -usefastmd5 - -Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - - -businessids - -The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) - - - -config - - -comment - - -identity - - -client - - -taskrunnernodb -When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - -ssl - - -directory - - -limit - - -db - - -business - - -realid - -The real host id that will have aliases (locally) - - - -aliasid - -The set of aliases assign to this host separated by '|' or blank space - - - -aliases - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +hostid + +Host ID in NON SSL mode + + + +sslhostid + +Host ID in SSL mode + + + +cryptokey + +Des CryptoKey File containing the key in Des mode for R66 passwords + + + +authentfile + +Authentication File containing Authentications for partners + + + +trustuseclientauthenticate + +True if R66 will only allow client through SSL authentication + + + +serverhome + +Home Directory for the OpenR66 Server (relative path to this Home) + + + +in + +Default Receive Directory + + + +out + +Default Send Directory + + + +arch + +Default Archive Directory + + + +work + +Default Working Directory + + + +conf + +Configuration Directory + + + +serverthread + +Number of Threads on Server side (=Number of Cores) + + + +clientthread + +Number of Threads on Client side (=10xServer) + + + +memorylimit + +Memory Limit for R66 Server Java Process + + + +sessionlimit + +Bandwidth for one session (64Mb) + + + +globallimit + +Global Bandwidth (512Mb) + + + +delaylimit + +Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + + +runlimit + +Limit by batch of active transfers (10000) + + + +delaycommand + +Delay between 2 execution of the Commander (5s) + + + +delayretry + +Delay between 2 attemps in case of error (30s) + + + +timeoutcon + +Delay before a Time Out occurs (30s) + + + +blocksize + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + +gaprestart + +Gap to use when restarting a transfer as gap x blocksize + + + +usenio + +Usage of NIO support for the files. According to the JDK, it can enhance the performances + + + +usecpulimit + +Usage of CPU Limitation when new request starts + + + +usejdkcpulimit + +Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + + +cpulimit + +Limit of CPU usage in percentage from 0 to 1 + + + +connlimit + +Limit of concurrent connections usage from 0 + + + +lowcpulimit + +Low Limit of CPU usage in percentage from 0 to 1 + + + +highcpulimit + +High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated + + + +percentdecrease + +Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 + + + +delaythrottle + +Delay in ms, minimal as 500ms, best around 1000ms + + + +limitlowbandwidth + +Low Limit of Bandwidth when decreasing from 4096 + + + +digest + +Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 + + + +usefastmd5 + +Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + + +businessids + +The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) + + + +config + + +comment + + +identity + + +client + + +taskrunnernodb +When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + +ssl + + +directory + + +limit + + +db + + +business + + +realid + +The real host id that will have aliases (locally) + + + +aliasid + +The set of aliases assign to this host separated by '|' or blank space + + + +aliases + + + diff --git a/src/main/xample/jaxe-OpenR66-Limit-config.xml b/src/main/xample/jaxe-OpenR66-Limit-config.xml index ad3dadbd2..9d19c73e4 100644 --- a/src/main/xample/jaxe-OpenR66-Limit-config.xml +++ b/src/main/xample/jaxe-OpenR66-Limit-config.xml @@ -1,140 +1,140 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -config - - -comment - - -identity - - -hostid -Host ID in NON SSL mode - - -limit - - -sessionlimit -Bandwidth for one session (64Mb) - - -globallimit -Global Bandwidth (512Mb) - - -delaylimit -Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - -runlimit -Limit by batch of active transfers (10000) - - -delaycommand -Delay between 2 execution of the Commander (5s) - - -delayretry -Delay between 2 attemps in case of error (30s) - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +config + + +comment + + +identity + + +hostid +Host ID in NON SSL mode + + +limit + + +sessionlimit +Bandwidth for one session (64Mb) + + +globallimit +Global Bandwidth (512Mb) + + +delaylimit +Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + +runlimit +Limit by batch of active transfers (10000) + + +delaycommand +Delay between 2 execution of the Commander (5s) + + +delayretry +Delay between 2 attemps in case of error (30s) + + + diff --git a/src/main/xample/jaxe-OpenR66-Rule-config.xml b/src/main/xample/jaxe-OpenR66-Rule-config.xml index 0c048f23a..2d69396fe 100644 --- a/src/main/xample/jaxe-OpenR66-Rule-config.xml +++ b/src/main/xample/jaxe-OpenR66-Rule-config.xml @@ -1,202 +1,202 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -tasks - - -task - - -type - -Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP - - - -path -Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." - - -delay -Maximum delay for execution of the task in ms - - -comment - - -idrule -Rule ID - - -hostids -List of Host Ids allowed to use this rule. No Host Id means all allowed. - - -hostid -Host ID allowed to use this rule - - -mode -1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE - - -recvpath -Default Receive Directory - - -sendpath -Default Send Directory - - -archivepath -Default Archive Directory - - -workpath -Default Working Directory - - -rpretasks -List of tasks -if any- to execute before transfer on receiver side - - -rposttasks -List of tasks -if any- to execute after transfer on receiver side - - -rerrortasks -List of tasks -if any- to execute after an error on receiver side - - -spretasks -List of tasks -if any- to execute before transfer on sender side - - -sposttasks -List of tasks -if any- to execute after transfer on sender side - - -serrortasks -List of tasks -if any- to execute after an error on sender side - - -rule - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +tasks + + +task + + +type + +Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP + + + +path +Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." + + +delay +Maximum delay for execution of the task in ms + + +comment + + +idrule +Rule ID + + +hostids +List of Host Ids allowed to use this rule. No Host Id means all allowed. + + +hostid +Host ID allowed to use this rule + + +mode +1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE + + +recvpath +Default Receive Directory + + +sendpath +Default Send Directory + + +archivepath +Default Archive Directory + + +workpath +Default Working Directory + + +rpretasks +List of tasks -if any- to execute before transfer on receiver side + + +rposttasks +List of tasks -if any- to execute after transfer on receiver side + + +rerrortasks +List of tasks -if any- to execute after an error on receiver side + + +spretasks +List of tasks -if any- to execute before transfer on sender side + + +sposttasks +List of tasks -if any- to execute after transfer on sender side + + +serrortasks +List of tasks -if any- to execute after an error on sender side + + +rule + + + diff --git a/src/main/xample/jaxe-OpenR66-Rules-config.xml b/src/main/xample/jaxe-OpenR66-Rules-config.xml index 34fb4ddc3..c452ffc06 100644 --- a/src/main/xample/jaxe-OpenR66-Rules-config.xml +++ b/src/main/xample/jaxe-OpenR66-Rules-config.xml @@ -1,207 +1,207 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -tasks - - -task - - -type - -Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP - - - -path -Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." - - -delay -Maximum delay for execution of the task in ms - - -comment - - -idrule -Rule ID - - -hostids -List of Host Ids allowed to use this rule. No Host Id means all allowed. - - -hostid -Host ID allowed to use this rule - - -mode -1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE - - -recvpath -Default Receive Directory - - -sendpath -Default Send Directory - - -archivepath -Default Archive Directory - - -workpath -Default Working Directory - - -rpretasks -List of tasks -if any- to execute before transfer on receiver side - - -rposttasks -List of tasks -if any- to execute after transfer on receiver side - - -rerrortasks -List of tasks -if any- to execute after an error on receiver side - - -spretasks -List of tasks -if any- to execute before transfer on sender side - - -sposttasks -List of tasks -if any- to execute after transfer on sender side - - -serrortasks -List of tasks -if any- to execute after an error on sender side - - -rules - - -rule - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +tasks + + +task + + +type + +Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECOUTPUT, EXECJAVA, TRANSFER, VALIDFILEPATH, DELETE, LINKRENAME, RESCHEDULE, TAR, ZIP, TRANSCODE, SNMP + + + +path +Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ..." + + +delay +Maximum delay for execution of the task in ms + + +comment + + +idrule +Rule ID + + +hostids +List of Host Ids allowed to use this rule. No Host Id means all allowed. + + +hostid +Host ID allowed to use this rule + + +mode +1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 5=SENDTHROUGHMODE 6=RECVTHROUGHMODE 7=SENDMD5THROUGHMODE 8=RECVMD5THROUGHMODE + + +recvpath +Default Receive Directory + + +sendpath +Default Send Directory + + +archivepath +Default Archive Directory + + +workpath +Default Working Directory + + +rpretasks +List of tasks -if any- to execute before transfer on receiver side + + +rposttasks +List of tasks -if any- to execute after transfer on receiver side + + +rerrortasks +List of tasks -if any- to execute after an error on receiver side + + +spretasks +List of tasks -if any- to execute before transfer on sender side + + +sposttasks +List of tasks -if any- to execute after transfer on sender side + + +serrortasks +List of tasks -if any- to execute after an error on sender side + + +rules + + +rule + + + diff --git a/src/main/xample/jaxe-OpenR66-Server-config.xml b/src/main/xample/jaxe-OpenR66-Server-config.xml index 6049de75c..87a48b376 100644 --- a/src/main/xample/jaxe-OpenR66-Server-config.xml +++ b/src/main/xample/jaxe-OpenR66-Server-config.xml @@ -1,684 +1,684 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -hostid - -Host ID in NON SSL mode - - - -sslhostid - -Host ID in SSL mode - - - -cryptokey - -Des CryptoKey File containing the key in Des mode for R66 passwords - - - -authentfile - -Authentication File containing Authentications for partners - - - -serveradmin - -Username for Administrator access - - - -serverpasswdfile -GoldenGate Password File containing the password for Administrator access - - -serverpasswd - - Password for Administrator access using Crypto Key - - - -usenossl - -True (Default) if R66 will allow no SSL mode connection - - - -usessl - -True if R66 will allow SSL mode connection - - - -usehttpcomp - -True if Administrator (HTTPS) will allow HTTP compression - - - -uselocalexec - -By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemon tends to reach better performances through execution delegation - - - -lexecaddr - -Address of LocalExec Daemon - - - -lexecport - -Port of LocalExec Daemon - - - -httpadmin - -Home Directory for HTTPS file support for Administrator - - - -checkaddress - -True if R66 will check remote IP address while accepting a new connection - - - -checkclientaddress - -True if R66 will check remote IP address also for remote Client - - - -pastlimit - -Monitoring: how long in ms to get back in monitoring - - - -minimaldelay - -Monitoring: minimal interval in ms before redo real monitoring - - - -snmpconfig - -Configuration XML File for SNMP service - - - -multiplemonitors - -Set the number of servers that act in the same group as a single instance of a OpenR66 File Transfer Monitor - - - -serverport - -Port used in NON SSL mode - - - -serversslport - -Port used in SSL mode - - - -serverhttpport - -Port used for monitoring in HTTP mode - - - -serverhttpsport - -Port used for Administrator access in HTTPS mode - - - -trustuseclientauthenticate - -True if R66 will only allow client through SSL authentication - - - -serverhome - -Home Directory for the OpenR66 Server (relative path to this Home) - - - -in - -Default Receive Directory - - - -out - -Default Send Directory - - - -arch - -Default Archive Directory - - - -work - -Default Working Directory - - - -conf - -Configuration Directory - - - -serverthread - -Number of Threads on Server side (=Number of Cores) - - - -clientthread - -Number of Threads on Client side (=10xServer) - - - -memorylimit - -Memory Limit for R66 Server Java Process - - - -sessionlimit - -Bandwidth for one session (64Mb) - - - -globallimit - -Global Bandwidth (512Mb) - - - -delaylimit - -Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - - -runlimit - -Limit by batch of active transfers (10000) - - - -delaycommand - -Delay between 2 execution of the Commander (5s) - - - -delayretry - -Delay between 2 attemps in case of error (30s) - - - -timeoutcon - -Delay before a Time Out occurs (30s) - - - -blocksize - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - -gaprestart - -Gap to use when restarting a transfer as gap x blocksize - - - -usenio - -Usage of NIO support for the files. According to the JDK, it can enhance the performances - - - -usecpulimit - -Usage of CPU Limitation when new request starts - - - -usejdkcpulimit - -Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - - -cpulimit - -Limit of CPU usage in percentage from 0 to 1 - - - -connlimit - -Limit of concurrent connections usage from 0 - - - -lowcpulimit - -Low Limit of CPU usage in percentage from 0 to 1 - - - -highcpulimit - -High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated - - - -percentdecrease - -Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 - - - -delaythrottle - -Delay in ms, minimal as 500ms, best around 1000ms - - - -limitlowbandwidth - -Low Limit of Bandwidth when decreasing from 4096 - - - -digest - -Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 - - - -usefastmd5 - -Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - - -usethrift - -If set to less or = 0, will not use Thrift support, if set greater than 0 (preferably greater than 1024) will enable Thrift support on the TCP port specified by this number - - - -checkversion - -New protocol extension using checkversion to check the compatibility - - - -globaldigest - -Global digest by transfer enable - - - -dbdriver - -4 types of database are currently supported: oracle, mysql, postgresql, h2 - - - -dbserver - -Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - - -dbuser - -Database User - - - -dbpasswd - -Database User's Password - - - -taskrunnernodb - -When a server with no DB, do R66 will use XML files as permanent information on Transfer Tasks - - - -businessids - -The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) - - - -role - -If specified for one host, this will override database roles for ALL hosts (from version 2.4.9). By default, local server should be added as role = FULLADMIN. - - - -roleid - -The host ids (1 by 1) that will override database roles - - - -roleset - -The role assign to this host between NOACCESS,READONLY,TRANSFER,RULE,HOST,LIMIT,SYSTEM,LOGCONTROL,PARTNER(READONLY,TRANSFER),CONFIGADMIN(PARTNER,RULE,HOST),FULLADMIN(CONFIGADMIN,LIMIT,SYSTEM,LOGCONTROL) - - - -realid - -The real host id that will have aliases (locally) - - - -aliasid - -The set of aliases assign to this host separated by '|' or blank space - - - -config - - -comment - - -identity - - -server - - -network - - -ssl - - -directory - - -limit - - -db - - -business - - -roles - - -aliases - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +hostid + +Host ID in NON SSL mode + + + +sslhostid + +Host ID in SSL mode + + + +cryptokey + +Des CryptoKey File containing the key in Des mode for R66 passwords + + + +authentfile + +Authentication File containing Authentications for partners + + + +serveradmin + +Username for Administrator access + + + +serverpasswdfile +GoldenGate Password File containing the password for Administrator access + + +serverpasswd + + Password for Administrator access using Crypto Key + + + +usenossl + +True (Default) if R66 will allow no SSL mode connection + + + +usessl + +True if R66 will allow SSL mode connection + + + +usehttpcomp + +True if Administrator (HTTPS) will allow HTTP compression + + + +uselocalexec + +By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemon tends to reach better performances through execution delegation + + + +lexecaddr + +Address of LocalExec Daemon + + + +lexecport + +Port of LocalExec Daemon + + + +httpadmin + +Home Directory for HTTPS file support for Administrator + + + +checkaddress + +True if R66 will check remote IP address while accepting a new connection + + + +checkclientaddress + +True if R66 will check remote IP address also for remote Client + + + +pastlimit + +Monitoring: how long in ms to get back in monitoring + + + +minimaldelay + +Monitoring: minimal interval in ms before redo real monitoring + + + +snmpconfig + +Configuration XML File for SNMP service + + + +multiplemonitors + +Set the number of servers that act in the same group as a single instance of a OpenR66 File Transfer Monitor + + + +serverport + +Port used in NON SSL mode + + + +serversslport + +Port used in SSL mode + + + +serverhttpport + +Port used for monitoring in HTTP mode + + + +serverhttpsport + +Port used for Administrator access in HTTPS mode + + + +trustuseclientauthenticate + +True if R66 will only allow client through SSL authentication + + + +serverhome + +Home Directory for the OpenR66 Server (relative path to this Home) + + + +in + +Default Receive Directory + + + +out + +Default Send Directory + + + +arch + +Default Archive Directory + + + +work + +Default Working Directory + + + +conf + +Configuration Directory + + + +serverthread + +Number of Threads on Server side (=Number of Cores) + + + +clientthread + +Number of Threads on Client side (=10xServer) + + + +memorylimit + +Memory Limit for R66 Server Java Process + + + +sessionlimit + +Bandwidth for one session (64Mb) + + + +globallimit + +Global Bandwidth (512Mb) + + + +delaylimit + +Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + + +runlimit + +Limit by batch of active transfers (10000) + + + +delaycommand + +Delay between 2 execution of the Commander (5s) + + + +delayretry + +Delay between 2 attemps in case of error (30s) + + + +timeoutcon + +Delay before a Time Out occurs (30s) + + + +blocksize + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + +gaprestart + +Gap to use when restarting a transfer as gap x blocksize + + + +usenio + +Usage of NIO support for the files. According to the JDK, it can enhance the performances + + + +usecpulimit + +Usage of CPU Limitation when new request starts + + + +usejdkcpulimit + +Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + + +cpulimit + +Limit of CPU usage in percentage from 0 to 1 + + + +connlimit + +Limit of concurrent connections usage from 0 + + + +lowcpulimit + +Low Limit of CPU usage in percentage from 0 to 1 + + + +highcpulimit + +High Limit of CPU usage in percentage from 0 to 1, 0 meaning no throttle activated + + + +percentdecrease + +Decrease/Increase of bandwidth when limits are reached in percentage from 0 to 1 + + + +delaythrottle + +Delay in ms, minimal as 500ms, best around 1000ms + + + +limitlowbandwidth + +Low Limit of Bandwidth when decreasing from 4096 + + + +digest + +Digest to use: CRC32=0, ADLER32=1, MD5=2, MD2=3, SHA1=4, SHA256=5, SHA384=6, SHA512=7 + + + +usefastmd5 + +Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + + +usethrift + +If set to less or = 0, will not use Thrift support, if set greater than 0 (preferably greater than 1024) will enable Thrift support on the TCP port specified by this number + + + +checkversion + +New protocol extension using checkversion to check the compatibility + + + +globaldigest + +Global digest by transfer enable + + + +dbdriver + +4 types of database are currently supported: oracle, mysql, postgresql, h2 + + + +dbserver + +Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + + +dbuser + +Database User + + + +dbpasswd + +Database User's Password + + + +taskrunnernodb + +When a server with no DB, do R66 will use XML files as permanent information on Transfer Tasks + + + +businessids + +The host ids (1 by 1) that will be allow to use Business Requests (from version 2.3) + + + +role + +If specified for one host, this will override database roles for ALL hosts (from version 2.4.9). By default, local server should be added as role = FULLADMIN. + + + +roleid + +The host ids (1 by 1) that will override database roles + + + +roleset + +The role assign to this host between NOACCESS,READONLY,TRANSFER,RULE,HOST,LIMIT,SYSTEM,LOGCONTROL,PARTNER(READONLY,TRANSFER),CONFIGADMIN(PARTNER,RULE,HOST),FULLADMIN(CONFIGADMIN,LIMIT,SYSTEM,LOGCONTROL) + + + +realid + +The real host id that will have aliases (locally) + + + +aliasid + +The set of aliases assign to this host separated by '|' or blank space + + + +config + + +comment + + +identity + + +server + + +network + + +ssl + + +directory + + +limit + + +db + + +business + + +roles + + +aliases + + + diff --git a/src/main/xample/jaxe-OpenR66-SubmitClient-config.xml b/src/main/xample/jaxe-OpenR66-SubmitClient-config.xml index 507c04169..8a82703c0 100644 --- a/src/main/xample/jaxe-OpenR66-SubmitClient-config.xml +++ b/src/main/xample/jaxe-OpenR66-SubmitClient-config.xml @@ -1,237 +1,237 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -hostid - -Host ID in NON SSL mode - - - -sslhostid - -Host ID in SSL mode - - - -cryptokey - -Des CryptoKey File containing the key in Des mode for R66 passwords - - - -serverhome - -Home Directory for the OpenR66 Server (relative path to this Home) - - - -in - -Default Receive Directory - - - -out - -Default Send Directory - - - -arch - -Default Archive Directory - - - -work - -Default Working Directory - - - -conf - -Configuration Directory - - - -dbdriver - -4 types of database are currently supported: oracle, mysql, postgresql, h2 - - - -dbserver - -Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - - -dbuser - -Database User - - - -dbpasswd - -Database User's Password - - - -config - - -comment - - -identity - - -directory - - -limit - - -blocksize - -Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - - -db - - -realid - -The real host id that will have aliases (locally) - - - -aliasid - -The set of aliases assign to this host separated by '|' or blank space - - - -aliases - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +hostid + +Host ID in NON SSL mode + + + +sslhostid + +Host ID in SSL mode + + + +cryptokey + +Des CryptoKey File containing the key in Des mode for R66 passwords + + + +serverhome + +Home Directory for the OpenR66 Server (relative path to this Home) + + + +in + +Default Receive Directory + + + +out + +Default Send Directory + + + +arch + +Default Archive Directory + + + +work + +Default Working Directory + + + +conf + +Configuration Directory + + + +dbdriver + +4 types of database are currently supported: oracle, mysql, postgresql, h2 + + + +dbserver + +Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + + +dbuser + +Database User + + + +dbpasswd + +Database User's Password + + + +config + + +comment + + +identity + + +directory + + +limit + + +blocksize + +Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + + +db + + +realid + +The real host id that will have aliases (locally) + + + +aliasid + +The set of aliases assign to this host separated by '|' or blank space + + + +aliases + + + diff --git a/src/main/xample/jaxe-SnmpConfiguration-config.xml b/src/main/xample/jaxe-SnmpConfiguration-config.xml index 9ef44937e..82741acb9 100644 --- a/src/main/xample/jaxe-SnmpConfiguration-config.xml +++ b/src/main/xample/jaxe-SnmpConfiguration-config.xml @@ -1,205 +1,205 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -??? - -keypath -JKS KeyStore for R66 Access in SSL Mode - (containing Server Certificate) - - - -keystorepass -Password for the KeyStore - - -keypass -Password for the Server Certificate within the - KeyStore - - - -trustkeypath -JKS Trust KeyStore for R66 Access in SSL Mode - with Client Authentication (containing Client Certificate) - - - -trustkeystorepass -Password for the Trust KeyStore - - - -admkeypath -JKS HTTP KeyStore for Administrator Access in - HTTPS Mode (containing Server Certificate) - - - -admkeystorepass -Password for the HTTP KeyStore - - - -admkeypass -Password for the HTTP Server Certificate within - the HTTP KeyStore - - - -snmpconfig - - -comment - - -config - - -localaddress -Local Address to use as listen in format udp:address/port or tcp:address/port - - -nbthread -Number of threads to use (4) - - -filtered -Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. - - -usetrap -Use Trap (True) or Inform (False) when generating push event - - -trapinformlevel -Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning 5 Every events - - -targets - - -target - - -name -Name To use as target - - -domain -1 Value between: UdpIpv4 UdpIpv6 UdpIpv4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z - - - -address -As address/port as 192.168.0.1/162 - - -timeout -Maximum delay to wait with an Inform mode event - - -retries -Number of retries once the Inform is sent and not acknowledged - - -isv2 -This entry is conformed with V2C or with V3 of SNMP - - -securities - - -security - - -securityname - - -securityauthprotocol - - -securityauthpass - - -securityprivprotocol - - -securityprivpass - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +??? + +keypath +JKS KeyStore for R66 Access in SSL Mode + (containing Server Certificate) + + + +keystorepass +Password for the KeyStore + + +keypass +Password for the Server Certificate within the + KeyStore + + + +trustkeypath +JKS Trust KeyStore for R66 Access in SSL Mode + with Client Authentication (containing Client Certificate) + + + +trustkeystorepass +Password for the Trust KeyStore + + + +admkeypath +JKS HTTP KeyStore for Administrator Access in + HTTPS Mode (containing Server Certificate) + + + +admkeystorepass +Password for the HTTP KeyStore + + + +admkeypass +Password for the HTTP Server Certificate within + the HTTP KeyStore + + + +snmpconfig + + +comment + + +config + + +localaddress +Local Address to use as listen in format udp:address/port or tcp:address/port + + +nbthread +Number of threads to use (4) + + +filtered +Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. + + +usetrap +Use Trap (True) or Inform (False) when generating push event + + +trapinformlevel +Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning 5 Every events + + +targets + + +target + + +name +Name To use as target + + +domain +1 Value between: UdpIpv4 UdpIpv6 UdpIpv4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z + + + +address +As address/port as 192.168.0.1/162 + + +timeout +Maximum delay to wait with an Inform mode event + + +retries +Number of retries once the Inform is sent and not acknowledged + + +isv2 +This entry is conformed with V2C or with V3 of SNMP + + +securities + + +security + + +securityname + + +securityauthprotocol + + +securityauthpass + + +securityprivprotocol + + +securityprivpass + + + diff --git a/src/site/apt/Config-OpenR66-Client.apt b/src/site/apt/Config-OpenR66-Client.apt index 015505a1d..68f1ef4fe 100644 --- a/src/site/apt/Config-OpenR66-Client.apt +++ b/src/site/apt/Config-OpenR66-Client.apt @@ -1,177 +1,177 @@ -OpenR66 Client Configuration File - -*config - - *comment:string Optional - -**identity - - *hostid:nonEmptyString - - Host ID in NON SSL mode - - *sslhostid:nonEmptyString Optional - - Host ID in SSL mode - - *cryptokey:Des-File - - Des CryptoKey File containing the key in Des mode for R66 passwords - - *authentfile:XML-File Optional - - Authentication File containing Authentications for partners - -**client Optional - - *taskrunnernodb:booleanType Optional default="False" - - When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - -**ssl Optional - - *keypath:JKS-File - - JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) - - *keystorepass:nonEmptyString - - Password for the KeyStore - - *keypass:nonEmptyString - - Password for the Server Certificate within the KeyStore - - *trustkeypath:JKS-File - - JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) - - *trustkeystorepass:nonEmptyString - - Password for the Trust KeyStore - - *trustuseclientauthenticate:booleanType default="False" - - True if R66 will only allow client through SSL authentication - -**directory - - *serverhome:directoryType - - Home Directory for the OpenR66 Server (relative path to this Home) - - *in:nonEmptyString Optional default="IN" - - Default Receive Directory - - *out:nonEmptyString Optional default="OUT" - - Default Send Directory - - *arch:nonEmptyString Optional default="ARCH" - - Default Archive Directory - - *work:nonEmptyString Optional default="WORK" - - Default Working Directory - - *conf:nonEmptyString Optional default="CONF" - - Configuration Directory - -**limit - - *serverthread:nonNulInteger default="8" Optional - - Number of Threads on Server side (=Number of Cores) - - *clientthread:nonNulInteger default="80" Optional - - Number of Threads on Client side (=10xServer) - - *memorylimit:nonNulInteger default="4000000000" Optional - - Memory Limit for R66 Server Java Process - - *sessionlimit:nonNegInteger default="8388608" Optional - - HBandwidth for one session (64Mb) - - *globallimit:nonNegInteger default="67108864" Optional - - Global Bandwidth (512Mb) - - *delaylimit:nonNulInteger default="10000" Optional - - Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - *runlimit:nonNulInteger default="10000" Optional - - Limite by batch of active transfers (10000) - - *delaycommand:nonNulInteger default="5000" Optional - - Delay between 2 execution of the Commander (5s) - - *delayretry:nonNulInteger default="30000" Optional - - Delay between 2 attemps in case of error (30s) - - *timeoutcon:nonNulInteger default="30000" Optional - - Delay before a Time Out occurs (30s) - - *blocksize:nonNulInteger default="65536" Optional - - Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - *gaprestart:nonNulInteger default="30" Optional - - Gap to use when restarting a transfer as gap x blocksize - - *usenio:booleanType default="False" Optional - - Usage of NIO support for the files. According to the JDK, it can enhance the performances - - *usecpulimit:booleanType default="False" Optional - - Usage of CPU Limitation when new request starts - - *usejdkcpulimit:booleanType default="False" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *cpulimit:decimalType default="0.0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *connlimit:nonNegInteger default="0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *usefastmd5:booleanType default="True" - - Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - *fastmd5:SODLL-File Optional - - Library JNI Filepath. If the path is empty, the pure Java version will be used - -**db Optional - - *dbdriver:address - - 4 types of database are currently supported: oracle, mysql, postgresql, h2 - - *dbserver:normString - - Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - *dbuser:address - - Database User - - *dbpasswd:nonEmptyString - - Database User's Password +OpenR66 Client Configuration File + +*config + + *comment:string Optional + +**identity + + *hostid:nonEmptyString + + Host ID in NON SSL mode + + *sslhostid:nonEmptyString Optional + + Host ID in SSL mode + + *cryptokey:Des-File + + Des CryptoKey File containing the key in Des mode for R66 passwords + + *authentfile:XML-File Optional + + Authentication File containing Authentications for partners + +**client Optional + + *taskrunnernodb:booleanType Optional default="False" + + When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + +**ssl Optional + + *keypath:JKS-File + + JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) + + *keystorepass:nonEmptyString + + Password for the KeyStore + + *keypass:nonEmptyString + + Password for the Server Certificate within the KeyStore + + *trustkeypath:JKS-File + + JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) + + *trustkeystorepass:nonEmptyString + + Password for the Trust KeyStore + + *trustuseclientauthenticate:booleanType default="False" + + True if R66 will only allow client through SSL authentication + +**directory + + *serverhome:directoryType + + Home Directory for the OpenR66 Server (relative path to this Home) + + *in:nonEmptyString Optional default="IN" + + Default Receive Directory + + *out:nonEmptyString Optional default="OUT" + + Default Send Directory + + *arch:nonEmptyString Optional default="ARCH" + + Default Archive Directory + + *work:nonEmptyString Optional default="WORK" + + Default Working Directory + + *conf:nonEmptyString Optional default="CONF" + + Configuration Directory + +**limit + + *serverthread:nonNulInteger default="8" Optional + + Number of Threads on Server side (=Number of Cores) + + *clientthread:nonNulInteger default="80" Optional + + Number of Threads on Client side (=10xServer) + + *memorylimit:nonNulInteger default="4000000000" Optional + + Memory Limit for R66 Server Java Process + + *sessionlimit:nonNegInteger default="8388608" Optional + + HBandwidth for one session (64Mb) + + *globallimit:nonNegInteger default="67108864" Optional + + Global Bandwidth (512Mb) + + *delaylimit:nonNulInteger default="10000" Optional + + Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + *runlimit:nonNulInteger default="10000" Optional + + Limite by batch of active transfers (10000) + + *delaycommand:nonNulInteger default="5000" Optional + + Delay between 2 execution of the Commander (5s) + + *delayretry:nonNulInteger default="30000" Optional + + Delay between 2 attemps in case of error (30s) + + *timeoutcon:nonNulInteger default="30000" Optional + + Delay before a Time Out occurs (30s) + + *blocksize:nonNulInteger default="65536" Optional + + Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + *gaprestart:nonNulInteger default="30" Optional + + Gap to use when restarting a transfer as gap x blocksize + + *usenio:booleanType default="False" Optional + + Usage of NIO support for the files. According to the JDK, it can enhance the performances + + *usecpulimit:booleanType default="False" Optional + + Usage of CPU Limitation when new request starts + + *usejdkcpulimit:booleanType default="False" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *cpulimit:decimalType default="0.0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *connlimit:nonNegInteger default="0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *usefastmd5:booleanType default="True" + + Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + *fastmd5:SODLL-File Optional + + Library JNI Filepath. If the path is empty, the pure Java version will be used + +**db Optional + + *dbdriver:address + + 4 types of database are currently supported: oracle, mysql, postgresql, h2 + + *dbserver:normString + + Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + *dbuser:address + + Database User + + *dbpasswd:nonEmptyString + + Database User's Password diff --git a/src/site/apt/Config-OpenR66-ClientNoDB.apt b/src/site/apt/Config-OpenR66-ClientNoDB.apt index bccac526a..4838e1535 100644 --- a/src/site/apt/Config-OpenR66-ClientNoDB.apt +++ b/src/site/apt/Config-OpenR66-ClientNoDB.apt @@ -1,160 +1,160 @@ -OpenR66 Client Without Database Configuration File - -*config - - *comment:string Optional - -**identity - - *hostid:nonEmptyString - - Host ID in NON SSL mode - - *sslhostid:nonEmptyString Optional - - Host ID in SSL mode - - *cryptokey:Des-File - - Des CryptoKey File containing the key in Des mode for R66 passwords - - *authentfile:XML-File - - Authentication File containing Authentications for partners - -**client Optional - - *taskrunnernodb:booleanType Optional default="False" - - When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks - -**ssl Optional - - *keypath:JKS-File - - JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) - - *keystorepass:nonEmptyString - - Password for the KeyStore - - *keypass:nonEmptyString - - Password for the Server Certificate within the KeyStore - - *trustkeypath:JKS-File - - JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) - - *trustkeystorepass:nonEmptyString - - Password for the Trust KeyStore - - *trustuseclientauthenticate:booleanType default="False" - - True if R66 will only allow client through SSL authentication - -**directory - - *serverhome:directoryType - - Home Directory for the OpenR66 Server (relative path to this Home) - - *in:nonEmptyString Optional default="IN" - - Default Receive Directory - - *out:nonEmptyString Optional default="OUT" - - Default Send Directory - - *arch:nonEmptyString Optional default="ARCH" - - Default Archive Directory - - *work:nonEmptyString Optional default="WORK" - - Default Working Directory - - *conf:nonEmptyString Optional default="CONF" - - Configuration Directory - -**limit - - *serverthread:nonNulInteger default="8" Optional - - Number of Threads on Server side (=Number of Cores) - - *clientthread:nonNulInteger default="80" Optional - - Number of Threads on Client side (=10xServer) - - *memorylimit:nonNulInteger default="4000000000" Optional - - Memory Limit for R66 Server Java Process - - *sessionlimit:nonNegInteger default="8388608" Optional - - HBandwidth for one session (64Mb) - - *globallimit:nonNegInteger default="67108864" Optional - - Global Bandwidth (512Mb) - - *delaylimit:nonNulInteger default="10000" Optional - - Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - *runlimit:nonNulInteger default="10000" Optional - - Limite by batch of active transfers (10000) - - *delaycommand:nonNulInteger default="5000" Optional - - Delay between 2 execution of the Commander (5s) - - *delayretry:nonNulInteger default="30000" Optional - - Delay between 2 attemps in case of error (30s) - - *timeoutcon:nonNulInteger default="30000" Optional - - Delay before a Time Out occurs (30s) - - *blocksize:nonNulInteger default="65536" Optional - - Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - *gaprestart:nonNulInteger default="30" Optional - - Gap to use when restarting a transfer as gap x blocksize - - *usenio:booleanType default="False" Optional - - Usage of NIO support for the files. According to the JDK, it can enhance the performances - - *usecpulimit:booleanType default="False" Optional - - Usage of CPU Limitation when new request starts - - *usejdkcpulimit:booleanType default="False" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *cpulimit:decimalType default="0.0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *connlimit:nonNegInteger default="0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *usefastmd5:booleanType default="True" - - Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - *fastmd5:SODLL-File Optional - - Library JNI Filepath. If the path is empty, the pure Java version will be used +OpenR66 Client Without Database Configuration File + +*config + + *comment:string Optional + +**identity + + *hostid:nonEmptyString + + Host ID in NON SSL mode + + *sslhostid:nonEmptyString Optional + + Host ID in SSL mode + + *cryptokey:Des-File + + Des CryptoKey File containing the key in Des mode for R66 passwords + + *authentfile:XML-File + + Authentication File containing Authentications for partners + +**client Optional + + *taskrunnernodb:booleanType Optional default="False" + + When client with no DB, do R66 will use XML files as permanent information on Transfer Tasks + +**ssl Optional + + *keypath:JKS-File + + JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) + + *keystorepass:nonEmptyString + + Password for the KeyStore + + *keypass:nonEmptyString + + Password for the Server Certificate within the KeyStore + + *trustkeypath:JKS-File + + JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) + + *trustkeystorepass:nonEmptyString + + Password for the Trust KeyStore + + *trustuseclientauthenticate:booleanType default="False" + + True if R66 will only allow client through SSL authentication + +**directory + + *serverhome:directoryType + + Home Directory for the OpenR66 Server (relative path to this Home) + + *in:nonEmptyString Optional default="IN" + + Default Receive Directory + + *out:nonEmptyString Optional default="OUT" + + Default Send Directory + + *arch:nonEmptyString Optional default="ARCH" + + Default Archive Directory + + *work:nonEmptyString Optional default="WORK" + + Default Working Directory + + *conf:nonEmptyString Optional default="CONF" + + Configuration Directory + +**limit + + *serverthread:nonNulInteger default="8" Optional + + Number of Threads on Server side (=Number of Cores) + + *clientthread:nonNulInteger default="80" Optional + + Number of Threads on Client side (=10xServer) + + *memorylimit:nonNulInteger default="4000000000" Optional + + Memory Limit for R66 Server Java Process + + *sessionlimit:nonNegInteger default="8388608" Optional + + HBandwidth for one session (64Mb) + + *globallimit:nonNegInteger default="67108864" Optional + + Global Bandwidth (512Mb) + + *delaylimit:nonNulInteger default="10000" Optional + + Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + *runlimit:nonNulInteger default="10000" Optional + + Limite by batch of active transfers (10000) + + *delaycommand:nonNulInteger default="5000" Optional + + Delay between 2 execution of the Commander (5s) + + *delayretry:nonNulInteger default="30000" Optional + + Delay between 2 attemps in case of error (30s) + + *timeoutcon:nonNulInteger default="30000" Optional + + Delay before a Time Out occurs (30s) + + *blocksize:nonNulInteger default="65536" Optional + + Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + *gaprestart:nonNulInteger default="30" Optional + + Gap to use when restarting a transfer as gap x blocksize + + *usenio:booleanType default="False" Optional + + Usage of NIO support for the files. According to the JDK, it can enhance the performances + + *usecpulimit:booleanType default="False" Optional + + Usage of CPU Limitation when new request starts + + *usejdkcpulimit:booleanType default="False" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *cpulimit:decimalType default="0.0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *connlimit:nonNegInteger default="0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *usefastmd5:booleanType default="True" + + Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + *fastmd5:SODLL-File Optional + + Library JNI Filepath. If the path is empty, the pure Java version will be used \ No newline at end of file diff --git a/src/site/apt/Config-OpenR66-Server.apt b/src/site/apt/Config-OpenR66-Server.apt index c34eedb75..f5b4aa53a 100644 --- a/src/site/apt/Config-OpenR66-Server.apt +++ b/src/site/apt/Config-OpenR66-Server.apt @@ -1,259 +1,259 @@ -OpenR66 Server Configuration File - -*config - - *comment:string Optional - -**identity - - *hostid:nonEmptyString - - Host ID in NON SSL mode - - *sslhostid:nonEmptyString Optional - - Host ID in SSL mode - - *cryptokey:Des-File - - Des CryptoKey File containing the key in Des mode for R66 passwords - - *authentfile:XML-File Optional - - Authentication File containing Authentications for partners - -**server - - *serveradmin:nonEmptyString - - Username for Administrator access - - *serverpasswd:nonEmptyString - - Password for Administrator access using Crypto Key - - *usenossl:booleanType default="True" - - True (Default) if R66 will allow no SSL mode connection - - *usessl:booleanType default="False" - - True if R66 will allow SSL mode connection - - *usehttpcomp:booleanType default="False" - - True if Administrator (HTTPS) will allow HTTP compression - - *uselocalexec:booleanType default="False" - - By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemin tends to reach better performances through execution delegation - - *lexecaddr:address default="127.0.0.1" Optional - - Address of LocalExec Daemon - - *lexecport:nonNulInteger default="9999" Optional - - Port of LocalExec Daemon - - *httpadmin:directoryType - - Home Directory for HTTPS file support for Administrator - - *admkeypath:JKS-File - - JKS HTTP KeyStore for Administrator Access in HTTPS Mode (containing Server Certificate) - - *admkeystorepass:nonEmptyString - - Password for the HTTP KeyStore - - *admkeypass:nonEmptyString - - Password for the HTTP Server Certificate within the HTTP KeyStore - - *checkaddress:booleanType default="False" Optional - - True if R66 will check remote IP address while accepting a new connection - - *checkclientaddress:booleanType default="False" Optional - - True if R66 will check remote IP address also for remote Client - - *pastlimit:nonNulInteger default="86400000" Optional - - Monitoring: how long in ms to get back in monitoring - - *minimaldelay:nonNulInteger default="5000" Optional - - Monitoring: minimal interval in ms before redo real monitoring - - *snmpconfig:XML-File Optional - - Configuration XML File for SNMP¨service - -**network - - *serverport:nonNulInteger default="6666" - - Port used in NON SSL mode - - *serversslport:nonNulInteger Optional default="6667" - - Port used in SSL mode - - *serverhttpport:nonNulInteger default="8066" - - Port used for monitoring in HTTP mode - - *serverhttpsport:nonNulInteger default="8067" - - Port used for Administrator access in HTTPS mode - -**ssl Optional - - *keypath:JKS-File - - JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) - - *keystorepass:nonEmptyString - - Password for the KeyStore - - *keypass:nonEmptyString - - Password for the Server Certificate within the KeyStore - - *trustkeypath:JKS-File - - JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) - - *trustkeystorepass:nonEmptyString - - Password for the Trust KeyStore - - *trustuseclientauthenticate:booleanType default="False" - - True if R66 will only allow client through SSL authentication - -**directory - - *serverhome:directoryType - - Home Directory for the OpenR66 Server (relative path to this Home) - - *in:nonEmptyString Optional default="IN" - - Default Receive Directory - - *out:nonEmptyString Optional default="OUT" - - Default Send Directory - - *arch:nonEmptyString Optional default="ARCH" - - Default Archive Directory - - *work:nonEmptyString Optional default="WORK" - - Default Working Directory - - *conf:nonEmptyString Optional default="CONF" - - Configuration Directory - -**limit - - *serverthread:nonNulInteger default="8" Optional - - Number of Threads on Server side (=Number of Cores) - - *clientthread:nonNulInteger default="80" Optional - - Number of Threads on Client side (=10xServer) - - *memorylimit:nonNulInteger default="4000000000" Optional - - Memory Limit for R66 Server Java Process - - *sessionlimit:nonNegInteger default="8388608" Optional - - HBandwidth for one session (64Mb) - - *globallimit:nonNegInteger default="67108864" Optional - - Global Bandwidth (512Mb) - - *delaylimit:nonNulInteger default="10000" Optional - - Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - *runlimit:nonNulInteger default="10000" Optional - - Limite by batch of active transfers (10000) - - *delaycommand:nonNulInteger default="5000" Optional - - Delay between 2 execution of the Commander (5s) - - *delayretry:nonNulInteger default="30000" Optional - - Delay between 2 attemps in case of error (30s) - - *timeoutcon:nonNulInteger default="30000" Optional - - Delay before a Time Out occurs (30s) - - *blocksize:nonNulInteger default="65536" Optional - - Block size (64Ko). A value between 8 KB to 16 MB is recommanded - - *gaprestart:nonNulInteger default="30" Optional - - Gap to use when restarting a transfer as gap x blocksize - - *usenio:booleanType default="False" Optional - - Usage of NIO support for the files. According to the JDK, it can enhance the performances - - *usecpulimit:booleanType default="False" Optional - - Usage of CPU Limitation when new request starts - - *usejdkcpulimit:booleanType default="False" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *cpulimit:decimalType default="0.0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *connlimit:nonNegInteger default="0" Optional - - Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library - - *usefastmd5:booleanType default="True" - - Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations - - *fastmd5:SODLL-File Optional - - Library JNI Filepath. If the path is empty, the pure Java version will be used - -**db - - *dbdriver:address - - 4 types of database are currently supported: oracle, mysql, postgresql, h2 - - *dbserver:normString - - Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - *dbuser:address - - Database User - - *dbpasswd:nonEmptyString - - Database User's Password +OpenR66 Server Configuration File + +*config + + *comment:string Optional + +**identity + + *hostid:nonEmptyString + + Host ID in NON SSL mode + + *sslhostid:nonEmptyString Optional + + Host ID in SSL mode + + *cryptokey:Des-File + + Des CryptoKey File containing the key in Des mode for R66 passwords + + *authentfile:XML-File Optional + + Authentication File containing Authentications for partners + +**server + + *serveradmin:nonEmptyString + + Username for Administrator access + + *serverpasswd:nonEmptyString + + Password for Administrator access using Crypto Key + + *usenossl:booleanType default="True" + + True (Default) if R66 will allow no SSL mode connection + + *usessl:booleanType default="False" + + True if R66 will allow SSL mode connection + + *usehttpcomp:booleanType default="False" + + True if Administrator (HTTPS) will allow HTTP compression + + *uselocalexec:booleanType default="False" + + By default, use the System.exec() but can lead to limitation in performances (JDK limitation). The usage of the GoldenGate LocalExec Daemin tends to reach better performances through execution delegation + + *lexecaddr:address default="127.0.0.1" Optional + + Address of LocalExec Daemon + + *lexecport:nonNulInteger default="9999" Optional + + Port of LocalExec Daemon + + *httpadmin:directoryType + + Home Directory for HTTPS file support for Administrator + + *admkeypath:JKS-File + + JKS HTTP KeyStore for Administrator Access in HTTPS Mode (containing Server Certificate) + + *admkeystorepass:nonEmptyString + + Password for the HTTP KeyStore + + *admkeypass:nonEmptyString + + Password for the HTTP Server Certificate within the HTTP KeyStore + + *checkaddress:booleanType default="False" Optional + + True if R66 will check remote IP address while accepting a new connection + + *checkclientaddress:booleanType default="False" Optional + + True if R66 will check remote IP address also for remote Client + + *pastlimit:nonNulInteger default="86400000" Optional + + Monitoring: how long in ms to get back in monitoring + + *minimaldelay:nonNulInteger default="5000" Optional + + Monitoring: minimal interval in ms before redo real monitoring + + *snmpconfig:XML-File Optional + + Configuration XML File for SNMP¨service + +**network + + *serverport:nonNulInteger default="6666" + + Port used in NON SSL mode + + *serversslport:nonNulInteger Optional default="6667" + + Port used in SSL mode + + *serverhttpport:nonNulInteger default="8066" + + Port used for monitoring in HTTP mode + + *serverhttpsport:nonNulInteger default="8067" + + Port used for Administrator access in HTTPS mode + +**ssl Optional + + *keypath:JKS-File + + JKS KeyStore for R66 Access in SSL Mode (containing Server Certificate) + + *keystorepass:nonEmptyString + + Password for the KeyStore + + *keypass:nonEmptyString + + Password for the Server Certificate within the KeyStore + + *trustkeypath:JKS-File + + JKS Trust KeyStore for R66 Access in SSL Mode with Client Authentication (containing Client Certificate) + + *trustkeystorepass:nonEmptyString + + Password for the Trust KeyStore + + *trustuseclientauthenticate:booleanType default="False" + + True if R66 will only allow client through SSL authentication + +**directory + + *serverhome:directoryType + + Home Directory for the OpenR66 Server (relative path to this Home) + + *in:nonEmptyString Optional default="IN" + + Default Receive Directory + + *out:nonEmptyString Optional default="OUT" + + Default Send Directory + + *arch:nonEmptyString Optional default="ARCH" + + Default Archive Directory + + *work:nonEmptyString Optional default="WORK" + + Default Working Directory + + *conf:nonEmptyString Optional default="CONF" + + Configuration Directory + +**limit + + *serverthread:nonNulInteger default="8" Optional + + Number of Threads on Server side (=Number of Cores) + + *clientthread:nonNulInteger default="80" Optional + + Number of Threads on Client side (=10xServer) + + *memorylimit:nonNulInteger default="4000000000" Optional + + Memory Limit for R66 Server Java Process + + *sessionlimit:nonNegInteger default="8388608" Optional + + HBandwidth for one session (64Mb) + + *globallimit:nonNegInteger default="67108864" Optional + + Global Bandwidth (512Mb) + + *delaylimit:nonNulInteger default="10000" Optional + + Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + *runlimit:nonNulInteger default="10000" Optional + + Limite by batch of active transfers (10000) + + *delaycommand:nonNulInteger default="5000" Optional + + Delay between 2 execution of the Commander (5s) + + *delayretry:nonNulInteger default="30000" Optional + + Delay between 2 attemps in case of error (30s) + + *timeoutcon:nonNulInteger default="30000" Optional + + Delay before a Time Out occurs (30s) + + *blocksize:nonNulInteger default="65536" Optional + + Block size (64Ko). A value between 8 KB to 16 MB is recommanded + + *gaprestart:nonNulInteger default="30" Optional + + Gap to use when restarting a transfer as gap x blocksize + + *usenio:booleanType default="False" Optional + + Usage of NIO support for the files. According to the JDK, it can enhance the performances + + *usecpulimit:booleanType default="False" Optional + + Usage of CPU Limitation when new request starts + + *usejdkcpulimit:booleanType default="False" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *cpulimit:decimalType default="0.0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *connlimit:nonNegInteger default="0" Optional + + Usage of CPU limitation based on Native JDK support, else (False) on Java Sysmon library + + *usefastmd5:booleanType default="True" + + Usage of FastMD5 library. The library greatly improves the performances for the MD5 computations + + *fastmd5:SODLL-File Optional + + Library JNI Filepath. If the path is empty, the pure Java version will be used + +**db + + *dbdriver:address + + 4 types of database are currently supported: oracle, mysql, postgresql, h2 + + *dbserver:normString + + Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + *dbuser:address + + Database User + + *dbpasswd:nonEmptyString + + Database User's Password diff --git a/src/site/apt/Config-OpenR66-SubmitClient.apt b/src/site/apt/Config-OpenR66-SubmitClient.apt index 8b43144d8..ae2364f69 100644 --- a/src/site/apt/Config-OpenR66-SubmitClient.apt +++ b/src/site/apt/Config-OpenR66-SubmitClient.apt @@ -1,69 +1,69 @@ -OpenR66 Client for Submit Only Configuration File - -*config - - *comment:string Optional - -**identity - - *hostid:nonEmptyString - - Host ID in NON SSL mode - - *sslhostid:nonEmptyString Optional - - Host ID in SSL mode - - *cryptokey:Des-File - - Des CryptoKey File containing the key in Des mode for R66 passwords - -**directory - - *serverhome:directoryType - - Home Directory for the OpenR66 Server (relative path to this Home) - - *in:nonEmptyString Optional default="IN" - - Default Receive Directory - - *out:nonEmptyString Optional default="OUT" - - Default Send Directory - - *arch:nonEmptyString Optional default="ARCH" - - Default Archive Directory - - *work:nonEmptyString Optional default="WORK" - - Default Working Directory - - *conf:nonEmptyString Optional default="CONF" - - Configuration Directory - -**limit - - *blocksize:nonNulInteger default="65536" Optional - - Block size (64Ko). A value between 8 KB to 16 MB is recommanded - -**db - - *dbdriver:address - - 4 types of database are currently supported: oracle, mysql, postgresql, h2 - - *dbserver:normString - - Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection - - *dbuser:address - - Database User - - *dbpasswd:nonEmptyString - - Database User's Password +OpenR66 Client for Submit Only Configuration File + +*config + + *comment:string Optional + +**identity + + *hostid:nonEmptyString + + Host ID in NON SSL mode + + *sslhostid:nonEmptyString Optional + + Host ID in SSL mode + + *cryptokey:Des-File + + Des CryptoKey File containing the key in Des mode for R66 passwords + +**directory + + *serverhome:directoryType + + Home Directory for the OpenR66 Server (relative path to this Home) + + *in:nonEmptyString Optional default="IN" + + Default Receive Directory + + *out:nonEmptyString Optional default="OUT" + + Default Send Directory + + *arch:nonEmptyString Optional default="ARCH" + + Default Archive Directory + + *work:nonEmptyString Optional default="WORK" + + Default Working Directory + + *conf:nonEmptyString Optional default="CONF" + + Configuration Directory + +**limit + + *blocksize:nonNulInteger default="65536" Optional + + Block size (64Ko). A value between 8 KB to 16 MB is recommanded + +**db + + *dbdriver:address + + 4 types of database are currently supported: oracle, mysql, postgresql, h2 + + *dbserver:normString + + Connection to the database in JDBC mode (jdbc:type://[host:port]....). Use the database documentation to find the correct syntax for the JDBC connection + + *dbuser:address + + Database User + + *dbpasswd:nonEmptyString + + Database User's Password diff --git a/src/site/apt/Config-Snmp.apt b/src/site/apt/Config-Snmp.apt index afaef79c7..818f436b0 100644 --- a/src/site/apt/Config-Snmp.apt +++ b/src/site/apt/Config-Snmp.apt @@ -1,79 +1,79 @@ -OpenR66 SNMP Configuration File - -*snmpconfig - - *comment:string Optional - -**config - - *localaddress:nonEmptyString Multiple - - Local Address to use as listen in format udp:address/port or tcp:address/port - - *nbthread:nonNulInteger Optional default="4" - - Number of threads to use (4) - - *filtered:booleanType default="False" Optional - - Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. - - *usetrap:booleanType default="True" Optional - - Use Trap (True) or Inform (False) when generating push event - - *trapinformlevel:nonNegInteger default="0" Optional - - Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning - -**targets - - *target Multiple Optional - - *name:nonEmptyString - - Name To use as target - - *domain:nonEmptyString default="UdpIpv4" - - 1 Value between: UdpIpV4 UdpIpv6 UdpIpV4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z - - *address:nonEmptyString - - As address/port as 192.168.0.1/162 - - *timeout:nonNegInteger default="200" Optional - - Maximum delay in ms to wait with an Inform mode event - - *retries:nonNegInteger default="1" Optional - - Number of retries once the Inform is sent and not acknowledged - - *isv2:booleanType default="True" Optional - - Is this entry is conformed with V2C or with V3 of SNMP - -**securities - - *security Multiple Optional - - *securityname:nonEmptyString - - Name To use as Name Entry for External Manager - - *securityauthprotocol:nonEmptyString Optional - - Protocol between SHA or MD5 - - *securityauthpass:string Optional - - Password (might be empty) - - *securityprivprotocol:nonEmptyString Optional - - Optional Protocol as P3DES, PAES128, PAES192, PAES256, PDES - - *securityprivpass:string Optional - - Password (might be empty) +OpenR66 SNMP Configuration File + +*snmpconfig + + *comment:string Optional + +**config + + *localaddress:nonEmptyString Multiple + + Local Address to use as listen in format udp:address/port or tcp:address/port + + *nbthread:nonNulInteger Optional default="4" + + Number of threads to use (4) + + *filtered:booleanType default="False" Optional + + Enables or disables source address filtering for incoming SNMPv1 or SNMPv2c packets. By default source address filtering is disabled! If enabled, only messages received for community based security models are processed, that match an address in the snmpTargetAddressTable with the transport tag associated with the community used. + + *usetrap:booleanType default="True" Optional + + Use Trap (True) or Inform (False) when generating push event + + *trapinformlevel:nonNegInteger default="0" Optional + + Level of trap or inform event generated: 0 None 1 Start/Stop 2 Critical 3 Error 4 Every events in Warning + +**targets + + *target Multiple Optional + + *name:nonEmptyString + + Name To use as target + + *domain:nonEmptyString default="UdpIpv4" + + 1 Value between: UdpIpV4 UdpIpv6 UdpIpV4e UdpIpv6z TcpIpv4 TcpIpv6 TcpIpv4z TcpIpv6z + + *address:nonEmptyString + + As address/port as 192.168.0.1/162 + + *timeout:nonNegInteger default="200" Optional + + Maximum delay in ms to wait with an Inform mode event + + *retries:nonNegInteger default="1" Optional + + Number of retries once the Inform is sent and not acknowledged + + *isv2:booleanType default="True" Optional + + Is this entry is conformed with V2C or with V3 of SNMP + +**securities + + *security Multiple Optional + + *securityname:nonEmptyString + + Name To use as Name Entry for External Manager + + *securityauthprotocol:nonEmptyString Optional + + Protocol between SHA or MD5 + + *securityauthpass:string Optional + + Password (might be empty) + + *securityprivprotocol:nonEmptyString Optional + + Optional Protocol as P3DES, PAES128, PAES192, PAES256, PDES + + *securityprivpass:string Optional + + Password (might be empty) diff --git a/src/site/apt/OpenR66-Authent.apt b/src/site/apt/OpenR66-Authent.apt index 85aa216da..a5ca1e0ba 100644 --- a/src/site/apt/OpenR66-Authent.apt +++ b/src/site/apt/OpenR66-Authent.apt @@ -1,41 +1,41 @@ -OpenR66 Authentication Configuration File - -*authent - - *comment:string Optional - -**entry Multiple(1:n) - - Used to initialize remote Hosts table at setup or with client with no database support - - *hostid:nonEmptyString - - Host ID of remote Host - - *address:address (DNS or IP) - - Address of remote host (IP or DNS entry) - - *port:nonNulInteger - - Port associated with the Address of the remote Host - - *isssl:booleanType default="False" - - True if this Address Entry is for SSL mode - - *admin:booleanType Optional default="False" - - True if this Address Entry allows Admin access through R66 Protocol - - *isclient:booleanType Optional default="False" - - True if this Address Entry is for a Client - - *keyfile:GGP-File choice 1 - - GoldenGate Password File containing the password for this host - - *key:nonEmptyString choice 2 - - GoldenGate Password for this host +OpenR66 Authentication Configuration File + +*authent + + *comment:string Optional + +**entry Multiple(1:n) + + Used to initialize remote Hosts table at setup or with client with no database support + + *hostid:nonEmptyString + + Host ID of remote Host + + *address:address (DNS or IP) + + Address of remote host (IP or DNS entry) + + *port:nonNulInteger + + Port associated with the Address of the remote Host + + *isssl:booleanType default="False" + + True if this Address Entry is for SSL mode + + *admin:booleanType Optional default="False" + + True if this Address Entry allows Admin access through R66 Protocol + + *isclient:booleanType Optional default="False" + + True if this Address Entry is for a Client + + *keyfile:GGP-File choice 1 + + GoldenGate Password File containing the password for this host + + *key:nonEmptyString choice 2 + + GoldenGate Password for this host diff --git a/src/site/apt/OpenR66-Limit.apt b/src/site/apt/OpenR66-Limit.apt index e54e3700b..8fdfebcfd 100644 --- a/src/site/apt/OpenR66-Limit.apt +++ b/src/site/apt/OpenR66-Limit.apt @@ -1,38 +1,38 @@ -OpenR66 Limit Configuration File - -*config - - *comment:string Optional - -**identity - - *hostid:nonEmptyString - - Host ID in NON SSL mode - -**limit - - *sessionlimit:nonNegInteger default="8388608" Optional - - Bandwidth for one session (64Mb) - - *globallimit:nonNegInteger default="67108864" Optional - - Global Bandwidth (512Mb) - - *delaylimit:nonNulInteger default="10000" Optional - - Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value - - *runlimit:nonNulInteger default="10000" Optional - - Limit by batch of active transfers (10000) - - *delaycommand:nonNulInteger default="5000" Optional - - Delay between 2 execution of the Commander (5s) - - *delayretry:nonNulInteger default="30000" Optional - - Delay between 2 attemps in case of error (30s) +OpenR66 Limit Configuration File + +*config + + *comment:string Optional + +**identity + + *hostid:nonEmptyString + + Host ID in NON SSL mode + +**limit + + *sessionlimit:nonNegInteger default="8388608" Optional + + Bandwidth for one session (64Mb) + + *globallimit:nonNegInteger default="67108864" Optional + + Global Bandwidth (512Mb) + + *delaylimit:nonNulInteger default="10000" Optional + + Delay between 2 checks of Bandwidth (10s). The less this value, the better the bandwidth limitation is done. However take care to not give too low value + + *runlimit:nonNulInteger default="10000" Optional + + Limit by batch of active transfers (10000) + + *delaycommand:nonNulInteger default="5000" Optional + + Delay between 2 execution of the Commander (5s) + + *delayretry:nonNulInteger default="30000" Optional + + Delay between 2 attemps in case of error (30s) \ No newline at end of file diff --git a/src/site/apt/OpenR66-Rule.apt b/src/site/apt/OpenR66-Rule.apt index efcbaa9a4..02f7d620d 100644 --- a/src/site/apt/OpenR66-Rule.apt +++ b/src/site/apt/OpenR66-Rule.apt @@ -1,79 +1,79 @@ -OpenR66 Rule Configuration File - -*rule - - *comment:string Optional - - *idrule:nonEmptyString - - Rule ID - - *hostids - - List of Host Ids allowed to use this rule. No Host Id means all allowed. - - *hostid:nonEmptyString unbounded - - Host ID allowed to use this rule - - *mode:nonNulInteger - - 1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 - - *recvpath:nonEmptyString Optional default="IN" - - Default Receive Directory - - *sendpath:nonEmptyString Optional default="OUT" - - Default Send Directory - - *archivepath:nonEmptyString Optional default="ARCH" - - Default Archive Directory - - *workpath:nonEmptyString Optional default="WORK" - - Default Working Directory - - *rpretasks - - List of tasks -if any- to execute before transfer on receiver side - - *rposttasks - - List of tasks -if any- to execute after transfer on receiver side - - *rerrortasks - - List of tasks -if any- to execute after an error on receiver side - - *spretasks - - List of tasks -if any- to execute before transfer on sender side - - *sposttasks - - List of tasks -if any- to execute after transfer on sender side - - *serrortasks - - List of tasks -if any- to execute after an error on sender side - -Where List of tasks is - -*tasks - -**task Optional unbounded - - *type:nonEmptyString - - Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECJAVA, EXECOUTPUT, LINKRENAME, VALIDFILEPATH, DELETE, TAR, ZIP - - *path:nonEmptyString - - Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ... - - *delay:nonNegInteger - - Maximum delay for execution of the task in ms +OpenR66 Rule Configuration File + +*rule + + *comment:string Optional + + *idrule:nonEmptyString + + Rule ID + + *hostids + + List of Host Ids allowed to use this rule. No Host Id means all allowed. + + *hostid:nonEmptyString unbounded + + Host ID allowed to use this rule + + *mode:nonNulInteger + + 1=SEND 2=RECV 3=SEND+MD5 4=RECV+MD5 + + *recvpath:nonEmptyString Optional default="IN" + + Default Receive Directory + + *sendpath:nonEmptyString Optional default="OUT" + + Default Send Directory + + *archivepath:nonEmptyString Optional default="ARCH" + + Default Archive Directory + + *workpath:nonEmptyString Optional default="WORK" + + Default Working Directory + + *rpretasks + + List of tasks -if any- to execute before transfer on receiver side + + *rposttasks + + List of tasks -if any- to execute after transfer on receiver side + + *rerrortasks + + List of tasks -if any- to execute after an error on receiver side + + *spretasks + + List of tasks -if any- to execute before transfer on sender side + + *sposttasks + + List of tasks -if any- to execute after transfer on sender side + + *serrortasks + + List of tasks -if any- to execute after an error on sender side + +Where List of tasks is + +*tasks + +**task Optional unbounded + + *type:nonEmptyString + + Type of Task: LOG, MOVE, MOVERENAME, COPY, COPYRENAME, EXEC, EXECMOVE, EXECJAVA, EXECOUTPUT, LINKRENAME, VALIDFILEPATH, DELETE, TAR, ZIP + + *path:nonEmptyString + + Argument -often a path- applied to the task where substitution can occur like #TRUEFULLPATH#, #FILESIZE#, #RULE#, #DATE#, #TRANSFERID#, ... + + *delay:nonNegInteger + + Maximum delay for execution of the task in ms diff --git a/src/site/apt/commands.apt b/src/site/apt/commands.apt index 9c64994d3..6af0765fd 100644 --- a/src/site/apt/commands.apt +++ b/src/site/apt/commands.apt @@ -1,328 +1,328 @@ -OpenR66-Command - - OpenR66 is mainly a set of commands,from the server, to the clients, through utilities. - -*R66Server - - It launches the OpenR66 Server using as unique argument the full XML configuration file. - It loads the rest of the configuration (or update its configuration) from the database - specified in the XML configuration file. - - By default, three services are opened: - - * Non SSL file transfer monitor - - * SSL file transfer monitor - - * HTTP file transfer observer - - [] - - By default, 5 subdirectories (under the main home) are defined: - - *Config directory where configurations files are stored - - *Archive directory where archive transfer can be put (using post actions) or where transfer logs - are placed - - *Input directory where received files are stored (except if a post action moves it) - - *Output directory where to be sent files are stored (or linked) - - *Working directory where currently received files are temporarily placed - -*Utilities: - -**ServerInitDatabase - - The first step in installation of an OpenR66 Server or heavy client is to construct the XML - configuration files and to initiate the database that support file transfers and configurations. - This function is an helper for database initialization. - - * The first argument is the JDBC database connection XML file. It will try to create the - database tables and to initiate the sequence (unique Id by host of runners from runner table). - - From there any argument are optional but in that order. Any existing data will be replaced. No data are deleted if not replaced. - - * -initdb : try to create database. It stops at the first error but the program continues. - - * -dir directory : This argument is the directory from where to load rules into the database using the XML - rule files present in this directory (rules table). - - * -auth fileHost : This argument is to load the host authentication XML file into the database (hosts table). - - * -limit limitConfig : This argument is to load the bandwidth XML file into the database (configuration table). - - [] - - From that point, the OpenR66 server (R66Server) can be started. - -**ServerExportConfiguration - - One of the ideas of OpenR66 is the ability to centralized some information asynchronously - into a centralized database. This centralization can be in two ways: - - * Import new rules, host authentication or bandwidth limitation: this can be done using - the ServerInitDatabase after some file transfers from a post operation which could execute - this utility. - - * Export rules, hosts authentication and actual runners (done or not): this is the goal - of this utility. It takes two arguments: - - * The client configuration XML file - - * The directory where to export files in XML format - - It will export Rules, all present Runners, Host Authentications. - - -**ConfigExport - - This tool enables to ask the server remotely to export Rules and Hosts configuration into one file each. - It could be used before a retrieve of the configuration in a central repository. - - Options are: - - * The first argument is the client XML configuration file - - * -hosts : export all Hosts configuration - - * -rules : export all Rules configuration - -**ConfigImport - - This tool enables to ask the server remotely to import Rules and Hosts configuration from one file each. - It could be used before a upload the configuration from a central repository after transmission. - - Options are: - - * The first argument is the client XML configuration file - - * -hosts : import all Hosts configuration - - * -purgehosts : purge all hosts configuration before importing new configuration - - * -rules : import all Rules configuration - - * -purgerules : purge all rules configuration before importing new configuration - -**ServerShutdown - - The OpenR66 Server can be shutdown mainly in two ways: - - * Sending a -SIGTERM signal (or under Unix a -SIGUSR1 signal) to the JVM process hosting - the OpenR66 Server. - - * The prefered way is to use the HTTPS Administrator interface. - - * Another preferred way is to use this utility which sends a shutdown request through network - but using a key shared physically (adminkey). This utility takes the same XML configuration - file than the server (where the admin key is referred but not stored in any database) and - uses the SSL service. - - * If one wants to used the non SSL service, it should create a new utility and changing: - - * "SERVER_SSLPORT" to "SERVER_PORT" - - * "createConnectionWithRetry(socketServerAddress,true, null);" to "createConnectionWithRetry(socketServerAddress,false, null);". - -**LogExport - - If one wants to centralized in asynchronous way the transfer logs, this utility is made for it. - Its purpose is to export logs into the archive directory and to eventually purge them from - database. It sends a local request to the server, which really export the logs into a file. - No file are transfered, they are just export to a file in the global archive directory. - To use it, two main ways can be achieved: - - * The local server runs this tool referring the OpenR66 Server using the client configuration - XML file and then running a log request. - - * Directly runs a transfer request where the rule execute at pre processing this utility - (again either in receive or send mode according to the initiate server). - - * The First argument is the Client Configuration (eventually without database access). - - * The rest of arguments can be: - - *'-clean' option: Change all UpdatedInfo to Done where GlobalLastTask is ALLDONETASK and - status is CompleteOk (sometimes some runners can be done but UpdatedInfo could be erroneous - - no impact but clean function -). - - *'-purge' option: This option removes all ALLDONETASK from those that will be exported. - - *'-start' option: This option specifies the low limit to select runners from start runner - time. If not specified, there is no low limit. - - *'-stop' option: This option specifies the upper limit to select runners from start runner - time. If not specified, there is no upper limit. - -**ChangeBandwidthLimits - - This tool enables to change dynamically the bandwidth limitations (only in memory, not in - database). To use it, it should be used locally with the admin account. - - * The First argument is the Client Configuration (eventually without database access). - - * The rest of arguments can be: - - *'-wglob' option: Write Global limitation in Bytes by Second (minimum 1024 so 1KBs). - - *'-rglob' option: Read Global limitation in Bytes by Second (minimum 1024 so 1KBs). - - *'-wsess' option: Write Session limitation in Bytes by Second (minimum 1024 so 1KBs). - - *'-rsess' option: Read Session limitation in Bytes by Second (minimum 1024 so 1KBs). - -*Clients: - -**SubmitTransfer - - To transfer a file, two main methods exist. This one is a submission request, so an - asynchronous operation since once the request is submitted, the client returns without - waiting for the end of the operation. - - It takes the following argument: - - * The client XML configuration file as first argument, the one including database access - - * At least 3 other arguments are necessary: - - *'-to' option: specifies the remote Host Id (either the Id for SSL or not ). - - *'-file' option: specifies the file to transfer (either in receive or send mode). - - *'-rule' option: specifies the rule to apply (which specifies the transfer mode, - the pre, post or error operations, ...). - - * Or at least 2 other arguments are necessary: - - *'-to' option: specifies the remote Host Id (either the Id for SSL or not ). - - *'-id' option: specifies the Id of a previous transfer (stopped or in error). - - * Other options are: - - *'-info' option: specifies the optional information that is send at the same time with - the transfer request (extra information that could be needed by the remote host). - - *'-md5' option: specifies that each block transfer will be checked with a MD5 key. If - the rule used is already in MD5 mode, this option will change nothing. - - *'-block' option: specifies the block size (default is 64 KB). - - *'-nolog' option: specifies that this transfer will not be logged (only on requester side). - - *'-start' "time start" as yyyyMMddHHmmss (override previous -delay options) - - *'-delay' "+delay in ms" as delay in ms from current time(override previous -start options) - - *'-delay' "delay in ms" as time in ms (override previous -start options) - -**DirectTransfer - - This is the second method to transfer a file. This method is direct, so as a synchronous - operation. This time the client will do the real work (transferring the file). - The options are exactly the same than with SubmitTransfer. However two cases exist: - - *Heavy client: The client XML configuration file includes the database access. - All transfer operations will be logged (eventually deleted at the end from the client side - if the '-nolog' option is set). This option is useful for "production" clients in a data center. - - *Light client: The client XML configuration file does not included the database access. - All transfer operations will not be logged at all (at client side). This option is useful - for "light client" like personal computers where transferring files to or from a data center - is a necessity. - - However, both clients can only be the initiator of the transfer (receive or send), since no service is running once the client is over. - -**SendThroughClient - - This method is not a full implemented method. It is a way to route a file transfer from - one protocol in Java to OpenR66. For instance, if a protocol like HTTP upload or FTP upload - allows to get a file upload by packet, you can then route this file transfer through OpenR66 - to a final OpenR66 Server using the protocol but without writing an intermediary file - (directly write the bytes from the upload to the OpenR66 SendThroughClient interface). - A simple example is shown in TestSendThroughClient. - - So this method needs some minor developments to be implemented. - -**RecvThroughClient - - This method is not a full implemented method. It is a way to route a file transfer to one - protocol in Java to OpenR66. For instance, if a protocol like HTTP or FTP download allows to - get a file downloaded by packet, you can then route directly the file transfer from OpenR66 - from a remote OpenR66 Server using the protocol directly but without writing an intermediary - file (directly write the bytes from the download from the OpenR66 RecvThroughHandler - interface). A simple example is shown in TestRecvThroughClient. - - So this method needs some minor developments to be implemented. - -**ProgressBarTransfer - - This method is not a full implemented method. It is a way to implement a file transfer within - a Graphical User Interface or to get information on progression during the transfer. - Such an example is presented in the R66GUI. - - So this method needs some minor developments to be implemented. - -**RequestTransfer - - This utility is used to get information for a specific runner or to have an action on this runner. - - The arguments are the following: - - * The first argument is the client XML configuration file including the database access. - - *'-id' option: this is the Runner Id. - - *'-to' or '-from' option (exclusive): this specifies the way of the request transfer. - '-to' specifies that the original request was initiated by the current running host to - the remote specified host. '-from' specifies that the original request was initiated by - the remote specified host. - - * Optional arguments (exclusive): without any of those arguments, the request only returns - the current information of the runner. - - *'-cancel' option: the runner will be canceled. Any file currently in writing will be deleted. - - *'-stop' option: the runner will be stopped (but not canceled). - - *'-restart' option: the runner will be restart (if stopped). - -**RequestInformation - - This utility is used to get information for a file, a directory, with or without wildcard - characters ('*' and '?"). - - The arguments are the following: - - * The first argument is the client XML configuration file including the database access. - - *'-to' option: specifies the requested host. - - *'-rule' option: the rule - - *'-file' the optional file for which to get info (may contain wildcard characters) - - * Optional arguments (exclusive): without any of those arguments, the request only - returns the existence of the file or directory. - - *'-exist' to test the existence. - - *'-detail' to get the detail on file. - - *'-list' to get the list of files. - - *'-mlsx' to get the list and details of files - -**Message - - This utility is used to send a short message to another server (like a ping in OpenR66 protocol) - - The arguments are the following: - - * The first argument is the client XML configuration file - - *'-to' option: specifies the requested host. - - *'-msg' option: the msg to send +OpenR66-Command + + OpenR66 is mainly a set of commands,from the server, to the clients, through utilities. + +*R66Server + + It launches the OpenR66 Server using as unique argument the full XML configuration file. + It loads the rest of the configuration (or update its configuration) from the database + specified in the XML configuration file. + + By default, three services are opened: + + * Non SSL file transfer monitor + + * SSL file transfer monitor + + * HTTP file transfer observer + + [] + + By default, 5 subdirectories (under the main home) are defined: + + *Config directory where configurations files are stored + + *Archive directory where archive transfer can be put (using post actions) or where transfer logs + are placed + + *Input directory where received files are stored (except if a post action moves it) + + *Output directory where to be sent files are stored (or linked) + + *Working directory where currently received files are temporarily placed + +*Utilities: + +**ServerInitDatabase + + The first step in installation of an OpenR66 Server or heavy client is to construct the XML + configuration files and to initiate the database that support file transfers and configurations. + This function is an helper for database initialization. + + * The first argument is the JDBC database connection XML file. It will try to create the + database tables and to initiate the sequence (unique Id by host of runners from runner table). + + From there any argument are optional but in that order. Any existing data will be replaced. No data are deleted if not replaced. + + * -initdb : try to create database. It stops at the first error but the program continues. + + * -dir directory : This argument is the directory from where to load rules into the database using the XML + rule files present in this directory (rules table). + + * -auth fileHost : This argument is to load the host authentication XML file into the database (hosts table). + + * -limit limitConfig : This argument is to load the bandwidth XML file into the database (configuration table). + + [] + + From that point, the OpenR66 server (R66Server) can be started. + +**ServerExportConfiguration + + One of the ideas of OpenR66 is the ability to centralized some information asynchronously + into a centralized database. This centralization can be in two ways: + + * Import new rules, host authentication or bandwidth limitation: this can be done using + the ServerInitDatabase after some file transfers from a post operation which could execute + this utility. + + * Export rules, hosts authentication and actual runners (done or not): this is the goal + of this utility. It takes two arguments: + + * The client configuration XML file + + * The directory where to export files in XML format + + It will export Rules, all present Runners, Host Authentications. + + +**ConfigExport + + This tool enables to ask the server remotely to export Rules and Hosts configuration into one file each. + It could be used before a retrieve of the configuration in a central repository. + + Options are: + + * The first argument is the client XML configuration file + + * -hosts : export all Hosts configuration + + * -rules : export all Rules configuration + +**ConfigImport + + This tool enables to ask the server remotely to import Rules and Hosts configuration from one file each. + It could be used before a upload the configuration from a central repository after transmission. + + Options are: + + * The first argument is the client XML configuration file + + * -hosts : import all Hosts configuration + + * -purgehosts : purge all hosts configuration before importing new configuration + + * -rules : import all Rules configuration + + * -purgerules : purge all rules configuration before importing new configuration + +**ServerShutdown + + The OpenR66 Server can be shutdown mainly in two ways: + + * Sending a -SIGTERM signal (or under Unix a -SIGUSR1 signal) to the JVM process hosting + the OpenR66 Server. + + * The prefered way is to use the HTTPS Administrator interface. + + * Another preferred way is to use this utility which sends a shutdown request through network + but using a key shared physically (adminkey). This utility takes the same XML configuration + file than the server (where the admin key is referred but not stored in any database) and + uses the SSL service. + + * If one wants to used the non SSL service, it should create a new utility and changing: + + * "SERVER_SSLPORT" to "SERVER_PORT" + + * "createConnectionWithRetry(socketServerAddress,true, null);" to "createConnectionWithRetry(socketServerAddress,false, null);". + +**LogExport + + If one wants to centralized in asynchronous way the transfer logs, this utility is made for it. + Its purpose is to export logs into the archive directory and to eventually purge them from + database. It sends a local request to the server, which really export the logs into a file. + No file are transfered, they are just export to a file in the global archive directory. + To use it, two main ways can be achieved: + + * The local server runs this tool referring the OpenR66 Server using the client configuration + XML file and then running a log request. + + * Directly runs a transfer request where the rule execute at pre processing this utility + (again either in receive or send mode according to the initiate server). + + * The First argument is the Client Configuration (eventually without database access). + + * The rest of arguments can be: + + *'-clean' option: Change all UpdatedInfo to Done where GlobalLastTask is ALLDONETASK and + status is CompleteOk (sometimes some runners can be done but UpdatedInfo could be erroneous + - no impact but clean function -). + + *'-purge' option: This option removes all ALLDONETASK from those that will be exported. + + *'-start' option: This option specifies the low limit to select runners from start runner + time. If not specified, there is no low limit. + + *'-stop' option: This option specifies the upper limit to select runners from start runner + time. If not specified, there is no upper limit. + +**ChangeBandwidthLimits + + This tool enables to change dynamically the bandwidth limitations (only in memory, not in + database). To use it, it should be used locally with the admin account. + + * The First argument is the Client Configuration (eventually without database access). + + * The rest of arguments can be: + + *'-wglob' option: Write Global limitation in Bytes by Second (minimum 1024 so 1KBs). + + *'-rglob' option: Read Global limitation in Bytes by Second (minimum 1024 so 1KBs). + + *'-wsess' option: Write Session limitation in Bytes by Second (minimum 1024 so 1KBs). + + *'-rsess' option: Read Session limitation in Bytes by Second (minimum 1024 so 1KBs). + +*Clients: + +**SubmitTransfer + + To transfer a file, two main methods exist. This one is a submission request, so an + asynchronous operation since once the request is submitted, the client returns without + waiting for the end of the operation. + + It takes the following argument: + + * The client XML configuration file as first argument, the one including database access + + * At least 3 other arguments are necessary: + + *'-to' option: specifies the remote Host Id (either the Id for SSL or not ). + + *'-file' option: specifies the file to transfer (either in receive or send mode). + + *'-rule' option: specifies the rule to apply (which specifies the transfer mode, + the pre, post or error operations, ...). + + * Or at least 2 other arguments are necessary: + + *'-to' option: specifies the remote Host Id (either the Id for SSL or not ). + + *'-id' option: specifies the Id of a previous transfer (stopped or in error). + + * Other options are: + + *'-info' option: specifies the optional information that is send at the same time with + the transfer request (extra information that could be needed by the remote host). + + *'-md5' option: specifies that each block transfer will be checked with a MD5 key. If + the rule used is already in MD5 mode, this option will change nothing. + + *'-block' option: specifies the block size (default is 64 KB). + + *'-nolog' option: specifies that this transfer will not be logged (only on requester side). + + *'-start' "time start" as yyyyMMddHHmmss (override previous -delay options) + + *'-delay' "+delay in ms" as delay in ms from current time(override previous -start options) + + *'-delay' "delay in ms" as time in ms (override previous -start options) + +**DirectTransfer + + This is the second method to transfer a file. This method is direct, so as a synchronous + operation. This time the client will do the real work (transferring the file). + The options are exactly the same than with SubmitTransfer. However two cases exist: + + *Heavy client: The client XML configuration file includes the database access. + All transfer operations will be logged (eventually deleted at the end from the client side + if the '-nolog' option is set). This option is useful for "production" clients in a data center. + + *Light client: The client XML configuration file does not included the database access. + All transfer operations will not be logged at all (at client side). This option is useful + for "light client" like personal computers where transferring files to or from a data center + is a necessity. + + However, both clients can only be the initiator of the transfer (receive or send), since no service is running once the client is over. + +**SendThroughClient + + This method is not a full implemented method. It is a way to route a file transfer from + one protocol in Java to OpenR66. For instance, if a protocol like HTTP upload or FTP upload + allows to get a file upload by packet, you can then route this file transfer through OpenR66 + to a final OpenR66 Server using the protocol but without writing an intermediary file + (directly write the bytes from the upload to the OpenR66 SendThroughClient interface). + A simple example is shown in TestSendThroughClient. + + So this method needs some minor developments to be implemented. + +**RecvThroughClient + + This method is not a full implemented method. It is a way to route a file transfer to one + protocol in Java to OpenR66. For instance, if a protocol like HTTP or FTP download allows to + get a file downloaded by packet, you can then route directly the file transfer from OpenR66 + from a remote OpenR66 Server using the protocol directly but without writing an intermediary + file (directly write the bytes from the download from the OpenR66 RecvThroughHandler + interface). A simple example is shown in TestRecvThroughClient. + + So this method needs some minor developments to be implemented. + +**ProgressBarTransfer + + This method is not a full implemented method. It is a way to implement a file transfer within + a Graphical User Interface or to get information on progression during the transfer. + Such an example is presented in the R66GUI. + + So this method needs some minor developments to be implemented. + +**RequestTransfer + + This utility is used to get information for a specific runner or to have an action on this runner. + + The arguments are the following: + + * The first argument is the client XML configuration file including the database access. + + *'-id' option: this is the Runner Id. + + *'-to' or '-from' option (exclusive): this specifies the way of the request transfer. + '-to' specifies that the original request was initiated by the current running host to + the remote specified host. '-from' specifies that the original request was initiated by + the remote specified host. + + * Optional arguments (exclusive): without any of those arguments, the request only returns + the current information of the runner. + + *'-cancel' option: the runner will be canceled. Any file currently in writing will be deleted. + + *'-stop' option: the runner will be stopped (but not canceled). + + *'-restart' option: the runner will be restart (if stopped). + +**RequestInformation + + This utility is used to get information for a file, a directory, with or without wildcard + characters ('*' and '?"). + + The arguments are the following: + + * The first argument is the client XML configuration file including the database access. + + *'-to' option: specifies the requested host. + + *'-rule' option: the rule + + *'-file' the optional file for which to get info (may contain wildcard characters) + + * Optional arguments (exclusive): without any of those arguments, the request only + returns the existence of the file or directory. + + *'-exist' to test the existence. + + *'-detail' to get the detail on file. + + *'-list' to get the list of files. + + *'-mlsx' to get the list and details of files + +**Message + + This utility is used to send a short message to another server (like a ping in OpenR66 protocol) + + The arguments are the following: + + * The first argument is the client XML configuration file + + *'-to' option: specifies the requested host. + + *'-msg' option: the msg to send diff --git a/src/site/apt/configuration.apt b/src/site/apt/configuration.apt index a428c095b..0fcd8b53d 100644 --- a/src/site/apt/configuration.apt +++ b/src/site/apt/configuration.apt @@ -1,146 +1,146 @@ -WaarpR66 Server and Clients Configuration - -*How to configure Waarp OpenR66 - -**Configuration files - - In the zip distribution (available at Github for download), - you will find an extra directory named: where several examples files are located as: - , . Other files like are for clients, and - , , , <*.rule.xml>, certs/*.cer/*.jks/*.ggp - are for initialization or password storage. - - A detailed description of their contents can be found in {{{./Config-OpenR66-Server.html}Config OpenR66 Server}}, - {{{./Config-OpenR66-Client.html}Config OpenR66 Client}}, {{{./Config-OpenR66-ClientNoDB.html}Config OpenR66 Client with No Database}}, - {{{./Config-OpenR66-SubmitClient.html}Config OpenR66 Client for Submit Only}}, {{{./OpenR66-Limit.html}Config OpenR66 Limits}}, - {{{./OpenR66-Rule.html}Config OpenR66 Rule}}, - {{{./OpenR66-Authent.html}Config OpenR66 Authentications}} - and {{{./Config-Snmp.html}Config for OpenR66 SNMP support}}. - - The first ones () specifies the general behavior for the OpenR66 Server: - - * server names, ports, home directory and subdirectories, ssl key - - * server admin name and password (for administrator access and shutdown function) - - * server special configuration like threads number, timeout of connection, deleteOnAbort, - usenio, fastmd5, blocksize - - * server database configuration - - [] - - The second one () is a configuration file for OpenR66 Client: - - * client names, home directory and subdirectories, optionally ssl key - - * server special configuration like threads number, timeout of connection, deleteOnAbort, - usenio, fastmd5, blocksize - - * optionally server database configuration - - [] - - The file is an example of how to instantiate the database with the correct values in it. - The values are from: - - * : host name and database access - - * rules_directory where <*.rule.xml> files are: all information needed to process a rule (directories, - actions on pre transfer, post transfer and error status). - - * host_authent_file (host name, address, ports and ssl support) and - the associated <*.ggp> for password: - - * limit_configuration_file where session and global limit for bandwitdth are specified. - -**Steps - - *Create keys for SSH and Passwords (see {{{./sslconfig.html}Config OpenR66 OpenSSL and WaarpPassword GUI project}}) - - *Create configurations files (server configuration file, authentication configuration file, rule configuration file, snmp configuration file) for a server - - *Create configurations files (client configuration file, authentication configuration file, rule configuration file) for a client - - *Create the database using the ServerInitDatabase (see {{{./commands.html}Commands detail}}) - - A simplified picture of the OpenR66 Database schema is shown here: - -[images/OpenR66-database.png] Waarp OpenR66 Database Schema - - *Make some tests for server using Message command to all declared interface (NOSSL and SSL) (see {{{./commands.html}Commands detail}}) - -*How to run Waarp OpenR66 - - It can be started like: - ----------------------------------------- - java ... classpath and jvm settings ... ----------------------------------------- - - Note that in the classpath you need : - - *External jars: - - *{{{http://netty.io}Netty}} - - *{{{http://commons.apache.org/io/}Apache-Commons-IO}} - - *{{{http://commons.apache.org/exec/}Apache-Commons-Exec}} - - *{{{http://commons.apache.org/compress/}Apache-Commons-Compress}} - - *{{{http://commons.apache.org/codec/}Apache-Commons-Codec}} - - *{{{http://www.dom4j.org/}DOM4J}} - - *{{{http://jaxen.codehaus.org/}Jaxen}} - - *{{{http://www.slf4j.org/}SLF4J}} - - *{{{http://logback.qos.ch/}Logback}} - - *{{{https://github.com/jezhumble/javasysmon}JavaSysMon}} - - *{{{http://www.snmp4j.org}SNMP4J}} - - * for instance for H2, PostGreSQL, Oracle, MySQL - - *Waarp jars: - - * - - * - - * - - * - - * - - [] - - To shutdown the service, either you do if Unix (not under Windows) - ----------------------------------------- - kill -s USR1 ----------------------------------------- - - Or use the TERM (15) signal - ----------------------------------------- - kill -s TERM ----------------------------------------- - - or much better you connect as an admin user into the Administrator (HTTPS) and ask to shutdown - - or you use the command line: - ----------------------------------------- - java ... classpath and jvm settings ... ----------------------------------------- - - where the password is the one in the for admin actions. - - - Hope this helps a bit... If you have any questions, remarks, just ask! +WaarpR66 Server and Clients Configuration + +*How to configure Waarp OpenR66 + +**Configuration files + + In the zip distribution (available at Github for download), + you will find an extra directory named: where several examples files are located as: + , . Other files like are for clients, and + , , , <*.rule.xml>, certs/*.cer/*.jks/*.ggp + are for initialization or password storage. + + A detailed description of their contents can be found in {{{./Config-OpenR66-Server.html}Config OpenR66 Server}}, + {{{./Config-OpenR66-Client.html}Config OpenR66 Client}}, {{{./Config-OpenR66-ClientNoDB.html}Config OpenR66 Client with No Database}}, + {{{./Config-OpenR66-SubmitClient.html}Config OpenR66 Client for Submit Only}}, {{{./OpenR66-Limit.html}Config OpenR66 Limits}}, + {{{./OpenR66-Rule.html}Config OpenR66 Rule}}, + {{{./OpenR66-Authent.html}Config OpenR66 Authentications}} + and {{{./Config-Snmp.html}Config for OpenR66 SNMP support}}. + + The first ones () specifies the general behavior for the OpenR66 Server: + + * server names, ports, home directory and subdirectories, ssl key + + * server admin name and password (for administrator access and shutdown function) + + * server special configuration like threads number, timeout of connection, deleteOnAbort, + usenio, fastmd5, blocksize + + * server database configuration + + [] + + The second one () is a configuration file for OpenR66 Client: + + * client names, home directory and subdirectories, optionally ssl key + + * server special configuration like threads number, timeout of connection, deleteOnAbort, + usenio, fastmd5, blocksize + + * optionally server database configuration + + [] + + The file is an example of how to instantiate the database with the correct values in it. + The values are from: + + * : host name and database access + + * rules_directory where <*.rule.xml> files are: all information needed to process a rule (directories, + actions on pre transfer, post transfer and error status). + + * host_authent_file (host name, address, ports and ssl support) and + the associated <*.ggp> for password: + + * limit_configuration_file where session and global limit for bandwitdth are specified. + +**Steps + + *Create keys for SSH and Passwords (see {{{./sslconfig.html}Config OpenR66 OpenSSL and WaarpPassword GUI project}}) + + *Create configurations files (server configuration file, authentication configuration file, rule configuration file, snmp configuration file) for a server + + *Create configurations files (client configuration file, authentication configuration file, rule configuration file) for a client + + *Create the database using the ServerInitDatabase (see {{{./commands.html}Commands detail}}) + + A simplified picture of the OpenR66 Database schema is shown here: + +[images/OpenR66-database.png] Waarp OpenR66 Database Schema + + *Make some tests for server using Message command to all declared interface (NOSSL and SSL) (see {{{./commands.html}Commands detail}}) + +*How to run Waarp OpenR66 + + It can be started like: + +---------------------------------------- + java ... classpath and jvm settings ... +---------------------------------------- + + Note that in the classpath you need : + + *External jars: + + *{{{http://netty.io}Netty}} + + *{{{http://commons.apache.org/io/}Apache-Commons-IO}} + + *{{{http://commons.apache.org/exec/}Apache-Commons-Exec}} + + *{{{http://commons.apache.org/compress/}Apache-Commons-Compress}} + + *{{{http://commons.apache.org/codec/}Apache-Commons-Codec}} + + *{{{http://www.dom4j.org/}DOM4J}} + + *{{{http://jaxen.codehaus.org/}Jaxen}} + + *{{{http://www.slf4j.org/}SLF4J}} + + *{{{http://logback.qos.ch/}Logback}} + + *{{{https://github.com/jezhumble/javasysmon}JavaSysMon}} + + *{{{http://www.snmp4j.org}SNMP4J}} + + * for instance for H2, PostGreSQL, Oracle, MySQL + + *Waarp jars: + + * + + * + + * + + * + + * + + [] + + To shutdown the service, either you do if Unix (not under Windows) + +---------------------------------------- + kill -s USR1 +---------------------------------------- + + Or use the TERM (15) signal + +---------------------------------------- + kill -s TERM +---------------------------------------- + + or much better you connect as an admin user into the Administrator (HTTPS) and ask to shutdown + + or you use the command line: + +---------------------------------------- + java ... classpath and jvm settings ... +---------------------------------------- + + where the password is the one in the for admin actions. + + + Hope this helps a bit... If you have any questions, remarks, just ask! diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt index b43556b90..316c86e24 100644 --- a/src/site/apt/index.apt +++ b/src/site/apt/index.apt @@ -1,58 +1,58 @@ -Waarp OpenR66 - - The Waarp OpenR66 project is a proposal of a file transfer monitor for real production - environment. It supports send and receive file transfer, multiple simultaneous file transfer, - transfer through support (for instance from a web server routed through OpenR66 to another server), - multiplexing network connection (only one network socket is used between two servers), pre- - post- or error- transfer action (several possibilities including execution of external scripts), - MD5 packet validation (optional), SSL support (optional), bandwidth limitation both at global - (all sockets) or local (one socket at a time) (optional), Web supervision included, simple - database support (H2, Oracle, PostGreSQL or MySQL databases are supported) that allow to - enhance supervision or production handling, heavy or light clients where clients can only - initiate transfers (send or receive) but do not accept a new transfer from external servers - (heavy clients are using a database connection, while light clients are not using at all - databases, useful for simple PC for instance). - - A new possibility of High Availability and horizontal scalability are proposed, - based on an external Load Balancer on - TCP basis (as HA-Proxy) and a Shared Storage (like a NAS). The idea is to load-balance - the R66 file transfer monitors as a same server (sharing both database, storage and in front - through the load balancer, the same IP and port). It does not prevent a transfer to be in error - if one of the servers goes down, but does allow a quick restart. - -Dependency - - It is based mainly on the NETTY framework (NIO great framework support at {{http://netty.io}} - and is tend to be really efficient, both in term of memory, threads and network bandwidth. - -Specificities - - Bandwidth limitation can be configured both - in store and retrieve, per session (although only one value is set by default, but it can be - changed dynamically if needed) or globally to the server and of course with no limitation at - all if wanted. Limitation should be enough to change the bandwidth behavior for instance - depending on the time in the day, so as to allow to limit bandwidth usage when users are at - work and in contrary to allow more speed when only batchs are running. - - The specificity of this project is you can adapt this software to your particular needs by - changing the pre or post action (even error actions) on transfers (not only transfer). - -[images/waarp.jpg] Waarp Main Project Logo - - See global Waarp project at {{http://waarp.github.com/Waarp/}} and particular OpenR66 project at - {{http://github.com/WaarpR66/}} - -Benchmarks - - Some pre benchmarks were done on PC and a Power5 server (12 CPU). In every benchmarks, the java - used memory was less than 200 Mbytes, the CPU was always less than 4 CPU by JVM (server or client). - The tested file has a size of 1,12 Mbytes. - - * 100 synchronous clients using one multiplexing network connection: 32 transmissions by second - or 286 Mbits (with or without MD5) - - * 1000 asynchronous transfers (submitted work) using one multiplexing network connection: - 59 transmissions by second or 527 Mbits - - * 1000 synchronous clients using 10 multiplexing network connection (100 synchronous clients - by network client): 70 transmissions by second or 627 Mbits +Waarp OpenR66 + + The Waarp OpenR66 project is a proposal of a file transfer monitor for real production + environment. It supports send and receive file transfer, multiple simultaneous file transfer, + transfer through support (for instance from a web server routed through OpenR66 to another server), + multiplexing network connection (only one network socket is used between two servers), pre- + post- or error- transfer action (several possibilities including execution of external scripts), + MD5 packet validation (optional), SSL support (optional), bandwidth limitation both at global + (all sockets) or local (one socket at a time) (optional), Web supervision included, simple + database support (H2, Oracle, PostGreSQL or MySQL databases are supported) that allow to + enhance supervision or production handling, heavy or light clients where clients can only + initiate transfers (send or receive) but do not accept a new transfer from external servers + (heavy clients are using a database connection, while light clients are not using at all + databases, useful for simple PC for instance). + + A new possibility of High Availability and horizontal scalability are proposed, + based on an external Load Balancer on + TCP basis (as HA-Proxy) and a Shared Storage (like a NAS). The idea is to load-balance + the R66 file transfer monitors as a same server (sharing both database, storage and in front + through the load balancer, the same IP and port). It does not prevent a transfer to be in error + if one of the servers goes down, but does allow a quick restart. + +Dependency + + It is based mainly on the NETTY framework (NIO great framework support at {{http://netty.io}} + and is tend to be really efficient, both in term of memory, threads and network bandwidth. + +Specificities + + Bandwidth limitation can be configured both + in store and retrieve, per session (although only one value is set by default, but it can be + changed dynamically if needed) or globally to the server and of course with no limitation at + all if wanted. Limitation should be enough to change the bandwidth behavior for instance + depending on the time in the day, so as to allow to limit bandwidth usage when users are at + work and in contrary to allow more speed when only batchs are running. + + The specificity of this project is you can adapt this software to your particular needs by + changing the pre or post action (even error actions) on transfers (not only transfer). + +[images/waarp.jpg] Waarp Main Project Logo + + See global Waarp project at {{http://waarp.github.com/Waarp/}} and particular OpenR66 project at + {{http://github.com/WaarpR66/}} + +Benchmarks + + Some pre benchmarks were done on PC and a Power5 server (12 CPU). In every benchmarks, the java + used memory was less than 200 Mbytes, the CPU was always less than 4 CPU by JVM (server or client). + The tested file has a size of 1,12 Mbytes. + + * 100 synchronous clients using one multiplexing network connection: 32 transmissions by second + or 286 Mbits (with or without MD5) + + * 1000 asynchronous transfers (submitted work) using one multiplexing network connection: + 59 transmissions by second or 527 Mbits + + * 1000 synchronous clients using 10 multiplexing network connection (100 synchronous clients + by network client): 70 transmissions by second or 627 Mbits diff --git a/src/site/apt/protocol.apt b/src/site/apt/protocol.apt index 276ce17df..16b3b5cb8 100644 --- a/src/site/apt/protocol.apt +++ b/src/site/apt/protocol.apt @@ -1,171 +1,171 @@ -OpenR66-Protocol - - We describe here the logic of the protocol. - - A simplified picture is shown here: - -[images/OpenR66-Protocol.png] Waarp Protocol - - First we describe the different value that can be found. - -UpdatedInfo status - - A Request (DbTaskRunner) can have several UpdatedInfo status: - - *UNKNOWN : no particular information on it. - - *NOTUPDATED : in used by other database object when they are taken into account. - - *INTERRUPTED : a request is interrupted but can be rescheduled. - - *TOSUBMIT : a request is proposed to be submited by the Commander (or other database object are - supposed to be taken into account). - - *INERROR : a request is in error and can not be submited by the Commander until its status is - changed explicitely. - - *RUNNING : a request is currently running. - - *DONE : a request is over and fully done. - -Step values - - A Request can have several Step values: - - *NOTASK : the request has never started. - - *PRETASK : the request is currently in Pre transfer step. - - *TRANSFERTASK : the request is currently in transfer step. - - *POSTTASK : the request is currently in Post transfer step (valid transfer only). - - *ALLDONETASK : the request is fully finished (UpdatedInfo is in DONE status too). - - *ERRORTASK : the request is currently in the Error step while an error occurs (either in PRE, - TRANSFER or POST step). - - [] - - A Request has two Step values: - - *GlobalStep : the current request step value - - *GlobalLastStep : this is the last valid request step value. When GlobalStep is in ERROR step, - GlobalLastStep says in which step it was before entering in error. This information is used to - enable restart of the Request from this valid last step. - -Detailed information - - Each Step values and UpdatedInfo has an ErrorCode detailed information: - - *InitOk : stands for correct initialization of the Request (startup and authentication) - - *PreProcessingOk, TransferOk, PostProcessingOk : stand for correct ending of the specified step - - *CompleteOk : stands for all action are correct (ALLDONE for step and DONE for UpdatedInfo) - - *Running : stands for current Step is in Running status. - - *StoppedTransfer, CanceledTransfer : stand for a Request where an action stopped or canceled - the given Request. A Stopped Request can be restart from the current status. A Canceled Request - starts from the beginning of the current step. For instance for the Transfer step, Stopped will - imply that restart is from the current valid transferred block, while Cancel will imply to - restart from the very beginning of the transfer (first block). - - *QueryAlreadyFinished : stands for special code where the Request is in fact remotely already - finished and so can be finished locally. - - * Other codes specifies different kinds of error (NotKnownHost, Shutdown, RemoteError, ...). - -Sequential logic - - A request of transfer follows a sequential logic: - - * The request is registered in the database with a TOSUBMIT status. - - * A Request that was in a INTERRUPTED status is changed in a TOSUBMIT status. - - * The Commander get some requests with the TOSUBMIT status and makes them as RUNNING status. - - * The Commander submits those requests as separates ClientRunners. - - * The ClientRunner first checks that the given Request is not a "Self Requested" request, - meaning that only requester host can execute a ClientRunner, except if this request was in - the POSTTASK step so that Requested Host can finalize the request. - - * The ClientRunner gets the remote requested Host address and tries to open the connection. - If a network conection with the given requested host is already opened, this network connection - is reused by the new ClientRunner. - - * The connection can use SSL support (different port than non SSL). This is an option of transfer. - This option is selected while selecting the Host ID for SSL support for the remote Requested Host. - This option is CPU and Memory consuming. - - * Once the network connection is found, a private connection (in memory connection) is opened to - enable the multiplexing of this request with other requests on the same network connection. - This private connection is attached to a new LocalChannelReference which references the Request, - the session, the remote and private connections. A valid LocalChannelReference contains two - private connection Ids, one for the local private connection, and one for the remote private - connection. - - * A Startup Message is sent to the local private connection to initiate it. - - * The same Startup Message is sent back to the remote private connection to initiate too the - relation between them and to instantiate the same LocalChannelReference on the remote host. - - * Once the LocalChannelReference is OK, the Requester host sends an Authent Message in order - to authenticate this host. - - * The Requested host sends back its own Authent Message too. In case of Check of IP, the authentication - is confirmed if both password and IP are aligned with the local definition of the remote partner. - - * Once authenticated, the Requester Host sends the Request Message. - - * The Requested Host check if the authentication and the request are compatibles, check some - constraints (like CPU or connexion limits), check some - specific options on the request itself (start, restart, ...) and sends back the validated - request to the Requester Host. - - * The Request is in InitOk as detailed information. - - * The validated Request is now running the Pre Task step. - - * Once finished, the Request is in PreProcessingOK status. - - * Now the transmission can start. The sender (which could be either the Requested or the - Requester host) launch its own RetrieveRunner. This RetrieveRunner sends to the other host - all DataBlock Messages. - - * Each DataBlock Message can include a MD5 control of the packet in it (option of transfer). - This option is not mandatory and is CPU consuming. - - * Once all DataBlock are sent, the RetrieveRunner sends an EndTransfer Message to the receiver - host. - - * The receiver host executes first its PostProcessing actions. - - * The Request is first in TransferOk status for Receiver. - - * The Request is in PostProcesseingOk status for receiver. - - * The receiver sends back the validated EndTransfer Message. - - * The Request is in TransferOk status for Sender. - - * The Request is now on Finalize way. Sender host executes the Post actions on its turn. - - * The Request is in PostProcesseingOk status for Sender. - - * Once the PostProcessing is over, the RetrieveRunner (Sender) sends to the remote host a - EndRequest Message. - - * The remote host sends back the validated EndRequest Message. - - * The Request is now totally finished and its status is CompleteOk ALLDONE on both side. - - [] - - At each step, an error can occurs and will stop the request, setting its UpdatedInfo to - INERROR or INTERRUPTED status. The GlobalStep could be in ERROR status if the ERROR step - action is run. +OpenR66-Protocol + + We describe here the logic of the protocol. + + A simplified picture is shown here: + +[images/OpenR66-Protocol.png] Waarp Protocol + + First we describe the different value that can be found. + +UpdatedInfo status + + A Request (DbTaskRunner) can have several UpdatedInfo status: + + *UNKNOWN : no particular information on it. + + *NOTUPDATED : in used by other database object when they are taken into account. + + *INTERRUPTED : a request is interrupted but can be rescheduled. + + *TOSUBMIT : a request is proposed to be submited by the Commander (or other database object are + supposed to be taken into account). + + *INERROR : a request is in error and can not be submited by the Commander until its status is + changed explicitely. + + *RUNNING : a request is currently running. + + *DONE : a request is over and fully done. + +Step values + + A Request can have several Step values: + + *NOTASK : the request has never started. + + *PRETASK : the request is currently in Pre transfer step. + + *TRANSFERTASK : the request is currently in transfer step. + + *POSTTASK : the request is currently in Post transfer step (valid transfer only). + + *ALLDONETASK : the request is fully finished (UpdatedInfo is in DONE status too). + + *ERRORTASK : the request is currently in the Error step while an error occurs (either in PRE, + TRANSFER or POST step). + + [] + + A Request has two Step values: + + *GlobalStep : the current request step value + + *GlobalLastStep : this is the last valid request step value. When GlobalStep is in ERROR step, + GlobalLastStep says in which step it was before entering in error. This information is used to + enable restart of the Request from this valid last step. + +Detailed information + + Each Step values and UpdatedInfo has an ErrorCode detailed information: + + *InitOk : stands for correct initialization of the Request (startup and authentication) + + *PreProcessingOk, TransferOk, PostProcessingOk : stand for correct ending of the specified step + + *CompleteOk : stands for all action are correct (ALLDONE for step and DONE for UpdatedInfo) + + *Running : stands for current Step is in Running status. + + *StoppedTransfer, CanceledTransfer : stand for a Request where an action stopped or canceled + the given Request. A Stopped Request can be restart from the current status. A Canceled Request + starts from the beginning of the current step. For instance for the Transfer step, Stopped will + imply that restart is from the current valid transferred block, while Cancel will imply to + restart from the very beginning of the transfer (first block). + + *QueryAlreadyFinished : stands for special code where the Request is in fact remotely already + finished and so can be finished locally. + + * Other codes specifies different kinds of error (NotKnownHost, Shutdown, RemoteError, ...). + +Sequential logic + + A request of transfer follows a sequential logic: + + * The request is registered in the database with a TOSUBMIT status. + + * A Request that was in a INTERRUPTED status is changed in a TOSUBMIT status. + + * The Commander get some requests with the TOSUBMIT status and makes them as RUNNING status. + + * The Commander submits those requests as separates ClientRunners. + + * The ClientRunner first checks that the given Request is not a "Self Requested" request, + meaning that only requester host can execute a ClientRunner, except if this request was in + the POSTTASK step so that Requested Host can finalize the request. + + * The ClientRunner gets the remote requested Host address and tries to open the connection. + If a network conection with the given requested host is already opened, this network connection + is reused by the new ClientRunner. + + * The connection can use SSL support (different port than non SSL). This is an option of transfer. + This option is selected while selecting the Host ID for SSL support for the remote Requested Host. + This option is CPU and Memory consuming. + + * Once the network connection is found, a private connection (in memory connection) is opened to + enable the multiplexing of this request with other requests on the same network connection. + This private connection is attached to a new LocalChannelReference which references the Request, + the session, the remote and private connections. A valid LocalChannelReference contains two + private connection Ids, one for the local private connection, and one for the remote private + connection. + + * A Startup Message is sent to the local private connection to initiate it. + + * The same Startup Message is sent back to the remote private connection to initiate too the + relation between them and to instantiate the same LocalChannelReference on the remote host. + + * Once the LocalChannelReference is OK, the Requester host sends an Authent Message in order + to authenticate this host. + + * The Requested host sends back its own Authent Message too. In case of Check of IP, the authentication + is confirmed if both password and IP are aligned with the local definition of the remote partner. + + * Once authenticated, the Requester Host sends the Request Message. + + * The Requested Host check if the authentication and the request are compatibles, check some + constraints (like CPU or connexion limits), check some + specific options on the request itself (start, restart, ...) and sends back the validated + request to the Requester Host. + + * The Request is in InitOk as detailed information. + + * The validated Request is now running the Pre Task step. + + * Once finished, the Request is in PreProcessingOK status. + + * Now the transmission can start. The sender (which could be either the Requested or the + Requester host) launch its own RetrieveRunner. This RetrieveRunner sends to the other host + all DataBlock Messages. + + * Each DataBlock Message can include a MD5 control of the packet in it (option of transfer). + This option is not mandatory and is CPU consuming. + + * Once all DataBlock are sent, the RetrieveRunner sends an EndTransfer Message to the receiver + host. + + * The receiver host executes first its PostProcessing actions. + + * The Request is first in TransferOk status for Receiver. + + * The Request is in PostProcesseingOk status for receiver. + + * The receiver sends back the validated EndTransfer Message. + + * The Request is in TransferOk status for Sender. + + * The Request is now on Finalize way. Sender host executes the Post actions on its turn. + + * The Request is in PostProcesseingOk status for Sender. + + * Once the PostProcessing is over, the RetrieveRunner (Sender) sends to the remote host a + EndRequest Message. + + * The remote host sends back the validated EndRequest Message. + + * The Request is now totally finished and its status is CompleteOk ALLDONE on both side. + + [] + + At each step, an error can occurs and will stop the request, setting its UpdatedInfo to + INERROR or INTERRUPTED status. The GlobalStep could be in ERROR status if the ERROR step + action is run. diff --git a/src/site/apt/sslconfig.apt b/src/site/apt/sslconfig.apt index da1ef495f..2f6bfa88f 100644 --- a/src/site/apt/sslconfig.apt +++ b/src/site/apt/sslconfig.apt @@ -1,80 +1,80 @@ -OpenR66 SSL configuration - -*How to configure Waarp OpenR66 SSL - - To generate the stores for OpenR66 , you need to create 2 JKS keyStore. - To generate those files, you can use the "keytool" command from the JDK or using - the free tool KeyTool IUI (last known version in 2.4.1). - -*Using Keytool IUI: - -**For SSL connection without authentication of clients (also valid for Administration): - - * Server side: - - Create one jks KeyStore (server.jks) with one Private Key Version 3 using - RSA algorithm. Use this KeyStore as KeyStore for the Server. - To do that, suing KeyTool IUI: - - 1) Create an empty KeyStore - - 2) Create a Private Key Version 3 with RSA algorithm added to this KeyStore - - * Client side: - - Create one jks TrustStore (clientTrust.jks) with the Certificate Chain of - the Server Key from the Server as a Regular Certificate. - Use this KeyStore as Trustore for the Client. - To do that, using KeyTool IUI: - - 1) From the Server Keytore, export Private Key (2 files with one Certificate - Chain) - - 2) Create one jks TrustStore (Empty KeyStore) - - 3) Import the Trusted Certificate as Regular Certificate (Certificate Chain - as .der file) - -**For SSL connection with authentication of clients: - - A) First do as without authentication of clients for the server authentication - side. - server.jks for the Server's KeyStore and clientTrust.jks for the Client's - TrustStore. - - B) Handle the reverse authentication of multiples clients within the server - - * Client side: - - Create one jks KeyStore with one Private Key Version 3 using RSA algorithm - for each Client (client1.jks, client2.jks, clientn.jks). - Use this KeyStore as KeyStore for the Client. - To do that, suing KeyTool IUI: - - 1) Create an empty KeyStore - - 2) Create a Private Key Version 3 with RSA algorithm added to this KeyStore - - * Server side: - - Create one jks TrustStore (serverTrust.jks) with the Certificate Chain of - the Client Key from the Client as a Regular Certificate. - Use this KeyStore as Trustore for the Server. - To do that, using KeyTool IUI: - - 1) Create one jks TrustStore (Empty KeyStore) - - 2) From the Client Keytore, export Private Key (2 files with one - Certificate Chain) - - 3) Import the Trusted Certificate as Regular Certificate (Certificate - Chain as .der file) - - 4) Import all Trusted Certificates as with 2 and 3 in the same TrustStore - -*Password Keys - - For Host passwords, admin passwords, OpenR66 uses encrypted password using private DES key. - We provide a GUI to generate the DES key (*.des file) and those passwords in files (*.ggp files). - +OpenR66 SSL configuration + +*How to configure Waarp OpenR66 SSL + + To generate the stores for OpenR66 , you need to create 2 JKS keyStore. + To generate those files, you can use the "keytool" command from the JDK or using + the free tool KeyTool IUI (last known version in 2.4.1). + +*Using Keytool IUI: + +**For SSL connection without authentication of clients (also valid for Administration): + + * Server side: + + Create one jks KeyStore (server.jks) with one Private Key Version 3 using + RSA algorithm. Use this KeyStore as KeyStore for the Server. + To do that, suing KeyTool IUI: + + 1) Create an empty KeyStore + + 2) Create a Private Key Version 3 with RSA algorithm added to this KeyStore + + * Client side: + + Create one jks TrustStore (clientTrust.jks) with the Certificate Chain of + the Server Key from the Server as a Regular Certificate. + Use this KeyStore as Trustore for the Client. + To do that, using KeyTool IUI: + + 1) From the Server Keytore, export Private Key (2 files with one Certificate + Chain) + + 2) Create one jks TrustStore (Empty KeyStore) + + 3) Import the Trusted Certificate as Regular Certificate (Certificate Chain + as .der file) + +**For SSL connection with authentication of clients: + + A) First do as without authentication of clients for the server authentication + side. + server.jks for the Server's KeyStore and clientTrust.jks for the Client's + TrustStore. + + B) Handle the reverse authentication of multiples clients within the server + + * Client side: + + Create one jks KeyStore with one Private Key Version 3 using RSA algorithm + for each Client (client1.jks, client2.jks, clientn.jks). + Use this KeyStore as KeyStore for the Client. + To do that, suing KeyTool IUI: + + 1) Create an empty KeyStore + + 2) Create a Private Key Version 3 with RSA algorithm added to this KeyStore + + * Server side: + + Create one jks TrustStore (serverTrust.jks) with the Certificate Chain of + the Client Key from the Client as a Regular Certificate. + Use this KeyStore as Trustore for the Server. + To do that, using KeyTool IUI: + + 1) Create one jks TrustStore (Empty KeyStore) + + 2) From the Client Keytore, export Private Key (2 files with one + Certificate Chain) + + 3) Import the Trusted Certificate as Regular Certificate (Certificate + Chain as .der file) + + 4) Import all Trusted Certificates as with 2 and 3 in the same TrustStore + +*Password Keys + + For Host passwords, admin passwords, OpenR66 uses encrypted password using private DES key. + We provide a GUI to generate the DES key (*.des file) and those passwords in files (*.ggp files). + It can be found in the subproject WaarpPassword Gui project. \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml index ab762c285..13adfb764 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -1,27 +1,27 @@ - - - - org.apache.maven/skins - maven-default-skin - 1.0 - - - - Waarp Project - images/waarp.jpg - http://www.waarp.it - - - - - - - - - - - - - - - + + + + org.apache.maven/skins + maven-default-skin + 1.0 + + + + Waarp Project + images/waarp.jpg + http://www.waarp.it + + + + + + + + + + + + + + + diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java index 6185e816c..0e16a6043 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java @@ -1,106 +1,106 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.AbstractBusinessRequest; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.task.test.TestExecJavaTask; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for internal Business test - * - * @author Frederic Bregier - * - */ -public class TestBusinessRequest extends AbstractBusinessRequest { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger; - - public TestBusinessRequest(NetworkTransaction networkTransaction, - R66Future future, String remoteHost, BusinessRequestPacket packet) { - super(TestBusinessRequest.class, future, remoteHost, networkTransaction, packet); - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestBusinessRequest.class); - } - if (args.length < 1) { - logger - .error("Needs at least the configuration file as first argument"); - return; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return; - } - Configuration.configuration.pipelineInit(); - - final NetworkTransaction networkTransaction = new NetworkTransaction(); - DbHostAuth host = Configuration.configuration.HOST_AUTH; - ExecutorService executorService = Executors.newCachedThreadPool(); - int nb = 100; - - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start Test of Transaction"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - BusinessRequestPacket packet = new BusinessRequestPacket( - TestExecJavaTask.class.getName() + " business 0 other arguments", 0); - TestBusinessRequest transaction = new TestBusinessRequest( - networkTransaction, arrayFuture[i], host.getHostid(), - packet); - executorService.execute(transaction); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - long time2 = System.currentTimeMillis(); - logger.warn("Success: " + success + " Error: " + error + " NB/s: " + - success * 100 * 1000 / (time2 - time1)); - executorService.shutdown(); - networkTransaction.closeAll(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.AbstractBusinessRequest; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.task.test.TestExecJavaTask; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for internal Business test + * + * @author Frederic Bregier + * + */ +public class TestBusinessRequest extends AbstractBusinessRequest { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger; + + public TestBusinessRequest(NetworkTransaction networkTransaction, + R66Future future, String remoteHost, BusinessRequestPacket packet) { + super(TestBusinessRequest.class, future, remoteHost, networkTransaction, packet); + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestBusinessRequest.class); + } + if (args.length < 1) { + logger + .error("Needs at least the configuration file as first argument"); + return; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return; + } + Configuration.configuration.pipelineInit(); + + final NetworkTransaction networkTransaction = new NetworkTransaction(); + DbHostAuth host = Configuration.configuration.HOST_AUTH; + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = 100; + + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + BusinessRequestPacket packet = new BusinessRequestPacket( + TestExecJavaTask.class.getName() + " business 0 other arguments", 0); + TestBusinessRequest transaction = new TestBusinessRequest( + networkTransaction, arrayFuture[i], host.getHostid(), + packet); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn("Success: " + success + " Error: " + error + " NB/s: " + + success * 100 * 1000 / (time2 - time1)); + executorService.shutdown(); + networkTransaction.closeAll(); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java b/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java index 2c5ddf982..b3aaf0057 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java @@ -1,183 +1,183 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.ProgressBarTransfer; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * @author Frederic Bregier - * - */ -public class TestProgressBarTransfer extends ProgressBarTransfer { - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param id - * @param networkTransaction - * @param callbackdelay - */ - public TestProgressBarTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, long id, NetworkTransaction networkTransaction, - long callbackdelay) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, - blocksize, id, networkTransaction, callbackdelay); - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.client.ProgressBarTransfer#callBack(int, int) - */ - @Override - public void callBack(int currentBlock, int blocksize) { - if (filesize == 0) { - System.err.println("Block: " + currentBlock + " BSize: " + blocksize); - } else { - System.err.println("Block: " + currentBlock + " BSize: " + blocksize + " on " + - (int) (Math.ceil(((double) filesize / (double) blocksize)))); - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.client.ProgressBarTransfer#lastCallBack(boolean, int, int) - */ - @Override - public void lastCallBack(boolean success, int currentBlock, int blocksize) { - if (filesize == 0) { - System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " - + blocksize); - } else { - System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " - + blocksize + - " Size=" + filesize); - } - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(ProgressBarTransfer.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(2); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); - - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - TestProgressBarTransfer transaction = new TestProgressBarTransfer(future, - rhost, localFilename, rule, fileInfo, ismd5, block, idt, - networkTransaction, 100); - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in status:\nWARNED\n " - + result.runner.toShortString() - + - "\n " - + rhost - + "" - + - "\n " - + - (result.file != null ? result.file.toString() + "" - : "no file") - + "\n delay: " + delay); - } else { - logger.info("Transfer in status:\nSUCCESS\n " - + result.runner.toShortString() - + - "\n " - + rhost - + "" - + - "\n " - + - (result.file != null ? result.file.toString() + "" - : "no file") - + "\n delay: " + delay); - } - if (nolog) { - // In case of success, delete the runner - try { - result.runner.delete(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot apply nolog to\n " + result.runner.toShortString(), - e); - } - } - } else { - if (result == null || result.runner == null) { - logger.error("Transfer in\n FAILURE with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(ErrorCode.Unknown.ordinal()); - } - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer is\n WARNED\n " + result.runner.toShortString() + - "\n " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in\n FAILURE\n " + result.runner.toShortString() + - "\n " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - // In case something wrong append - if (future.isDone() && future.isSuccess()) { - System.exit(0); - } else { - System.exit(66); - } - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.ProgressBarTransfer; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * @author Frederic Bregier + * + */ +public class TestProgressBarTransfer extends ProgressBarTransfer { + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param id + * @param networkTransaction + * @param callbackdelay + */ + public TestProgressBarTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, long id, NetworkTransaction networkTransaction, + long callbackdelay) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, + blocksize, id, networkTransaction, callbackdelay); + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.client.ProgressBarTransfer#callBack(int, int) + */ + @Override + public void callBack(int currentBlock, int blocksize) { + if (filesize == 0) { + System.err.println("Block: " + currentBlock + " BSize: " + blocksize); + } else { + System.err.println("Block: " + currentBlock + " BSize: " + blocksize + " on " + + (int) (Math.ceil(((double) filesize / (double) blocksize)))); + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.client.ProgressBarTransfer#lastCallBack(boolean, int, int) + */ + @Override + public void lastCallBack(boolean success, int currentBlock, int blocksize) { + if (filesize == 0) { + System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " + + blocksize); + } else { + System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " + + blocksize + + " Size=" + filesize); + } + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(ProgressBarTransfer.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + System.exit(2); + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); + + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + TestProgressBarTransfer transaction = new TestProgressBarTransfer(future, + rhost, localFilename, rule, fileInfo, ismd5, block, idt, + networkTransaction, 100); + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in status:\nWARNED\n " + + result.runner.toShortString() + + + "\n " + + rhost + + "" + + + "\n " + + + (result.file != null ? result.file.toString() + "" + : "no file") + + "\n delay: " + delay); + } else { + logger.info("Transfer in status:\nSUCCESS\n " + + result.runner.toShortString() + + + "\n " + + rhost + + "" + + + "\n " + + + (result.file != null ? result.file.toString() + "" + : "no file") + + "\n delay: " + delay); + } + if (nolog) { + // In case of success, delete the runner + try { + result.runner.delete(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot apply nolog to\n " + result.runner.toShortString(), + e); + } + } + } else { + if (result == null || result.runner == null) { + logger.error("Transfer in\n FAILURE with no Id", future.getCause()); + networkTransaction.closeAll(); + System.exit(ErrorCode.Unknown.ordinal()); + } + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer is\n WARNED\n " + result.runner.toShortString() + + "\n " + rhost + "", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in\n FAILURE\n " + result.runner.toShortString() + + "\n " + rhost + "", future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + // In case something wrong append + if (future.isDone() && future.isSuccess()) { + System.exit(0); + } else { + System.exit(66); + } + } + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java b/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java index f53855d09..3d1b6b49b 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java @@ -1,145 +1,145 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.RecvThroughClient; -import org.waarp.openr66.client.RecvThroughHandler; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for Recv Through client - * - * @author Frederic Bregier - * - */ -public class TestRecvThroughClient extends RecvThroughClient { - public static class TestRecvThroughHandler extends RecvThroughHandler { - - /* - * (non-Javadoc) - * @see - * org.waarp.openr66.client.RecvThroughHandler#writeChannelBuffer(org.jboss.netty.buffer - * .ChannelBuffer) - */ - @Override - public void writeChannelBuffer(ChannelBuffer buffer) - throws OpenR66ProtocolBusinessException { - buffer.skipBytes(buffer.readableBytes()); - // byte [] array = this.getByte(buffer); - // FIXME one should use the array for its own goal - // logger.debug("Write {}", array.length); - } - - } - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - */ - public TestRecvThroughClient(R66Future future, TestRecvThroughHandler handler, - String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction) { - super(future, handler, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, networkTransaction); - } - - /** - * @param args - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestRecvThroughHandler.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - R66Future future = new R66Future(true); - TestRecvThroughHandler handler = new TestRecvThroughHandler(); - TestRecvThroughClient transaction = new TestRecvThroughClient(future, - handler, - rhost, localFilename, rule, fileInfo, ismd5, block, - networkTransaction); - long time1 = System.currentTimeMillis(); - transaction.run(); - future.awaitUninterruptibly(); - - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Warning with Id: " + - result.runner.getSpecialId() + " on file: " + - (result.file != null ? result.file.toString() : "no file") - + " delay: " + delay); - } else { - logger.warn("Success with Id: " + - result.runner.getSpecialId() + " on Final file: " + - (result.file != null ? result.file.toString() : "no file") - + " delay: " + delay); - } - } else { - if (result == null || result.runner == null) { - logger.warn("Transfer in Error with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(1); - } - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in Warning with Id: " + - result.runner.getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in Error with Id: " + - result.runner.getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.RecvThroughClient; +import org.waarp.openr66.client.RecvThroughHandler; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for Recv Through client + * + * @author Frederic Bregier + * + */ +public class TestRecvThroughClient extends RecvThroughClient { + public static class TestRecvThroughHandler extends RecvThroughHandler { + + /* + * (non-Javadoc) + * @see + * org.waarp.openr66.client.RecvThroughHandler#writeChannelBuffer(org.jboss.netty.buffer + * .ChannelBuffer) + */ + @Override + public void writeChannelBuffer(ChannelBuffer buffer) + throws OpenR66ProtocolBusinessException { + buffer.skipBytes(buffer.readableBytes()); + // byte [] array = this.getByte(buffer); + // FIXME one should use the array for its own goal + // logger.debug("Write {}", array.length); + } + + } + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + */ + public TestRecvThroughClient(R66Future future, TestRecvThroughHandler handler, + String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, NetworkTransaction networkTransaction) { + super(future, handler, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + DbConstant.ILLEGALVALUE, networkTransaction); + } + + /** + * @param args + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestRecvThroughHandler.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + R66Future future = new R66Future(true); + TestRecvThroughHandler handler = new TestRecvThroughHandler(); + TestRecvThroughClient transaction = new TestRecvThroughClient(future, + handler, + rhost, localFilename, rule, fileInfo, ismd5, block, + networkTransaction); + long time1 = System.currentTimeMillis(); + transaction.run(); + future.awaitUninterruptibly(); + + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Warning with Id: " + + result.runner.getSpecialId() + " on file: " + + (result.file != null ? result.file.toString() : "no file") + + " delay: " + delay); + } else { + logger.warn("Success with Id: " + + result.runner.getSpecialId() + " on Final file: " + + (result.file != null ? result.file.toString() : "no file") + + " delay: " + delay); + } + } else { + if (result == null || result.runner == null) { + logger.warn("Transfer in Error with no Id", future.getCause()); + networkTransaction.closeAll(); + System.exit(1); + } + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in Warning with Id: " + + result.runner.getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in Error with Id: " + + result.runner.getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java index aa0d35cd9..7830dc67f 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java @@ -1,220 +1,220 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import org.jboss.netty.channel.ChannelFuture; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.exception.FileEndOfTransferException; -import org.waarp.common.exception.FileTransferException; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.SendThroughClient; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.filesystem.R66File; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for Send Through client - * - * @author Frederic Bregier - * - */ -public class TestSendThroughClient extends SendThroughClient { - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - */ - public TestSendThroughClient(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, networkTransaction); - } - - public boolean sendFile() { - R66File r66file = localChannelReference.getSession().getFile(); - boolean retrieveDone = false; - try { - DataBlock block = null; - try { - block = r66file.readDataBlock(); - } catch (FileEndOfTransferException e) { - // Last block (in fact, no data to read) - retrieveDone = true; - return retrieveDone; - } - if (block == null) { - // Last block (in fact, no data to read) - retrieveDone = true; - return retrieveDone; - } - ChannelFuture future1 = null, future2 = null; - if (block != null) { - future1 = this.writeWhenPossible(block); - } - // While not last block - while (block != null && !block.isEOF()) { - try { - block = r66file.readDataBlock(); - } catch (FileEndOfTransferException e) { - // Wait for last write - retrieveDone = true; - try { - future1.await(); - } catch (InterruptedException e1) { - } - return future1.isSuccess(); - } - future2 = this.writeWhenPossible(block); - try { - future1.await(); - } catch (InterruptedException e) { - } - if (!future1.isSuccess()) { - return false; - } - future1 = future2; - } - // Wait for last write - if (future1 != null) { - try { - future1.await(); - } catch (InterruptedException e) { - } - return future1.isSuccess(); - } - retrieveDone = true; - return retrieveDone; - } catch (FileTransferException e) { - // An error occurs! - this.transferInError(new OpenR66ProtocolSystemException(e)); - return false; - } catch (OpenR66ProtocolPacketException e) { - // An error occurs! - this.transferInError(e); - return false; - } catch (OpenR66RunnerErrorException e) { - // An error occurs! - this.transferInError(e); - return false; - } catch (OpenR66ProtocolSystemException e) { - // An error occurs! - this.transferInError(e); - return false; - } - } - - /** - * @param args - */ - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestSendThroughClient.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - R66Future future = new R66Future(true); - TestSendThroughClient transaction = new TestSendThroughClient(future, - rhost, localFilename, rule, fileInfo, ismd5, block, - networkTransaction); - long time1 = System.currentTimeMillis(); - if (!transaction.initiateRequest()) { - logger.error("Transfer in Error", future.getCause()); - return; - } - if (transaction.sendFile()) { - transaction.finalizeRequest(); - } else { - transaction.transferInError(null); - } - future.awaitUninterruptibly(); - - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Warning with Id: " + - result.runner.getSpecialId() + " on file: " + - (result.file != null ? result.file.toString() : "no file") - + " delay: " + delay); - } else { - logger.warn("Success with Id: " + - result.runner.getSpecialId() + " on Final file: " + - (result.file != null ? result.file.toString() : "no file") - + " delay: " + delay); - } - if (nolog) { - // In case of success, delete the runner - try { - result.runner.delete(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot apply nolog to " + result.runner.toString(), e); - } - } - } else { - if (result == null || result.runner == null) { - logger.warn("Transfer in Error with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(1); - } - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in Warning with Id: " + - result.runner.getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } else { - logger.error("Transfer in Error with Id: " + - result.runner.getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.code.ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - } - - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.exception.FileEndOfTransferException; +import org.waarp.common.exception.FileTransferException; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.SendThroughClient; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.filesystem.R66File; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for Send Through client + * + * @author Frederic Bregier + * + */ +public class TestSendThroughClient extends SendThroughClient { + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + */ + public TestSendThroughClient(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, NetworkTransaction networkTransaction) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + DbConstant.ILLEGALVALUE, networkTransaction); + } + + public boolean sendFile() { + R66File r66file = localChannelReference.getSession().getFile(); + boolean retrieveDone = false; + try { + DataBlock block = null; + try { + block = r66file.readDataBlock(); + } catch (FileEndOfTransferException e) { + // Last block (in fact, no data to read) + retrieveDone = true; + return retrieveDone; + } + if (block == null) { + // Last block (in fact, no data to read) + retrieveDone = true; + return retrieveDone; + } + ChannelFuture future1 = null, future2 = null; + if (block != null) { + future1 = this.writeWhenPossible(block); + } + // While not last block + while (block != null && !block.isEOF()) { + try { + block = r66file.readDataBlock(); + } catch (FileEndOfTransferException e) { + // Wait for last write + retrieveDone = true; + try { + future1.await(); + } catch (InterruptedException e1) { + } + return future1.isSuccess(); + } + future2 = this.writeWhenPossible(block); + try { + future1.await(); + } catch (InterruptedException e) { + } + if (!future1.isSuccess()) { + return false; + } + future1 = future2; + } + // Wait for last write + if (future1 != null) { + try { + future1.await(); + } catch (InterruptedException e) { + } + return future1.isSuccess(); + } + retrieveDone = true; + return retrieveDone; + } catch (FileTransferException e) { + // An error occurs! + this.transferInError(new OpenR66ProtocolSystemException(e)); + return false; + } catch (OpenR66ProtocolPacketException e) { + // An error occurs! + this.transferInError(e); + return false; + } catch (OpenR66RunnerErrorException e) { + // An error occurs! + this.transferInError(e); + return false; + } catch (OpenR66ProtocolSystemException e) { + // An error occurs! + this.transferInError(e); + return false; + } + } + + /** + * @param args + */ + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestSendThroughClient.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + R66Future future = new R66Future(true); + TestSendThroughClient transaction = new TestSendThroughClient(future, + rhost, localFilename, rule, fileInfo, ismd5, block, + networkTransaction); + long time1 = System.currentTimeMillis(); + if (!transaction.initiateRequest()) { + logger.error("Transfer in Error", future.getCause()); + return; + } + if (transaction.sendFile()) { + transaction.finalizeRequest(); + } else { + transaction.transferInError(null); + } + future.awaitUninterruptibly(); + + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Warning with Id: " + + result.runner.getSpecialId() + " on file: " + + (result.file != null ? result.file.toString() : "no file") + + " delay: " + delay); + } else { + logger.warn("Success with Id: " + + result.runner.getSpecialId() + " on Final file: " + + (result.file != null ? result.file.toString() : "no file") + + " delay: " + delay); + } + if (nolog) { + // In case of success, delete the runner + try { + result.runner.delete(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot apply nolog to " + result.runner.toString(), e); + } + } + } else { + if (result == null || result.runner == null) { + logger.warn("Transfer in Error with no Id", future.getCause()); + networkTransaction.closeAll(); + System.exit(1); + } + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in Warning with Id: " + + result.runner.getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } else { + logger.error("Transfer in Error with Id: " + + result.runner.getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + System.exit(result.code.ordinal()); + } + } + } finally { + networkTransaction.closeAll(); + } + + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java index 032900bcc..9d0ea17b0 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java @@ -1,286 +1,286 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.waarp.common.database.DbSession; -import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; -import org.waarp.common.database.exception.WaarpDatabaseException; -import org.waarp.common.file.DataBlock; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.openr66.client.RecvThroughHandler; -import org.waarp.openr66.client.SendThroughClient; -import org.waarp.openr66.commander.ClientRunner; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * WARNING: This class is not functional neither integrated
- * - * Test class for Send Through to another R66 Server as forward
- * Only a subpart of SenThroughClient is to be made since steps 1-2 and steps 7-8 are only for - * client, not for server. - * - * 3) Prepare the request of transfer:
- * R66Future futureReq = new R66Future(true);
- * TestSendThroughForward transaction = new TestSendThroughForward(futureReq,...);
- * if (! transaction.initiateRequest()) { error }
- *
- * 4) Once initiateRequest() gives true, you are ready to send the data in through mode using the - * TestRecvThroughForwardHandler:
- *
- * 5) Once you have finished, so this is the last block, you have to do the following:
- * If the last block is not empty:
- * DataBlock block = transaction.transformToDataBlock(data);
- * block.setEOF(true);
- * futureWrite = transaction.writeWhenPossible(block);
- * futureWrite.awaitUninterruptibly();
- *
- * If the last block is empty, it is already handled by TestRecvThroughForwardHandler
- *
- * 6) If everything is in success:
- * transaction.finalizeRequest();
- *
- * And now wait for the transfer to finish:
- * futureReq.awaitUninterruptibly();
- * R66Result result = futureReq.getResult();
- *
- * - * @author Frederic Bregier - * - */ -public class TestSendThroughForward extends SendThroughClient { - public TestRecvThroughForwardHandler handler; - public DbSession dbSession; - public volatile boolean foundEOF = false; - protected DbTaskRunner sourceRunner; - - public static class TestRecvThroughForwardHandler extends RecvThroughHandler { - - protected TestSendThroughForward client; - - /* - * (non-Javadoc) - * @see - * org.waarp.openr66.client.RecvThroughHandler#writeChannelBuffer(org.jboss.netty.buffer - * .ChannelBuffer) - */ - @Override - public void writeChannelBuffer(ChannelBuffer buffer) - throws OpenR66ProtocolBusinessException { - DataBlock block = new DataBlock(); - if (buffer.readableBytes() <= 0) { - // last block - block.setEOF(true); - } else { - block.setBlock(buffer); - } - try { - client.writeWhenPossible(block).await(); - } catch (OpenR66RunnerErrorException e) { - client.transferInError(e); - } catch (OpenR66ProtocolPacketException e) { - client.transferInError(e); - } catch (OpenR66ProtocolSystemException e) { - client.transferInError(e); - } catch (InterruptedException e) { - client.transferInError(new OpenR66ProtocolSystemException(e)); - } - if (block.isEOF()) { - client.finalizeRequest(); - client.foundEOF = true; - } - } - - } - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - * @param idt - * Id Transfer if any temptative already exists - * @param dbSession - * @param runner - * (recv runner) - */ - public TestSendThroughForward(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction, long idt, - DbSession dbSession, DbTaskRunner runner) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - idt, networkTransaction); - handler = new TestRecvThroughForwardHandler(); - handler.client = this; - this.dbSession = dbSession; - this.sourceRunner = runner; - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.client.SendThroughClient#initiateRequest() - */ - @Override - public boolean initiateRequest() { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestSendThroughForward.class); - } - DbRule rule; - try { - rule = new DbRule(DbConstant.admin.session, rulename); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Rule: " + rulename, e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; - } - int mode = rule.mode; - if (isMD5) { - mode = RequestPacket.getModeMD5(mode); - } - RequestPacket request = new RequestPacket(rulename, - mode, filename, blocksize, sourceRunner.getRank(), - id, fileinfo, -1); - // Not isRecv since it is the requester, so send => isSender is true - boolean isSender = true; - try { - try { - // no delay - taskRunner = - new DbTaskRunner(DbConstant.admin.session, rule, isSender, request, - remoteHost, null); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get task", e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; - } - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - runner.setRecvThroughHandler(handler); - runner.setSendThroughMode(); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - localChannelReference = runner.initRequest(); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.error("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(exc); - return false; - } - try { - localChannelReference.waitReadyForSendThrough(); - } catch (OpenR66Exception e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } - if (taskRunner.getRank() < sourceRunner.getRank()) { - sourceRunner.setRankAtStartup(taskRunner.getRank()); - } - // now start the send from external data - return true; - } finally { - if (taskRunner != null) { - // not delete but sourceRunner and taskRunner should be stopped - // and taskRunner not allowed to be restarted alone - if (future.isFailed()) { - taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); - taskRunner.forceSaveStatus(); - } - } - } - } - - /* - * (non-Javadoc) - * @see org.waarp.openr66.client.SendThroughClient#finalizeRequest() - */ - @Override - public void finalizeRequest() { - if (foundEOF) { - return; - } - super.finalizeRequest(); - } - - /* - * (non-Javadoc) - * @see - * org.waarp.openr66.client.SendThroughClient#transferInError(org.waarp.openr66.protocol.exception - * .OpenR66Exception) - */ - @Override - public void transferInError(OpenR66Exception e) { - super.transferInError(e); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.waarp.common.database.DbSession; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.file.DataBlock; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.openr66.client.RecvThroughHandler; +import org.waarp.openr66.client.SendThroughClient; +import org.waarp.openr66.commander.ClientRunner; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNotYetConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * WARNING: This class is not functional neither integrated
+ * + * Test class for Send Through to another R66 Server as forward
+ * Only a subpart of SenThroughClient is to be made since steps 1-2 and steps 7-8 are only for + * client, not for server. + * + * 3) Prepare the request of transfer:
+ * R66Future futureReq = new R66Future(true);
+ * TestSendThroughForward transaction = new TestSendThroughForward(futureReq,...);
+ * if (! transaction.initiateRequest()) { error }
+ *
+ * 4) Once initiateRequest() gives true, you are ready to send the data in through mode using the + * TestRecvThroughForwardHandler:
+ *
+ * 5) Once you have finished, so this is the last block, you have to do the following:
+ * If the last block is not empty:
+ * DataBlock block = transaction.transformToDataBlock(data);
+ * block.setEOF(true);
+ * futureWrite = transaction.writeWhenPossible(block);
+ * futureWrite.awaitUninterruptibly();
+ *
+ * If the last block is empty, it is already handled by TestRecvThroughForwardHandler
+ *
+ * 6) If everything is in success:
+ * transaction.finalizeRequest();
+ *
+ * And now wait for the transfer to finish:
+ * futureReq.awaitUninterruptibly();
+ * R66Result result = futureReq.getResult();
+ *
+ * + * @author Frederic Bregier + * + */ +public class TestSendThroughForward extends SendThroughClient { + public TestRecvThroughForwardHandler handler; + public DbSession dbSession; + public volatile boolean foundEOF = false; + protected DbTaskRunner sourceRunner; + + public static class TestRecvThroughForwardHandler extends RecvThroughHandler { + + protected TestSendThroughForward client; + + /* + * (non-Javadoc) + * @see + * org.waarp.openr66.client.RecvThroughHandler#writeChannelBuffer(org.jboss.netty.buffer + * .ChannelBuffer) + */ + @Override + public void writeChannelBuffer(ChannelBuffer buffer) + throws OpenR66ProtocolBusinessException { + DataBlock block = new DataBlock(); + if (buffer.readableBytes() <= 0) { + // last block + block.setEOF(true); + } else { + block.setBlock(buffer); + } + try { + client.writeWhenPossible(block).await(); + } catch (OpenR66RunnerErrorException e) { + client.transferInError(e); + } catch (OpenR66ProtocolPacketException e) { + client.transferInError(e); + } catch (OpenR66ProtocolSystemException e) { + client.transferInError(e); + } catch (InterruptedException e) { + client.transferInError(new OpenR66ProtocolSystemException(e)); + } + if (block.isEOF()) { + client.finalizeRequest(); + client.foundEOF = true; + } + } + + } + + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + * @param idt + * Id Transfer if any temptative already exists + * @param dbSession + * @param runner + * (recv runner) + */ + public TestSendThroughForward(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, + int blocksize, NetworkTransaction networkTransaction, long idt, + DbSession dbSession, DbTaskRunner runner) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + idt, networkTransaction); + handler = new TestRecvThroughForwardHandler(); + handler.client = this; + this.dbSession = dbSession; + this.sourceRunner = runner; + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.client.SendThroughClient#initiateRequest() + */ + @Override + public boolean initiateRequest() { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestSendThroughForward.class); + } + DbRule rule; + try { + rule = new DbRule(DbConstant.admin.session, rulename); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Rule: " + rulename, e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; + } + int mode = rule.mode; + if (isMD5) { + mode = RequestPacket.getModeMD5(mode); + } + RequestPacket request = new RequestPacket(rulename, + mode, filename, blocksize, sourceRunner.getRank(), + id, fileinfo, -1); + // Not isRecv since it is the requester, so send => isSender is true + boolean isSender = true; + try { + try { + // no delay + taskRunner = + new DbTaskRunner(DbConstant.admin.session, rule, isSender, request, + remoteHost, null); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get task", e); + future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; + } + ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); + runner.setRecvThroughHandler(handler); + runner.setSendThroughMode(); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + localChannelReference = runner.initRequest(); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; + } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.error("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, taskRunner)); + future.setFailure(exc); + return false; + } + try { + localChannelReference.waitReadyForSendThrough(); + } catch (OpenR66Exception e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } + if (taskRunner.getRank() < sourceRunner.getRank()) { + sourceRunner.setRankAtStartup(taskRunner.getRank()); + } + // now start the send from external data + return true; + } finally { + if (taskRunner != null) { + // not delete but sourceRunner and taskRunner should be stopped + // and taskRunner not allowed to be restarted alone + if (future.isFailed()) { + taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); + taskRunner.forceSaveStatus(); + } + } + } + } + + /* + * (non-Javadoc) + * @see org.waarp.openr66.client.SendThroughClient#finalizeRequest() + */ + @Override + public void finalizeRequest() { + if (foundEOF) { + return; + } + super.finalizeRequest(); + } + + /* + * (non-Javadoc) + * @see + * org.waarp.openr66.client.SendThroughClient#transferInError(org.waarp.openr66.protocol.exception + * .OpenR66Exception) + */ + @Override + public void transferInError(OpenR66Exception e) { + super.transferInError(e); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java b/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java index c6e58c3d3..9f7d966cd 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java @@ -1,110 +1,110 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import java.sql.Timestamp; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.SubmitTransfer; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for multiple SubmitTransfer - * - * @author Frederic Bregier - * - */ -public class TestSubmitTransfer extends SubmitTransfer { - static int nb = 100; - - /** - * @param args - * @param rank - * @return True if OK - */ - protected static boolean getSpecialParams(String[] args, int rank) { - for (int i = rank; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-nb")) { - i++; - nb = Integer.parseInt(args[i]); - } else if (args[i].equalsIgnoreCase("-md5")) { - } else if (args[i].charAt(0) == '-') { - i++;// jump one - } - } - return true; - } - - public TestSubmitTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - Timestamp starttime) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, starttime); - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); - } - if (!getParams(args, true)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - getSpecialParams(args, 1); - - ExecutorService executorService = Executors.newCachedThreadPool(); - R66Future[] arrayFuture = new R66Future[nb]; - - logger.warn("Start Test Submit"); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - Timestamp newstart = ttimestart; - if (newstart != null) { - // delay of 10 ms between each - newstart = new Timestamp(newstart.getTime() + i * 10); - } - TestSubmitTransfer transaction = new TestSubmitTransfer(arrayFuture[i], - rhost, localFilename, rule, fileInfo, ismd5, block, newstart); - // executorService.execute(transaction); - transaction.run(); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - executorService.shutdown(); - logger.warn("Prepare transfer Success: " + success + " Error: " + error); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import java.sql.Timestamp; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.SubmitTransfer; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for multiple SubmitTransfer + * + * @author Frederic Bregier + * + */ +public class TestSubmitTransfer extends SubmitTransfer { + static int nb = 100; + + /** + * @param args + * @param rank + * @return True if OK + */ + protected static boolean getSpecialParams(String[] args, int rank) { + for (int i = rank; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-nb")) { + i++; + nb = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-md5")) { + } else if (args[i].charAt(0) == '-') { + i++;// jump one + } + } + return true; + } + + public TestSubmitTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, + Timestamp starttime) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + DbConstant.ILLEGALVALUE, starttime); + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(SubmitTransfer.class); + } + if (!getParams(args, true)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + getSpecialParams(args, 1); + + ExecutorService executorService = Executors.newCachedThreadPool(); + R66Future[] arrayFuture = new R66Future[nb]; + + logger.warn("Start Test Submit"); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + Timestamp newstart = ttimestart; + if (newstart != null) { + // delay of 10 ms between each + newstart = new Timestamp(newstart.getTime() + i * 10); + } + TestSubmitTransfer transaction = new TestSubmitTransfer(arrayFuture[i], + rhost, localFilename, rule, fileInfo, ismd5, block, newstart); + // executorService.execute(transaction); + transaction.run(); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + executorService.shutdown(); + logger.warn("Prepare transfer Success: " + success + " Error: " + error); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java b/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java index 17a97e607..259562884 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java @@ -1,142 +1,142 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import java.util.List; - -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TSocket; -import org.apache.thrift.transport.TTransport; -import org.apache.thrift.transport.TTransportException; -import org.waarp.thrift.r66.Action; -import org.waarp.thrift.r66.R66Request; -import org.waarp.thrift.r66.R66Result; -import org.waarp.thrift.r66.R66Service; -import org.waarp.thrift.r66.RequestMode; - -/** - * Example of Java class to interact with the Thrift R66 service - * @author "Frederic Bregier" - * - */ -public class TestThriftClientExample { - private static final int PORT = 4266; - private static final int tries = 10000; - - public static void main(String[] args) { - TTransport transport = null; - try { - transport = new TSocket("localhost", PORT); - TProtocol protocol = new TBinaryProtocol(transport); - R66Service.Client client = new R66Service.Client(protocol); - transport.open(); - R66Request request = new R66Request(RequestMode.INFOFILE); - request.setDestuid("hostas"); - request.setFromuid("tests"); - request.setRule("rule3"); - request.setAction(Action.List); - - System.out.println("REQUEST1: " + request.toString()); - List list = client.infoListQuery(request); - System.out.println("RESULT1: " + list.size()); - for (String slist :list) { - System.out.println(slist); - } - - long start = System.currentTimeMillis(); - for (int i = 0; i < tries; i++) { - list = client.infoListQuery(request); - } - long end = System.currentTimeMillis(); - System.out - .println("Delay: " + (end - start) + " : " + ((tries * 1000) / (end - start))); - - - long startEx = System.currentTimeMillis(); - boolean dontknow = false; - for (int i = 0; i < tries; i++) { - dontknow = client.isStillRunning("tests", "hostas", 1346080633424L); - } - long endEx = System.currentTimeMillis(); - System.out.println("StillRunning: "+dontknow); - System.out - .println("Delay: " + (endEx - startEx) + " : " + ((tries * 1000) / (endEx - startEx))); - - request.setMode(RequestMode.INFOREQUEST); - request.setTid(1346080633424L); - request.setAction(Action.Detail); - R66Result result = client.infoTransferQuery(request); - System.out.println("RESULT2: " + result.toString()); - long startQu = System.currentTimeMillis(); - for (int i = 0; i < tries; i++) { - result = client.infoTransferQuery(request); - } - long endQu = System.currentTimeMillis(); - System.out - .println("Delay: " + (endQu - startQu) + " : " + ((tries * 1000) / (endQu - startQu))); - - System.out.println("Exist: " - + - client.isStillRunning(request.getFromuid(), request.getDestuid(), - request.getTid())); - - request.setMode(RequestMode.INFOFILE); - request.setAction(Action.Mlsx); - list = client.infoListQuery(request); - System.out.println("RESULT3: " + list.size()); - for (String slist :list) { - System.out.println(slist); - } - - request = new R66Request(RequestMode.ASYNCTRANSFER); - request.setDestuid("hostbs"); - request.setRule("rule3"); - request.setFile("Documents2.rar"); - request.setInfo("Submitted from Thrift"); - result = client.transferRequestQuery(request); - System.out.println("RESULT4: " + result); - - request = new R66Request(RequestMode.SYNCTRANSFER); - request.setDestuid("hostbs"); - request.setRule("rule3"); - request.setFile("Documents2.rar"); - request.setInfo("Submitted from Thrift"); - result = client.transferRequestQuery(request); - System.out.println("RESULT5: " + result); - - // Wrong request - request = new R66Request(RequestMode.INFOFILE); - - System.out.println("WRONG REQUEST: " + request.toString()); - list = client.infoListQuery(request); - System.out.println("RESULT of Wrong Request: " + list.size()); - for (String slist :list) { - System.out.println(slist); - } - - } catch (TTransportException e) { - e.printStackTrace(); - } catch (TException e) { - e.printStackTrace(); - } - transport.close(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import java.util.List; + +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; +import org.waarp.thrift.r66.Action; +import org.waarp.thrift.r66.R66Request; +import org.waarp.thrift.r66.R66Result; +import org.waarp.thrift.r66.R66Service; +import org.waarp.thrift.r66.RequestMode; + +/** + * Example of Java class to interact with the Thrift R66 service + * @author "Frederic Bregier" + * + */ +public class TestThriftClientExample { + private static final int PORT = 4266; + private static final int tries = 10000; + + public static void main(String[] args) { + TTransport transport = null; + try { + transport = new TSocket("localhost", PORT); + TProtocol protocol = new TBinaryProtocol(transport); + R66Service.Client client = new R66Service.Client(protocol); + transport.open(); + R66Request request = new R66Request(RequestMode.INFOFILE); + request.setDestuid("hostas"); + request.setFromuid("tests"); + request.setRule("rule3"); + request.setAction(Action.List); + + System.out.println("REQUEST1: " + request.toString()); + List list = client.infoListQuery(request); + System.out.println("RESULT1: " + list.size()); + for (String slist :list) { + System.out.println(slist); + } + + long start = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + list = client.infoListQuery(request); + } + long end = System.currentTimeMillis(); + System.out + .println("Delay: " + (end - start) + " : " + ((tries * 1000) / (end - start))); + + + long startEx = System.currentTimeMillis(); + boolean dontknow = false; + for (int i = 0; i < tries; i++) { + dontknow = client.isStillRunning("tests", "hostas", 1346080633424L); + } + long endEx = System.currentTimeMillis(); + System.out.println("StillRunning: "+dontknow); + System.out + .println("Delay: " + (endEx - startEx) + " : " + ((tries * 1000) / (endEx - startEx))); + + request.setMode(RequestMode.INFOREQUEST); + request.setTid(1346080633424L); + request.setAction(Action.Detail); + R66Result result = client.infoTransferQuery(request); + System.out.println("RESULT2: " + result.toString()); + long startQu = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + result = client.infoTransferQuery(request); + } + long endQu = System.currentTimeMillis(); + System.out + .println("Delay: " + (endQu - startQu) + " : " + ((tries * 1000) / (endQu - startQu))); + + System.out.println("Exist: " + + + client.isStillRunning(request.getFromuid(), request.getDestuid(), + request.getTid())); + + request.setMode(RequestMode.INFOFILE); + request.setAction(Action.Mlsx); + list = client.infoListQuery(request); + System.out.println("RESULT3: " + list.size()); + for (String slist :list) { + System.out.println(slist); + } + + request = new R66Request(RequestMode.ASYNCTRANSFER); + request.setDestuid("hostbs"); + request.setRule("rule3"); + request.setFile("Documents2.rar"); + request.setInfo("Submitted from Thrift"); + result = client.transferRequestQuery(request); + System.out.println("RESULT4: " + result); + + request = new R66Request(RequestMode.SYNCTRANSFER); + request.setDestuid("hostbs"); + request.setRule("rule3"); + request.setFile("Documents2.rar"); + request.setInfo("Submitted from Thrift"); + result = client.transferRequestQuery(request); + System.out.println("RESULT5: " + result); + + // Wrong request + request = new R66Request(RequestMode.INFOFILE); + + System.out.println("WRONG REQUEST: " + request.toString()); + list = client.infoListQuery(request); + System.out.println("RESULT of Wrong Request: " + list.size()); + for (String slist :list) { + System.out.println(slist); + } + + } catch (TTransportException e) { + e.printStackTrace(); + } catch (TException e) { + e.printStackTrace(); + } + transport.close(); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java index b20e421ba..e60eae2b2 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java @@ -1,168 +1,168 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import java.net.SocketAddress; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.jboss.netty.channel.Channels; -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.logging.WaarpInternalLogger; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.context.R66FiniteDualStates; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.exception.OpenR66Exception; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; -import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.TestPacket; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.ChannelUtils; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for internal ping pong test - * - * @author Frederic Bregier - * - */ -public class TestTransaction implements Runnable { - /** - * Internal Logger - */ - private static WaarpInternalLogger logger; - - final private NetworkTransaction networkTransaction; - - final private R66Future future; - - private final SocketAddress socketAddress; - - final private TestPacket testPacket; - - public TestTransaction(NetworkTransaction networkTransaction, - R66Future future, SocketAddress socketAddress, TestPacket packet) { - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestTransaction.class); - } - this.networkTransaction = networkTransaction; - this.future = future; - this.socketAddress = socketAddress; - testPacket = packet; - } - - public void run() { - LocalChannelReference localChannelReference = null; - OpenR66Exception lastException = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - localChannelReference = networkTransaction - .createConnection(socketAddress, false, future); - break; - } catch (OpenR66ProtocolNetworkException e1) { - lastException = e1; - localChannelReference = null; - } catch (OpenR66ProtocolRemoteShutdownException e1) { - lastException = e1; - localChannelReference = null; - break; - } catch (OpenR66ProtocolNoConnectionException e1) { - lastException = e1; - localChannelReference = null; - break; - } - } - if (localChannelReference == null) { - logger.error("Cannot connect: " + lastException.getMessage()); - future.setResult(null); - future.setFailure(lastException); - return; - } else if (lastException != null) { - logger.info("Connection retry since ", lastException); - } - localChannelReference.sessionNewState(R66FiniteDualStates.TEST); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, testPacket, false); - } catch (OpenR66ProtocolPacketException e) { - future.setResult(null); - future.setFailure(e); - Channels.close(localChannelReference.getLocalChannel()); - return; - } - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(TestTransaction.class); - } - if (args.length < 1) { - logger - .error("Needs at least the configuration file as first argument"); - return; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return; - } - Configuration.configuration.pipelineInit(); - - final NetworkTransaction networkTransaction = new NetworkTransaction(); - DbHostAuth host = Configuration.configuration.HOST_AUTH; - final SocketAddress socketServerAddress = host.getSocketAddress(); - ExecutorService executorService = Executors.newCachedThreadPool(); - int nb = 100; - - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start Test of Transaction"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - TestPacket packet = new TestPacket("Test", "" + i, 0); - TestTransaction transaction = new TestTransaction( - networkTransaction, arrayFuture[i], socketServerAddress, - packet); - executorService.execute(transaction); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - long time2 = System.currentTimeMillis(); - logger.warn("Success: " + success + " Error: " + error + " NB/s: " + - success * TestPacket.pingpong * 1000 / (time2 - time1)); - executorService.shutdown(); - networkTransaction.closeAll(); - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import java.net.SocketAddress; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.jboss.netty.channel.Channels; +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.logging.WaarpInternalLogger; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.exception.OpenR66Exception; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNetworkException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.TestPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for internal ping pong test + * + * @author Frederic Bregier + * + */ +public class TestTransaction implements Runnable { + /** + * Internal Logger + */ + private static WaarpInternalLogger logger; + + final private NetworkTransaction networkTransaction; + + final private R66Future future; + + private final SocketAddress socketAddress; + + final private TestPacket testPacket; + + public TestTransaction(NetworkTransaction networkTransaction, + R66Future future, SocketAddress socketAddress, TestPacket packet) { + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestTransaction.class); + } + this.networkTransaction = networkTransaction; + this.future = future; + this.socketAddress = socketAddress; + testPacket = packet; + } + + public void run() { + LocalChannelReference localChannelReference = null; + OpenR66Exception lastException = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { + try { + localChannelReference = networkTransaction + .createConnection(socketAddress, false, future); + break; + } catch (OpenR66ProtocolNetworkException e1) { + lastException = e1; + localChannelReference = null; + } catch (OpenR66ProtocolRemoteShutdownException e1) { + lastException = e1; + localChannelReference = null; + break; + } catch (OpenR66ProtocolNoConnectionException e1) { + lastException = e1; + localChannelReference = null; + break; + } + } + if (localChannelReference == null) { + logger.error("Cannot connect: " + lastException.getMessage()); + future.setResult(null); + future.setFailure(lastException); + return; + } else if (lastException != null) { + logger.info("Connection retry since ", lastException); + } + localChannelReference.sessionNewState(R66FiniteDualStates.TEST); + try { + ChannelUtils.writeAbstractLocalPacket(localChannelReference, testPacket, false); + } catch (OpenR66ProtocolPacketException e) { + future.setResult(null); + future.setFailure(e); + Channels.close(localChannelReference.getLocalChannel()); + return; + } + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(TestTransaction.class); + } + if (args.length < 1) { + logger + .error("Needs at least the configuration file as first argument"); + return; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return; + } + Configuration.configuration.pipelineInit(); + + final NetworkTransaction networkTransaction = new NetworkTransaction(); + DbHostAuth host = Configuration.configuration.HOST_AUTH; + final SocketAddress socketServerAddress = host.getSocketAddress(); + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = 100; + + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestPacket packet = new TestPacket("Test", "" + i, 0); + TestTransaction transaction = new TestTransaction( + networkTransaction, arrayFuture[i], socketServerAddress, + packet); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn("Success: " + success + " Error: " + error + " NB/s: " + + success * TestPacket.pingpong * 1000 / (time2 - time1)); + executorService.shutdown(); + networkTransaction.closeAll(); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java b/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java index f5f3b0f20..5aec5385e 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java @@ -1,148 +1,148 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project 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. - * - * Waarp 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 Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.jboss.netty.logging.InternalLoggerFactory; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.common.logging.WaarpInternalLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.client.DirectTransfer; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; -import org.waarp.openr66.protocol.utils.R66Future; - -/** - * Test class for multiple DirectTransfer - * - * @author Frederic Bregier - * - */ -public class TestTransferNoDb extends DirectTransfer { - static int nb = 100; - - /** - * @param args - * @param rank - * @return True if OK - */ - protected static boolean getSpecialParams(String[] args, int rank) { - for (int i = rank; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-nb")) { - i++; - nb = Integer.parseInt(args[i]); - } else if (args[i].equalsIgnoreCase("-md5")) { - } else if (args[i].charAt(0) == '-') { - i++;// jump one - } - } - return true; - } - - public TestTransferNoDb(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - long id, - NetworkTransaction networkTransaction) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, id, - networkTransaction); - } - - public static void main(String[] args) { - InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isConnected) { - DbConstant.admin.close(); - } - System.exit(1); - } - getSpecialParams(args, 1); - Configuration.configuration.CLIENT_THREAD = nb; - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - ExecutorService executorService = Executors.newCachedThreadPool(); - - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start of Test Transfer"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - TestTransferNoDb transaction = new TestTransferNoDb(arrayFuture[i], - rhost, localFilename, rule, fileInfo, ismd5, block, - DbConstant.ILLEGALVALUE, - networkTransaction); - executorService.execute(transaction); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - int success = 0; - int error = 0; - int warn = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - R66Result result = arrayFuture[i].getResult(); - if (arrayFuture[i].isSuccess()) { - if (result.runner.getErrorInfo() == ErrorCode.Warning) { - warn++; - } else { - success++; - } - } else { - if (result.runner != null && - result.runner.getErrorInfo() == ErrorCode.Warning) { - warn++; - } else { - error++; - } - } - } - long time2 = System.currentTimeMillis(); - long length = 0; - // Get the first result as testing only - R66Result result = arrayFuture[0].getResult(); - logger.warn("Final file: " + - (result.file != null ? result.file.toString() : "no file")); - try { - length = result.file != null ? result.file.length() : 0L; - } catch (CommandAbstractException e) { - } - long delay = time2 - time1; - float nbs = success * 1000; - nbs /= delay; - float mbs = nbs * length / 1024; - logger.warn("Success: " + success + " Warning: " + warn + " Error: " + - error + " delay: " + delay + " NB/s: " + nbs + " KB/s: " + mbs); - executorService.shutdown(); - } finally { - networkTransaction.closeAll(); - } - } - -} +/** + * This file is part of Waarp Project. + * + * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the + * COPYRIGHT.txt in the distribution for a full listing of individual contributors. + * + * All Waarp Project 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. + * + * Waarp 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 Waarp . If not, see + * . + */ +package org.waarp.openr66.protocol.test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.jboss.netty.logging.InternalLoggerFactory; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.common.logging.WaarpInternalLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.openr66.client.DirectTransfer; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.R66Future; + +/** + * Test class for multiple DirectTransfer + * + * @author Frederic Bregier + * + */ +public class TestTransferNoDb extends DirectTransfer { + static int nb = 100; + + /** + * @param args + * @param rank + * @return True if OK + */ + protected static boolean getSpecialParams(String[] args, int rank) { + for (int i = rank; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-nb")) { + i++; + nb = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-md5")) { + } else if (args[i].charAt(0) == '-') { + i++;// jump one + } + } + return true; + } + + public TestTransferNoDb(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, + long id, + NetworkTransaction networkTransaction) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, id, + networkTransaction); + } + + public static void main(String[] args) { + InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpInternalLoggerFactory.getLogger(DirectTransfer.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isConnected) { + DbConstant.admin.close(); + } + System.exit(1); + } + getSpecialParams(args, 1); + Configuration.configuration.CLIENT_THREAD = nb; + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + ExecutorService executorService = Executors.newCachedThreadPool(); + + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start of Test Transfer"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestTransferNoDb transaction = new TestTransferNoDb(arrayFuture[i], + rhost, localFilename, rule, fileInfo, ismd5, block, + DbConstant.ILLEGALVALUE, + networkTransaction); + executorService.execute(transaction); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + } + int success = 0; + int error = 0; + int warn = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + R66Result result = arrayFuture[i].getResult(); + if (arrayFuture[i].isSuccess()) { + if (result.runner.getErrorInfo() == ErrorCode.Warning) { + warn++; + } else { + success++; + } + } else { + if (result.runner != null && + result.runner.getErrorInfo() == ErrorCode.Warning) { + warn++; + } else { + error++; + } + } + } + long time2 = System.currentTimeMillis(); + long length = 0; + // Get the first result as testing only + R66Result result = arrayFuture[0].getResult(); + logger.warn("Final file: " + + (result.file != null ? result.file.toString() : "no file")); + try { + length = result.file != null ? result.file.length() : 0L; + } catch (CommandAbstractException e) { + } + long delay = time2 - time1; + float nbs = success * 1000; + nbs /= delay; + float mbs = nbs * length / 1024; + logger.warn("Success: " + success + " Warning: " + warn + " Error: " + + error + " delay: " + delay + " NB/s: " + nbs + " KB/s: " + mbs); + executorService.shutdown(); + } finally { + networkTransaction.closeAll(); + } + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/test/package-info.java b/src/test/java/org/waarp/openr66/protocol/test/package-info.java index 02a112eac..1f4b756a0 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/package-info.java +++ b/src/test/java/org/waarp/openr66/protocol/test/package-info.java @@ -1,7 +1,7 @@ -/** - * Classes implementing Test only - * - * @apiviz.exclude - */ -package org.waarp.openr66.protocol.test; - +/** + * Classes implementing Test only + * + * @apiviz.exclude + */ +package org.waarp.openr66.protocol.test; +