diff --git a/gclc/LICENSE.txt b/gclc/LICENSE.txt new file mode 100644 index 0000000..1753629 --- /dev/null +++ b/gclc/LICENSE.txt @@ -0,0 +1,517 @@ + CeCILL FREE SOFTWARE LICENSE AGREEMENT + +Version 2.1 dated 2013-06-21 + + + Notice + +This Agreement is a Free Software license agreement that is the result +of discussions between its authors in order to ensure compliance with +the two main principles guiding its drafting: + + * firstly, compliance with the principles governing the distribution + of Free Software: access to source code, broad rights granted to users, + * secondly, the election of a governing law, French law, with which it + is conformant, both as regards the law of torts and intellectual + property law, and the protection that it offers to both authors and + holders of the economic rights over software. + +The authors of the CeCILL (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) +license are: + +Commissariat à l'énergie atomique et aux énergies alternatives - CEA, a +public scientific, technical and industrial research establishment, +having its principal place of business at 25 rue Leblanc, immeuble Le +Ponant D, 75015 Paris, France. + +Centre National de la Recherche Scientifique - CNRS, a public scientific +and technological establishment, having its principal place of business +at 3 rue Michel-Ange, 75794 Paris cedex 16, France. + +Institut National de Recherche en Informatique et en Automatique - +Inria, a public scientific and technological establishment, having its +principal place of business at Domaine de Voluceau, Rocquencourt, BP +105, 78153 Le Chesnay cedex, France. + + + Preamble + +The purpose of this Free Software license agreement is to grant users +the right to modify and redistribute the software governed by this +license within the framework of an open source distribution model. + +The exercising of this right is conditional upon certain obligations for +users so as to preserve this status for all subsequent redistributions. + +In consideration of access to the source code and the rights to copy, +modify and redistribute granted by the license, users are provided only +with a limited warranty and the software's author, the holder of the +economic rights, and the successive licensors only have limited liability. + +In this respect, the risks associated with loading, using, modifying +and/or developing or reproducing the software by the user are brought to +the user's attention, given its Free Software status, which may make it +complicated to use, with the result that its use is reserved for +developers and experienced professionals having in-depth computer +knowledge. Users are therefore encouraged to load and test the +suitability of the software as regards their requirements in conditions +enabling the security of their systems and/or data to be ensured and, +more generally, to use and operate it in the same conditions of +security. This Agreement may be freely reproduced and published, +provided it is not altered, and that no provisions are either added or +removed herefrom. + +This Agreement may apply to any or all software for which the holder of +the economic rights decides to submit the use thereof to its provisions. + +Frequently asked questions can be found on the official website of the +CeCILL licenses family (http://www.cecill.info/index.en.html) for any +necessary clarification. + + + Article 1 - DEFINITIONS + +For the purpose of this Agreement, when the following expressions +commence with a capital letter, they shall have the following meaning: + +Agreement: means this license agreement, and its possible subsequent +versions and annexes. + +Software: means the software in its Object Code and/or Source Code form +and, where applicable, its documentation, "as is" when the Licensee +accepts the Agreement. + +Initial Software: means the Software in its Source Code and possibly its +Object Code form and, where applicable, its documentation, "as is" when +it is first distributed under the terms and conditions of the Agreement. + +Modified Software: means the Software modified by at least one +Contribution. + +Source Code: means all the Software's instructions and program lines to +which access is required so as to modify the Software. + +Object Code: means the binary files originating from the compilation of +the Source Code. + +Holder: means the holder(s) of the economic rights over the Initial +Software. + +Licensee: means the Software user(s) having accepted the Agreement. + +Contributor: means a Licensee having made at least one Contribution. + +Licensor: means the Holder, or any other individual or legal entity, who +distributes the Software under the Agreement. + +Contribution: means any or all modifications, corrections, translations, +adaptations and/or new functions integrated into the Software by any or +all Contributors, as well as any or all Internal Modules. + +Module: means a set of sources files including their documentation that +enables supplementary functions or services in addition to those offered +by the Software. + +External Module: means any or all Modules, not derived from the +Software, so that this Module and the Software run in separate address +spaces, with one calling the other when they are run. + +Internal Module: means any or all Module, connected to the Software so +that they both execute in the same address space. + +GNU GPL: means the GNU General Public License version 2 or any +subsequent version, as published by the Free Software Foundation Inc. + +GNU Affero GPL: means the GNU Affero General Public License version 3 or +any subsequent version, as published by the Free Software Foundation Inc. + +EUPL: means the European Union Public License version 1.1 or any +subsequent version, as published by the European Commission. + +Parties: mean both the Licensee and the Licensor. + +These expressions may be used both in singular and plural form. + + + Article 2 - PURPOSE + +The purpose of the Agreement is the grant by the Licensor to the +Licensee of a non-exclusive, transferable and worldwide license for the +Software as set forth in Article 5 <#scope> hereinafter for the whole +term of the protection granted by the rights over said Software. + + + Article 3 - ACCEPTANCE + +3.1 The Licensee shall be deemed as having accepted the terms and +conditions of this Agreement upon the occurrence of the first of the +following events: + + * (i) loading the Software by any or all means, notably, by + downloading from a remote server, or by loading from a physical medium; + * (ii) the first time the Licensee exercises any of the rights granted + hereunder. + +3.2 One copy of the Agreement, containing a notice relating to the +characteristics of the Software, to the limited warranty, and to the +fact that its use is restricted to experienced users has been provided +to the Licensee prior to its acceptance as set forth in Article 3.1 +<#accepting> hereinabove, and the Licensee hereby acknowledges that it +has read and understood it. + + + Article 4 - EFFECTIVE DATE AND TERM + + + 4.1 EFFECTIVE DATE + +The Agreement shall become effective on the date when it is accepted by +the Licensee as set forth in Article 3.1 <#accepting>. + + + 4.2 TERM + +The Agreement shall remain in force for the entire legal term of +protection of the economic rights over the Software. + + + Article 5 - SCOPE OF RIGHTS GRANTED + +The Licensor hereby grants to the Licensee, who accepts, the following +rights over the Software for any or all use, and for the term of the +Agreement, on the basis of the terms and conditions set forth hereinafter. + +Besides, if the Licensor owns or comes to own one or more patents +protecting all or part of the functions of the Software or of its +components, the Licensor undertakes not to enforce the rights granted by +these patents against successive Licensees using, exploiting or +modifying the Software. If these patents are transferred, the Licensor +undertakes to have the transferees subscribe to the obligations set +forth in this paragraph. + + + 5.1 RIGHT OF USE + +The Licensee is authorized to use the Software, without any limitation +as to its fields of application, with it being hereinafter specified +that this comprises: + + 1. permanent or temporary reproduction of all or part of the Software + by any or all means and in any or all form. + + 2. loading, displaying, running, or storing the Software on any or all + medium. + + 3. entitlement to observe, study or test its operation so as to + determine the ideas and principles behind any or all constituent + elements of said Software. This shall apply when the Licensee + carries out any or all loading, displaying, running, transmission or + storage operation as regards the Software, that it is entitled to + carry out hereunder. + + + 5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS + +The right to make Contributions includes the right to translate, adapt, +arrange, or make any or all modifications to the Software, and the right +to reproduce the resulting software. + +The Licensee is authorized to make any or all Contributions to the +Software provided that it includes an explicit notice that it is the +author of said Contribution and indicates the date of the creation thereof. + + + 5.3 RIGHT OF DISTRIBUTION + +In particular, the right of distribution includes the right to publish, +transmit and communicate the Software to the general public on any or +all medium, and by any or all means, and the right to market, either in +consideration of a fee, or free of charge, one or more copies of the +Software by any means. + +The Licensee is further authorized to distribute copies of the modified +or unmodified Software to third parties according to the terms and +conditions set forth hereinafter. + + + 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION + +The Licensee is authorized to distribute true copies of the Software in +Source Code or Object Code form, provided that said distribution +complies with all the provisions of the Agreement and is accompanied by: + + 1. a copy of the Agreement, + + 2. a notice relating to the limitation of both the Licensor's warranty + and liability as set forth in Articles 8 and 9, + +and that, in the event that only the Object Code of the Software is +redistributed, the Licensee allows effective access to the full Source +Code of the Software for a period of at least three years from the +distribution of the Software, it being understood that the additional +acquisition cost of the Source Code shall not exceed the cost of the +data transfer. + + + 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE + +When the Licensee makes a Contribution to the Software, the terms and +conditions for the distribution of the resulting Modified Software +become subject to all the provisions of this Agreement. + +The Licensee is authorized to distribute the Modified Software, in +source code or object code form, provided that said distribution +complies with all the provisions of the Agreement and is accompanied by: + + 1. a copy of the Agreement, + + 2. a notice relating to the limitation of both the Licensor's warranty + and liability as set forth in Articles 8 and 9, + +and, in the event that only the object code of the Modified Software is +redistributed, + + 3. a note stating the conditions of effective access to the full source + code of the Modified Software for a period of at least three years + from the distribution of the Modified Software, it being understood + that the additional acquisition cost of the source code shall not + exceed the cost of the data transfer. + + + 5.3.3 DISTRIBUTION OF EXTERNAL MODULES + +When the Licensee has developed an External Module, the terms and +conditions of this Agreement do not apply to said External Module, that +may be distributed under a separate license agreement. + + + 5.3.4 COMPATIBILITY WITH OTHER LICENSES + +The Licensee can include a code that is subject to the provisions of one +of the versions of the GNU GPL, GNU Affero GPL and/or EUPL in the +Modified or unmodified Software, and distribute that entire code under +the terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL. + +The Licensee can include the Modified or unmodified Software in a code +that is subject to the provisions of one of the versions of the GNU GPL, +GNU Affero GPL and/or EUPL and distribute that entire code under the +terms of the same version of the GNU GPL, GNU Affero GPL and/or EUPL. + + + Article 6 - INTELLECTUAL PROPERTY + + + 6.1 OVER THE INITIAL SOFTWARE + +The Holder owns the economic rights over the Initial Software. Any or +all use of the Initial Software is subject to compliance with the terms +and conditions under which the Holder has elected to distribute its work +and no one shall be entitled to modify the terms and conditions for the +distribution of said Initial Software. + +The Holder undertakes that the Initial Software will remain ruled at +least by this Agreement, for the duration set forth in Article 4.2 <#term>. + + + 6.2 OVER THE CONTRIBUTIONS + +The Licensee who develops a Contribution is the owner of the +intellectual property rights over this Contribution as defined by +applicable law. + + + 6.3 OVER THE EXTERNAL MODULES + +The Licensee who develops an External Module is the owner of the +intellectual property rights over this External Module as defined by +applicable law and is free to choose the type of agreement that shall +govern its distribution. + + + 6.4 JOINT PROVISIONS + +The Licensee expressly undertakes: + + 1. not to remove, or modify, in any manner, the intellectual property + notices attached to the Software; + + 2. to reproduce said notices, in an identical manner, in the copies of + the Software modified or not. + +The Licensee undertakes not to directly or indirectly infringe the +intellectual property rights on the Software of the Holder and/or +Contributors, and to take, where applicable, vis-à-vis its staff, any +and all measures required to ensure respect of said intellectual +property rights of the Holder and/or Contributors. + + + Article 7 - RELATED SERVICES + +7.1 Under no circumstances shall the Agreement oblige the Licensor to +provide technical assistance or maintenance services for the Software. + +However, the Licensor is entitled to offer this type of services. The +terms and conditions of such technical assistance, and/or such +maintenance, shall be set forth in a separate instrument. Only the +Licensor offering said maintenance and/or technical assistance services +shall incur liability therefor. + +7.2 Similarly, any Licensor is entitled to offer to its licensees, under +its sole responsibility, a warranty, that shall only be binding upon +itself, for the redistribution of the Software and/or the Modified +Software, under terms and conditions that it is free to decide. Said +warranty, and the financial terms and conditions of its application, +shall be subject of a separate instrument executed between the Licensor +and the Licensee. + + + Article 8 - LIABILITY + +8.1 Subject to the provisions of Article 8.2, the Licensee shall be +entitled to claim compensation for any direct loss it may have suffered +from the Software as a result of a fault on the part of the relevant +Licensor, subject to providing evidence thereof. + +8.2 The Licensor's liability is limited to the commitments made under +this Agreement and shall not be incurred as a result of in particular: +(i) loss due the Licensee's total or partial failure to fulfill its +obligations, (ii) direct or consequential loss that is suffered by the +Licensee due to the use or performance of the Software, and (iii) more +generally, any consequential loss. In particular the Parties expressly +agree that any or all pecuniary or business loss (i.e. loss of data, +loss of profits, operating loss, loss of customers or orders, +opportunity cost, any disturbance to business activities) or any or all +legal proceedings instituted against the Licensee by a third party, +shall constitute consequential loss and shall not provide entitlement to +any or all compensation from the Licensor. + + + Article 9 - WARRANTY + +9.1 The Licensee acknowledges that the scientific and technical +state-of-the-art when the Software was distributed did not enable all +possible uses to be tested and verified, nor for the presence of +possible defects to be detected. In this respect, the Licensee's +attention has been drawn to the risks associated with loading, using, +modifying and/or developing and reproducing the Software which are +reserved for experienced users. + +The Licensee shall be responsible for verifying, by any or all means, +the suitability of the product for its requirements, its good working +order, and for ensuring that it shall not cause damage to either persons +or properties. + +9.2 The Licensor hereby represents, in good faith, that it is entitled +to grant all the rights over the Software (including in particular the +rights set forth in Article 5 <#scope>). + +9.3 The Licensee acknowledges that the Software is supplied "as is" by +the Licensor without any other express or tacit warranty, other than +that provided for in Article 9.2 <#good-faith> and, in particular, +without any warranty as to its commercial value, its secured, safe, +innovative or relevant nature. + +Specifically, the Licensor does not warrant that the Software is free +from any error, that it will operate without interruption, that it will +be compatible with the Licensee's own equipment and software +configuration, nor that it will meet the Licensee's requirements. + +9.4 The Licensor does not either expressly or tacitly warrant that the +Software does not infringe any third party intellectual property right +relating to a patent, software or any other property right. Therefore, +the Licensor disclaims any and all liability towards the Licensee +arising out of any or all proceedings for infringement that may be +instituted in respect of the use, modification and redistribution of the +Software. Nevertheless, should such proceedings be instituted against +the Licensee, the Licensor shall provide it with technical and legal +expertise for its defense. Such technical and legal expertise shall be +decided on a case-by-case basis between the relevant Licensor and the +Licensee pursuant to a memorandum of understanding. The Licensor +disclaims any and all liability as regards the Licensee's use of the +name of the Software. No warranty is given as regards the existence of +prior rights over the name of the Software or as regards the existence +of a trademark. + + + Article 10 - TERMINATION + +10.1 In the event of a breach by the Licensee of its obligations +hereunder, the Licensor may automatically terminate this Agreement +thirty (30) days after notice has been sent to the Licensee and has +remained ineffective. + +10.2 A Licensee whose Agreement is terminated shall no longer be +authorized to use, modify or distribute the Software. However, any +licenses that it may have granted prior to termination of the Agreement +shall remain valid subject to their having been granted in compliance +with the terms and conditions hereof. + + + Article 11 - MISCELLANEOUS + + + 11.1 EXCUSABLE EVENTS + +Neither Party shall be liable for any or all delay, or failure to +perform the Agreement, that may be attributable to an event of force +majeure, an act of God or an outside cause, such as defective +functioning or interruptions of the electricity or telecommunications +networks, network paralysis following a virus attack, intervention by +government authorities, natural disasters, water damage, earthquakes, +fire, explosions, strikes and labor unrest, war, etc. + +11.2 Any failure by either Party, on one or more occasions, to invoke +one or more of the provisions hereof, shall under no circumstances be +interpreted as being a waiver by the interested Party of its right to +invoke said provision(s) subsequently. + +11.3 The Agreement cancels and replaces any or all previous agreements, +whether written or oral, between the Parties and having the same +purpose, and constitutes the entirety of the agreement between said +Parties concerning said purpose. No supplement or modification to the +terms and conditions hereof shall be effective as between the Parties +unless it is made in writing and signed by their duly authorized +representatives. + +11.4 In the event that one or more of the provisions hereof were to +conflict with a current or future applicable act or legislative text, +said act or legislative text shall prevail, and the Parties shall make +the necessary amendments so as to comply with said act or legislative +text. All other provisions shall remain effective. Similarly, invalidity +of a provision of the Agreement, for any reason whatsoever, shall not +cause the Agreement as a whole to be invalid. + + + 11.5 LANGUAGE + +The Agreement is drafted in both French and English and both versions +are deemed authentic. + + + Article 12 - NEW VERSIONS OF THE AGREEMENT + +12.1 Any person is authorized to duplicate and distribute copies of this +Agreement. + +12.2 So as to ensure coherence, the wording of this Agreement is +protected and may only be modified by the authors of the License, who +reserve the right to periodically publish updates or new versions of the +Agreement, each with a separate number. These subsequent versions may +address new issues encountered by Free Software. + +12.3 Any Software distributed under a given version of the Agreement may +only be subsequently distributed under the same version of the Agreement +or a subsequent version, subject to the provisions of Article 5.3.4 +<#compatibility>. + + + Article 13 - GOVERNING LAW AND JURISDICTION + +13.1 The Agreement is governed by French law. The Parties agree to +endeavor to seek an amicable solution to any disagreements or disputes +that may arise during the performance of the Agreement. + +13.2 Failing an amicable solution within two (2) months as from their +occurrence, and unless emergency proceedings are necessary, the +disagreements or disputes shall be referred to the Paris Courts having +jurisdiction, by the more diligent Party. diff --git a/gclc/pom.xml b/gclc/pom.xml index 084e82a..fb16a65 100644 --- a/gclc/pom.xml +++ b/gclc/pom.xml @@ -1,88 +1,82 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4.0.0 - gclc - 2.0.6-SNAPSHOT - jar - http://www.bigeon.fr/emmanuel - - UTF-8 - git.bigeon.net - - - - junit - junit - 4.11 - test - - - - fr.bigeon - ebigeon-config - 1.7.1 - - - - - com.mycila - license-maven-plugin - -
fr/bigeon/gclc/licensing/cecill/CeCILL-header.txt
- - Bigeon Emmanuel - emmanuel@bigeon.fr - -
- - - - check - - - -
-
-
- 2014 - Generic Command Ligne console - provide a generic framework for console applications - - - scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git - gclc-1.3.5 - -
+ + + 4.0.0 + gclc + 2.0.6-SNAPSHOT + jar + http://www.bigeon.fr/emmanuel + + UTF-8 + git.bigeon.net + emmanuel@bigeon.fr + cecill_2.1 + + + + junit + junit + 4.11 + test + + + + net.bigeon.config + ebigeon-config + 1.8.3 + + + + + org.codehaus.mojo + license-maven-plugin + + + properties + properties + + + + + + + + manual + CeCILL 2.1 + https://cecill.info/licences/Licence_CeCILL_V2.1-en.html + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + com.github.sevntu-checkstyle + dsm-maven-plugin + 2.2.0 + + + + + + emmanuel@bigeon.fr + Emmanuel Bigeon + bigeon.net + + PM + + + + 2014 + Generic Command Ligne console + A generic framework for console applications, with customized command input and output streams. + + + scm:git:gogs@git.code.bigeon.net:emmanuel/gclc.git + + net.bigeon + diff --git a/gclc/src/main/java/fr/bigeon/gclc/ApplicationAttachement.java b/gclc/src/main/java/fr/bigeon/gclc/ApplicationAttachement.java index e9ec38f..24f8088 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/ApplicationAttachement.java +++ b/gclc/src/main/java/fr/bigeon/gclc/ApplicationAttachement.java @@ -1,59 +1,58 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.ApplicationAttachement.java - * Created on: Apr 19, 2017 - */ -package fr.bigeon.gclc; - -import fr.bigeon.gclc.command.ICommandProvider; -import fr.bigeon.gclc.exception.InvalidCommandName; - -/** Represent a functionnality set that can be added to a console application. - * - * @author Emmanuel Bigeon */ -public interface ApplicationAttachement { - /** Attach this object to a console application. - *

- * The attaching usually consist in the addition of commands in the console - * application. The attached command should be specific to the attachement - * (typically, the generic help command or the script command should not be - * added through this mechanism). - * - * @param application the application - * @throws InvalidCommandName if a command name is invalid for the - * application. */ - void attach(ICommandProvider application) throws InvalidCommandName; -} +/** + * gclc:fr.bigeon.gclc.ApplicationAttachement.java + * Created on: Apr 19, 2017 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import fr.bigeon.gclc.command.ICommandProvider; +import fr.bigeon.gclc.exception.InvalidCommandName; + +/** Represent a functionnality set that can be added to a console application. + * + * @author Emmanuel Bigeon */ +public interface ApplicationAttachement { + /** Attach this object to a console application. + *

+ * The attaching usually consist in the addition of commands in the console + * application. The attached command should be specific to the attachement + * (typically, the generic help command or the script command should not be + * added through this mechanism). + * + * @param application the application + * @throws InvalidCommandName if a command name is invalid for the + * application. */ + void attach(ICommandProvider application) throws InvalidCommandName; +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java b/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java index 694cfb6..257e4ff 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java +++ b/gclc/src/main/java/fr/bigeon/gclc/CommandRequestListener.java @@ -1,50 +1,49 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.CommandRequestListener.java - * Created on: Mar 19, 2015 - */ -package fr.bigeon.gclc; - -/** Command Request Listeners are listeners that are notified before a command - * is executed by the ConsoleApplication. - * - * @author Emmanuel Bigeon */ -public interface CommandRequestListener { - /** Indicates that the given command was requested to the application. - * - * @param command the command */ - void commandRequest(String command); -} +/** + * gclc:fr.bigeon.gclc.CommandRequestListener.java + * Created on: Mar 19, 2015 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** Command Request Listeners are listeners that are notified before a command + * is executed by the ConsoleApplication. + * + * @author Emmanuel Bigeon */ +public interface CommandRequestListener { + /** Indicates that the given command was requested to the application. + * + * @param command the command */ + void commandRequest(String command); +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java b/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java index c0345f8..9c3ad4a 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java +++ b/gclc/src/main/java/fr/bigeon/gclc/ConsoleApplication.java @@ -1,261 +1,294 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** gclc:fr.bigeon.gclc.ConsoleApplication.java - * Created on: Sep 6, 2014 */ -package fr.bigeon.gclc; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import fr.bigeon.gclc.command.ICommand; -import fr.bigeon.gclc.command.ICommandProvider; -import fr.bigeon.gclc.command.SubedCommand; -import fr.bigeon.gclc.exception.CommandParsingException; -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.i18n.Messages; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** - * A {@link ConsoleApplication} is an application that require the user to input - * commands. - *

- * A typical use case is the following: - * - *

- * {@link ConsoleOutput} out = new {@link fr.bigeon.gclc.manager.StreamConsoleOutput StreamConsoleOutput}();
- * {@link ConsoleInput} in = new {@link fr.bigeon.gclc.manager.StreamConsoleInput StreamConsoleInput}();
- * {@link ConsoleApplication} app = new {@link ConsoleApplication}(out, in, "welcome", "see you latter")};
- * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
- * app.{@link ConsoleApplication#start() start()};
- * 
- *

- * That will launch in the console application that will display "welcome", - * return a line and prompt the user for the command until he inputs the - * exit command. Then it will print "see you latter" and exit the - * start method. - * - * @author Emmanuel BIGEON */ -public final class ConsoleApplication implements ICommandProvider { - - /** The class logger. */ - private static final Logger LOGGER = Logger - .getLogger(ConsoleApplication.class.getName()); - /** The welcome message. */ - public final String header; - /** The good bye message. */ - public final String footer; - /** The standard output for the application. */ - private final ConsoleOutput out; - /** The standard input for the application. */ - private final ConsoleInput in; - /** The container of commands. */ - public final SubedCommand root; - /** The state of this application. */ - private boolean running; - /** The listeners. */ - private final List listeners = new ArrayList<>(); - - /** Create a console application. - * - * @param out the output - * @param in the input - * @param welcome the welcoming message - * @param goodbye the goodbye message */ - public ConsoleApplication(final ConsoleOutput out, final ConsoleInput in, - final String welcome, - final String goodbye) { - header = welcome; - footer = goodbye; - this.in = in; - this.out = out; - root = new SubedCommand(""); //$NON-NLS-1$ - } - - @Override - public boolean add(final ICommand cmd) throws InvalidCommandName { - return root.add(cmd); - } - - /** Add a listener for command requests. - * - * @param listener the command listener */ - public void addListener(final CommandRequestListener listener) { - listeners.add(listener); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, - * java.lang.String[]) */ - @Override - public void executeSub(final ConsoleOutput output, final ConsoleInput input, - final String command, - final String... args) throws CommandRunException { - root.executeSub(output, input, command, args); - } - - /** Signify to the application that no command should be inputed anymore. */ - public void exit() { - LOGGER.fine("Request exiting application..."); //$NON-NLS-1$ - running = false; - in.interruptPrompt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ - @Override - public ICommand get(final String command) { - return root.get(command); - } - - /** Interpret a command line. - *

- * This method will split the command in its part and execute the command - * with {@link #executeSub(ConsoleOutput, ConsoleInput, String, String...)}. - * - * @param cmd the command - * @throws IOException if the command could not be parsed */ - public void interpretCommand(final String cmd) throws IOException { - List args; - try { - args = GCLCConstants.splitCommand(cmd); - } catch (final CommandParsingException e1) { - out.println("Command line cannot be parsed"); //$NON-NLS-1$ - LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$ - return; - } - if (!args.isEmpty()) { - try { - executeSub(out, in, args.get(0), Arrays.copyOfRange( - args.toArray(new String[0]), 1, args.size())); - } catch (final CommandRunException e) { - LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$ - out.println(Messages - .getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$ - out.println(e.getLocalizedMessage()); - if (e.getType() == CommandRunExceptionType.USAGE) { - e.getSource().help(out); - } - } - } - } - - /** Test if the application is running. - * - * @return the running status */ - public boolean isRunning() { - return running; - } - - /** Remove a listener from this application. - * - * @param listener the command listener to remove */ - public void removeListener(final CommandRequestListener listener) { - listeners.remove(listener); - } - - /** The running loop content. - *

- * This consisting in getting the command, executing it and exiting - * (restarting the loop). */ - private void runLoop() { - try { - final String cmd = in.prompt(); - if (cmd == null || cmd.isEmpty()) { - return; - } - for (final CommandRequestListener listener : listeners) { - listener.commandRequest(cmd); - } - interpretCommand(cmd); - } catch (final InterruptedIOException e) { - LOGGER.info( - "Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$ - LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$ - e); - } catch (final IOException e) { - // The manager was closed - running = false; - LOGGER.warning( - "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ - LOGGER.log(Level.FINE, - "An exception caused the closing of the application", //$NON-NLS-1$ - e); - } - } - - /** Start the application. */ - public void start() { - try { - running = true; - if (header != null) { - out.println(header); - } - } catch (final IOException e) { - // The manager was closed - running = false; - LOGGER.warning( - "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ - LOGGER.log(Level.FINE, - "An exception caused the closing of the application", //$NON-NLS-1$ - e); - return; - } - do { - runLoop(); - } while (running); - if (footer != null) { - try { - out.println(footer); - } catch (final IOException e) { - // The manager was closed - running = false; - LOGGER.warning("Console manager alreaady closed."); //$NON-NLS-1$ - LOGGER.log(Level.FINE, - "Exception raised by goodbye message printing... Application will still close.", //$NON-NLS-1$ - e); - } - } - running = false; - LOGGER.fine("Exiting application."); //$NON-NLS-1$ - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** gclc:fr.bigeon.gclc.ConsoleApplication.java + * Created on: Sep 6, 2014 */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import fr.bigeon.gclc.command.ICommand; +import fr.bigeon.gclc.command.ICommandProvider; +import fr.bigeon.gclc.command.SubedCommand; +import fr.bigeon.gclc.exception.CommandParsingException; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.i18n.Messages; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** + * A {@link ConsoleApplication} is an application that require the user to input + * commands. + *

+ * A typical use case is the following: + * + *

+ * {@link ConsoleOutput} out = new {@link fr.bigeon.gclc.utils.StreamConsoleOutput StreamConsoleOutput}();
+ * {@link ConsoleInput} in = new {@link fr.bigeon.gclc.utils.StreamConsoleInput StreamConsoleInput}();
+ * {@link ConsoleApplication} app = new {@link ConsoleApplication}(out, in, "welcome", "see you latter")};
+ * app.{@link ConsoleApplication#add(ICommand) add}("my_command", new {@link ICommand MyCommand()});
+ * app.{@link ConsoleApplication#start() start()};
+ * 
+ *

+ * That will launch in the console application that will display "welcome", + * return a line and prompt the user for the command until he inputs the + * exit command. Then it will print "see you latter" and exit the + * start method. + * + * @author Emmanuel BIGEON */ +public final class ConsoleApplication implements ICommandProvider { + + /** The class logger. */ + private static final Logger LOGGER = Logger + .getLogger(ConsoleApplication.class.getName()); + /** The welcome message. */ + public final String header; + /** The good bye message. */ + public final String footer; + /** The standard output for the application. */ + private final ConsoleOutput out; + /** The standard input for the application. */ + private final ConsoleInput in; + /** The container of commands. */ + public final SubedCommand root; + /** The state of this application. */ + private boolean running; + /** The listeners. */ + private final List listeners = new ArrayList<>(); + + /** Create a console application. + * + * @param out the output + * @param in the input + * @param welcome the welcoming message + * @param goodbye the goodbye message */ + public ConsoleApplication(final ConsoleOutput out, final ConsoleInput in, + final String welcome, + final String goodbye) { + header = welcome; + footer = goodbye; + this.in = in; + this.out = out; + root = new SubedCommand(""); //$NON-NLS-1$ + } + + @Override + public boolean add(final ICommand cmd) throws InvalidCommandName { + return root.add(cmd); + } + + /** Add a listener for command requests. + * + * @param listener the command listener */ + public void addListener(final CommandRequestListener listener) { + listeners.add(listener); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommandProvider#executeSub(java.lang.String, + * java.lang.String[]) */ + @Override + public void executeSub(final ConsoleOutput output, final ConsoleInput input, + final String command, + final String... args) throws CommandRunException { + root.executeSub(output, input, command, args); + } + + /** Signify to the application that no command should be inputed anymore. */ + public void exit() { + LOGGER.fine("Request exiting application..."); //$NON-NLS-1$ + running = false; + in.interruptPrompt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ + @Override + public ICommand get(final String command) { + return root.get(command); + } + + /** Interpret a command line. + *

+ * This method will split the command in its part and execute the command + * with {@link #executeSub(ConsoleOutput, ConsoleInput, String, String...)}. + * + * @param cmd the command + * @throws IOException if the command could not be parsed */ + public void interpretCommand(final String cmd) throws IOException { + List args; + try { + args = GCLCConstants.splitCommand(cmd); + } catch (final CommandParsingException e1) { + out.println("Command line cannot be parsed"); //$NON-NLS-1$ + LOGGER.log(Level.FINE, "Invalid user command " + cmd, e1); //$NON-NLS-1$ + return; + } + if (!args.isEmpty()) { + try { + executeSub(out, in, args.get(0), Arrays.copyOfRange( + args.toArray(new String[0]), 1, args.size())); + } catch (final CommandRunException e) { + LOGGER.log(Level.FINE, "Command failed: " + cmd, e); //$NON-NLS-1$ + out.println(Messages + .getString("ConsoleApplication.cmd.failed", cmd)); //$NON-NLS-1$ + out.println(e.getLocalizedMessage()); + if (e.getType() == CommandRunExceptionType.USAGE) { + get(args.get(0)).help(out); + } + } + } + } + + /** Test if the application is running. + * + * @return the running status */ + public boolean isRunning() { + return running; + } + + /** Remove a listener from this application. + * + * @param listener the command listener to remove */ + public void removeListener(final CommandRequestListener listener) { + listeners.remove(listener); + } + + /** The running loop content. + *

+ * This consisting in getting the command, executing it and exiting + * (restarting the loop). */ + private void runLoop() { + try { + final String cmd = in.prompt(); + if (cmd == null || cmd.isEmpty()) { + return; + } + for (final CommandRequestListener listener : listeners) { + listener.commandRequest(cmd); + } + interpretCommand(cmd); + } catch (final InterruptedIOException e) { + LOGGER.info( + "Prompt interrupted. It is likely the application is closing."); //$NON-NLS-1$ + LOGGER.log(Level.FINER, "Interruption of the prompt.", //$NON-NLS-1$ + e); + } catch (final IOException e) { + // The manager was closed + running = false; + LOGGER.warning( + "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ + LOGGER.log(Level.FINE, + "An exception caused the closing of the application", //$NON-NLS-1$ + e); + } + } + + /** Start the application. */ + public void start() { + try { + running = true; + if (header != null) { + out.println(header); + } + } catch (final IOException e) { + // The manager was closed + running = false; + LOGGER.warning( + "The console manager was closed. Closing the application as no one can reach it."); //$NON-NLS-1$ + LOGGER.log(Level.FINE, + "An exception caused the closing of the application", //$NON-NLS-1$ + e); + return; + } + do { + runLoop(); + } while (running); + if (footer != null) { + try { + out.println(footer); + } catch (final IOException e) { + // The manager was closed + running = false; + LOGGER.warning("Console manager alreaady closed."); //$NON-NLS-1$ + LOGGER.log(Level.FINE, + "Exception raised by goodbye message printing... Application will still close.", //$NON-NLS-1$ + e); + } + } + running = false; + LOGGER.fine("Exiting application."); //$NON-NLS-1$ + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java b/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java index aa52fd8..9cbc005 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java +++ b/gclc/src/main/java/fr/bigeon/gclc/GCLCConstants.java @@ -1,143 +1,176 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.GCLCConstants.java - * Created on: Jun 8, 2016 - */ -package fr.bigeon.gclc; - -import java.util.ArrayList; -import java.util.List; - -import fr.bigeon.gclc.exception.CommandParsingException; - -/** A Utility class for GCLC - *

- * This class offers a method to split a line or arguments into the list of - * arguments. - * - * @author Emmanuel Bigeon */ -public final class GCLCConstants { - - /** The escaping character. */ - private static final char ESCAPING_CHAR = getSystemEscapingChar(); - - /** Hide utility class constructor. */ - private GCLCConstants() { - // utility class - } - - /** Get the end of a string argument. - * - * @param cmd the command to parse - * @param startIndex the starting point of the parsing - * @param index the index of the current position - * @return the argument - * @throws CommandParsingException if the end of string does not mark end of - * command and is not followed by a space */ - private static String endOfString(final String cmd, final int startIndex, - final int index) throws CommandParsingException { - if (index < cmd.length() && cmd.charAt(index) != ' ') { - throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$ - } - return cmd.substring(startIndex + 1, index - 1); - } - - /** Get the excaping character. - * - * @return the escaping character */ - private static char getSystemEscapingChar() { - return '\\'; - } - - /** Remove escaping characters from the string. - * - * @param arg the string to remove excaping character from - * @return the string without escape character */ - private static String removeEscaped(final String arg) { - final StringBuilder builder = new StringBuilder(); - int index = 0; - int endIndex = arg.indexOf(ESCAPING_CHAR); - while (endIndex != -1) { - builder.append(arg.subSequence(index, endIndex)); - index = endIndex + 1; - endIndex = arg.indexOf(ESCAPING_CHAR, index + 1); - } - builder.append(arg.substring(index)); - return builder.toString(); - } - - /** Splits a command in the diferrent arguments. - * - * @param cmd the command to split in its parts - * @return the list of argument preceded by the command name - * @throws CommandParsingException if the parsing of the command failed */ - public static List splitCommand(final String cmd) throws CommandParsingException { - final List args = new ArrayList<>(); - // parse the string to separate arguments - int index = 0; - int startIndex = 0; - boolean escaped = false; - boolean inString = false; - while (index < cmd.length()) { - final char c = cmd.charAt(index); - index++; - if (escaped || c == ESCAPING_CHAR) { - escaped = !escaped; - continue; - } - if (c == ' ' && !inString) { - final String arg = cmd.substring(startIndex, index - 1); - if (!arg.isEmpty()) { - args.add(removeEscaped(arg)); - } - startIndex = index; - } else if (c == '"') { - if (inString) { - args.add(endOfString(cmd, startIndex, index)); - index++; - startIndex = index; - } - inString = startIndex == index - 1; - } - } - if (startIndex < cmd.length()) { - final String arg = cmd.substring(startIndex, cmd.length()); - args.add(arg); - } - return args; - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.GCLCConstants.java + * Created on: Jun 8, 2016 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.util.ArrayList; +import java.util.List; + +import fr.bigeon.gclc.exception.CommandParsingException; + +/** A Utility class for GCLC + *

+ * This class offers a method to split a line or arguments into the list of + * arguments. + * + * @author Emmanuel Bigeon */ +public final class GCLCConstants { + + /** The escaping character. */ + private static final char ESCAPING_CHAR = getSystemEscapingChar(); + + /** Hide utility class constructor. */ + private GCLCConstants() { + // utility class + } + + /** Get the end of a string argument. + * + * @param cmd the command to parse + * @param startIndex the starting point of the parsing + * @param index the index of the current position + * @return the argument + * @throws CommandParsingException if the end of string does not mark end of + * command and is not followed by a space */ + private static String endOfString(final String cmd, final int startIndex, + final int index) throws CommandParsingException { + if (index < cmd.length() && cmd.charAt(index) != ' ') { + throw new CommandParsingException("Misplaced quote"); //$NON-NLS-1$ + } + return cmd.substring(startIndex + 1, index - 1); + } + + /** Get the excaping character. + * + * @return the escaping character */ + private static char getSystemEscapingChar() { + return '\\'; + } + + /** Remove escaping characters from the string. + * + * @param arg the string to remove excaping character from + * @return the string without escape character */ + private static String removeEscaped(final String arg) { + final StringBuilder builder = new StringBuilder(); + int index = 0; + int endIndex = arg.indexOf(ESCAPING_CHAR); + while (endIndex != -1) { + builder.append(arg.subSequence(index, endIndex)); + index = endIndex + 1; + endIndex = arg.indexOf(ESCAPING_CHAR, index + 1); + } + builder.append(arg.substring(index)); + return builder.toString(); + } + + /** Splits a command in the diferrent arguments. + * + * @param cmd the command to split in its parts + * @return the list of argument preceded by the command name + * @throws CommandParsingException if the parsing of the command failed */ + public static List splitCommand(final String cmd) throws CommandParsingException { + final List args = new ArrayList<>(); + // parse the string to separate arguments + int index = 0; + int startIndex = 0; + boolean escaped = false; + boolean inString = false; + while (index < cmd.length()) { + final char c = cmd.charAt(index); + index++; + if (escaped || c == ESCAPING_CHAR) { + escaped = !escaped; + continue; + } + if (c == ' ' && !inString) { + final String arg = cmd.substring(startIndex, index - 1); + if (!arg.isEmpty()) { + args.add(removeEscaped(arg)); + } + startIndex = index; + } else if (c == '"') { + if (inString) { + args.add(endOfString(cmd, startIndex, index)); + index++; + startIndex = index; + } + inString = startIndex == index - 1; + } + } + if (startIndex < cmd.length()) { + final String arg = cmd.substring(startIndex, cmd.length()); + args.add(arg); + } + return args; + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/Command.java b/gclc/src/main/java/fr/bigeon/gclc/command/Command.java index b40769d..1c95520 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/Command.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/Command.java @@ -1,149 +1,148 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * acide:fr.bigeon.acide.Command.java - * Created on: Jul 31, 2014 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; - -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** A command to execute. - *

- * It is mandatory that it has a name and that name cannot start with minus - * character or contain spaces. - *

- * A command can be executed, with parameters that will be provided as an array - * of strings. - *

- * The help mechanism is doing the following: - *

- *

- * The default behavior for the brief message is to print the tip preceeded by a - * couple of spaces. - * - * @author Emmanuel BIGEON */ -public abstract class Command implements ICommand { - - /** The linux end of line character. */ - private static final String EOL_LINUX = "\n"; //$NON-NLS-1$ - /** The name of the command. */ - protected final String name; - - /** Create the command. - * - * @param name the command name */ - public Command(final String name) { - super(); - this.name = name; - } - - /** Get the brief part of the command help. - *

- * This method may be overriden by implementations to improve the help - * content. The default behavior is to print the tip. - * - * @return a brief description of the command - * @see Command#help(ConsoleOutput, String...) */ - protected String brief() { - return " " + tip(); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ - @Override - public final String getCommandName() { - return name; - } - - /** Prints a help content for this command to the console output. - *

- * This help is following the given format: - * - *

-     * [Command name]
-     * [brief message]
-     *
-     * Usage:
-     * [Usage pattern]
-     *
-     * [Usage details]
-     * 
- * - * @see fr.bigeon.gclc.command.ICommand#help(ConsoleOutput, String...) */ - @Override - public final void help(final ConsoleOutput manager, - final String... args) throws IOException { - manager.println(getCommandName()); - manager.println(brief()); - manager.println(); - manager.println("Usage:"); //$NON-NLS-1$ - manager.println(usagePattern()); - manager.println(); - final String details = usageDetail(); - if (details != null && !details.isEmpty()) { - manager.print(details); - if (!(details.endsWith(EOL_LINUX) || - details.endsWith(System.lineSeparator()))) { - manager.println(); - } - } - } - - /** This method return the detail of the help. - *

- * It immediatly follows the {@link #usagePattern() usage pattern}. - * - * @return the detailed help (should end with end of line or be empty) */ - protected abstract String usageDetail(); - - /** This prints the usage pattern for the command. - *

- * It follows the brief introduction on the command ({@link #brief()}) - * - * @return the usage pattern */ - protected String usagePattern() { - return getCommandName(); - } -} +/** + * acide:fr.bigeon.acide.Command.java + * Created on: Jul 31, 2014 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A command to execute. + *

+ * It is mandatory that it has a name and that name cannot start with minus + * character or contain spaces. + *

+ * A command can be executed, with parameters that will be provided as an array + * of strings. + *

+ * The help mechanism is doing the following: + *

+ *

+ * The default behavior for the brief message is to print the tip preceeded by a + * couple of spaces. + * + * @author Emmanuel BIGEON */ +public abstract class Command implements ICommand { + + /** The linux end of line character. */ + private static final String EOL_LINUX = "\n"; //$NON-NLS-1$ + /** The name of the command. */ + protected final String name; + + /** Create the command. + * + * @param name the command name */ + public Command(final String name) { + super(); + this.name = name; + } + + /** Get the brief part of the command help. + *

+ * This method may be overriden by implementations to improve the help + * content. The default behavior is to print the tip. + * + * @return a brief description of the command + * @see Command#help(ConsoleOutput, String...) */ + protected String brief() { + return " " + tip(); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ + @Override + public final String getCommandName() { + return name; + } + + /** Prints a help content for this command to the console output. + *

+ * This help is following the given format: + * + *

+     * [Command name]
+     * [brief message]
+     *
+     * Usage:
+     * [Usage pattern]
+     *
+     * [Usage details]
+     * 
+ * + * @see fr.bigeon.gclc.command.ICommand#help(ConsoleOutput, String...) */ + @Override + public final void help(final ConsoleOutput manager, + final String... args) throws IOException { + manager.println(getCommandName()); + manager.println(brief()); + manager.println(); + manager.println("Usage:"); //$NON-NLS-1$ + manager.println(usagePattern()); + manager.println(); + final String details = usageDetail(); + if (details != null && !details.isEmpty()) { + manager.print(details); + if (!(details.endsWith(EOL_LINUX) || + details.endsWith(System.lineSeparator()))) { + manager.println(); + } + } + } + + /** This method return the detail of the help. + *

+ * It immediatly follows the {@link #usagePattern() usage pattern}. + * + * @return the detailed help (should end with end of line or be empty) */ + protected abstract String usageDetail(); + + /** This prints the usage pattern for the command. + *

+ * It follows the brief introduction on the command ({@link #brief()}) + * + * @return the usage pattern */ + protected String usagePattern() { + return getCommandName(); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java b/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java index be15f3b..32bccda 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/CommandParameters.java @@ -1,214 +1,213 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.CommandParameters.java - * Created on: Dec 24, 2014 - */ -package fr.bigeon.gclc.command; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import fr.bigeon.gclc.exception.CommandParsingException; - -/** An object representing a collection of parameters. - *

- * It is used for defaulting values. - * - * @author Emmanuel BIGEON */ -public final class CommandParameters { - /** Number of element for a string argument. */ - private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2; - /** Boolean arguments. */ - private final Map booleanArguments = new HashMap<>(); - /** String arguments. */ - private final Map stringArguments = new HashMap<>(); - /** Arguments restriction on the named ones. */ - private final boolean strict; - /** additional (unnamed) parameters. */ - private final List additional = new ArrayList<>(); - - /** Create a command parameter object. - * - * @param bools the boolean parameters - * @param strings the string parameters - * @param strict if the argument are restricted to the declared ones */ - public CommandParameters(final Set bools, final Set strings, - final boolean strict) { - for (final String string : bools) { - booleanArguments.put(string, Boolean.FALSE); - } - for (final String string : strings) { - stringArguments.put(string, null); - } - this.strict = strict; - } - - /** Get the value of a string argument. - * - * @param key the key - * @return the associated value, null if it was not specified */ - public String get(final String key) { - return stringArguments.get(key); - } - - /** Get the additional (unrecognized) arguments. - * - * @return additional non parsed parameters */ - public List getAdditionals() { - return Collections.unmodifiableList(additional); - } - - /** Get the value of a boolean argument. - * - * @param key the key - * @return if the key was specified */ - public boolean getBool(final String key) { - return booleanArguments.containsKey(key) && - booleanArguments.get(key).booleanValue(); - } - - /** Get the boolean arguments. - * - * @return the boolean arguments */ - public Set getBooleanArgumentKeys() { - return booleanArguments.keySet(); - } - - /** Get the string arguments. - * - * @return the boolean arguments */ - public Set getStringArgumentKeys() { - return stringArguments.keySet(); - } - - /** Test if an argument exists in this object. - * - * @param key the key - * @return if the key is present in string arguments or boolean ones. */ - public boolean hasArgument(final String key) { - return stringArguments.containsKey(key) || - booleanArguments.containsKey(key); - } - - /** Attempt to parse an argument. - *

- * This method return 0 if the parsing was incorrect, or the number of - * parsed elements. - * - * @param arg the argument - * @param next the next element - * @return the number of element read */ - private int parseArg(final String arg, final String next) { - if (!arg.startsWith("-")) { //$NON-NLS-1$ - if (strict) { - return 0; - } - additional.add(arg); - return 1; - } - final String name = arg.substring(1); - if (booleanArguments.containsKey(name)) { - booleanArguments.put(name, Boolean.TRUE); - return 1; - } - if (stringArguments.containsKey(name)) { - return parseStringArg(name, next); - } - if (strict) { - return 0; - } - additional.add(name); - return 1; - } - - /** Parse arguments. - * - * @param args the arguments to parse - * @throws CommandParsingException if the arguments parsing failed */ - public void parseArgs(final String... args) throws CommandParsingException { - int i = 0; - while (i < args.length) { - String next = null; - if (i < args.length - 1) { - next = args[i + 1]; - } - final int p = parseArg(args[i], next); - if (p == 0) { - throw new CommandParsingException( - "Invalid parameter " + args[i]); //$NON-NLS-1$ - } - i += p; - } - - } - - /** Add a string arg value. - * - * @param name the string arg name - * @param next the string arg value - * @return 2 or 0 if next is invalid */ - private int parseStringArg(final String name, final String next) { - if (next == null) { - return 0; - } - stringArguments.put(name, next); - return STRINGARG_NUMBER_OF_ELEMENTS; - } - - /** Set a boolean parameter value. - * - * @param string the key - * @param value the value */ - public void set(final String string, final boolean value) { - if (booleanArguments.containsKey(string)) { - booleanArguments.put(string, Boolean.valueOf(value)); - } - } - - /** Set a string parameter value. - * - * @param string the key - * @param value the value */ - public void set(final String string, final String value) { - if (stringArguments.containsKey(string)) { - stringArguments.put(string, value); - } - } -} +/** + * gclc:fr.bigeon.gclc.command.CommandParameters.java + * Created on: Dec 24, 2014 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import fr.bigeon.gclc.exception.CommandParsingException; + +/** An object representing a collection of parameters. + *

+ * It is used for defaulting values. + * + * @author Emmanuel BIGEON */ +public final class CommandParameters { + /** Number of element for a string argument. */ + private static final int STRINGARG_NUMBER_OF_ELEMENTS = 2; + /** Boolean arguments. */ + private final Map booleanArguments = new HashMap<>(); + /** String arguments. */ + private final Map stringArguments = new HashMap<>(); + /** Arguments restriction on the named ones. */ + private final boolean strict; + /** additional (unnamed) parameters. */ + private final List additional = new ArrayList<>(); + + /** Create a command parameter object. + * + * @param bools the boolean parameters + * @param strings the string parameters + * @param strict if the argument are restricted to the declared ones */ + public CommandParameters(final Set bools, final Set strings, + final boolean strict) { + for (final String string : bools) { + booleanArguments.put(string, Boolean.FALSE); + } + for (final String string : strings) { + stringArguments.put(string, null); + } + this.strict = strict; + } + + /** Get the value of a string argument. + * + * @param key the key + * @return the associated value, null if it was not specified */ + public String get(final String key) { + return stringArguments.get(key); + } + + /** Get the additional (unrecognized) arguments. + * + * @return additional non parsed parameters */ + public List getAdditionals() { + return Collections.unmodifiableList(additional); + } + + /** Get the value of a boolean argument. + * + * @param key the key + * @return if the key was specified */ + public boolean getBool(final String key) { + return booleanArguments.containsKey(key) && + booleanArguments.get(key).booleanValue(); + } + + /** Get the boolean arguments. + * + * @return the boolean arguments */ + public Set getBooleanArgumentKeys() { + return booleanArguments.keySet(); + } + + /** Get the string arguments. + * + * @return the boolean arguments */ + public Set getStringArgumentKeys() { + return stringArguments.keySet(); + } + + /** Test if an argument exists in this object. + * + * @param key the key + * @return if the key is present in string arguments or boolean ones. */ + public boolean hasArgument(final String key) { + return stringArguments.containsKey(key) || + booleanArguments.containsKey(key); + } + + /** Attempt to parse an argument. + *

+ * This method return 0 if the parsing was incorrect, or the number of + * parsed elements. + * + * @param arg the argument + * @param next the next element + * @return the number of element read */ + private int parseArg(final String arg, final String next) { + if (!arg.startsWith("-")) { //$NON-NLS-1$ + if (strict) { + return 0; + } + additional.add(arg); + return 1; + } + final String name = arg.substring(1); + if (booleanArguments.containsKey(name)) { + booleanArguments.put(name, Boolean.TRUE); + return 1; + } + if (stringArguments.containsKey(name)) { + return parseStringArg(name, next); + } + if (strict) { + return 0; + } + additional.add(name); + return 1; + } + + /** Parse arguments. + * + * @param args the arguments to parse + * @throws CommandParsingException if the arguments parsing failed */ + public void parseArgs(final String... args) throws CommandParsingException { + int i = 0; + while (i < args.length) { + String next = null; + if (i < args.length - 1) { + next = args[i + 1]; + } + final int p = parseArg(args[i], next); + if (p == 0) { + throw new CommandParsingException( + "Invalid parameter " + args[i]); //$NON-NLS-1$ + } + i += p; + } + + } + + /** Add a string arg value. + * + * @param name the string arg name + * @param next the string arg value + * @return 2 or 0 if next is invalid */ + private int parseStringArg(final String name, final String next) { + if (next == null) { + return 0; + } + stringArguments.put(name, next); + return STRINGARG_NUMBER_OF_ELEMENTS; + } + + /** Set a boolean parameter value. + * + * @param string the key + * @param value the value */ + public void set(final String string, final boolean value) { + if (booleanArguments.containsKey(string)) { + booleanArguments.put(string, Boolean.valueOf(value)); + } + } + + /** Set a string parameter value. + * + * @param string the key + * @param value the value */ + public void set(final String string, final String value) { + if (stringArguments.containsKey(string)) { + stringArguments.put(string, value); + } + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java b/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java index 9adfb54..0377260 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/CommandProvider.java @@ -1,125 +1,121 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** acide:fr.bigeon.acide.CommandProvider.java - * Created on: Aug 6, 2014 */ -package fr.bigeon.gclc.command; - -import java.util.ArrayList; -import java.util.List; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.i18n.Messages; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** A command provider is a map of key word to command to execute. - * - * @author Emmanuel BIGEON */ -public class CommandProvider implements ICommandProvider { - /** The minus character. */ - private static final String MINUS = "-"; //$NON-NLS-1$ - /** The space character. */ - private static final String SPACE = " "; //$NON-NLS-1$ - /** The commands map. */ - protected final List commands; - - /** Create a command provider. */ - public CommandProvider() { - super(); - commands = new ArrayList<>(); - } - - /** Test the command name validity. - * - * @param name the command name - * @throws InvalidCommandName if the name is invalid */ - private static void testCommandName(final String name) throws InvalidCommandName { - if (name == null || name.isEmpty() || name.startsWith(MINUS) || - name.contains(SPACE)) { - throw new InvalidCommandName(); - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommandProvider#add(java.lang.String, - * fr.bigeon.gclc.command.Command) */ - @Override - public final boolean add(final ICommand value) throws InvalidCommandName { - final String name = value.getCommandName(); - testCommandName(name); - if (commands.contains(value)) { - return true; - } - for (final ICommand iCommand : commands) { - if (iCommand.getCommandName().equals(value.getCommandName())) { - throw new InvalidCommandName( - "Name already used: " + value.getCommandName()); //$NON-NLS-1$ - } - } - return commands.add(value); - } - - /* (non-Javadoc) - * @see - * fr.bigeon.gclc.command.ICommandProvider#executeSub(fr.bigeon.gclc.manager - * .ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String, - * java.lang.String[]) */ - @Override - public final void executeSub(final ConsoleOutput out, final ConsoleInput in, - final String cmd, - final String... args) throws CommandRunException { - for (final ICommand command : commands) { - if (command.getCommandName().equals(cmd)) { - command.execute(out, in, args); - return; - } - } - throw new CommandRunException( - Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ - @Override - public final ICommand get(final String commandName) { - for (final ICommand command : commands) { - if (command.getCommandName().equals(commandName)) { - return command; - } - } - return null; - } -} +/** acide:fr.bigeon.acide.CommandProvider.java + * Created on: Aug 6, 2014 */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.util.ArrayList; +import java.util.List; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.i18n.Messages; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A command provider is a map of key word to command to execute. + * + * @author Emmanuel BIGEON */ +public class CommandProvider implements ICommandProvider { + /** The minus character. */ + private static final String MINUS = "-"; //$NON-NLS-1$ + /** The space character. */ + private static final String SPACE = " "; //$NON-NLS-1$ + /** The commands map. */ + protected final List commands; + + /** Create a command provider. */ + public CommandProvider() { + super(); + commands = new ArrayList<>(); + } + + /** Test the command name validity. + * + * @param name the command name + * @throws InvalidCommandName if the name is invalid */ + private static void testCommandName(final String name) throws InvalidCommandName { + if (name == null || name.isEmpty() || name.startsWith(MINUS) + || name.contains(SPACE)) { + throw new InvalidCommandName(); + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommandProvider#add(java.lang.String, + * fr.bigeon.gclc.command.Command) */ + @Override + public final boolean add(final ICommand value) throws InvalidCommandName { + final String name = value.getCommandName(); + testCommandName(name); + if (commands.contains(value)) { + return true; + } + for (final ICommand iCommand : commands) { + if (iCommand.getCommandName().equals(value.getCommandName())) { + throw new InvalidCommandName( + "Name already used: " + value.getCommandName()); //$NON-NLS-1$ + } + } + return commands.add(value); + } + + /* (non-Javadoc) + * @see + * fr.bigeon.gclc.command.ICommandProvider#executeSub(fr.bigeon.gclc.manager + * .ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, java.lang.String, + * java.lang.String[]) */ + @Override + public final void executeSub(final ConsoleOutput out, final ConsoleInput in, + final String cmd, final String... args) throws CommandRunException { + final ICommand command = get(cmd); + if (command == null) { + throw new CommandRunException( + Messages.getString("CommandProvider.unrecognized", cmd), null); //$NON-NLS-1$ + } + command.execute(out, in, args); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommandProvider#get(java.lang.String) */ + @Override + public final ICommand get(final String commandName) { + for (final ICommand command : commands) { + if (command.getCommandName().equals(commandName)) { + return command; + } + } + return null; + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java b/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java index fee9065..b46a384 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/HelpExecutor.java @@ -1,117 +1,150 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.HelpExecutor.java - * Created on: Sep 6, 2014 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.prompt.CLIPrompterMessages; - -/** A command to print help of an other command. - *

- * This command will display the help of an other command - * - * @author Emmanuel BIGEON */ -public final class HelpExecutor extends Command { - - /** The command to execute the help of. */ - private final ICommand cmd; - - /** Create the help command. - * - * @param cmdName the command name - * @param cmd the command to execute the help of */ - public HelpExecutor(final String cmdName, - final ICommand cmd) { - super(cmdName); - this.cmd = cmd; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#brief() */ - @Override - protected String brief() { - if (cmd instanceof SubedCommand) { - return " A command to get help for other commands"; //$NON-NLS-1$ - } - return " A command to retrieve help for " + cmd.getCommandName(); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput, - * String[]) */ - @Override - public void execute(final ConsoleOutput out, final ConsoleInput in, - final String... args) throws CommandRunException { - try { - cmd.help(out, args); - } catch (final IOException e) { - throw new CommandRunException(CommandRunExceptionType.INTERACTION, - "Console manager closed", e, this); //$NON-NLS-1$ - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#tip() */ - @Override - public String tip() { - return CLIPrompterMessages.getString("help.cmd.tip"); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() - */ - @Override - protected String usageDetail() { - return null; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usagePattern() */ - @Override - protected String usagePattern() { - if (cmd instanceof SubedCommand) { - return getCommandName() + " "; //$NON-NLS-1$ - } - return getCommandName(); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.HelpExecutor.java + * Created on: Sep 6, 2014 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.prompt.CLIPrompterMessages; + +/** A command to print help of an other command. + *

+ * This command will display the help of an other command + * + * @author Emmanuel BIGEON */ +public final class HelpExecutor extends Command { + + /** The command to execute the help of. */ + private final ICommand cmd; + + /** Create the help command. + * + * @param cmdName the command name + * @param cmd the command to execute the help of */ + public HelpExecutor(final String cmdName, + final ICommand cmd) { + super(cmdName); + this.cmd = cmd; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#brief() */ + @Override + protected String brief() { + if (cmd instanceof SubedCommand) { + return " A command to get help for other commands"; //$NON-NLS-1$ + } + return " A command to retrieve help for " + cmd.getCommandName(); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput, + * String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + try { + cmd.help(out, args); + } catch (final IOException e) { + throw new CommandRunException(CommandRunExceptionType.INTERACTION, + "Console manager closed", e); //$NON-NLS-1$ + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#tip() */ + @Override + public String tip() { + return CLIPrompterMessages.getString("help.cmd.tip"); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() + */ + @Override + protected String usageDetail() { + return null; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usagePattern() */ + @Override + protected String usagePattern() { + if (cmd instanceof SubedCommand) { + return getCommandName() + " "; //$NON-NLS-1$ + } + return getCommandName(); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ICommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/ICommand.java index 0d22f8a..ff1c310 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ICommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ICommand.java @@ -1,80 +1,113 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ICommand.java - * Created on: May 31, 2016 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** The contract of commands. - *

- * This interface describe the contract of commands - * - * @author Emmanuel Bigeon */ -public interface ICommand { - - /** Execute the command on the given output and input. - * - * @param out the normal output - * @param in the input - * @param args the arguments - * @throws CommandRunException if the command failed */ - void execute(ConsoleOutput out, ConsoleInput in, - String... args) throws CommandRunException; - - /** Get teh command name. - * - * @return the command's name */ - String getCommandName(); - - /** This prints the help associated to this command. - * - * @param output the output to print the data - * @param args the arguments called with the help - * @throws IOException if the manager was closed */ - void help(ConsoleOutput output, String... args) throws IOException; - - /** Get a tip (brief helping message) for the command. - * - * @return a tip on the command */ - String tip(); - -} \ No newline at end of file +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ICommand.java + * Created on: May 31, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** The contract of commands. + *

+ * This interface describe the contract of commands + * + * @author Emmanuel Bigeon */ +public interface ICommand { + + /** Execute the command on the given output and input. + * + * @param out the normal output + * @param in the input + * @param args the arguments + * @throws CommandRunException if the command failed */ + void execute(ConsoleOutput out, ConsoleInput in, + String... args) throws CommandRunException; + + /** Get teh command name. + * + * @return the command's name */ + String getCommandName(); + + /** This prints the help associated to this command. + * + * @param output the output to print the data + * @param args the arguments called with the help + * @throws IOException if the manager was closed */ + void help(ConsoleOutput output, String... args) throws IOException; + + /** Get a tip (brief helping message) for the command. + * + * @return a tip on the command */ + String tip(); + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java b/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java index 49f748e..bd3f8e3 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ICommandProvider.java @@ -1,84 +1,117 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** gclc:fr.bigeon.gclc.command.ICommandProvider.java - * Created on: Sep 6, 2014 */ -package fr.bigeon.gclc.command; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** An ICommadProvider is a provider of commands that can register commands - * under some keywords. - * - * @author Emmanuel BIGEON */ -public interface ICommandProvider { - - /** Adds a command to this provider, if no command was associated with the - * given key. - * - * @param value the command to execute - * @return if the command was added - * @throws InvalidCommandName if the command name is invalid */ - boolean add(ICommand value) throws InvalidCommandName; - - /** Execute the command with the given name. - *

- * If no command with this name is found, an error command is usually - * executed. If there are several commands with the same name, the behavior - * is unspecified. Depending on the implementation, it may run an error - * command or prompt the user for a choice. - * - * @param out the output - * @param in the input - * @param command the name of the command the user wishes to execute - * @param args the arguments for the command - * @throws CommandRunException if the command failed to run */ - void executeSub(ConsoleOutput out, ConsoleInput in, String command, - String... args) throws CommandRunException; - - /** Get the command with the given name. - *

- * If no command with this name is found, an error command is usually - * returned. If there are several commands with the same name, the behavior - * is unspecified. Depending on the implementation, it may return an error - * command or the first command with this name found. - * - * @param command the name of the command the user wishes to execute - * @return the command to execute */ - ICommand get(String command); - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** gclc:fr.bigeon.gclc.command.ICommandProvider.java + * Created on: Sep 6, 2014 */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** An ICommadProvider is a provider of commands that can register commands + * under some keywords. + * + * @author Emmanuel BIGEON */ +public interface ICommandProvider { + + /** Adds a command to this provider, if no command was associated with the + * given key. + * + * @param value the command to execute + * @return if the command was added + * @throws InvalidCommandName if the command name is invalid */ + boolean add(ICommand value) throws InvalidCommandName; + + /** Execute the command with the given name. + *

+ * If no command with this name is found, an error command is usually + * executed. If there are several commands with the same name, the behavior + * is unspecified. Depending on the implementation, it may run an error + * command or prompt the user for a choice. + * + * @param out the output + * @param in the input + * @param command the name of the command the user wishes to execute + * @param args the arguments for the command + * @throws CommandRunException if the command failed to run */ + void executeSub(ConsoleOutput out, ConsoleInput in, String command, + String... args) throws CommandRunException; + + /** Get the command with the given name. + *

+ * If no command with this name is found, an error command is usually + * returned. If there are several commands with the same name, the behavior + * is unspecified. Depending on the implementation, it may return an error + * command or the first command with this name found. + * + * @param command the name of the command the user wishes to execute + * @return the command to execute */ + ICommand get(String command); + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java index 1704877..2bc598e 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommand.java @@ -1,160 +1,193 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ParametrizedCommand.java - * Created on: Dec 24, 2014 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; -import java.util.Set; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidParameterException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** A command relying on the {@link CommandParameters} to store parameters - * values. - * - * @author Emmanuel BIGEON */ -public abstract class ParametrizedCommand extends Command { - - private final ParametrizedCommandData data; - - /** Create a parametrized command. - *

- * Implementation are supposed to call the - * {@link #addBooleanParameter(String)} and - * {@link #addStringParameter(String, boolean)} method to set the - * parameters. - * - * @param name the name */ - public ParametrizedCommand(final String name) { - this(name, true); - } - - /** Create a parametrized command. - *

- * Implementation are supposed to call the - * {@link #addBooleanParameter(String)} and - * {@link #addStringParameter(String, boolean)} method to set the - * parameters. - * - * @param name the name - * @param strict if the arguments are restricted to the declared ones */ - public ParametrizedCommand(final String name, final boolean strict) { - super(name); - data = new ParametrizedCommandData(strict); - } - - /** Add a boolean parameter to defined parmaters. - * - * @param flag the boolean flag - * @throws InvalidParameterException if the parameter is already defined as - * a string parameter */ - protected final void addBooleanParameter(final String flag) throws InvalidParameterException { - data.addBooleanParameter(flag); - } - - /** Add a string parameter to defined parmaters. - * - * @param flag the parameter flag - * @param needed if the parameter's absence should cause an exception - * @throws InvalidParameterException if the parameter is already defined as - * a boolean parameter */ - protected final void addStringParameter(final String flag, - final boolean needed) throws InvalidParameterException { - data.addStringParameter(flag, needed); - } - - /** Actually performs the execution after parsing the parameters. - * - * @param out the output - * @param in the input - * @param parameters the command parameters - * @throws CommandRunException if the command failed */ - protected abstract void doExecute(ConsoleOutput out, ConsoleInput in, - CommandParameters parameters) throws CommandRunException; - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ - @Override - public final void execute(final ConsoleOutput output, - final ConsoleInput input, - final String... args) throws CommandRunException { - try { - doExecute(output, input, data.getParameters(input, args)); - } catch (final IOException e) { - throw new CommandRunException("Unable to get parameters", e, this); - } - } - - /** Retrieve the boolean parameters (aka flags). - * - * @return the set of boolean parameters */ - public final Set getBooleanParameters() { - return data.getBooleanParameters(); - } - - /** Retrieve the parameter names. - * - * @return the stringParams */ - public final Set getParameters() { - return data.getParameters(); - } - - /** Get the string parameters names. - * - * @return the stringParams */ - public final Set getStringParameters() { - return data.getStringParameters(); - } - - /** Test if a parameter is needed. - * - * @param param the parameter name - * @return if the parameter is needed */ - public final boolean isNeeded(final String param) { - return data.isNeeded(param); - } - - /** If the command refuse unrecognized parameters. - * - * @return the strict */ - public final boolean isStrict() { - return data.isStrict(); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ParametrizedCommand.java + * Created on: Dec 24, 2014 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.util.Set; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidParameterException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A command relying on the {@link CommandParameters} to store parameters + * values. + * + * @author Emmanuel BIGEON */ +public abstract class ParametrizedCommand extends Command { + + private final ParametrizedCommandData data; + + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param name the name */ + public ParametrizedCommand(final String name) { + this(name, true); + } + + /** Create a parametrized command. + *

+ * Implementation are supposed to call the + * {@link #addBooleanParameter(String)} and + * {@link #addStringParameter(String, boolean)} method to set the + * parameters. + * + * @param name the name + * @param strict if the arguments are restricted to the declared ones */ + public ParametrizedCommand(final String name, final boolean strict) { + super(name); + data = new ParametrizedCommandData(strict); + } + + /** Add a boolean parameter to defined parmaters. + * + * @param flag the boolean flag + * @throws InvalidParameterException if the parameter is already defined as + * a string parameter */ + protected final void addBooleanParameter(final String flag) throws InvalidParameterException { + data.addBooleanParameter(flag); + } + + /** Add a string parameter to defined parmaters. + * + * @param flag the parameter flag + * @param needed if the parameter's absence should cause an exception + * @throws InvalidParameterException if the parameter is already defined as + * a boolean parameter */ + protected final void addStringParameter(final String flag, + final boolean needed) throws InvalidParameterException { + data.addStringParameter(flag, needed); + } + + /** Actually performs the execution after parsing the parameters. + * + * @param out the output + * @param in the input + * @param parameters the command parameters + * @throws CommandRunException if the command failed */ + protected abstract void doExecute(ConsoleOutput out, ConsoleInput in, + CommandParameters parameters) throws CommandRunException; + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#execute(java.lang.String[]) */ + @Override + public final void execute(final ConsoleOutput output, + final ConsoleInput input, + final String... args) throws CommandRunException { + try { + doExecute(output, input, data.getParameters(input, args)); + } catch (final IOException e) { + throw new CommandRunException("Unable to get parameters", e); + } + } + + /** Retrieve the boolean parameters (aka flags). + * + * @return the set of boolean parameters */ + public final Set getBooleanParameters() { + return data.getBooleanParameters(); + } + + /** Retrieve the parameter names. + * + * @return the stringParams */ + public final Set getParameters() { + return data.getParameters(); + } + + /** Get the string parameters names. + * + * @return the stringParams */ + public final Set getStringParameters() { + return data.getStringParameters(); + } + + /** Test if a parameter is needed. + * + * @param param the parameter name + * @return if the parameter is needed */ + public final boolean isNeeded(final String param) { + return data.isNeeded(param); + } + + /** If the command refuse unrecognized parameters. + * + * @return the strict */ + public final boolean isStrict() { + return data.isStrict(); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommandData.java b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommandData.java index 8bbb118..d058a07 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommandData.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/ParametrizedCommandData.java @@ -1,210 +1,252 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ParametrizedCommand.java - * Created on: Dec 24, 2014 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import fr.bigeon.gclc.exception.CommandParsingException; -import fr.bigeon.gclc.exception.InvalidParameterException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.EmptyInput; - -/** An object to handle standardized command parameters. - * - * @author Emmanuel BIGEON */ -public final class ParametrizedCommandData { - - /** The boolean parameters mandatory status. */ - private final Set boolParams = new HashSet<>(); - /** The string parameters mandatory status. */ - private final Map stringParams = new HashMap<>(); - /** The parameters mandatory status. */ - private final Map params = new HashMap<>(); - /** The restriction of provided parameters on execution to declared paramters in - * the status maps. */ - private final boolean strict; - - public ParametrizedCommandData() { - this(true); - } - - public ParametrizedCommandData(final boolean strict) { - this.strict = strict; - } - - /** Add a boolean parameter to defined parmaters. - * - * @param flag the boolean flag - * @throws InvalidParameterException if the parameter is already defined as a - * string parameter */ - public final void addBooleanParameter(final String flag) - throws InvalidParameterException { - if (params.containsKey(flag) && stringParams.containsKey(flag)) { - throw new InvalidParameterException("Parameter is already defined as string"); //$NON-NLS-1$ - } - boolParams.add(flag); - params.put(flag, Boolean.FALSE); - } - - /** Add a string parameter to defined parmaters. - * - * @param flag the parameter flag - * @param needed if the parameter's absence should cause an exception - * @throws InvalidParameterException if the parameter is already defined as a - * boolean parameter */ - public final void addStringParameter(final String flag, final boolean needed) - throws InvalidParameterException { - if (params.containsKey(flag)) { - checkParam(flag, needed); - return; - } - stringParams.put(flag, Boolean.valueOf(needed)); - params.put(flag, Boolean.valueOf(needed)); - } - - /** Check a parameter. - * - * @param param the string parameter - * @param needed if the parameter is needed - * @throws InvalidParameterException if the new definition is invalid */ - private void checkParam(final String param, final boolean needed) - throws InvalidParameterException { - if (stringParams.containsKey(param)) { - final Boolean need = Boolean - .valueOf(needed || stringParams.get(param).booleanValue()); - stringParams.put(param, need); - params.put(param, need); - return; - } - throw new InvalidParameterException("Parameter is already defined as boolean"); //$NON-NLS-1$ - } - - public final CommandParameters getParameters(final ConsoleInput input, - final String... args) - throws IOException { - final CommandParameters parameters = new CommandParameters(boolParams, - stringParams.keySet(), strict); - try { - parameters.parseArgs(args); - } catch (final CommandParsingException e) { - throw new IOException(e); - } - final List toProvide = new ArrayList<>(); - for (final Entry string : params.entrySet()) { - if (string.getValue().booleanValue() - && parameters.get(string.getKey()) == null) { - if (input == null || input == EmptyInput.INSTANCE) { - throw new IOException(); - } - toProvide.add(string.getKey()); - } - } - // for each needed parameters that is missing, prompt the user. - fillParameters(input, toProvide, parameters); - return parameters; - } - - /** Fill the undefined parameters. - *

- * This method prompts the user to fill the needed parameters. - * - * @param input the input to prompt through - * @param parameters the parameter list to complete - * @param toProvide the parameters to ask for - * @throws IOException if the manager was closed */ - private final static void fillParameters(final ConsoleInput input, - final List toProvide, final CommandParameters parameters) - throws IOException { - for (final String string : toProvide) { - String value; - value = input.prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$ - while (value.isEmpty()) { - value = input - .prompt(MessageFormat.format("value of {0}? (cannot be empty) ", //$NON-NLS-1$ - string)); - } - parameters.set(string, value); - } - } - - /** Retrieve the boolean parameters (aka flags). - * - * @return the set of boolean parameters */ - public final Set getBooleanParameters() { - return Collections.unmodifiableSet(boolParams); - } - - /** Retrieve the parameter names. - * - * @return the stringParams */ - public final Set getParameters() { - return params.keySet(); - } - - /** Get the string parameters names. - * - * @return the stringParams */ - public final Set getStringParameters() { - return stringParams.keySet(); - } - - /** Test if a parameter is needed. - * - * @param param the parameter name - * @return if the parameter is needed */ - public final boolean isNeeded(final String param) { - return params.containsKey(param) && params.get(param).booleanValue(); - } - - /** If the command refuse unrecognized parameters. - * - * @return the strict */ - public final boolean isStrict() { - return strict; - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ParametrizedCommand.java + * Created on: Dec 24, 2014 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import fr.bigeon.gclc.exception.CommandParsingException; +import fr.bigeon.gclc.exception.InvalidParameterException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.EmptyInput; + +/** An object to handle standardized command parameters. + * + * @author Emmanuel BIGEON */ +public final class ParametrizedCommandData { + + /** The boolean parameters mandatory status. */ + private final Set boolParams = new HashSet<>(); + /** The string parameters mandatory status. */ + private final Map stringParams = new HashMap<>(); + /** The parameters mandatory status. */ + private final Map params = new HashMap<>(); + /** The restriction of provided parameters on execution to declared paramters in + * the status maps. */ + private final boolean strict; + + /** The data for the parametrized command. */ + public ParametrizedCommandData() { + this(true); + } + + /** The data for a parametrized command. + * + * @param strict if the command was refusing unrecognized parameters */ + public ParametrizedCommandData(final boolean strict) { + this.strict = strict; + } + + /** Add a boolean parameter to defined parmaters. + * + * @param flag the boolean flag + * @throws InvalidParameterException if the parameter is already defined as a + * string parameter */ + public final void addBooleanParameter(final String flag) + throws InvalidParameterException { + if (params.containsKey(flag) && stringParams.containsKey(flag)) { + throw new InvalidParameterException("Parameter is already defined as string"); //$NON-NLS-1$ + } + boolParams.add(flag); + params.put(flag, Boolean.FALSE); + } + + /** Add a string parameter to defined parmaters. + * + * @param flag the parameter flag + * @param needed if the parameter's absence should cause an exception + * @throws InvalidParameterException if the parameter is already defined as a + * boolean parameter */ + public final void addStringParameter(final String flag, final boolean needed) + throws InvalidParameterException { + if (params.containsKey(flag)) { + checkParam(flag, needed); + return; + } + stringParams.put(flag, Boolean.valueOf(needed)); + params.put(flag, Boolean.valueOf(needed)); + } + + /** Check a parameter. + * + * @param param the string parameter + * @param needed if the parameter is needed + * @throws InvalidParameterException if the new definition is invalid */ + private void checkParam(final String param, final boolean needed) + throws InvalidParameterException { + if (stringParams.containsKey(param)) { + final Boolean need = Boolean + .valueOf(needed || stringParams.get(param).booleanValue()); + stringParams.put(param, need); + params.put(param, need); + return; + } + throw new InvalidParameterException("Parameter is already defined as boolean"); //$NON-NLS-1$ + } + + /** Get the parameters from an input. + * + * @param input the input + * @param args the command arguments + * @return the command object + * @throws IOException if the command could not be filled. */ + public final CommandParameters getParameters(final ConsoleInput input, + final String... args) throws IOException { + final CommandParameters parameters = new CommandParameters(boolParams, + stringParams.keySet(), strict); + try { + parameters.parseArgs(args); + } catch (final CommandParsingException e) { + throw new IOException(e); + } + final List toProvide = new ArrayList<>(); + for (final Entry string : params.entrySet()) { + if (string.getValue().booleanValue() + && parameters.get(string.getKey()) == null) { + if (input == null || input == EmptyInput.INSTANCE) { + throw new IOException(); + } + toProvide.add(string.getKey()); + } + } + // for each needed parameters that is missing, prompt the user. + fillParameters(input, toProvide, parameters); + return parameters; + } + + /** Fill the undefined parameters. + *

+ * This method prompts the user to fill the needed parameters. + * + * @param input the input to prompt through + * @param parameters the parameter list to complete + * @param toProvide the parameters to ask for + * @throws IOException if the manager was closed */ + private final static void fillParameters(final ConsoleInput input, + final List toProvide, final CommandParameters parameters) + throws IOException { + for (final String string : toProvide) { + String value; + value = input.prompt(MessageFormat.format("value of {0}? ", string)); //$NON-NLS-1$ + while (value.isEmpty()) { + value = input + .prompt(MessageFormat.format("value of {0}? (cannot be empty) ", //$NON-NLS-1$ + string)); + } + parameters.set(string, value); + } + } + + /** Retrieve the boolean parameters (aka flags). + * + * @return the set of boolean parameters */ + public final Set getBooleanParameters() { + return Collections.unmodifiableSet(boolParams); + } + + /** Retrieve the parameter names. + * + * @return the stringParams */ + public final Set getParameters() { + return params.keySet(); + } + + /** Get the string parameters names. + * + * @return the stringParams */ + public final Set getStringParameters() { + return stringParams.keySet(); + } + + /** Test if a parameter is needed. + * + * @param param the parameter name + * @return if the parameter is needed */ + public final boolean isNeeded(final String param) { + return params.containsKey(param) && params.get(param).booleanValue(); + } + + /** If the command refuse unrecognized parameters. + * + * @return the strict */ + public final boolean isStrict() { + return strict; + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java index 93cde92..7f7a4bb 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/SubedCommand.java @@ -1,188 +1,218 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** gclc:fr.bigeon.gclc.command.SubedCommand.java - * Created on: Sep 6, 2014 */ -package fr.bigeon.gclc.command; - -import java.io.IOException; -import java.util.Arrays; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** - *

- * A subed command is a command that can execute sub commands depending on the - * first argument. - * - * @author Emmanuel BIGEON */ -public final class SubedCommand extends CommandProvider implements ICommand { - - /** The tab character. */ - private static final String TAB = "\t"; //$NON-NLS-1$ - /** The command to execute when this command is called with no sub - * arguments. - *

- * This may be null, in which case the command should have arguments. */ - private final ICommand noArgCommand; - /** A tip on this command. */ - private final String tip; - /** The name of the command. */ - private final String name; - - /** Create the command that defines sub commands. - * - * @param name the name of the command */ - public SubedCommand(final String name) { - super(); - this.name = name; - noArgCommand = null; - tip = null; - } - - /** Create the command that defines sub commands. - * - * @param name the name of the command - * @param noArgCommand the command to execute when no extra parameter are - * provided */ - public SubedCommand(final String name, final ICommand noArgCommand) { - super(); - this.name = name; - this.noArgCommand = noArgCommand; - tip = null; - } - - /** Create the command that defines sub commands. - * - * @param name the name of the command - * @param noArgCommand the command to execute - * @param tip the help tip associated */ - public SubedCommand(final String name, final ICommand noArgCommand, - final String tip) { - super(); - this.name = name; - this.noArgCommand = noArgCommand; - this.tip = tip; - } - - /** Create the command that defines sub commands. - * - * @param name the name of the command - * @param tip the help tip associated */ - public SubedCommand(final String name, final String tip) { - super(); - this.name = name; - noArgCommand = null; - this.tip = tip; - } - - /* (non-Javadoc) - * @see fr.bigeon.acide.Command#execute(java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput output, final ConsoleInput input, - final String... args) throws CommandRunException { - if (args.length == 0 || args[0].startsWith("-")) { //$NON-NLS-1$ - if (noArgCommand != null) { - noArgCommand.execute(output, input, args); - } else { - throw new CommandRunException("Unrecognized command", this); //$NON-NLS-1$ - } - } else { - - try { - executeSub(output, input, args[0], - Arrays.copyOfRange(args, 1, args.length)); - } catch (final CommandRunException e) { - if (e.getSource() != null) { - throw e; - } - throw new CommandRunException(CommandRunExceptionType.USAGE, - e.getLocalizedMessage(), e, this); - } - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ - @Override - public String getCommandName() { - return name; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#help() */ - @Override - public void help(final ConsoleOutput manager, - final String... args) throws IOException { - if (args.length != 0 && !args[0].startsWith("-")) { //$NON-NLS-1$ - // Specific - final ICommand c = get(args[0]); - if (c != null) { - c.help(manager, Arrays.copyOfRange(args, 1, args.length)); - } else { - manager.println("No command "+Arrays.toString(args)); - } - } else { - // Generic - if (noArgCommand != null && noArgCommand.tip() != null) { - manager.println(TAB + noArgCommand.tip()); - } - for (final ICommand cmd : commands) { - if (cmd.tip() == null) { - manager.println(TAB + cmd.getCommandName()); - } else { - manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$ - cmd.tip()); - } - } - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#tip() */ - @Override - public String tip() { - return tip; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() */ - @Override - public String toString() { - return "SubedCommand " + super.toString(); //$NON-NLS-1$ - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** gclc:fr.bigeon.gclc.command.SubedCommand.java + * Created on: Sep 6, 2014 */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.util.Arrays; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** + *

+ * A subed command is a command that can execute sub commands depending on the + * first argument. + * + * @author Emmanuel BIGEON */ +public final class SubedCommand extends CommandProvider implements ICommand { + + /** The tab character. */ + private static final String TAB = "\t"; //$NON-NLS-1$ + /** The command to execute when this command is called with no sub + * arguments. + *

+ * This may be null, in which case the command should have arguments. */ + private final ICommand noArgCommand; + /** A tip on this command. */ + private final String tip; + /** The name of the command. */ + private final String name; + + /** Create the command that defines sub commands. + * + * @param name the name of the command */ + public SubedCommand(final String name) { + super(); + this.name = name; + noArgCommand = null; + tip = null; + } + + /** Create the command that defines sub commands. + * + * @param name the name of the command + * @param noArgCommand the command to execute when no extra parameter are + * provided */ + public SubedCommand(final String name, final ICommand noArgCommand) { + super(); + this.name = name; + this.noArgCommand = noArgCommand; + tip = null; + } + + /** Create the command that defines sub commands. + * + * @param name the name of the command + * @param noArgCommand the command to execute + * @param tip the help tip associated */ + public SubedCommand(final String name, final ICommand noArgCommand, + final String tip) { + super(); + this.name = name; + this.noArgCommand = noArgCommand; + this.tip = tip; + } + + /** Create the command that defines sub commands. + * + * @param name the name of the command + * @param tip the help tip associated */ + public SubedCommand(final String name, final String tip) { + super(); + this.name = name; + noArgCommand = null; + this.tip = tip; + } + + /* (non-Javadoc) + * @see fr.bigeon.acide.Command#execute(java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput output, final ConsoleInput input, + final String... args) throws CommandRunException { + if (args.length == 0 || args[0].startsWith("-")) { //$NON-NLS-1$ + if (noArgCommand != null) { + noArgCommand.execute(output, input, args); + } else { + throw new CommandRunException("Unrecognized command"); //$NON-NLS-1$ + } + } else { + + try { + executeSub(output, input, args[0], + Arrays.copyOfRange(args, 1, args.length)); + } catch (final CommandRunException e) { + throw new CommandRunException(CommandRunExceptionType.USAGE, + e.getLocalizedMessage(), e); + } + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ + @Override + public String getCommandName() { + return name; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#help() */ + @Override + public void help(final ConsoleOutput manager, + final String... args) throws IOException { + if (args.length != 0 && !args[0].startsWith("-")) { //$NON-NLS-1$ + // Specific + final ICommand c = get(args[0]); + if (c != null) { + c.help(manager, Arrays.copyOfRange(args, 1, args.length)); + } else { + manager.println("No command "+Arrays.toString(args)); + } + } else { + // Generic + if (noArgCommand != null && noArgCommand.tip() != null) { + manager.println(TAB + noArgCommand.tip()); + } + for (final ICommand cmd : commands) { + if (cmd.tip() == null) { + manager.println(TAB + cmd.getCommandName()); + } else { + manager.println(TAB + cmd.getCommandName() + ": " + //$NON-NLS-1$ + cmd.tip()); + } + } + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#tip() */ + @Override + public String tip() { + return tip; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() */ + @Override + public String toString() { + return "SubedCommand " + super.toString(); //$NON-NLS-1$ + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/base/ExitCommand.java similarity index 66% rename from gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java rename to gclc/src/main/java/fr/bigeon/gclc/command/base/ExitCommand.java index cd14335..48a9658 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ExitCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/base/ExitCommand.java @@ -1,101 +1,135 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.ExitCommand.java - * Created on: Jun 8, 2016 - */ -package fr.bigeon.gclc.command; - -import java.io.IOException; - -import fr.bigeon.gclc.ConsoleApplication; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.prompt.CLIPrompterMessages; - -/** A command to exit a {@link ConsoleApplication}. - * - * @author Emmanuel BIGEON */ -public class ExitCommand implements ICommand { - /** The exit command manual message key. */ - private static final String EXIT_MAN = "exit.man"; //$NON-NLS-1$ - /** The tip of the exit command. */ - private static final String EXIT = "exit.tip"; //$NON-NLS-1$ - /** The application that will be exited when this command runs. */ - private final ConsoleApplication app; - /** The exit command name. */ - private final String name; - - /** Create the exiting command. - * - * @param name the name of the command - * @param app the application to exit */ - public ExitCommand(final String name, final ConsoleApplication app) { - this.name = name; - this.app = app; - } - - /** The actions to take before exiting. - *

- * This method is intended to be overriden by sub classes. */ - protected void beforeExit() { - // Do nothing by default - } - - @Override - public final void execute(final ConsoleOutput output, - final ConsoleInput input, final String... args) { - beforeExit(); - app.exit(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ - @Override - public final String getCommandName() { - return name; - } - - @Override - public final void help(final ConsoleOutput manager, - final String... args) throws IOException { - manager.println( - CLIPrompterMessages.getString(EXIT_MAN, (Object[]) args)); - } - @Override - public final String tip() { - return CLIPrompterMessages.getString(EXIT); - } -} \ No newline at end of file +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.ExitCommand.java + * Created on: Jun 8, 2016 + */ +package fr.bigeon.gclc.command.base; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.ConsoleApplication; +import fr.bigeon.gclc.command.ICommand; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.prompt.CLIPrompterMessages; + +/** A command to exit a {@link ConsoleApplication}. + * + * @author Emmanuel BIGEON */ +public final class ExitCommand implements ICommand { + /** The exit command manual message key. */ + private static final String EXIT_MAN = "exit.man"; //$NON-NLS-1$ + /** The tip of the exit command. */ + private static final String EXIT = "exit.tip"; //$NON-NLS-1$ + /** The application that will be exited when this command runs. */ + private final ConsoleApplication app; + /** The exit command name. */ + private final String name; + + /** Create the exiting command. + * + * @param name the name of the command + * @param app the application to exit */ + public ExitCommand(final String name, final ConsoleApplication app) { + this.name = name; + this.app = app; + } + + /** The actions to take before exiting. + *

+ * This method is intended to be overriden by sub classes. */ + protected void beforeExit() { + // Do nothing by default + } + + @Override + public final void execute(final ConsoleOutput output, + final ConsoleInput input, final String... args) { + beforeExit(); + app.exit(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ + @Override + public final String getCommandName() { + return name; + } + + @Override + public final void help(final ConsoleOutput manager, + final String... args) throws IOException { + manager.println( + CLIPrompterMessages.getString(EXIT_MAN, (Object[]) args)); + } + @Override + public final String tip() { + return CLIPrompterMessages.getString(EXIT); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java b/gclc/src/main/java/fr/bigeon/gclc/command/base/MockCommand.java similarity index 63% rename from gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java rename to gclc/src/main/java/fr/bigeon/gclc/command/base/MockCommand.java index c36c895..82cdca8 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/MockCommand.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/base/MockCommand.java @@ -1,93 +1,127 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.MockCommand.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.command; - -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** This implement a command that does nothing. - *

- * This class is intended for testing purpose only. - * - * @author Emmanuel Bigeon */ -public final class MockCommand implements ICommand { - - /** The command name. */ - private final String name; - - /** Create the command. - * - * @param name the command name */ - public MockCommand(final String name) { - this.name = name; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput, - * String[]) */ - @Override - public void execute(final ConsoleOutput out, final ConsoleInput in, - final String... args) { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ - @Override - public String getCommandName() { - return name; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager. - * ConsoleManager, java.lang.String[]) */ - @Override - public void help(final ConsoleOutput manager, - final String... args) { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() */ - @Override - public String tip() { - return null; - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.MockCommand.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.command.base; + +import fr.bigeon.gclc.command.ICommand; +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** This implement a command that does nothing. + *

+ * This class is intended for testing purpose only. + * + * @author Emmanuel Bigeon */ +public final class MockCommand implements ICommand { + + /** The command name. */ + private final String name; + + /** Create the command. + * + * @param name the command name */ + public MockCommand(final String name) { + this.name = name; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(ConsoleOutput, ConsoleInput, + * String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#getCommandName() */ + @Override + public String getCommandName() { + return name; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#help(fr.bigeon.gclc.manager. + * ConsoleManager, java.lang.String[]) */ + @Override + public void help(final ConsoleOutput manager, + final String... args) { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#tip() */ + @Override + public String tip() { + return null; + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java b/gclc/src/main/java/fr/bigeon/gclc/command/base/ScriptExecution.java similarity index 78% rename from gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java rename to gclc/src/main/java/fr/bigeon/gclc/command/base/ScriptExecution.java index 6d6788b..a4b3943 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/ScriptExecution.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/base/ScriptExecution.java @@ -1,217 +1,246 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ScriptExecution.java - * Created on: Jun 12, 2016 - */ -package fr.bigeon.gclc.command; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.List; - -import fr.bigeon.gclc.ConsoleApplication; -import fr.bigeon.gclc.GCLCConstants; -import fr.bigeon.gclc.exception.CommandParsingException; -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** A command that will launch a series of command from a file. - *

- * This command will read a file and execute each non empty non commented line - * as a command of the application. - * - * @author Emmanuel Bigeon */ -public final class ScriptExecution extends Command { - - /** The tab character. */ - private static final String TAB = "\t"; //$NON-NLS-1$ - /** the space character. */ - private static final String SPACE = " "; //$NON-NLS-1$ - /** The application. */ - private final ConsoleApplication application; - /** The commenting prefix. */ - private final String commentPrefix; - /** The charset for files. */ - private final Charset charset; - - /** Create the script command. - * - * @param name the name of the command - * @param application the application - * @param commentPrefix the comment prefix in the script files - * @param charset the charset to use for files */ - public ScriptExecution(final String name, final ConsoleApplication application, - final String commentPrefix, final Charset charset) { - super(name); - this.application = application; - this.commentPrefix = commentPrefix; - this.charset = charset; - } - - /** Check the arguments. - * - * @param args the arguments - * @throws CommandRunException if the arguments were not the ones - * expected */ - private void checkArgs(final String[] args) throws CommandRunException { - if (args.length == 0) { - throw new CommandRunException(CommandRunExceptionType.USAGE, - "Expecting a file", this); //$NON-NLS-1$ - } - } - - - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput out, final ConsoleInput in, - final String... args) throws CommandRunException { - checkArgs(args); - final String scriptFile = args[0]; - final String[] params = Arrays.copyOfRange(args, 1, args.length); - String cmd; - int lineNo = -1; - try (InputStreamReader fReader = new InputStreamReader( - new FileInputStream(scriptFile), charset); - BufferedReader reader = new BufferedReader(fReader)) { - while ((cmd = reader.readLine()) != null) { - lineNo++; - final String cmdLine = readCommandLine(cmd, params); - if (cmdLine == null) { - continue; - } - final List ps = GCLCConstants.splitCommand(cmdLine); - final String command = ps.remove(0); - application.executeSub(out, in, command, - ps.toArray(new String[0])); - } - } catch (final CommandParsingException e) { - throw new CommandRunException(MessageFormat.format( - "Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$ - e, this); - } catch (final IOException e) { - throw new CommandRunException("Unable to read script", //$NON-NLS-1$ - e, this); - } catch (final CommandRunException e) { - throw manageRunException(e, lineNo); - } - } - - /** This method will create the correct exception. The exception source must - * be this command. - * - * @param e the exception - * @param lineNo the line nu;ber - * @return the exception to actually throw */ - private CommandRunException manageRunException(final CommandRunException e, - final int lineNo) { - if (e.getSource() == this) { - // ensure closing? - return e; - } - return new CommandRunException(CommandRunExceptionType.EXECUTION, - MessageFormat.format( - "The script could not complete due to command failure at line {0} ({1})", //$NON-NLS-1$ - Integer.valueOf(lineNo), e.getLocalizedMessage()), - e, this); - } - - /** Read a line of the script. - * - * @param cmd the line - * @param params the formatting parameters - * @return the command if it is indeed one, null otherwise - * @throws CommandRunException if the line stqrted with a space character */ - private String readCommandLine(final String cmd, - final Object[] params) throws CommandRunException { - if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) { - throw new CommandRunException( - "Invalid line in script (line starts with space character)", //$NON-NLS-1$ - this); - } - if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) { - // Comment line - return null; - } - return MessageFormat.format(cmd, params); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#tip() */ - @Override - public String tip() { - return "Execute a script"; //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @Override - protected String usageDetail() { - final StringBuilder builder = new StringBuilder(); - builder.append( - " scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$ - builder.append(System.lineSeparator()); - builder.append(System.lineSeparator()); - builder.append( - " The script file must contain one line commands. The lines must never"); //$NON-NLS-1$ - builder.append(System.lineSeparator()); - builder.append( - "start with whitespace characters. The lines starting with"); //$NON-NLS-1$ - builder.append(System.lineSeparator()); - builder.append('"'); - builder.append(commentPrefix); - builder.append("\" will be ignored as well as empty lines."); //$NON-NLS-1$ - builder.append(System.lineSeparator()); - - return builder.toString(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usagePattern() */ - @Override - protected String usagePattern() { - return super.usagePattern() + " "; //$NON-NLS-1$ - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ScriptExecution.java + * Created on: Jun 12, 2016 + */ +package fr.bigeon.gclc.command.base; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.List; + +import fr.bigeon.gclc.ConsoleApplication; +import fr.bigeon.gclc.GCLCConstants; +import fr.bigeon.gclc.command.Command; +import fr.bigeon.gclc.exception.CommandParsingException; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A command that will launch a series of command from a file. + *

+ * This command will read a file and execute each non empty non commented line + * as a command of the application. + * + * @author Emmanuel Bigeon */ +public final class ScriptExecution extends Command { + + /** The tab character. */ + private static final String TAB = "\t"; //$NON-NLS-1$ + /** the space character. */ + private static final String SPACE = " "; //$NON-NLS-1$ + /** The application. */ + private final ConsoleApplication application; + /** The commenting prefix. */ + private final String commentPrefix; + /** The charset for files. */ + private final Charset charset; + + /** Create the script command. + * + * @param name the name of the command + * @param application the application + * @param commentPrefix the comment prefix in the script files + * @param charset the charset to use for files */ + public ScriptExecution(final String name, final ConsoleApplication application, + final String commentPrefix, final Charset charset) { + super(name); + this.application = application; + this.commentPrefix = commentPrefix; + this.charset = charset; + } + + /** Check the arguments. + * + * @param args the arguments + * @throws CommandRunException if the arguments were not the ones + * expected */ + private static void checkArgs(final String[] args) throws CommandRunException { + if (args.length == 0) { + throw new CommandRunException(CommandRunExceptionType.USAGE, + "Expecting a file"); //$NON-NLS-1$ + } + } + + + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + checkArgs(args); + final String scriptFile = args[0]; + final String[] params = Arrays.copyOfRange(args, 1, args.length); + String cmd; + int lineNo = -1; + try (InputStreamReader fReader = new InputStreamReader( + new FileInputStream(scriptFile), charset); + BufferedReader reader = new BufferedReader(fReader)) { + while ((cmd = reader.readLine()) != null) { + lineNo++; + final String cmdLine = readCommandLine(cmd, params); + if (cmdLine == null) { + continue; + } + final List ps = GCLCConstants.splitCommand(cmdLine); + final String command = ps.remove(0); + application.executeSub(out, in, command, + ps.toArray(new String[0])); + } + } catch (final CommandParsingException e) { + throw new CommandRunException(MessageFormat.format( + "Invalid command in script ({0})", e.getLocalizedMessage()), //$NON-NLS-1$ + e); + } catch (final IOException e) { + throw new CommandRunException("Unable to read script", //$NON-NLS-1$ + e); + } catch (final CommandRunException e) { + throw manageRunException(e, lineNo); + } + } + + /** This method will create the correct exception. The exception source must + * be this command. + * + * @param e the exception + * @param lineNo the line nu;ber + * @return the exception to actually throw */ + private static CommandRunException manageRunException(final CommandRunException e, + final int lineNo) { + return new CommandRunException(CommandRunExceptionType.EXECUTION, + MessageFormat.format( + "The script could not complete due to command failure at line {0} ({1})", //$NON-NLS-1$ + Integer.valueOf(lineNo), e.getLocalizedMessage()), + e); + } + + /** Read a line of the script. + * + * @param cmd the line + * @param params the formatting parameters + * @return the command if it is indeed one, null otherwise + * @throws CommandRunException if the line stqrted with a space character */ + private String readCommandLine(final String cmd, + final Object[] params) throws CommandRunException { + if (cmd.startsWith(SPACE) || cmd.startsWith(TAB)) { + throw new CommandRunException( + "Invalid line in script (line starts with space character)"); + } + if (cmd.isEmpty() || cmd.startsWith(commentPrefix)) { + // Comment line + return null; + } + return MessageFormat.format(cmd, params); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#tip() */ + @Override + public String tip() { + return "Execute a script"; //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + final StringBuilder builder = new StringBuilder(); + builder.append( + " scriptfile: path to the file containing the script to execute."); //$NON-NLS-1$ + builder.append(System.lineSeparator()); + builder.append(System.lineSeparator()); + builder.append( + " The script file must contain one line commands. The lines must never"); //$NON-NLS-1$ + builder.append(System.lineSeparator()); + builder.append( + "start with whitespace characters. The lines starting with"); //$NON-NLS-1$ + builder.append(System.lineSeparator()); + builder.append('"'); + builder.append(commentPrefix); + builder.append("\" will be ignored as well as empty lines."); //$NON-NLS-1$ + builder.append(System.lineSeparator()); + + return builder.toString(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usagePattern() */ + @Override + protected String usagePattern() { + return super.usagePattern() + " "; //$NON-NLS-1$ + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/base/package-info.java b/gclc/src/main/java/fr/bigeon/gclc/command/base/package-info.java new file mode 100644 index 0000000..9319452 --- /dev/null +++ b/gclc/src/main/java/fr/bigeon/gclc/command/base/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author Emmanuel Bigeon + * + */ +package fr.bigeon.gclc.command.base; diff --git a/gclc/src/main/java/fr/bigeon/gclc/command/package-info.java b/gclc/src/main/java/fr/bigeon/gclc/command/package-info.java index 76163a6..284cd7e 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/command/package-info.java +++ b/gclc/src/main/java/fr/bigeon/gclc/command/package-info.java @@ -1,49 +1,83 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ - -/** gclc:fr.bigeon.gclc.command.package-info.java - * Created on: Sep 6, 2014 */ -/** This package groups elements related to - * {@link fr.bigeon.gclc.command.ICommand} - *

- * There are some implementations, such as the - * {@link fr.bigeon.gclc.command.ParametrizedCommand} for commands with a - * predefined set of flags and option taking a string as value, the - * {@link fr.bigeon.gclc.command.SubedCommand} for a command that is declined in - * a set of sub commands, the {@link fr.bigeon.gclc.command.HelpExecutor} for - * help display of other commands and the - * - * @author Emmanuel BIGEON */ -package fr.bigeon.gclc.command; \ No newline at end of file +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ + +/** gclc:fr.bigeon.gclc.command.package-info.java + * Created on: Sep 6, 2014 */ +/** This package groups elements related to + * {@link fr.bigeon.gclc.command.ICommand} + *

+ * There are some implementations, such as the + * {@link fr.bigeon.gclc.command.ParametrizedCommand} for commands with a + * predefined set of flags and option taking a string as value, the + * {@link fr.bigeon.gclc.command.SubedCommand} for a command that is declined in + * a set of sub commands, the {@link fr.bigeon.gclc.command.HelpExecutor} for + * help display of other commands and the + * + * @author Emmanuel BIGEON */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandParsingException.java b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandParsingException.java index 3f46cd7..6da820f 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandParsingException.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandParsingException.java @@ -1,71 +1,104 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.CommandParsingException.java - * Created on: Jun 1, 2016 - */ -package fr.bigeon.gclc.exception; - -/** An exception raised during command parsing. - * - * @author Emmanuel Bigeon */ -public class CommandParsingException extends Exception { - - /** svuid. */ - private static final long serialVersionUID = 1L; - - /** Create the exception with a message. - * - * @param message the message */ - public CommandParsingException(final String message) { - super(message); - } - - /** Create the exception with a message and a cause. - * - * @param message the message - * @param cause the cause */ - public CommandParsingException(final String message, final Throwable cause) { - super(message, cause); - } - - /** Create the exception with a message. - * - * @param cause the cause */ - public CommandParsingException(final Throwable cause) { - super(cause); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.CommandParsingException.java + * Created on: Jun 1, 2016 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** An exception raised during command parsing. + * + * @author Emmanuel Bigeon */ +public class CommandParsingException extends Exception { + + /** svuid. */ + private static final long serialVersionUID = 1L; + + /** Create the exception with a message. + * + * @param message the message */ + public CommandParsingException(final String message) { + super(message); + } + + /** Create the exception with a message and a cause. + * + * @param message the message + * @param cause the cause */ + public CommandParsingException(final String message, final Throwable cause) { + super(message, cause); + } + + /** Create the exception with a message. + * + * @param cause the cause */ + public CommandParsingException(final Throwable cause) { + super(cause); + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java index 59dcec9..a6ff30e 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunException.java @@ -1,130 +1,142 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.CommandRunException.java - * Created on: Feb 10, 2015 - */ -package fr.bigeon.gclc.exception; - -import fr.bigeon.gclc.command.ICommand; - -/** An exception thrown when a command failed to run correctly. - * - * @author Emmanuel BIGEON */ -public final class CommandRunException extends Exception { - - /** the SVUID. */ - private static final long serialVersionUID = 1L; - - /** The type of run exception. */ - private final CommandRunExceptionType type; - /** The command that caused the error. */ - private transient ICommand source; - - /** Create the exception. - * - * @param type the type of exception - * @param message the message - * @param source the source */ - public CommandRunException(final CommandRunExceptionType type, - final String message, final ICommand source) { - super(message); - this.type = type; - this.source = source; - } - - /** Create the exception with a cause. - * - * @param type the type of exception - * @param message a message - * @param cause the cause - * @param source the source */ - public CommandRunException(final CommandRunExceptionType type, - final String message, final Throwable cause, - final ICommand source) { - super(message, cause); - this.type = type; - this.source = source; - } - - /** Create the exception with type - * {@link CommandRunExceptionType#EXECUTION}. - * - * @param message a message - * @param source the source */ - public CommandRunException(final String message, final ICommand source) { - super(message); - type = CommandRunExceptionType.EXECUTION; - this.source = source; - } - - /** Create the exception with type {@link CommandRunExceptionType#EXECUTION} - * and a cause. - * - * @param message a message - * @param cause the cause - * @param source the source */ - public CommandRunException(final String message, final Throwable cause, - final ICommand source) { - super(message, cause); - type = CommandRunExceptionType.EXECUTION; - this.source = source; - } - - /* (non-Javadoc) - * @see java.lang.Throwable#getLocalizedMessage() */ - @Override - public String getLocalizedMessage() { - if (getCause() != null) { - return super.getLocalizedMessage() + ": " + //$NON-NLS-1$ - getCause().getLocalizedMessage(); - } - return super.getLocalizedMessage(); - } - - /** Get the exception raising command. - * - * @return the source */ - public ICommand getSource() { - return source; - } - - /** Get the exception type. - * - * @return the type */ - public CommandRunExceptionType getType() { - return type; - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.CommandRunException.java + * Created on: Feb 10, 2015 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 Bigeon + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ + +/** An exception thrown when a command failed to run correctly. + * + * @author Emmanuel BIGEON */ +public final class CommandRunException extends Exception { + + /** the SVUID. */ + private static final long serialVersionUID = 1L; + + /** The type of run exception. */ + private final CommandRunExceptionType type; + + /** Create the exception. + * + * @param type the type of exception + * @param message the message */ + public CommandRunException(final CommandRunExceptionType type, + final String message) { + super(message); + this.type = type; + } + + /** Create the exception with a cause. + * + * @param type the type of exception + * @param message a message + * @param cause the cause */ + public CommandRunException(final CommandRunExceptionType type, + final String message, final Throwable cause) { + super(message, cause); + this.type = type; + } + + /** Create the exception with type {@link CommandRunExceptionType#EXECUTION}. + * + * @param message a message */ + public CommandRunException(final String message) { + super(message); + type = CommandRunExceptionType.EXECUTION; + } + + /** Create the exception with type {@link CommandRunExceptionType#EXECUTION} and + * a cause. + * + * @param message a message + * @param cause the cause */ + public CommandRunException(final String message, final Throwable cause) { + super(message, cause); + type = CommandRunExceptionType.EXECUTION; + } + + /* (non-Javadoc) + * @see java.lang.Throwable#getLocalizedMessage() */ + @Override + public String getLocalizedMessage() { + if (getCause() != null) { + return super.getLocalizedMessage() + ": " + //$NON-NLS-1$ + getCause().getLocalizedMessage(); + } + return super.getLocalizedMessage(); + } + + /** Get the exception type. + * + * @return the type */ + public CommandRunExceptionType getType() { + return type; + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunExceptionType.java b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunExceptionType.java index 3487d5f..bd25616 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunExceptionType.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/CommandRunExceptionType.java @@ -1,51 +1,84 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.CommandRunExceptionType.java - * Created on: Jun 12, 2016 - */ -package fr.bigeon.gclc.exception; - -/** The command run exception possible types. - * - * @author Emmanuel Bigeon */ -public enum CommandRunExceptionType { - /** Type of exception due to a wrong usage. */ - USAGE, - /** Type of exception due to a problem in execution. */ - EXECUTION, - /** Type of exception due to the impossibility to interact with user. */ - INTERACTION; -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.CommandRunExceptionType.java + * Created on: Jun 12, 2016 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** The command run exception possible types. + * + * @author Emmanuel Bigeon */ +public enum CommandRunExceptionType { + /** Type of exception due to a wrong usage. */ + USAGE, + /** Type of exception due to a problem in execution. */ + EXECUTION, + /** Type of exception due to the impossibility to interact with user. */ + INTERACTION; +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidCommandName.java b/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidCommandName.java index fb02729..0ee7690 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidCommandName.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidCommandName.java @@ -1,77 +1,110 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.InvalidCommandName.java - * Created on: Dec 23, 2014 - */ -package fr.bigeon.gclc.exception; - -/** Exception sent from the application when a command is added but the name of - * the command is already used. - * - * @author Emmanuel BIGEON */ -public class InvalidCommandName extends Exception { - - /** the SVUID. */ - private static final long serialVersionUID = 1L; - - /** Default constructor. */ - public InvalidCommandName() { - super(); - } - - /** Create the exception with a message. - * - * @param message the message */ - public InvalidCommandName(final String message) { - super(message); - } - - /** Create the exception with a message and a cause. - * - * @param message the message - * @param cause the cause */ - public InvalidCommandName(final String message, final Throwable cause) { - super(message, cause); - } - - /** Create the exception with a cause. - * - * @param cause the cause */ - public InvalidCommandName(final Throwable cause) { - super(cause); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.InvalidCommandName.java + * Created on: Dec 23, 2014 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** Exception sent from the application when a command is added but the name of + * the command is already used. + * + * @author Emmanuel BIGEON */ +public class InvalidCommandName extends Exception { + + /** the SVUID. */ + private static final long serialVersionUID = 1L; + + /** Default constructor. */ + public InvalidCommandName() { + super(); + } + + /** Create the exception with a message. + * + * @param message the message */ + public InvalidCommandName(final String message) { + super(message); + } + + /** Create the exception with a message and a cause. + * + * @param message the message + * @param cause the cause */ + public InvalidCommandName(final String message, final Throwable cause) { + super(message, cause); + } + + /** Create the exception with a cause. + * + * @param cause the cause */ + public InvalidCommandName(final Throwable cause) { + super(cause); + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidParameterException.java b/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidParameterException.java index fe9c6c1..4e8856e 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidParameterException.java +++ b/gclc/src/main/java/fr/bigeon/gclc/exception/InvalidParameterException.java @@ -1,75 +1,105 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.InvalidParameterException.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.exception; - -/** This exception is thrown during command definitions to indicate a wrong - * parameter definition. - *

- * This class is particularly used by - * {@link fr.bigeon.gclc.command.ParametrizedCommand parameterized commands}. - * - * @author Emmanuel Bigeon */ -public class InvalidParameterException extends Exception { - - /** the SVUID. */ - private static final long serialVersionUID = 1L; - - /** Create the exception with a message. - * - * @param message the message */ - public InvalidParameterException(final String message) { - super(message); - } - - /** Create the exception with a message and a cause. - * - * @param message the message - * @param cause the cause */ - public InvalidParameterException(final String message, final Throwable cause) { - super(message, cause); - } - - /** Create the exception with a cause. - * - * @param cause the cause */ - public InvalidParameterException(final Throwable cause) { - super(cause); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.InvalidParameterException.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** This exception is thrown during command definitions to indicate a wrong + * parameter definition. + * + * @author Emmanuel Bigeon */ +public class InvalidParameterException extends Exception { + + /** the SVUID. */ + private static final long serialVersionUID = 1L; + + /** Create the exception with a message. + * + * @param message the message */ + public InvalidParameterException(final String message) { + super(message); + } + + /** Create the exception with a message and a cause. + * + * @param message the message + * @param cause the cause */ + public InvalidParameterException(final String message, final Throwable cause) { + super(message, cause); + } + + /** Create the exception with a cause. + * + * @param cause the cause */ + public InvalidParameterException(final Throwable cause) { + super(cause); + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java b/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java index 3d48c3b..8abd02f 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java +++ b/gclc/src/main/java/fr/bigeon/gclc/i18n/Messages.java @@ -1,81 +1,114 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.i18n.Messages.java - * Created on: Jun 1, 2016 - */ -package fr.bigeon.gclc.i18n; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** Internationalization class. - * - * @author Emmanuel Bigeon */ -public final class Messages { - /** The resource bundle name. */ - private static final String BUNDLE_NAME = "fr.bigeon.gclc.l10n.messages"; //$NON-NLS-1$ - - /** The resource bundle. */ - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - - /** The class logger. */ - private static final Logger LOGGER = Logger - .getLogger(Messages.class.getName()); - - /** Utility class. */ - private Messages() { - // Utility class - } - - /** Get formatted internationalized messages. - * - * @param key the message key - * @param args the formatting arguments - * @return the formatted internationalized message */ - public static String getString(final String key, final Object... args) { - try { - return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); - } catch (final MissingResourceException e) { - LOGGER.log(Level.WARNING, - "Unrecognized internationalization message key: " + key, e); //$NON-NLS-1$ - return '!' + key + '!'; - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.i18n.Messages.java + * Created on: Jun 1, 2016 + */ +package fr.bigeon.gclc.i18n; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** Internationalization class. + * + * @author Emmanuel Bigeon */ +public final class Messages { + /** The resource bundle name. */ + private static final String BUNDLE_NAME = "fr.bigeon.gclc.l10n.messages"; //$NON-NLS-1$ + + /** The resource bundle. */ + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); + + /** The class logger. */ + private static final Logger LOGGER = Logger + .getLogger(Messages.class.getName()); + + /** Utility class. */ + private Messages() { + // Utility class + } + + /** Get formatted internationalized messages. + * + * @param key the message key + * @param args the formatting arguments + * @return the formatted internationalized message */ + public static String getString(final String key, final Object... args) { + try { + return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); + } catch (final MissingResourceException e) { + LOGGER.log(Level.WARNING, + "Unrecognized internationalization message key: " + key, e); //$NON-NLS-1$ + return '!' + key + '!'; + } + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleInput.java b/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleInput.java index f558a3e..b529744 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleInput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleInput.java @@ -1,118 +1,152 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.ConsoleInput.java - * Created on: Nov 13, 2017 - */ -package fr.bigeon.gclc.manager; - -import java.io.IOException; -import java.io.InterruptedIOException; - -import fr.bigeon.gclc.tools.StringProvider; - -/** A console application input. - * - * @author Emmanuel Bigeon */ -public interface ConsoleInput extends AutoCloseable { - - /** Closes the input. - * - * @throws IOException if the close raised an exception */ - @Override - void close() throws IOException; - - /** Get the prompt string. - * - * @return the prompt prefix */ - StringProvider getPrompt(); - - /** Indicate to the input that is should interrompt the prompting, if - * possible. - *

- * The pending {@link #prompt()} or {@link #prompt(String)} operations - * should return immediatly. However the returned value can be anything - * (from the partial prompt content to an empty string or even a null - * pointer). */ - void interruptPrompt(); - - /** Test if the input is closed. - *

- * If this is true, {@link #prompt()} methods will return immediatly and a - * null chain. - * - * @return if the manager is closed. */ - boolean isClosed(); - - /** Prompt the user. - * - * @return the user inputed string - * @throws IOException if the manager is closed or could not read the prompt - * @throws InterruptedIOException if the prompt was interrupted */ - String prompt() throws IOException; - - /** Prompt the user, with an allotated time to answer. - * - * @param timeout the time to wait in milliseconds - * @return the user inputed string, null if the timeout was reached - * @throws IOException if the manager is closed or could not read the prompt - * @throws InterruptedIOException if the prompt was interrupted */ - String prompt(long timeout) throws IOException; - - /** Prompt the user, with a hint on what is prompted. - * - * @param message the message to prompt the user - * @return the user inputed string - * @throws IOException if the manager is closed or could not read the prompt - * @throws InterruptedIOException if the prompt was interrupted */ - String prompt(String message) throws IOException; - - /** Prompt the user, with a hint on what is prompted and an allotated time - * to answer. - * - * @param timeout the time to wait in milliseconds - * @param message the message to prompt the user - * @return the user inputed string, null if the timeout was reached - * @throws IOException if the manager is closed or could not read the prompt - * @throws InterruptedIOException if the prompt was interrupted */ - String prompt(String message, long timeout) throws IOException; - - /** Set a prompting prefix. - * - * @param prompt the prompt */ - void setPrompt(String prompt); - - void setPrompt(StringProvider string); -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.ConsoleInput.java + * Created on: Nov 13, 2017 + */ +package fr.bigeon.gclc.manager; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.io.InterruptedIOException; + +import fr.bigeon.gclc.tools.StringProvider; + +/** A console application input. + * + * @author Emmanuel Bigeon */ +public interface ConsoleInput extends AutoCloseable { + + /** Closes the input. + * + * @throws IOException if the close raised an exception */ + @Override + void close() throws IOException; + + /** Get the prompt string. + * + * @return the prompt prefix */ + StringProvider getPrompt(); + + /** Indicate to the input that is should interrompt the prompting, if possible. + *

+ * The pending {@link #prompt()} or {@link #prompt(String)} operations should + * return immediatly. However the returned value can be anything (from the + * partial prompt content to an empty string or even a null pointer). */ + void interruptPrompt(); + + /** Test if the input is closed. + *

+ * If this is true, {@link #prompt()} methods will return immediatly and a null + * chain. + * + * @return if the manager is closed. */ + boolean isClosed(); + + /** Prompt the user. + * + * @return the user inputed string + * @throws IOException if the manager is closed or could not read the prompt + * @throws InterruptedIOException if the prompt was interrupted */ + String prompt() throws IOException; + + /** Prompt the user, with an allotated time to answer. + * + * @param timeout the time to wait in milliseconds + * @return the user inputed string, null if the timeout was reached + * @throws IOException if the manager is closed or could not read the prompt + * @throws InterruptedIOException if the prompt was interrupted */ + String prompt(long timeout) throws IOException; + + /** Prompt the user, with a hint on what is prompted. + * + * @param message the message to prompt the user + * @return the user inputed string + * @throws IOException if the manager is closed or could not read the prompt + * @throws InterruptedIOException if the prompt was interrupted */ + String prompt(String message) throws IOException; + + /** Prompt the user, with a hint on what is prompted and an allotated time to + * answer. + * + * @param timeout the time to wait in milliseconds + * @param message the message to prompt the user + * @return the user inputed string, null if the timeout was reached + * @throws IOException if the manager is closed or could not read the prompt + * @throws InterruptedIOException if the prompt was interrupted */ + String prompt(String message, long timeout) throws IOException; + + /** Set a prompting prefix. + * + * @param prompt the prompt */ + void setPrompt(String prompt); + + /** Set the prompting string. + * + * @param string the prompt string */ + void setPrompt(StringProvider string); +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleOutput.java b/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleOutput.java index 25545ff..60ece86 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleOutput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/ConsoleOutput.java @@ -1,76 +1,109 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.ConsoleOutput.java - * Created on: Nov 13, 2017 - */ -package fr.bigeon.gclc.manager; - -import java.io.IOException; - -/** A console output definition. - * - * @author Emmanuel Bigeon */ -public interface ConsoleOutput extends AutoCloseable { - - /** Test if the output is closed. - * - * @return if the manager is closed. */ - boolean isClosed(); - - /** Print a string. - * - * @param text the message to print (without line break at the end). - * @throws IOException if the manager is closed or could not read the - * prompt */ - void print(String text) throws IOException; - - /** Prints an end of line. - * - * @throws IOException if the manager is closed or could not read the - * prompt */ - void println() throws IOException; - - /** Print a string followed by an end of line. - *

- * This is the same as calling successively {@link #print(String)} and - * {@link #println()}. - * - * @param message the message to print - * @throws IOException if the manager is closed or could not read the - * prompt */ - void println(String message) throws IOException; - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.ConsoleOutput.java + * Created on: Nov 13, 2017 + */ +package fr.bigeon.gclc.manager; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +/** A console output definition. + * + * @author Emmanuel Bigeon */ +public interface ConsoleOutput extends AutoCloseable { + + /** Test if the output is closed. + * + * @return if the manager is closed. */ + boolean isClosed(); + + /** Print a string. + * + * @param text the message to print (without line break at the end). + * @throws IOException if the manager is closed or could not read the + * prompt */ + void print(String text) throws IOException; + + /** Prints an end of line. + * + * @throws IOException if the manager is closed or could not read the + * prompt */ + void println() throws IOException; + + /** Print a string followed by an end of line. + *

+ * This is the same as calling successively {@link #print(String)} and + * {@link #println()}. + * + * @param message the message to print + * @throws IOException if the manager is closed or could not read the + * prompt */ + void println(String message) throws IOException; + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/EmptyInput.java b/gclc/src/main/java/fr/bigeon/gclc/manager/EmptyInput.java index 27452b0..a2d6e74 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/EmptyInput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/manager/EmptyInput.java @@ -1,124 +1,157 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.EmptyInput.java - * Created on: Nov 13, 2017 - */ -package fr.bigeon.gclc.manager; - -import fr.bigeon.gclc.tools.ConstantString; -import fr.bigeon.gclc.tools.StringProvider; - -/** A console input that return empty to all prompting. - * - * @author Emmanuel Bigeon */ -public final class EmptyInput implements ConsoleInput { - - /** The empty prompter. */ - public static final ConsoleInput INSTANCE = new EmptyInput(); - /** The empty input. */ - private EmptyInput() { - // - } - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#close() */ - @Override - public void close() { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */ - @Override - public StringProvider getPrompt() { - return new ConstantString(""); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */ - @Override - public void interruptPrompt() { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */ - @Override - public boolean isClosed() { - return false; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */ - @Override - public String prompt() { - return ""; //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(long) */ - @Override - public String prompt(final long timeout) { - return ""; //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */ - @Override - public String prompt(final String message) { - return ""; //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String, - * long) */ - @Override - public String prompt(final String message, - final long timeout) { - return ""; //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ - @Override - public void setPrompt(final String prompt) { - // - } - - @Override - public void setPrompt(StringProvider string) { - // - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.EmptyInput.java + * Created on: Nov 13, 2017 + */ +package fr.bigeon.gclc.manager; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import fr.bigeon.gclc.tools.ConstantString; +import fr.bigeon.gclc.tools.StringProvider; + +/** A console input that return empty to all prompting. + * + * @author Emmanuel Bigeon */ +public final class EmptyInput implements ConsoleInput { + + /** The empty prompter. */ + public static final ConsoleInput INSTANCE = new EmptyInput(); + /** The empty input. */ + private EmptyInput() { + // + } + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#close() */ + @Override + public void close() { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */ + @Override + public StringProvider getPrompt() { + return new ConstantString(""); //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */ + @Override + public void interruptPrompt() { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */ + @Override + public boolean isClosed() { + return false; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */ + @Override + public String prompt() { + return ""; //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(long) */ + @Override + public String prompt(final long timeout) { + return ""; //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */ + @Override + public String prompt(final String message) { + return ""; //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String, + * long) */ + @Override + public String prompt(final String message, + final long timeout) { + return ""; //$NON-NLS-1$ + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ + @Override + public void setPrompt(final String prompt) { + // + } + + @Override + public void setPrompt(StringProvider string) { + // + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java index e65c874..1a104d1 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java +++ b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompter.java @@ -1,516 +1,549 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** acide:fr.bigeon.acide.tool.CLIPrompter.java - * Created on: Jul 31, 2014 */ -package fr.bigeon.gclc.prompt; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** The {@link CLIPrompter} class is a utility class that provides method to - * prompt the user. - * - * @author Emmanuel BIGEON */ -public final class CLIPrompter { - - /** The zero integer. */ - private static final Integer ZERO = Integer.valueOf(0); - /** message key for format error in prompting a choice. */ - private static final String PROMPTCHOICE_FORMATERR = "promptchoice.formaterr"; //$NON-NLS-1$ - /** message key for out of bound error in prompting a choice. */ - private static final String PROMPTCHOICE_OUTOFBOUNDS = "promptchoice.outofbounds"; //$NON-NLS-1$ - /** message key for first form of no in prompting a choice. */ - private static final String PROMPTBOOL_CHOICES_NO1 = "promptbool.choices.no1"; //$NON-NLS-1$ - /** message key for first form of yes in prompting a choice. */ - private static final String PROMPTBOOL_CHOICES_YES1 = "promptbool.choices.yes1"; //$NON-NLS-1$ - /** Message key for boolean choosing. */ - private static final String BOOL_CHOICES = "promptbool.choices"; //$NON-NLS-1$ - /** Message key for the list end of prompt symbol. */ - private static final String LIST_DISP_KEY = "promptlist.exit.dispkey"; //$NON-NLS-1$ - /** Message key for the line prompt. */ - private static final String PROMPT = "prompt.lineprompt"; //$NON-NLS-1$ - /** Message key for the separation of choices selection. */ - private static final String LIST_CHOICE_SEP = "promptlist.multi.sepkey"; //$NON-NLS-1$ - /** The class logger. */ - private static final Logger LOGGER = Logger - .getLogger(CLIPrompter.class.getName()); - - /** Utility class. */ - private CLIPrompter() { - // Utility class - } - - /** Add a user choice to the list. - * - * @param val the string to parse - * @param chs the list of integers - * @param index the max index of choice - * @return if the parsing was done correctly */ - private static boolean addUserChoice(final String val, - final List chs, - final int index) { - if (val.isEmpty()) { - return true; - } - final int r; - r = Integer.parseInt(val); - if (r >= 0 && r <= index) { - chs.add(Integer.valueOf(r)); - return true; - } - return false; - } - - /** List the choices on the output. - * - * @param output the manager - * @param choices the choices - * @param cancel the cancel option if it exists - * @return the number of choices plus one (or the number of choices if there - * is a cancel) - * @throws IOException if the manager was closed */ - private static Integer listChoices(final ConsoleOutput output, - final List choices, - final String cancel) throws IOException { - int index = 0; - for (final U u : choices) { - output.println(index++ + ") " + u); //$NON-NLS-1$ - } - if (cancel != null) { - output.println(index++ + ") " + cancel); //$NON-NLS-1$ - } - return Integer.valueOf(index - 1); - } - - /** Prompt for a boolean value. - * - * @param manager the manager - * @param input the input - * @param message the prompting message - * @return the choice - * @throws IOException if the manager was closed */ - public static boolean promptBoolean(final ConsoleOutput manager, - final ConsoleInput input, - final String message) throws IOException { - String result = input - .prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES)); - boolean first = true; - final String choices = CLIPrompterMessages - .getString(PROMPTBOOL_CHOICES_YES1) + ", " + //$NON-NLS-1$ - CLIPrompterMessages - .getString(PROMPTBOOL_CHOICES_NO1); - while (!(result.equalsIgnoreCase( - CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_YES1)) || - CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_NO1) - .equalsIgnoreCase(result) || - CLIPrompterMessages.getString("promptbool.choices.no2") //$NON-NLS-1$ - .equalsIgnoreCase(result) || - CLIPrompterMessages.getString("promptbool.choices.yes2") //$NON-NLS-1$ - .equalsIgnoreCase(result))) { - if (!first) { - - manager.println(CLIPrompterMessages - .getString("promptbool.choices.invalid", choices)); //$NON-NLS-1$ - result = input.prompt( - message + CLIPrompterMessages.getString(BOOL_CHOICES)); - } - first = false; - } - return result.equalsIgnoreCase( - CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_YES1)) || - result.equalsIgnoreCase(CLIPrompterMessages - .getString("promptbool.choices.yes2")); //$NON-NLS-1$ - } - - /** Prompt for a choice. - * - * @param manager the manager - * @param input the input - * @param keys the keys to be printed - * @param choices the real choices - * @param message the message - * @param cancel the cancel option, or null - * @param the type of elements - * @return the choice - * @throws IOException if the manager was closed */ - public static U promptChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List keys, - final List choices, - final String message, - final String cancel) throws IOException { - final Integer index = promptChoice(manager, input, keys, message, - cancel); - if (index == null) { - return null; - } - return choices.get(index.intValue()); - } - - /** Prompt for a choice. - * - * @param manager the manager - * @param input the input - * @param The choices labels type - * @param The real choices objects - * @param choices the list of labels (in order to be displayed) - * @param choicesMap the map of label to actual objects - * @param message the prompting message - * @param cancel the cancel option if it exists (null otherwise) - * @return the chosen object - * @throws IOException if the manager was closed */ - public static T promptChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List choices, - final Map choicesMap, - final String message, - final String cancel) throws IOException { - final Integer res = promptChoice(manager, input, choices, message, - cancel); - if (res == null) { - return null; - } - return choicesMap.get(choices.get(res.intValue())); - } - - /** Prompt for a choice. - * - * @param manager the manager - * @param input the input - * @param the type of choices - * @param choices the list of choices - * @param message the prompting message - * @param cancel the cancel option, or null - * @return the index of the choice - * @throws IOException if the manager was closed */ - public static Integer promptChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List choices, - final String message, - final String cancel) throws IOException { - manager.println(message); - final Integer index = listChoices(manager, choices, cancel); - String result; - int r = -1; - while (true) { - result = input.prompt(CLIPrompterMessages.getString(PROMPT)); - try { - r = Integer.parseInt(result); - if (r >= 0 && r <= index.intValue()) { - break; - } - manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); - } catch (final NumberFormatException e) { - LOGGER.log(Level.FINER, - "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ - manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); - } - listChoices(manager, choices, cancel); - } - if (r == index.intValue() && cancel != null) { - return null; - } - return Integer.valueOf(r); - } - - /** Prompt for a choice. - * - * @param manager the manager - * @param input the input - * @param The choices labels type - * @param The real choices objects - * @param choicesMap the map of label to actual objects - * @param message the prompting message - * @param cancel the cancel option (or null) - * @return the chosen object - * @throws IOException if the manager was closed */ - public static T promptChoice(final ConsoleOutput manager, - final ConsoleInput input, - final Map choicesMap, - final String message, - final String cancel) throws IOException { - return promptChoice(manager, input, - new ArrayList<>(choicesMap.keySet()), choicesMap, message, - cancel); - } - - /** Prompt for an integer. - * - * @param manager the manager - * @param message the prompt message - * @return the integer - * @throws IOException if the manager was closed */ - public static int promptInteger(final ConsoleInput manager, - final String message) throws IOException { - boolean still = true; - int r = 0; - while (still) { - final String result = manager.prompt(message); - try { - if (result.isEmpty()) { - still = true; - continue; - } - r = Integer.parseInt(result); - still = false; - } catch (final NumberFormatException e) { - LOGGER.info("User input a non parsable integer: " + result); //$NON-NLS-1$ - LOGGER.log(Level.FINEST, "Unrecognized integer", e); //$NON-NLS-1$ - still = true; - } - } - return r; - } - - /** This methods prompt the user for a list of elements. - * - * @param manager the manager - * @param input the input - * @param message the message - * @return the list of user inputs - * @throws IOException if the manager was closed */ - public static List promptList(final ConsoleOutput manager, - final ConsoleInput input, - final String message) throws IOException { - return promptList(manager, input, message, - CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ - } - - /** This methods prompt the user for a list of elements. - * - * @param manager the manager - * @param input the input - * @param message the message - * @param ender the ending sequence for the list - * @return the list of user inputs - * @throws IOException if the manager was closed */ - public static List promptList(final ConsoleOutput manager, - final ConsoleInput input, - final String message, - final String ender) throws IOException { - final List strings = new ArrayList<>(); - manager.println( - message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender)); - String res = null; - while (!ender.equals(res)) { - res = input.prompt(CLIPrompterMessages.getString(PROMPT)); - if (!res.equals(ender)) { - strings.add(res); - } - } - return strings; - } - - /** Prompt for a text with several lines. - * - * @param manager the manager - * @param input the input - * @param message the prompting message - * @return the text - * @throws IOException if the manager was closed */ - public static String promptLongText(final ConsoleOutput manager, - final ConsoleInput input, - final String message) throws IOException { - return promptLongText(manager, input, message, CLIPrompterMessages - .getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$ - } - - /** Prompt for a text with several lines. - * - * @param manager the manager - * @param input the input - * @param message the prompting message - * @param ender the ender character - * @return the text - * @throws IOException if the manager was closed */ - public static String promptLongText(final ConsoleOutput manager, - final ConsoleInput input, - final String message, - final String ender) throws IOException { - manager.println(message + CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$ - final StringBuilder res = new StringBuilder(); - String line; - do { - line = input.prompt(CLIPrompterMessages.getString(PROMPT)); - if (!line.equals(ender)) { - res.append(line); - res.append(System.lineSeparator()); - } - } while (!line.equals(ender)); - return res.toString(); - } - - /** Prompt the user to select zero or more elements from a list. - * - * @param manager the manager - * @param input the input - * @param keys the keys to be printed - * @param choices the real choices - * @param message the message - * @param the type of elements - * @return the choice - * @throws IOException if the manager was closed */ - public static List promptMultiChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List keys, - final List choices, - final String message) throws IOException { - final List indices = promptMultiChoice(manager, input, keys, - message); - final List userChoices = new ArrayList<>(); - for (final Integer integer : indices) { - userChoices.add(choices.get(integer.intValue())); - } - return userChoices; - } - - /** Prompt the user to select zero or more elements from a list. - * - * @param manager the manager - * @param input the input - * @param The choices labels type - * @param The real choices objects - * @param choices the list of labels (in order to be displayed) - * @param choicesMap the map of label to actual objects - * @param message the prompting message - * @return the chosen objects (or an empty list) - * @throws IOException if the manager was closed */ - public static List promptMultiChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List choices, - final Map choicesMap, - final String message) throws IOException { - final List chs = promptMultiChoice(manager, input, choices, - message); - final List userChoices = new ArrayList<>(); - for (final Integer integer : chs) { - userChoices.add(choicesMap.get(choices.get(integer.intValue()))); - } - return userChoices; - } - - /** Prompt the user to select zero or more elements from a list. - * - * @param manager the manager - * @param input the input - * @param the type of choices - * @param choices the list of choices - * @param message the prompting message - * @return the indices of the choices - * @throws IOException if the manager was closed */ - public static List promptMultiChoice(final ConsoleOutput manager, - final ConsoleInput input, - final List choices, - final String message) throws IOException { - manager.println(message); - final Integer index = listChoices(manager, choices, null); - String result; - boolean keepOn = true; - final List chs = new ArrayList<>(); - while (keepOn) { - keepOn = false; - result = input.prompt(CLIPrompterMessages.getString(PROMPT)); - final String[] vals = result - .split(CLIPrompterMessages.getString(LIST_CHOICE_SEP)); - for (final String val : vals) { - boolean added; - try { - added = addUserChoice(val, chs, index.intValue()); - } catch (final NumberFormatException e) { - LOGGER.log(Level.FINER, - "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ - keepOn = true; - manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); - listChoices(manager, choices, null); - break; - } - if (!added) { - manager.println(CLIPrompterMessages - .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); - listChoices(manager, choices, null); - keepOn = true; - } - } - } - return chs; - } - - /** Prompt the user to select zero or more elements from a list. - * - * @param manager the manager - * @param input the input - * @param The choices labels type - * @param The real choices objects - * @param choicesMap the map of label to actual objects - * @param message the prompting message - * @return the chosen objects - * @throws IOException if the manager was closed */ - public static List promptMultiChoice(final ConsoleOutput manager, - final ConsoleInput input, - final Map choicesMap, - final String message) throws IOException { - return promptMultiChoice(manager, input, - new ArrayList<>(choicesMap.keySet()), choicesMap, message); - } - - /** Prompt the user for a non empty text. - * - * @param manager the manager - * @param prompt the prompting message - * @param reprompt the prompting message after empty input - * @return the non empty input - * @throws IOException if the manager was closed */ - public static String promptNonEmpty(final ConsoleInput manager, - final String prompt, - final String reprompt) throws IOException { - String res = manager.prompt(prompt); - while (res.isEmpty()) { - res = manager.prompt(reprompt); - } - return res; - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** acide:fr.bigeon.acide.tool.CLIPrompter.java + * Created on: Jul 31, 2014 */ +package fr.bigeon.gclc.prompt; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** The {@link CLIPrompter} class is a utility class that provides method to + * prompt the user. + * + * @author Emmanuel BIGEON */ +public final class CLIPrompter { + + /** The zero integer. */ + private static final Integer ZERO = Integer.valueOf(0); + /** message key for format error in prompting a choice. */ + private static final String PROMPTCHOICE_FORMATERR = "promptchoice.formaterr"; //$NON-NLS-1$ + /** message key for out of bound error in prompting a choice. */ + private static final String PROMPTCHOICE_OUTOFBOUNDS = "promptchoice.outofbounds"; //$NON-NLS-1$ + /** message key for first form of no in prompting a choice. */ + private static final String PROMPTBOOL_CHOICES_NO1 = "promptbool.choices.no1"; //$NON-NLS-1$ + /** message key for first form of yes in prompting a choice. */ + private static final String PROMPTBOOL_CHOICES_YES1 = "promptbool.choices.yes1"; //$NON-NLS-1$ + /** Message key for boolean choosing. */ + private static final String BOOL_CHOICES = "promptbool.choices"; //$NON-NLS-1$ + /** Message key for the list end of prompt symbol. */ + private static final String LIST_DISP_KEY = "promptlist.exit.dispkey"; //$NON-NLS-1$ + /** Message key for the line prompt. */ + private static final String PROMPT = "prompt.lineprompt"; //$NON-NLS-1$ + /** Message key for the separation of choices selection. */ + private static final String LIST_CHOICE_SEP = "promptlist.multi.sepkey"; //$NON-NLS-1$ + /** The class logger. */ + private static final Logger LOGGER = Logger + .getLogger(CLIPrompter.class.getName()); + + /** Utility class. */ + private CLIPrompter() { + // Utility class + } + + /** Add a user choice to the list. + * + * @param val the string to parse + * @param chs the list of integers + * @param index the max index of choice + * @return if the parsing was done correctly */ + private static boolean addUserChoice(final String val, + final List chs, + final int index) { + if (val.isEmpty()) { + return true; + } + final int r; + r = Integer.parseInt(val); + if (r >= 0 && r <= index) { + chs.add(Integer.valueOf(r)); + return true; + } + return false; + } + + /** List the choices on the output. + * + * @param output the manager + * @param choices the choices + * @param cancel the cancel option if it exists + * @return the number of choices plus one (or the number of choices if there + * is a cancel) + * @throws IOException if the manager was closed */ + private static Integer listChoices(final ConsoleOutput output, + final List choices, + final String cancel) throws IOException { + int index = 0; + for (final U u : choices) { + output.println(index++ + ") " + u); //$NON-NLS-1$ + } + if (cancel != null) { + output.println(index++ + ") " + cancel); //$NON-NLS-1$ + } + return Integer.valueOf(index - 1); + } + + /** Prompt for a boolean value. + * + * @param manager the manager + * @param input the input + * @param message the prompting message + * @return the choice + * @throws IOException if the manager was closed */ + public static boolean promptBoolean(final ConsoleOutput manager, + final ConsoleInput input, + final String message) throws IOException { + String result = input + .prompt(message + CLIPrompterMessages.getString(BOOL_CHOICES)); + boolean first = true; + final String choices = CLIPrompterMessages + .getString(PROMPTBOOL_CHOICES_YES1) + ", " + //$NON-NLS-1$ + CLIPrompterMessages + .getString(PROMPTBOOL_CHOICES_NO1); + while (!(result.equalsIgnoreCase( + CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_YES1)) || + CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_NO1) + .equalsIgnoreCase(result) || + CLIPrompterMessages.getString("promptbool.choices.no2") //$NON-NLS-1$ + .equalsIgnoreCase(result) || + CLIPrompterMessages.getString("promptbool.choices.yes2") //$NON-NLS-1$ + .equalsIgnoreCase(result))) { + if (!first) { + + manager.println(CLIPrompterMessages + .getString("promptbool.choices.invalid", choices)); //$NON-NLS-1$ + result = input.prompt( + message + CLIPrompterMessages.getString(BOOL_CHOICES)); + } + first = false; + } + return result.equalsIgnoreCase( + CLIPrompterMessages.getString(PROMPTBOOL_CHOICES_YES1)) || + result.equalsIgnoreCase(CLIPrompterMessages + .getString("promptbool.choices.yes2")); //$NON-NLS-1$ + } + + /** Prompt for a choice. + * + * @param manager the manager + * @param input the input + * @param keys the keys to be printed + * @param choices the real choices + * @param message the message + * @param cancel the cancel option, or null + * @param the type of elements + * @return the choice + * @throws IOException if the manager was closed */ + public static U promptChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List keys, + final List choices, + final String message, + final String cancel) throws IOException { + final Integer index = promptChoice(manager, input, keys, message, + cancel); + if (index == null) { + return null; + } + return choices.get(index.intValue()); + } + + /** Prompt for a choice. + * + * @param manager the manager + * @param input the input + * @param The choices labels type + * @param The real choices objects + * @param choices the list of labels (in order to be displayed) + * @param choicesMap the map of label to actual objects + * @param message the prompting message + * @param cancel the cancel option if it exists (null otherwise) + * @return the chosen object + * @throws IOException if the manager was closed */ + public static T promptChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List choices, + final Map choicesMap, + final String message, + final String cancel) throws IOException { + final Integer res = promptChoice(manager, input, choices, message, + cancel); + if (res == null) { + return null; + } + return choicesMap.get(choices.get(res.intValue())); + } + + /** Prompt for a choice. + * + * @param manager the manager + * @param input the input + * @param the type of choices + * @param choices the list of choices + * @param message the prompting message + * @param cancel the cancel option, or null + * @return the index of the choice + * @throws IOException if the manager was closed */ + public static Integer promptChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List choices, + final String message, + final String cancel) throws IOException { + manager.println(message); + final Integer index = listChoices(manager, choices, cancel); + String result; + int r = -1; + while (true) { + result = input.prompt(CLIPrompterMessages.getString(PROMPT)); + try { + r = Integer.parseInt(result); + if (r >= 0 && r <= index.intValue()) { + break; + } + manager.println(CLIPrompterMessages + .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); + } catch (final NumberFormatException e) { + LOGGER.log(Level.FINER, + "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ + manager.println(CLIPrompterMessages + .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); + } + listChoices(manager, choices, cancel); + } + if (r == index.intValue() && cancel != null) { + return null; + } + return Integer.valueOf(r); + } + + /** Prompt for a choice. + * + * @param manager the manager + * @param input the input + * @param The choices labels type + * @param The real choices objects + * @param choicesMap the map of label to actual objects + * @param message the prompting message + * @param cancel the cancel option (or null) + * @return the chosen object + * @throws IOException if the manager was closed */ + public static T promptChoice(final ConsoleOutput manager, + final ConsoleInput input, + final Map choicesMap, + final String message, + final String cancel) throws IOException { + return promptChoice(manager, input, + new ArrayList<>(choicesMap.keySet()), choicesMap, message, + cancel); + } + + /** Prompt for an integer. + * + * @param manager the manager + * @param message the prompt message + * @return the integer + * @throws IOException if the manager was closed */ + public static int promptInteger(final ConsoleInput manager, + final String message) throws IOException { + boolean still = true; + int r = 0; + while (still) { + final String result = manager.prompt(message); + try { + if (result.isEmpty()) { + still = true; + continue; + } + r = Integer.parseInt(result); + still = false; + } catch (final NumberFormatException e) { + LOGGER.info("User input a non parsable integer: " + result); //$NON-NLS-1$ + LOGGER.log(Level.FINEST, "Unrecognized integer", e); //$NON-NLS-1$ + still = true; + } + } + return r; + } + + /** This methods prompt the user for a list of elements. + * + * @param manager the manager + * @param input the input + * @param message the message + * @return the list of user inputs + * @throws IOException if the manager was closed */ + public static List promptList(final ConsoleOutput manager, + final ConsoleInput input, + final String message) throws IOException { + return promptList(manager, input, message, + CLIPrompterMessages.getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ + } + + /** This methods prompt the user for a list of elements. + * + * @param manager the manager + * @param input the input + * @param message the message + * @param ender the ending sequence for the list + * @return the list of user inputs + * @throws IOException if the manager was closed */ + public static List promptList(final ConsoleOutput manager, + final ConsoleInput input, + final String message, + final String ender) throws IOException { + final List strings = new ArrayList<>(); + manager.println( + message + CLIPrompterMessages.getString(LIST_DISP_KEY, ender)); + String res = null; + while (!ender.equals(res)) { + res = input.prompt(CLIPrompterMessages.getString(PROMPT)); + if (!res.equals(ender)) { + strings.add(res); + } + } + return strings; + } + + /** Prompt for a text with several lines. + * + * @param manager the manager + * @param input the input + * @param message the prompting message + * @return the text + * @throws IOException if the manager was closed */ + public static String promptLongText(final ConsoleOutput manager, + final ConsoleInput input, + final String message) throws IOException { + return promptLongText(manager, input, message, CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")); //$NON-NLS-1$ + } + + /** Prompt for a text with several lines. + * + * @param manager the manager + * @param input the input + * @param message the prompting message + * @param ender the ender character + * @return the text + * @throws IOException if the manager was closed */ + public static String promptLongText(final ConsoleOutput manager, + final ConsoleInput input, + final String message, + final String ender) throws IOException { + manager.println(message + CLIPrompterMessages + .getString("promptlongtext.exit.dispkey", ender)); //$NON-NLS-1$ + final StringBuilder res = new StringBuilder(); + String line; + do { + line = input.prompt(CLIPrompterMessages.getString(PROMPT)); + if (!line.equals(ender)) { + res.append(line); + res.append(System.lineSeparator()); + } + } while (!line.equals(ender)); + return res.toString(); + } + + /** Prompt the user to select zero or more elements from a list. + * + * @param manager the manager + * @param input the input + * @param keys the keys to be printed + * @param choices the real choices + * @param message the message + * @param the type of elements + * @return the choice + * @throws IOException if the manager was closed */ + public static List promptMultiChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List keys, + final List choices, + final String message) throws IOException { + final List indices = promptMultiChoice(manager, input, keys, + message); + final List userChoices = new ArrayList<>(); + for (final Integer integer : indices) { + userChoices.add(choices.get(integer.intValue())); + } + return userChoices; + } + + /** Prompt the user to select zero or more elements from a list. + * + * @param manager the manager + * @param input the input + * @param The choices labels type + * @param The real choices objects + * @param choices the list of labels (in order to be displayed) + * @param choicesMap the map of label to actual objects + * @param message the prompting message + * @return the chosen objects (or an empty list) + * @throws IOException if the manager was closed */ + public static List promptMultiChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List choices, + final Map choicesMap, + final String message) throws IOException { + final List chs = promptMultiChoice(manager, input, choices, + message); + final List userChoices = new ArrayList<>(); + for (final Integer integer : chs) { + userChoices.add(choicesMap.get(choices.get(integer.intValue()))); + } + return userChoices; + } + + /** Prompt the user to select zero or more elements from a list. + * + * @param manager the manager + * @param input the input + * @param the type of choices + * @param choices the list of choices + * @param message the prompting message + * @return the indices of the choices + * @throws IOException if the manager was closed */ + public static List promptMultiChoice(final ConsoleOutput manager, + final ConsoleInput input, + final List choices, + final String message) throws IOException { + manager.println(message); + final Integer index = listChoices(manager, choices, null); + String result; + boolean keepOn = true; + final List chs = new ArrayList<>(); + while (keepOn) { + keepOn = false; + result = input.prompt(CLIPrompterMessages.getString(PROMPT)); + final String[] vals = result + .split(CLIPrompterMessages.getString(LIST_CHOICE_SEP)); + for (final String val : vals) { + boolean added; + try { + added = addUserChoice(val, chs, index.intValue()); + } catch (final NumberFormatException e) { + LOGGER.log(Level.FINER, + "Unrecognized number. Prompting user again.", e); //$NON-NLS-1$ + keepOn = true; + manager.println(CLIPrompterMessages + .getString(PROMPTCHOICE_FORMATERR, ZERO, index)); + listChoices(manager, choices, null); + break; + } + if (!added) { + manager.println(CLIPrompterMessages + .getString(PROMPTCHOICE_OUTOFBOUNDS, ZERO, index)); + listChoices(manager, choices, null); + keepOn = true; + } + } + } + return chs; + } + + /** Prompt the user to select zero or more elements from a list. + * + * @param manager the manager + * @param input the input + * @param The choices labels type + * @param The real choices objects + * @param choicesMap the map of label to actual objects + * @param message the prompting message + * @return the chosen objects + * @throws IOException if the manager was closed */ + public static List promptMultiChoice(final ConsoleOutput manager, + final ConsoleInput input, + final Map choicesMap, + final String message) throws IOException { + return promptMultiChoice(manager, input, + new ArrayList<>(choicesMap.keySet()), choicesMap, message); + } + + /** Prompt the user for a non empty text. + * + * @param manager the manager + * @param prompt the prompting message + * @param reprompt the prompting message after empty input + * @return the non empty input + * @throws IOException if the manager was closed */ + public static String promptNonEmpty(final ConsoleInput manager, + final String prompt, + final String reprompt) throws IOException { + String res = manager.prompt(prompt); + while (res.isEmpty()) { + res = manager.prompt(reprompt); + } + return res; + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java index 250ec4b..873c80f 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java +++ b/gclc/src/main/java/fr/bigeon/gclc/prompt/CLIPrompterMessages.java @@ -1,79 +1,112 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * acide:fr.bigeon.acide.tool.CLIPrompterMessages.java - * Created on: Aug 6, 2014 - */ -package fr.bigeon.gclc.prompt; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** Utility class for the messages of the CLIPrompter. - * - * @author Emmanuel BIGEON */ -public final class CLIPrompterMessages { - /** The resource name. */ - private static final String BUNDLE_NAME = "fr.bigeon.gclc.messages"; //$NON-NLS-1$ - /** The resource. */ - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle - .getBundle(BUNDLE_NAME); - /** The logger. */ - private static final Logger LOGGER = Logger - .getLogger(CLIPrompterMessages.class.getName()); - - /** Utility class. */ - private CLIPrompterMessages() { - // Utility constructor - } - - /** Return the formatted message corresponding to the given key. - * - * @param key the message's key - * @param args the arguments - * @return the formatted message */ - public static String getString(final String key, final Object... args) { - try { - return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); - } catch (final MissingResourceException e) { - LOGGER.warning("Unrecognized key: " + key); //$NON-NLS-1$ - LOGGER.log(Level.FINE, "Missing key in " + BUNDLE_NAME, e); //$NON-NLS-1$ - return '!' + key + '!'; - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * acide:fr.bigeon.acide.tool.CLIPrompterMessages.java + * Created on: Aug 6, 2014 + */ +package fr.bigeon.gclc.prompt; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** Utility class for the messages of the CLIPrompter. + * + * @author Emmanuel BIGEON */ +public final class CLIPrompterMessages { + /** The resource name. */ + private static final String BUNDLE_NAME = "fr.bigeon.gclc.messages"; //$NON-NLS-1$ + /** The resource. */ + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); + /** The logger. */ + private static final Logger LOGGER = Logger + .getLogger(CLIPrompterMessages.class.getName()); + + /** Utility class. */ + private CLIPrompterMessages() { + // Utility constructor + } + + /** Return the formatted message corresponding to the given key. + * + * @param key the message's key + * @param args the arguments + * @return the formatted message */ + public static String getString(final String key, final Object... args) { + try { + return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); + } catch (final MissingResourceException e) { + LOGGER.warning("Unrecognized key: " + key); //$NON-NLS-1$ + LOGGER.log(Level.FINE, "Missing key in " + BUNDLE_NAME, e); //$NON-NLS-1$ + return '!' + key + '!'; + } + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/prompt/package-info.java b/gclc/src/main/java/fr/bigeon/gclc/prompt/package-info.java index 85ed457..61eb101 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/prompt/package-info.java +++ b/gclc/src/main/java/fr/bigeon/gclc/prompt/package-info.java @@ -1,47 +1,81 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** gclc:fr.bigeon.gclc.prompt.package-info.java - * Created on: Sep 6, 2014 */ -/** Client prompting related objects. - *

- * This package is used for the formatting of prompts for the user. The - * {@link fr.bigeon.gclc.prompt.CLIPrompter} class provides utility methods to - * retrieve certain basic type of data from the user or to give list choices. - *

- * The {@link fr.bigeon.gclc.prompt.CLIPrompterMessages} class is used for - * internationalization of the prompting methods. - * - * @author Emmanuel BIGEON */ -package fr.bigeon.gclc.prompt; \ No newline at end of file +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** gclc:fr.bigeon.gclc.prompt.package-info.java + * Created on: Sep 6, 2014 */ +/** Client prompting related objects. + *

+ * This package is used for the formatting of prompts for the user. The + * {@link fr.bigeon.gclc.prompt.CLIPrompter} class provides utility methods to + * retrieve certain basic type of data from the user or to give list choices. + *

+ * The {@link fr.bigeon.gclc.prompt.CLIPrompterMessages} class is used for + * internationalization of the prompting methods. + * + * @author Emmanuel BIGEON */ +package fr.bigeon.gclc.prompt; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/ConstantString.java b/gclc/src/main/java/fr/bigeon/gclc/tools/ConstantString.java index 2b3afab..451bc85 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/ConstantString.java +++ b/gclc/src/main/java/fr/bigeon/gclc/tools/ConstantString.java @@ -34,17 +34,57 @@ */ package fr.bigeon.gclc.tools; +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ + +/** A {@link StringProvider} that hold a constant string. + * + * @author Emmanuel Bigeon */ public class ConstantString implements StringProvider { - private String string; - - - - @Override - public String apply() { - return string; } + private final String string; + /* (non-Javadoc) + * @see fr.bigeon.gclc.tools.StringProvider#apply() */ + @Override + public String apply() { + return string; + } - public ConstantString(String string) { - this.string = string; - } + /** Create a provider for a string. + * + * @param string the string */ + public ConstantString(String string) { + this.string = string; + } } diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java b/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java index ecbe206..f2aa18c 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java +++ b/gclc/src/main/java/fr/bigeon/gclc/tools/PrintUtils.java @@ -1,116 +1,149 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * acide:fr.bigeon.acide.tools.PrintUtils.java - * Created on: Jan 20, 2015 - */ -package fr.bigeon.gclc.tools; - -import java.util.ArrayList; -import java.util.List; - -/** A tool class for printing text in a console. - * - * @author Emmanuel BIGEON */ -public final class PrintUtils { - - /** The continuation dot string. */ - private static final String CONT_DOT = "..."; //$NON-NLS-1$ - /** The continuation dot string length. */ - private static final int CONT_DOT_LENGTH = CONT_DOT.length(); - /** The empty string constant. */ - private static final String EMPTY = ""; //$NON-NLS-1$ - - /** Utility class. */ - private PrintUtils() { - // Utility class - } - - /** Print the text possibly cutting it if it goes over the authorized length - * and adding a mark of continuation. - * - * @param text the text to print - * @param nbCharacters the number of characters of the resulting text - * @param indicateTooLong if an indication shell be given that the text - * didn't fit - * @return the text to print (will be of exactly nbCharacters). */ - public static String print(final String text, final int nbCharacters, - final boolean indicateTooLong) { - StringBuilder res = new StringBuilder(text); - if (res.length() > nbCharacters) { - // Cut - if (indicateTooLong) { - // With suspension dots - res = res.replace(nbCharacters - CONT_DOT_LENGTH, text.length(), - CONT_DOT); - } else { - res = res.replace(nbCharacters, text.length(), ""); //$NON-NLS-1$ - } - } - while (res.length() < nbCharacters) { - // Add trailing space - res.append(' '); - } - return res.toString(); - } - - /** Wrap the text, cutting at spaces. - * - * @param description the element to wrap in lines - * @param i the length of the wrap - * @return the list of resulting strings */ - public static List wrap(final String description, final int i) { - final String[] originalLines = description - .split(System.lineSeparator()); - final List result = new ArrayList<>(); - for (final String string : originalLines) { - String toCut = string; - while (toCut.length() > i) { - int index = toCut.lastIndexOf(' ', i); - if (index == -1) { - result.add(toCut.substring(0, i)); - index = i - 1; - } else { - result.add(toCut.substring(0, index)); - } - toCut = toCut.substring(index + 1); - } - result.add(toCut); - result.add(EMPTY); - } - result.remove(result.size() - 1); - return result; - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * acide:fr.bigeon.acide.tools.PrintUtils.java + * Created on: Jan 20, 2015 + */ +package fr.bigeon.gclc.tools; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.util.ArrayList; +import java.util.List; + +/** A tool class for printing text in a console. + * + * @author Emmanuel BIGEON */ +public final class PrintUtils { + + /** The continuation dot string. */ + private static final String CONT_DOT = "..."; //$NON-NLS-1$ + /** The continuation dot string length. */ + private static final int CONT_DOT_LENGTH = CONT_DOT.length(); + /** The empty string constant. */ + private static final String EMPTY = ""; //$NON-NLS-1$ + + /** Utility class. */ + private PrintUtils() { + // Utility class + } + + /** Print the text possibly cutting it if it goes over the authorized length + * and adding a mark of continuation. + * + * @param text the text to print + * @param nbCharacters the number of characters of the resulting text + * @param indicateTooLong if an indication shell be given that the text + * didn't fit + * @return the text to print (will be of exactly nbCharacters). */ + public static String print(final String text, final int nbCharacters, + final boolean indicateTooLong) { + StringBuilder res = new StringBuilder(text); + if (res.length() > nbCharacters) { + // Cut + if (indicateTooLong) { + // With suspension dots + res = res.replace(nbCharacters - CONT_DOT_LENGTH, text.length(), + CONT_DOT); + } else { + res = res.replace(nbCharacters, text.length(), ""); //$NON-NLS-1$ + } + } + while (res.length() < nbCharacters) { + // Add trailing space + res.append(' '); + } + return res.toString(); + } + + /** Wrap the text, cutting at spaces. + * + * @param description the element to wrap in lines + * @param i the length of the wrap + * @return the list of resulting strings */ + public static List wrap(final String description, final int i) { + final String[] originalLines = description + .split(System.lineSeparator()); + final List result = new ArrayList<>(); + for (final String string : originalLines) { + String toCut = string; + while (toCut.length() > i) { + int index = toCut.lastIndexOf(' ', i); + if (index == -1) { + result.add(toCut.substring(0, i)); + index = i - 1; + } else { + result.add(toCut.substring(0, index)); + } + toCut = toCut.substring(index + 1); + } + result.add(toCut); + result.add(EMPTY); + } + result.remove(result.size() - 1); + return result; + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/StringProvider.java b/gclc/src/main/java/fr/bigeon/gclc/tools/StringProvider.java index dabc632..14140e4 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/StringProvider.java +++ b/gclc/src/main/java/fr/bigeon/gclc/tools/StringProvider.java @@ -34,16 +34,50 @@ */ package fr.bigeon.gclc.tools; -/** - * A string providing object. +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ + +/** A string providing object. *

* Implementations of this interface will provide a string, this internal state * of the object may be so that successive calls to the apply method return * different results. * - * @author Emmanuel - * - */ + * @author Emmanuel */ public interface StringProvider { - String apply(); + /** Provide a string. + * + * @return the string */ + String apply(); } diff --git a/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/utils/AOutputForwardRunnable.java similarity index 73% rename from gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/AOutputForwardRunnable.java index c282a48..63be57c 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/tools/AOutputForwardRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/AOutputForwardRunnable.java @@ -1,137 +1,168 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.tools.AOutputForwardRunnable.java - * Created on: Dec 1, 2016 - */ -package fr.bigeon.gclc.tools; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** An incomplete implematation used to forward messages from a piped console. - *

- * This forwarding can be interrupted without closing the piped manager. - * - * @author Emmanuel Bigeon */ -public abstract class AOutputForwardRunnable implements Runnable { - - /** The class logger. */ - private static final Logger LOGGER = Logger - .getLogger(AOutputForwardRunnable.class.getName()); - /** The default timeout (one tenth of second). */ - private static final long DEFAULT_TIMEOUT = 100; - /** The manager. */ - private final PipedConsoleOutput manager; - /** The timeout. */ - private final long timeout; - - /** Create a forwarding runnable. - * - * @param manager the manager */ - public AOutputForwardRunnable(final PipedConsoleOutput manager) { - super(); - this.manager = manager; - timeout = DEFAULT_TIMEOUT; - } - - /** Create a forward runnable with the given timeout. - *

- * Short timeout will be very responsive to the application actual messages, - * but may use computation time if the application is not verbose. Long - * timeout will save computation time, but will read batches of messages at - * once if the application is verbose. The right length for the timeout is - * likely to depend on the application and the use of it. - *

- * If you do not know what timeout length to use, please use the - * {@link #AOutputForwardRunnable(PipedConsoleOutput)} constructor. - * - * @param manager the manager - * @param timeout the timeout between message requests. */ - public AOutputForwardRunnable(final PipedConsoleOutput manager, - final long timeout) { - super(); - this.manager = manager; - this.timeout = timeout; - } - - /** Do forward the line. - * - * @param m the line to forward */ - protected abstract void forwardLine(String m); - - /** Test if the runable is still running. - * - * @return if the thread should keep running */ - protected abstract boolean isRunning(); - - /* (non-Javadoc) - * @see java.lang.Runnable#run() */ - @Override - public final void run() { - try { - while (isRunning()) { - while (isRunning() && !manager.available()) { - waitASec(); - } - if (!isRunning()) { - return; - } - final String m = manager.readNextLine(); - forwardLine(m); - } - } catch (final IOException e) { - LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$ - e); - } - } - - /** a method to wait some time. */ - protected final void waitASec() { - try { - synchronized (this) { - wait(timeout); - } - } catch (final InterruptedException e) { - LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$ - e); - Thread.currentThread().interrupt(); - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.tools.AOutputForwardRunnable.java + * Created on: Dec 1, 2016 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** An incomplete implematation used to forward messages from a piped console. + *

+ * This forwarding can be interrupted without closing the piped manager. + * + * @author Emmanuel Bigeon */ +public abstract class AOutputForwardRunnable implements Runnable { + + /** The class logger. */ + private static final Logger LOGGER = Logger + .getLogger(AOutputForwardRunnable.class.getName()); + /** The default timeout (one tenth of second). */ + private static final long DEFAULT_TIMEOUT = 100; + /** The manager. */ + private final PipedConsoleOutput manager; + /** The timeout. */ + private final long timeout; + + /** Create a forwarding runnable. + * + * @param manager the manager */ + public AOutputForwardRunnable(final PipedConsoleOutput manager) { + super(); + this.manager = manager; + timeout = DEFAULT_TIMEOUT; + } + + /** Create a forward runnable with the given timeout. + *

+ * Short timeout will be very responsive to the application actual messages, + * but may use computation time if the application is not verbose. Long + * timeout will save computation time, but will read batches of messages at + * once if the application is verbose. The right length for the timeout is + * likely to depend on the application and the use of it. + *

+ * If you do not know what timeout length to use, please use the + * {@link #AOutputForwardRunnable(PipedConsoleOutput)} constructor. + * + * @param manager the manager + * @param timeout the timeout between message requests. */ + public AOutputForwardRunnable(final PipedConsoleOutput manager, + final long timeout) { + super(); + this.manager = manager; + this.timeout = timeout; + } + + /** Do forward the line. + * + * @param m the line to forward */ + protected abstract void forwardLine(String m); + + /** Test if the runable is still running. + * + * @return if the thread should keep running */ + protected abstract boolean isRunning(); + + /* (non-Javadoc) + * @see java.lang.Runnable#run() */ + @Override + public final void run() { + try { + while (isRunning()) { + while (isRunning() && !manager.available()) { + waitASec(); + } + if (!isRunning()) { + return; + } + final String m = manager.readNextLine(); + forwardLine(m); + } + } catch (final IOException e) { + LOGGER.log(Level.SEVERE, "Unexpected problem in manager", //$NON-NLS-1$ + e); + } + } + + /** a method to wait some time. */ + protected final void waitASec() { + try { + synchronized (this) { + wait(timeout); + } + } catch (final InterruptedException e) { + LOGGER.log(Level.SEVERE, "Interrupted wait", //$NON-NLS-1$ + e); + Thread.currentThread().interrupt(); + } + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleInput.java b/gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleInput.java similarity index 75% rename from gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleInput.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleInput.java index ad13c34..ba85fd7 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleInput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleInput.java @@ -1,160 +1,194 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.manager; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -import fr.bigeon.gclc.tools.StringProvider; - -/** This console input allows to enter commands and retrieve the output as an - * input. - *

- * This console input is used to internally pilot an application. This can be - * used to test application behavior. - * - * @author Emmanuel Bigeon */ -public final class PipedConsoleInput - implements ConsoleInput { - - /** THe inner manager. */ - private final StreamConsoleInput innerManager; - /** The stream to pipe commands into. */ - private final PipedOutputStream commandInput; - /** The stream for the application to read commands from. */ - private final PipedInputStream in; - /** The writing thread. */ - private final WritingRunnable writing; - - /** Create a manager that will write and read through piped stream. - * - * @param outPrint the stream to write the prompting messages to - * @throws IOException if the piping failed for streams */ - public PipedConsoleInput(final PrintStream outPrint) throws IOException { - commandInput = new PipedOutputStream(); - in = new PipedInputStream(commandInput); - innerManager = new StreamConsoleInput(outPrint, in, - StandardCharsets.UTF_8); - writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8); - final Thread th = new Thread(writing, - "GCLC console piped input stream"); //$NON-NLS-1$ - th.start(); - } - - @Override - public void close() throws IOException { - writing.setRunning(false); - in.close(); - innerManager.close(); - commandInput.close(); - } - - @Override - public StringProvider getPrompt() { - return innerManager.getPrompt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ - @Override - public void interruptPrompt() { - innerManager.interruptPrompt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */ - @Override - public boolean isClosed() { - return innerManager.isClosed(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */ - @Override - public String prompt() throws IOException { - return innerManager - .prompt(innerManager.getPrompt() + System.lineSeparator()); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ - @Override - public String prompt(final long timeout) throws IOException { - return innerManager.prompt(timeout); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */ - @Override - public String prompt(final String message) throws IOException { - return innerManager.prompt(message + System.lineSeparator()); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String, - * long) */ - @Override - public String prompt(final String message, final long timeout) throws IOException { - return innerManager.prompt(message + System.lineSeparator(), timeout); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ - @Override - public void setPrompt(final String prompt) { - innerManager.setPrompt(prompt); - } - - @Override - public void setPrompt(StringProvider string) { - innerManager.setPrompt(string); - } - - /** Type a message in the input. - * - * @param content the content to type to the application - * @throws IOException if the typing failed */ - public void type(final String content) throws IOException { - writing.addMessage(content); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.tools.StringProvider; + +/** This console input allows to enter commands and retrieve the output as an + * input. + *

+ * This console input is used to internally pilot an application. This can be + * used to test application behavior. + * + * @author Emmanuel Bigeon */ +public final class PipedConsoleInput + implements ConsoleInput { + + /** THe inner manager. */ + private final StreamConsoleInput innerManager; + /** The stream to pipe commands into. */ + private final PipedOutputStream commandInput; + /** The stream for the application to read commands from. */ + private final PipedInputStream in; + /** The writing thread. */ + private final WritingRunnable writing; + + /** Create a manager that will write and read through piped stream. + * + * @param outPrint the stream to write the prompting messages to + * @throws IOException if the piping failed for streams */ + public PipedConsoleInput(final PrintStream outPrint) throws IOException { + commandInput = new PipedOutputStream(); + in = new PipedInputStream(commandInput); + innerManager = new StreamConsoleInput(outPrint, in, + StandardCharsets.UTF_8); + writing = new WritingRunnable(commandInput, StandardCharsets.UTF_8); + final Thread th = new Thread(writing, + "GCLC console piped input stream"); //$NON-NLS-1$ + th.start(); + } + + @Override + public void close() throws IOException { + writing.setRunning(false); + in.close(); + innerManager.close(); + commandInput.close(); + } + + @Override + public StringProvider getPrompt() { + return innerManager.getPrompt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#interruptPrompt() */ + @Override + public void interruptPrompt() { + innerManager.interruptPrompt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#isClosed() */ + @Override + public boolean isClosed() { + return innerManager.isClosed(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt() */ + @Override + public String prompt() throws IOException { + return innerManager + .prompt(innerManager.getPrompt() + System.lineSeparator()); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ + @Override + public String prompt(final long timeout) throws IOException { + return innerManager.prompt(timeout); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String) */ + @Override + public String prompt(final String message) throws IOException { + return innerManager.prompt(message + System.lineSeparator()); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#prompt(java.lang.String, + * long) */ + @Override + public String prompt(final String message, final long timeout) throws IOException { + return innerManager.prompt(message + System.lineSeparator(), timeout); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ + @Override + public void setPrompt(final String prompt) { + innerManager.setPrompt(prompt); + } + + @Override + public void setPrompt(StringProvider string) { + innerManager.setPrompt(string); + } + + /** Type a message in the input. + * + * @param content the content to type to the application + * @throws IOException if the typing failed */ + public void type(final String content) throws IOException { + writing.addMessage(content); + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleOutput.java b/gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleOutput.java similarity index 74% rename from gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleOutput.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleOutput.java index eb89110..8dc2a5b 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/PipedConsoleOutput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/PipedConsoleOutput.java @@ -1,153 +1,188 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.manager; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -/** This console output allows to retrieve the output as an input. - *

- * This console output is used to internally pilot an application. This can be - * used to test application behavior. - * - * @author Emmanuel Bigeon */ -public final class PipedConsoleOutput - implements ConsoleOutput { - - /** The encoding between streams. */ - private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ - /** THe inner manager. */ - private final StreamConsoleOutput innerManager; - /** The reader to get application return from. */ - private final BufferedReader commandBuffOutput; - /** The stream to get application return from. */ - private final PipedInputStream commandOutput; - /** The print writer for application to write return to. */ - private final PrintStream outPrint; - /** The reading thread. */ - private final ReadingRunnable reading; - - /** Create a manager that will write and read through piped stream. - * - * @throws IOException if the piping failed for streams */ - public PipedConsoleOutput() throws IOException { - commandOutput = new PipedInputStream(); - final PipedOutputStream out = new PipedOutputStream(commandOutput); - commandBuffOutput = new BufferedReader( - new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); - outPrint = new PrintStream(out, true, UTF_8); - innerManager = new StreamConsoleOutput(outPrint); - reading = new ReadingRunnable(commandBuffOutput); - final Thread th = new Thread(reading, "GCLC console output forward"); //$NON-NLS-1$ - th.setDaemon(true); - th.start(); - } - - /** Test if there is available data. - * - * @return the content of the next line written by the application - * @throws IOException if the reading failed */ - public boolean available() throws IOException { - return reading.hasMessage(); - } - - /* (non-Javadoc) - * @see java.lang.AutoCloseable#close() */ - @Override - public void close() throws IOException { - reading.setRunning(false); - innerManager.close(); - outPrint.close(); - commandBuffOutput.close(); - commandOutput.close(); - } - - /** Wait for a specific message to arrive. - *

- * When this method returns, the message was appended to the data, it - * may or may not be the next line of data. - * - * @param message the message - * @return the thread to join to wait for message delivery - * @see fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String) */ - public Thread getWaitForDelivery(final String message) { - return reading.getWaitForDelivery(message); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */ - @Override - public boolean isClosed() { - return innerManager.isClosed(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */ - @Override - public void print(final String object) throws IOException { - innerManager.print(object); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#println() */ - @Override - public void println() throws IOException { - innerManager.println(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String) */ - @Override - public void println(final String object) throws IOException { - innerManager.println(object); - } - - /** Read the next line of data. - * - * @return the content of the next line written by the application - * @throws IOException if the reading failed */ - public String readNextLine() throws IOException { - return reading.getMessage(); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc-test:fr.bigeon.gclc.test.TestConsoleManager.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** This console output allows to retrieve the output as an input. + *

+ * This console output is used to internally pilot an application. This can be + * used to test application behavior. + * + * @author Emmanuel Bigeon */ +public final class PipedConsoleOutput + implements ConsoleOutput { + + /** The encoding between streams. */ + private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ + /** THe inner manager. */ + private final StreamConsoleOutput innerManager; + /** The reader to get application return from. */ + private final BufferedReader commandBuffOutput; + /** The stream to get application return from. */ + private final PipedInputStream commandOutput; + /** The print writer for application to write return to. */ + private final PrintStream outPrint; + /** The reading thread. */ + private final ReadingRunnable reading; + + /** Create a manager that will write and read through piped stream. + * + * @throws IOException if the piping failed for streams */ + public PipedConsoleOutput() throws IOException { + commandOutput = new PipedInputStream(); + final PipedOutputStream out = new PipedOutputStream(commandOutput); + commandBuffOutput = new BufferedReader( + new InputStreamReader(commandOutput, StandardCharsets.UTF_8)); + outPrint = new PrintStream(out, true, UTF_8); + innerManager = new StreamConsoleOutput(outPrint); + reading = new ReadingRunnable(commandBuffOutput); + final Thread th = new Thread(reading, "GCLC console output forward"); //$NON-NLS-1$ + th.setDaemon(true); + th.start(); + } + + /** Test if there is available data. + * + * @return the content of the next line written by the application + * @throws IOException if the reading failed */ + public boolean available() throws IOException { + return reading.hasMessage(); + } + + /* (non-Javadoc) + * @see java.lang.AutoCloseable#close() */ + @Override + public void close() throws IOException { + reading.setRunning(false); + innerManager.close(); + outPrint.close(); + commandBuffOutput.close(); + commandOutput.close(); + } + + /** Wait for a specific message to arrive. + *

+ * When this method returns, the message was appended to the data, it + * may or may not be the next line of data. + * + * @param message the message + * @return the thread to join to wait for message delivery + * @see fr.bigeon.gclc.utils.ReadingRunnable#getWaitForDelivery(java.lang.String) */ + public Thread getWaitForDelivery(final String message) { + return reading.getWaitForDelivery(message); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */ + @Override + public boolean isClosed() { + return innerManager.isClosed(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */ + @Override + public void print(final String object) throws IOException { + innerManager.print(object); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#println() */ + @Override + public void println() throws IOException { + innerManager.println(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String) */ + @Override + public void println(final String object) throws IOException { + innerManager.println(object); + } + + /** Read the next line of data. + * + * @return the content of the next line written by the application + * @throws IOException if the reading failed */ + public String readNextLine() throws IOException { + return reading.getMessage(); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/utils/ReadingRunnable.java similarity index 85% rename from gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/ReadingRunnable.java index 7fbfba9..024325d 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/ReadingRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/ReadingRunnable.java @@ -1,354 +1,386 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java - * Created on: Nov 29, 2016 - */ -package fr.bigeon.gclc.manager; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** A runnable to read the piped output. - * - * @author Emmanuel Bigeon */ -public final class ReadingRunnable implements Runnable { - - /** The runnable to wait for arrival of a message in the queue. - * - * @author Emmanuel Bigeon */ - private final class ToWaitRunnable implements Runnable { - /** The Object. */ - private final Object obj; - /** The locking object. */ - private final Object start; - /** The message. */ - private final String message; - /** The started status. */ - private boolean started = false; - - /** Create the waiting runnable. - * - * @param obj the object to lock on - * @param start the object to notify when ready to wait - * @param message the message to wait for */ - public ToWaitRunnable(final Object obj, final Object start, - final String message) { - this.obj = obj; - this.start = start; - this.message = message; - } - - /** Test if the waiting runnable is started. - * - * @return the started */ - public boolean isStarted() { - synchronized (start) { - return started; - } - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() */ - @SuppressWarnings("synthetic-access") - @Override - public void run() { - synchronized (obj) { - synchronized (start) { - started = true; - start.notifyAll(); - } - while (isRunning()) { - try { - obj.wait(); - if (delivering.equals(message)) { - return; - } - } catch (final InterruptedException e) { - LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, - e); - Thread.currentThread().interrupt(); - } - } - } - } - } - - /** The thread intteruption logging message. */ - private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$ - /** The closed pipe message. */ - private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$ - /** Wait timeout. */ - private static final long TIMEOUT = 1000; - /** Class logger. */ - private static final Logger LOGGER = Logger - .getLogger(ReadingRunnable.class.getName()); - /** Read messages. */ - private final Deque messages = new ArrayDeque<>(); - /** the reader. */ - private final BufferedReader reader; - /** the state of this runnable. */ - private boolean running = true; - /** Synchro object. */ - private final Object lock = new Object(); - /** The waiting status for a message. */ - private boolean waiting; - /** The blocker for a given message. */ - private final Map messageBlocker = new HashMap<>(); - /** The lock. */ - private final Object messageBlockerLock = new Object(); - /** The message being delivered. */ - private String delivering; - - /** Create a reading runnable. - * - * @param reader the input to read from */ - public ReadingRunnable(final BufferedReader reader) { - super(); - this.reader = reader; - } - - /** Strip the string from head NULL characters. - * - * @param line the line to strip the null character from - * @return the resulting string */ - private static String stripNull(final String line) { - String res = line; - while (res.length() > 0 && res.charAt(0) == 0) { - LOGGER.severe( - "NULL character heading the result of the read. This is a stream problem..."); //$NON-NLS-1$ - res = res.substring(1); - } - return res; - } - - /** do wait for a message. - *

This method should only be called inside a loop. - * @param timeout the timeout of the wait. - * @throws IOException if the runnable was stopped and no essage was found. - */ - private void doWaitMessage(final long timeout) throws IOException { - try { - lock.wait(timeout); - } catch (final InterruptedException e) { - LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); - Thread.currentThread().interrupt(); - } - if (messages.isEmpty() && !running) { - throw new IOException(CLOSED_PIPE); - } - } - - /** Get the next message. - * - * @return the next read message - * @throws IOException if the pipe is closed */ - public String getMessage() throws IOException { - synchronized (lock) { - if (!running) { - throw new IOException(CLOSED_PIPE); - } - waiting = true; - waitMessage(TIMEOUT); - LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$ - waiting = false; - notifyMessage(messages.peek()); - return messages.poll(); - } - } - - /** Get the next message, but wait only a given time for it. - * - * @param timeout the read time out - * @return The next message that was in the input - * @throws IOException if the input was closed */ - public String getNextMessage(final long timeout) throws IOException { - synchronized (lock) { - if (!running) { - throw new IOException(CLOSED_PIPE); - } - waiting = true; - doWaitMessage(timeout); - waiting = false; - if (messages.isEmpty()) { - return null; - } - return messages.poll(); - } - } - - /** Get a waiting thread for a specific message delivery. - * - * @param message the message - * @return the thread to join to wait for message delivery */ - public Thread getWaitForDelivery(final String message) { - synchronized (messageBlockerLock) { - if (!messageBlocker.containsKey(message)) { - messageBlocker.put(message, new Object()); - } - final Object obj = messageBlocker.get(message); - final Object start = new Object(); - final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, - message); - final Thread th = new Thread(waitRunn); - - synchronized (start) { - th.start(); - while (!waitRunn.isStarted()) { - try { - start.wait(TIMEOUT); - } catch (final InterruptedException e) { - LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, - e); - Thread.currentThread().interrupt(); - } - } - } - return th; - } - } - - /** Test if some data is available. - * - * @return if a message is waiting - * @throws IOException if the pipe is closed */ - public boolean hasMessage() throws IOException { - synchronized (lock) { - if (!running) { - throw new IOException(CLOSED_PIPE); - } - return !messages.isEmpty(); - } - } - - /** Interrupts the wait on the next message by providing an empty - * message. */ - public void interrupt() { - synchronized (lock) { - if (waiting) { - messages.offer(""); //$NON-NLS-1$ - lock.notifyAll(); - } - } - } - - /** Test if this element is still running. - * - * @return the running */ - public boolean isRunning() { - synchronized (lock) { - return running; - } - } - - /** Notify the arrival of a given message. - * - * @param message the message */ - private void notifyMessage(final String message) { - synchronized (messageBlockerLock) { - delivering = message; - if (messageBlocker.containsKey(message)) { - final Object mLock = messageBlocker.get(message); - synchronized (mLock) { - mLock.notifyAll(); - } - messageBlocker.remove(message); - } - } - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() */ - @Override - public void run() { - while (running) { - try { - String line = reader.readLine(); - if (line == null) { - // Buffer end - running = false; - return; - } - LOGGER.finer("Read: " + line); //$NON-NLS-1$ - line = stripNull(line); - synchronized (lock) { - messages.add(line); - lock.notifyAll(); - } - } catch (final InterruptedIOException e) { - if (running) { - LOGGER.info("Reading interrupted"); //$NON-NLS-1$ - } - LOGGER.log(Level.FINER, - "Read interruption was caused by an exception", e); //$NON-NLS-1$ - } catch (final IOException e) { - LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$ - e); - if (running) { - LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$ - running = false; - } - return; - } - } - } - - /** Set the running status for this reading runnable. - * - * @param running the running to set */ - public void setRunning(final boolean running) { - synchronized (lock) { - this.running = running; - } - } - - /** Wait for the next message to be integratted. - * - * @param timeout the timeout to wait - * @throws IOException if the next message was not delivered and the - * runnable stopped. */ - private void waitMessage(final long timeout) throws IOException { - while (messages.isEmpty()) { - doWaitMessage(timeout); - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java + * Created on: Nov 29, 2016 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** A runnable to read the piped output. + * + * @author Emmanuel Bigeon */ +public final class ReadingRunnable implements Runnable { + + /** The runnable to wait for arrival of a message in the queue. + * + * @author Emmanuel Bigeon */ + private final class ToWaitRunnable implements Runnable { + /** The Object. */ + private final Object obj; + /** The locking object. */ + private final Object start; + /** The message. */ + private final String message; + /** The started status. */ + private boolean started = false; + + /** Create the waiting runnable. + * + * @param obj the object to lock on + * @param start the object to notify when ready to wait + * @param message the message to wait for */ + public ToWaitRunnable(final Object obj, final Object start, + final String message) { + this.obj = obj; + this.start = start; + this.message = message; + } + + /** Test if the waiting runnable is started. + * + * @return the started */ + public boolean isStarted() { + synchronized (start) { + return started; + } + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() */ + @Override + public void run() { + synchronized (obj) { + synchronized (start) { + started = true; + start.notifyAll(); + } + while (isRunning()) { + try { + obj.wait(); + if (delivering.equals(message)) { + return; + } + } catch (final InterruptedException e) { + LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, + e); + Thread.currentThread().interrupt(); + } + } + } + } + } + + /** The thread intteruption logging message. */ + private static final String THREAD_INTERRUPTION_EXCEPTION = "Thread interruption exception."; //$NON-NLS-1$ + /** The closed pipe message. */ + private static final String CLOSED_PIPE = "Closed pipe"; //$NON-NLS-1$ + /** Wait timeout. */ + private static final long TIMEOUT = 1000; + /** Class logger. */ + private static final Logger LOGGER = Logger + .getLogger(ReadingRunnable.class.getName()); + /** Read messages. */ + private final Deque messages = new ArrayDeque<>(); + /** the reader. */ + private final BufferedReader reader; + /** the state of this runnable. */ + private boolean running = true; + /** Synchro object. */ + private final Object lock = new Object(); + /** The waiting status for a message. */ + private boolean waiting; + /** The blocker for a given message. */ + private final Map messageBlocker = new HashMap<>(); + /** The lock. */ + private final Object messageBlockerLock = new Object(); + /** The message being delivered. */ + private String delivering; + + /** Create a reading runnable. + * + * @param reader the input to read from */ + public ReadingRunnable(final BufferedReader reader) { + super(); + this.reader = reader; + } + + /** Strip the string from head NULL characters. + * + * @param line the line to strip the null character from + * @return the resulting string */ + private static String stripNull(final String line) { + String res = line; + while (res.length() > 0 && res.charAt(0) == 0) { + LOGGER.severe( + "NULL character heading the result of the read. This is a stream problem..."); //$NON-NLS-1$ + res = res.substring(1); + } + return res; + } + + /** do wait for a message. + *

This method should only be called inside a loop. + * @param timeout the timeout of the wait. + * @throws IOException if the runnable was stopped and no essage was found. + */ + private void doWaitMessage(final long timeout) throws IOException { + try { + lock.wait(timeout); + } catch (final InterruptedException e) { + LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, e); + Thread.currentThread().interrupt(); + } + if (messages.isEmpty() && !running) { + throw new IOException(CLOSED_PIPE); + } + } + + /** Get the next message. + * + * @return the next read message + * @throws IOException if the pipe is closed */ + public String getMessage() throws IOException { + synchronized (lock) { + if (!running) { + throw new IOException(CLOSED_PIPE); + } + waiting = true; + waitMessage(TIMEOUT); + LOGGER.finest("Polled: " + messages.peek()); //$NON-NLS-1$ + waiting = false; + notifyMessage(messages.peek()); + return messages.poll(); + } + } + + /** Get the next message, but wait only a given time for it. + * + * @param timeout the read time out + * @return The next message that was in the input + * @throws IOException if the input was closed */ + public String getNextMessage(final long timeout) throws IOException { + synchronized (lock) { + if (!running) { + throw new IOException(CLOSED_PIPE); + } + waiting = true; + doWaitMessage(timeout); + waiting = false; + if (messages.isEmpty()) { + return null; + } + return messages.poll(); + } + } + + /** Get a waiting thread for a specific message delivery. + * + * @param message the message + * @return the thread to join to wait for message delivery */ + public Thread getWaitForDelivery(final String message) { + synchronized (messageBlockerLock) { + if (!messageBlocker.containsKey(message)) { + messageBlocker.put(message, new Object()); + } + final Object obj = messageBlocker.get(message); + final Object start = new Object(); + final ToWaitRunnable waitRunn = new ToWaitRunnable(obj, start, + message); + final Thread th = new Thread(waitRunn); + + synchronized (start) { + th.start(); + while (!waitRunn.isStarted()) { + try { + start.wait(TIMEOUT); + } catch (final InterruptedException e) { + LOGGER.log(Level.SEVERE, THREAD_INTERRUPTION_EXCEPTION, + e); + Thread.currentThread().interrupt(); + } + } + } + return th; + } + } + + /** Test if some data is available. + * + * @return if a message is waiting + * @throws IOException if the pipe is closed */ + public boolean hasMessage() throws IOException { + synchronized (lock) { + if (!running) { + throw new IOException(CLOSED_PIPE); + } + return !messages.isEmpty(); + } + } + + /** Interrupts the wait on the next message by providing an empty + * message. */ + public void interrupt() { + synchronized (lock) { + if (waiting) { + messages.offer(""); //$NON-NLS-1$ + lock.notifyAll(); + } + } + } + + /** Test if this element is still running. + * + * @return the running */ + public boolean isRunning() { + synchronized (lock) { + return running; + } + } + + /** Notify the arrival of a given message. + * + * @param message the message */ + private void notifyMessage(final String message) { + synchronized (messageBlockerLock) { + delivering = message; + if (messageBlocker.containsKey(message)) { + final Object mLock = messageBlocker.get(message); + synchronized (mLock) { + mLock.notifyAll(); + } + messageBlocker.remove(message); + } + } + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() */ + @Override + public void run() { + while (running) { + try { + String line = reader.readLine(); + if (line == null) { + // Buffer end + running = false; + return; + } + LOGGER.finer("Read: " + line); //$NON-NLS-1$ + line = stripNull(line); + synchronized (lock) { + messages.add(line); + lock.notifyAll(); + } + } catch (final InterruptedIOException e) { + if (running) { + LOGGER.info("Reading interrupted"); //$NON-NLS-1$ + } + LOGGER.log(Level.FINER, + "Read interruption was caused by an exception", e); //$NON-NLS-1$ + } catch (final IOException e) { + LOGGER.log(Level.FINE, "The stream reading threw an exception", //$NON-NLS-1$ + e); + if (running) { + LOGGER.severe("Unable to read from stream"); //$NON-NLS-1$ + running = false; + } + return; + } + } + } + + /** Set the running status for this reading runnable. + * + * @param running the running to set */ + public void setRunning(final boolean running) { + synchronized (lock) { + this.running = running; + } + } + + /** Wait for the next message to be integratted. + * + * @param timeout the timeout to wait + * @throws IOException if the next message was not delivered and the + * runnable stopped. */ + private void waitMessage(final long timeout) throws IOException { + while (messages.isEmpty()) { + doWaitMessage(timeout); + } + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/SinkOutput.java b/gclc/src/main/java/fr/bigeon/gclc/utils/SinkOutput.java similarity index 61% rename from gclc/src/main/java/fr/bigeon/gclc/manager/SinkOutput.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/SinkOutput.java index d03f643..125aced 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/SinkOutput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/SinkOutput.java @@ -1,89 +1,124 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.SinkOutput.java - * Created on: Nov 13, 2017 - */ -package fr.bigeon.gclc.manager; - -/** A console output that absorbs every message. - * - * @author Emmanuel Bigeon */ -public final class SinkOutput implements ConsoleOutput { - - /** The sink output. */ - public static final ConsoleOutput INSTANCE = new SinkOutput(); - - /** Singleton constructor. */ - private SinkOutput() { - // - } - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#close() */ - @Override - public void close() { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */ - @Override - public boolean isClosed() { - return false; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */ - @Override - public void print(final String text) { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#println() */ - @Override - public void println() { - // - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String) - */ - @Override - public void println(final String message) { - // - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.SinkOutput.java + * Created on: Nov 13, 2017 + */ +package fr.bigeon.gclc.utils; + +import fr.bigeon.gclc.manager.ConsoleOutput; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +/** A console output that absorbs every message. + * + * @author Emmanuel Bigeon */ +public final class SinkOutput implements ConsoleOutput { + + /** The sink output. */ + public static final ConsoleOutput INSTANCE = new SinkOutput(); + + /** Singleton constructor. */ + private SinkOutput() { + // + } + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#close() */ + @Override + public void close() { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#isClosed() */ + @Override + public boolean isClosed() { + return false; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#print(java.lang.String) */ + @Override + public void print(final String text) { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#println() */ + @Override + public void println() { + // + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleOutput#println(java.lang.String) + */ + @Override + public void println(final String message) { + // + } + +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleInput.java b/gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleInput.java similarity index 76% rename from gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleInput.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleInput.java index ff56edc..eb42ce2 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleInput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleInput.java @@ -1,190 +1,224 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.system.SystemConsoleManager.java - * Created on: Dec 19, 2014 - */ -package fr.bigeon.gclc.manager; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.nio.charset.Charset; - -import fr.bigeon.gclc.tools.ConstantString; -import fr.bigeon.gclc.tools.StringProvider; - -/** A console using the input stream and print stream. - *

- * The default constructor will use the system standart input and output. - * - * @author Emmanuel BIGEON */ -public final class StreamConsoleInput implements ConsoleInput { - - /** The default prompt. */ - public static final StringProvider DEFAULT_PROMPT = new ConstantString("> "); //$NON-NLS-1$ - - /** The command prompt. It can be changed. */ - private StringProvider prompt = DEFAULT_PROMPT; - - /** The print stream. */ - private final PrintStream out; - /** The input stream. */ - private final BufferedReader in; - - /** If the manager is closed. */ - private boolean closed = false; - - /** The prompting thread. */ - private final Thread promptThread; - - /** The reading runnable. */ - private final ReadingRunnable reading; - - /** This default constructor relies on the system defined standart output - * and input stream. */ - public StreamConsoleInput() { - this(System.out, System.in, Charset.defaultCharset()); - } - - /** Create the stream base console input. - * - * @param out the output stream - * @param in the input stream - * @param charset the charset for the input */ - public StreamConsoleInput(final PrintStream out, final InputStream in, - final Charset charset) { - super(); - this.out = out; - this.in = new BufferedReader(new InputStreamReader(in, charset)); - reading = new ReadingRunnable(this.in); - promptThread = new Thread(reading, "prompt"); //$NON-NLS-1$ - promptThread.setDaemon(true); - promptThread.start(); - } - - /** Check that the console input is not closed. - * - * @throws IOException if the stream was closed */ - private void checkOpen() throws IOException { - if (closed) { - throw new IOException(); - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ - @Override - public void close() throws IOException { - closed = true; - reading.setRunning(false); - promptThread.interrupt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */ - @Override - public StringProvider getPrompt() { - return prompt; - } - - /** Beware, in this implementation this is the same as closing the manager. - * - * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */ - @Override - public void interruptPrompt() { - reading.interrupt(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ - @Override - public boolean isClosed() { - return closed; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#prompt() */ - @Override - public String prompt() throws IOException { - return prompt(prompt.apply()); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ - @Override - public String prompt(final long timeout) throws IOException { - return prompt(prompt.apply(), timeout); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ - @Override - public String prompt(final String message) throws IOException { - checkOpen(); - if (out != null) { - out.print(message); - out.flush(); - } - return reading.getMessage(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ - @Override - public String prompt(final String message, - final long timeout) throws IOException { - checkOpen(); - if (out != null) { - out.print(message); - out.flush(); - } - return reading.getNextMessage(timeout); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ - @Override - public void setPrompt(final String prompt) { - this.prompt = new ConstantString(prompt); - } - - @Override - public void setPrompt(StringProvider string) { - this.prompt = string; - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.system.SystemConsoleManager.java + * Created on: Dec 19, 2014 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.nio.charset.Charset; + +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.tools.ConstantString; +import fr.bigeon.gclc.tools.StringProvider; + +/** A console using the input stream and print stream. + *

+ * The default constructor will use the system standart input and output. + * + * @author Emmanuel BIGEON */ +public final class StreamConsoleInput implements ConsoleInput { + + /** The default prompt. */ + public static final StringProvider DEFAULT_PROMPT = new ConstantString("> "); //$NON-NLS-1$ + + /** The command prompt. It can be changed. */ + private StringProvider prompt = DEFAULT_PROMPT; + + /** The print stream. */ + private final PrintStream out; + /** The input stream. */ + private final BufferedReader in; + + /** If the manager is closed. */ + private boolean closed = false; + + /** The prompting thread. */ + private final Thread promptThread; + + /** The reading runnable. */ + private final ReadingRunnable reading; + + /** This default constructor relies on the system defined standart output + * and input stream. */ + public StreamConsoleInput() { + this(System.out, System.in, Charset.defaultCharset()); + } + + /** Create the stream base console input. + * + * @param out the output stream + * @param in the input stream + * @param charset the charset for the input */ + public StreamConsoleInput(final PrintStream out, final InputStream in, + final Charset charset) { + super(); + this.out = out; + this.in = new BufferedReader(new InputStreamReader(in, charset)); + reading = new ReadingRunnable(this.in); + promptThread = new Thread(reading, "prompt"); //$NON-NLS-1$ + promptThread.setDaemon(true); + promptThread.start(); + } + + /** Check that the console input is not closed. + * + * @throws IOException if the stream was closed */ + private void checkOpen() throws IOException { + if (closed) { + throw new IOException(); + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ + @Override + public void close() throws IOException { + closed = true; + reading.setRunning(false); + promptThread.interrupt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#getPrompt() */ + @Override + public StringProvider getPrompt() { + return prompt; + } + + /** Beware, in this implementation this is the same as closing the manager. + * + * @see fr.bigeon.gclc.manager.ConsoleInput#interruptPrompt() */ + @Override + public void interruptPrompt() { + reading.interrupt(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ + @Override + public boolean isClosed() { + return closed; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#prompt() */ + @Override + public String prompt() throws IOException { + return prompt(prompt.apply()); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#prompt(long) */ + @Override + public String prompt(final long timeout) throws IOException { + return prompt(prompt.apply(), timeout); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ + @Override + public String prompt(final String message) throws IOException { + checkOpen(); + if (out != null) { + out.print(message); + out.flush(); + } + return reading.getMessage(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#prompt(java.lang.String) */ + @Override + public String prompt(final String message, + final long timeout) throws IOException { + checkOpen(); + if (out != null) { + out.print(message); + out.flush(); + } + return reading.getNextMessage(timeout); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String) */ + @Override + public void setPrompt(final String prompt) { + this.prompt = new ConstantString(prompt); + } + + @Override + public void setPrompt(StringProvider string) { + this.prompt = string; + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleOutput.java b/gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleOutput.java similarity index 67% rename from gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleOutput.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleOutput.java index cbe6639..07ba265 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/StreamConsoleOutput.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/StreamConsoleOutput.java @@ -1,115 +1,150 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.system.SystemConsoleManager.java - * Created on: Dec 19, 2014 - */ -package fr.bigeon.gclc.manager; - -import java.io.IOException; -import java.io.PrintStream; - -/** A console using the input stream and print stream. - *

- * The default constructor will use the system standart input and output. - * - * @author Emmanuel BIGEON */ -public final class StreamConsoleOutput implements ConsoleOutput { - /** The print stream. */ - private final PrintStream out; - /** If the manager is closed. */ - private boolean closed = false; - - /** This default constructor relies on the system defined standart output - * and input stream. */ - public StreamConsoleOutput() { - this(System.out); - } - - /** Create a print stream based console output. - * - * @param out the output stream */ - public StreamConsoleOutput(final PrintStream out) { - super(); - this.out = out; - } - - /** Check the open status. - * - * @throws IOException if the stream was closed */ - private void checkOpen() throws IOException { - if (closed) { - throw new IOException(); - } - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ - @Override - public void close() { - closed = true; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ - @Override - public boolean isClosed() { - return closed; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */ - @Override - public void print(final String object) throws IOException { - checkOpen(); - out.print(object); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#println() */ - @Override - public void println() throws IOException { - checkOpen(); - out.println(); - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */ - @Override - public void println(final String object) throws IOException { - checkOpen(); - out.println(object); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.system.SystemConsoleManager.java + * Created on: Dec 19, 2014 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.io.PrintStream; + +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A console using the input stream and print stream. + *

+ * The default constructor will use the system standart input and output. + * + * @author Emmanuel BIGEON */ +public final class StreamConsoleOutput implements ConsoleOutput { + /** The print stream. */ + private final PrintStream out; + /** If the manager is closed. */ + private boolean closed = false; + + /** This default constructor relies on the system defined standart output + * and input stream. */ + public StreamConsoleOutput() { + this(System.out); + } + + /** Create a print stream based console output. + * + * @param out the output stream */ + public StreamConsoleOutput(final PrintStream out) { + super(); + this.out = out; + } + + /** Check the open status. + * + * @throws IOException if the stream was closed */ + private void checkOpen() throws IOException { + if (closed) { + throw new IOException(); + } + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#close() */ + @Override + public void close() { + closed = true; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.manager.ConsoleManager#isClosed() */ + @Override + public boolean isClosed() { + return closed; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#print(java.lang.Object) */ + @Override + public void print(final String object) throws IOException { + checkOpen(); + out.print(object); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#println() */ + @Override + public void println() throws IOException { + checkOpen(); + out.println(); + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.ConsoleManager#println(java.lang.Object) */ + @Override + public void println(final String object) throws IOException { + checkOpen(); + out.println(object); + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java b/gclc/src/main/java/fr/bigeon/gclc/utils/WritingRunnable.java similarity index 74% rename from gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java rename to gclc/src/main/java/fr/bigeon/gclc/utils/WritingRunnable.java index 34107db..1a32aef 100644 --- a/gclc/src/main/java/fr/bigeon/gclc/manager/WritingRunnable.java +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/WritingRunnable.java @@ -1,160 +1,193 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java - * Created on: Nov 29, 2016 - */ -package fr.bigeon.gclc.manager; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** The runnable in charge of writing messages as they are read. - *

- * Messages are queued to be retrieved latter on. - * - * @author Emmanuel Bigeon */ -public final class WritingRunnable implements Runnable { - - /** Wait timeout. */ - private static final long TIMEOUT = 1000; - /** Class logger. */ - private static final Logger LOGGER = Logger - .getLogger(WritingRunnable.class.getName()); - /** Messages to write. */ - private final Deque messages = new ArrayDeque<>(); - /** Stream to write to. */ - private final OutputStream outPrint; - /** The charset. */ - private final Charset charset; - /** Runnable state. */ - private boolean running = true; - - /** Synchro object. */ - private final Object lock = new Object(); - - /** Create the writing runnable. - * - * @param outPrint the output to print to - * @param charset the charset of the stream */ - public WritingRunnable(final OutputStream outPrint, final Charset charset) { - super(); - this.outPrint = outPrint; - this.charset = charset; - } - - /** Add a message in the queue. - * - * @param message the message - * @throws IOException if the pipe is closed */ - public void addMessage(final String message) throws IOException { - synchronized (lock) { - if (!running) { - throw new IOException("Closed pipe"); //$NON-NLS-1$ - } - messages.offer(message); - lock.notifyAll(); - } - } - - /** Test if the message is running. - * - * @return the running */ - public boolean isRunning() { - synchronized (lock) { - return running; - } - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() */ - @Override - public void run() { - while (running) { - synchronized (lock) { - while (messages.isEmpty()) { - waitNextMessage(); - if (!running) { - return; - } - } - writeMessage(); - } - } - } - - /** Set the running status. - * - * @param running the running to set */ - public void setRunning(final boolean running) { - synchronized (lock) { - this.running = running; - } - } - - /** Wait for next message. */ - private void waitNextMessage() { - try { - lock.wait(TIMEOUT); - } catch (final InterruptedException e) { - if (running) { - LOGGER.log(Level.SEVERE, - "Thread interruption exception.", e); //$NON-NLS-1$ - } - Thread.currentThread().interrupt(); - } - } - - /** Write next message to output. */ - private void writeMessage() { - final String message = messages.poll(); - final ByteBuffer buff = charset - .encode(message + System.lineSeparator()); - if (buff.hasArray()) { - try { - outPrint.write(buff.array()); - } catch (final IOException e) { - LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$ - e); - } - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.test.utils.WritingRunnable.java + * Created on: Nov 29, 2016 + */ +package fr.bigeon.gclc.utils; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** The runnable in charge of writing messages as they are read. + *

+ * Messages are queued to be retrieved latter on. + * + * @author Emmanuel Bigeon */ +public final class WritingRunnable implements Runnable { + + /** Wait timeout. */ + private static final long TIMEOUT = 1000; + /** Class logger. */ + private static final Logger LOGGER = Logger + .getLogger(WritingRunnable.class.getName()); + /** Messages to write. */ + private final Deque messages = new ArrayDeque<>(); + /** Stream to write to. */ + private final OutputStream outPrint; + /** The charset. */ + private final Charset charset; + /** Runnable state. */ + private boolean running = true; + + /** Synchro object. */ + private final Object lock = new Object(); + + /** Create the writing runnable. + * + * @param outPrint the output to print to + * @param charset the charset of the stream */ + public WritingRunnable(final OutputStream outPrint, final Charset charset) { + super(); + this.outPrint = outPrint; + this.charset = charset; + } + + /** Add a message in the queue. + * + * @param message the message + * @throws IOException if the pipe is closed */ + public void addMessage(final String message) throws IOException { + synchronized (lock) { + if (!running) { + throw new IOException("Closed pipe"); //$NON-NLS-1$ + } + messages.offer(message); + lock.notifyAll(); + } + } + + /** Test if the message is running. + * + * @return the running */ + public boolean isRunning() { + synchronized (lock) { + return running; + } + } + + /* (non-Javadoc) + * @see java.lang.Runnable#run() */ + @Override + public void run() { + while (running) { + synchronized (lock) { + while (messages.isEmpty()) { + waitNextMessage(); + if (!running) { + return; + } + } + writeMessage(); + } + } + } + + /** Set the running status. + * + * @param running the running to set */ + public void setRunning(final boolean running) { + synchronized (lock) { + this.running = running; + } + } + + /** Wait for next message. */ + private void waitNextMessage() { + try { + lock.wait(TIMEOUT); + } catch (final InterruptedException e) { + if (running) { + LOGGER.log(Level.SEVERE, + "Thread interruption exception.", e); //$NON-NLS-1$ + } + Thread.currentThread().interrupt(); + } + } + + /** Write next message to output. */ + private void writeMessage() { + final String message = messages.poll(); + final ByteBuffer buff = charset + .encode(message + System.lineSeparator()); + if (buff.hasArray()) { + try { + outPrint.write(buff.array()); + } catch (final IOException e) { + LOGGER.log(Level.SEVERE, "Unable to write to stream", //$NON-NLS-1$ + e); + } + } + } +} diff --git a/gclc/src/main/java/fr/bigeon/gclc/utils/package-info.java b/gclc/src/main/java/fr/bigeon/gclc/utils/package-info.java new file mode 100644 index 0000000..f6eab75 --- /dev/null +++ b/gclc/src/main/java/fr/bigeon/gclc/utils/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author Emmanuel Bigeon + * + */ +package fr.bigeon.gclc.utils; diff --git a/gclc/src/main/resources/fr/bigeon/gclc/l10n/messages.properties b/gclc/src/main/resources/fr/bigeon/gclc/l10n/messages.properties index 944a47f..705369e 100644 --- a/gclc/src/main/resources/fr/bigeon/gclc/l10n/messages.properties +++ b/gclc/src/main/resources/fr/bigeon/gclc/l10n/messages.properties @@ -1,2 +1,35 @@ -CommandProvider.unrecognized=Unrecognized command "{0}" -ConsoleApplication.cmd.failed=The command "{0}" failed due to : +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 bigeon.fr +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +CommandProvider.unrecognized=Unrecognized command "{0}" +ConsoleApplication.cmd.failed=The command "{0}" failed due to : diff --git a/gclc/src/main/resources/fr/bigeon/gclc/licensing/cecill/CeCILL-header.txt b/gclc/src/main/resources/fr/bigeon/gclc/licensing/cecill/CeCILL-header.txt deleted file mode 100644 index 5c442bf..0000000 --- a/gclc/src/main/resources/fr/bigeon/gclc/licensing/cecill/CeCILL-header.txt +++ /dev/null @@ -1,32 +0,0 @@ -Copyright ${owner} (${project.inceptionYear}) - -${email} - -This software is a computer program whose purpose is to -${project.description}. - -This software is governed by the CeCILL license under French law and -abiding by the rules of distribution of free software. You can use, -modify and/or redistribute the software under the terms of the CeCILL -license as circulated by CEA, CNRS and INRIA at the following URL -"http://www.cecill.info". - -As a counterpart to the access to the source code and rights to copy, -modify and redistribute granted by the license, users are provided only -with a limited warranty and the software's author, the holder of the -economic rights, and the successive licensors have only limited -liability. - -In this respect, the user's attention is drawn to the risks associated -with loading, using, modifying and/or developing or reproducing the -software by the user in light of its specific status of free software, -that may mean that it is complicated to manipulate, and that also -therefore means that it is reserved for developers and experienced -professionals having in-depth computer knowledge. Users are therefore -encouraged to load and test the software's suitability as regards their -requirements in conditions enabling the security of their systems and/or -data to be ensured and, more generally, to use and operate it in the -same conditions as regards security. - -The fact that you are presently reading this means that you have had -knowledge of the CeCILL license and that you accept its terms. \ No newline at end of file diff --git a/gclc/src/main/resources/fr/bigeon/gclc/messages.properties b/gclc/src/main/resources/fr/bigeon/gclc/messages.properties index 5653569..da4eaa2 100644 --- a/gclc/src/main/resources/fr/bigeon/gclc/messages.properties +++ b/gclc/src/main/resources/fr/bigeon/gclc/messages.properties @@ -1,26 +1,59 @@ -exit.tip=Exit the application -help.cmd.tip=Display an help tip - -prompt.lineprompt=>\ - -promptlist.exit.defaultkey=\\q -promptlist.exit.dispkey=\ (exit with a new line made of "{0}") -promptlist.prompt=>\ -promptlist.multi.sepkey=\ - -promptbool.choices=\ (Y/N) -promptbool.choices.invalid=Invalid input. Please input one of {0}. -promptbool.choices.yes1=Y -promptbool.choices.yes2=yes -promptbool.choices.no1=N -promptbool.choices.no2=no - -promptchoice.outofbounds=Please choose something between {0} and {1}. The choices were: -promptchoice.formaterr=The input seems to be something that is not an integer.\ -Please choose something between {0} and {1}. The choices were: - -promptlongtext.exit.defaultkey=\\q -promptlongtext.exit.dispkey=\ (exit with a new line made of "{0}") - -unrecognized.cmd=Unrecognized command "{0}" -expected.cmd=A Command was expected but nothing was provided... +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 bigeon.fr +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +exit.tip=Exit the application +help.cmd.tip=Display an help tip + +prompt.lineprompt=>\ + +promptlist.exit.defaultkey=\\q +promptlist.exit.dispkey=\ (exit with a new line made of "{0}") +promptlist.prompt=>\ +promptlist.multi.sepkey=\ + +promptbool.choices=\ (Y/N) +promptbool.choices.invalid=Invalid input. Please input one of {0}. +promptbool.choices.yes1=Y +promptbool.choices.yes2=yes +promptbool.choices.no1=N +promptbool.choices.no2=no + +promptchoice.outofbounds=Please choose something between {0} and {1}. The choices were: +promptchoice.formaterr=The input seems to be something that is not an integer.\ +Please choose something between {0} and {1}. The choices were: + +promptlongtext.exit.defaultkey=\\q +promptlongtext.exit.dispkey=\ (exit with a new line made of "{0}") + +unrecognized.cmd=Unrecognized command "{0}" +expected.cmd=A Command was expected but nothing was provided... diff --git a/gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java b/gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java index 8742860..ec673ad 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java +++ b/gclc/src/test/java/fr/bigeon/gclc/CommandTestingApplication.java @@ -1,123 +1,156 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.CommandTestingApplication.java - * Created on: Jun 12, 2016 - */ -package fr.bigeon.gclc; - -import java.io.IOException; - -import fr.bigeon.gclc.command.ICommand; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.manager.PipedConsoleInput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon - * - */ -@SuppressWarnings("javadoc") -public class CommandTestingApplication implements AutoCloseable { - - private final ConsoleApplication application; - private final Thread th; - private final PipedConsoleOutput out; - private final PipedConsoleInput in; - - /** @throws IOException if the streams cannot be build */ - public CommandTestingApplication() throws IOException { - out = new PipedConsoleOutput(); - in = new PipedConsoleInput(null); - application = new ConsoleApplication(out, in, "", ""); - new ConsoleTestApplication().attach(application); - th = new Thread(new Runnable() { - - @SuppressWarnings("synthetic-access") - @Override - public void run() { - application.start(); - } - }); - - th.start(); - } - - /** @param cmd the command - * @return if the command was added - * @throws InvalidCommandName if the command name is invalid - * @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */ - public final boolean add(final ICommand cmd) throws InvalidCommandName { - return application.add(cmd); - } - - @Override - public void close() throws IOException { - application.exit(); - out.close(); - in.close(); - } - - /** @return the application */ - public ConsoleApplication getApplication() { - return application; - } - - /** @return the next written line, null if it is the prompt - * @throws IOException if the reading failed */ - public String readNextLine() throws IOException { - final String ret = out.readNextLine(); - return ret; - } - - public void sendCommand(final String cmd) throws IOException { - in.type(cmd); - } - - /** @throws IOException if the writing failed */ - public void waitAndStop() throws IOException { - in.type(ConsoleTestApplication.EXIT); - try { - th.join(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.CommandTestingApplication.java + * Created on: Jun 12, 2016 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.command.ICommand; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.utils.PipedConsoleInput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon + * + */ +@SuppressWarnings("javadoc") +public class CommandTestingApplication implements AutoCloseable { + + private final ConsoleApplication application; + private final Thread th; + private final PipedConsoleOutput out; + private final PipedConsoleInput in; + + /** @throws IOException if the streams cannot be build */ + public CommandTestingApplication() throws IOException { + out = new PipedConsoleOutput(); + in = new PipedConsoleInput(null); + application = new ConsoleApplication(out, in, "", ""); + new ConsoleTestApplication().attach(application); + th = new Thread(new Runnable() { + + @SuppressWarnings("synthetic-access") + @Override + public void run() { + application.start(); + } + }); + + th.start(); + } + + /** @param cmd the command + * @return if the command was added + * @throws InvalidCommandName if the command name is invalid + * @see fr.bigeon.gclc.ConsoleApplication#add(fr.bigeon.gclc.command.ICommand) */ + public final boolean add(final ICommand cmd) throws InvalidCommandName { + return application.add(cmd); + } + + @Override + public void close() throws IOException { + application.exit(); + out.close(); + in.close(); + } + + /** @return the application */ + public ConsoleApplication getApplication() { + return application; + } + + /** @return the next written line, null if it is the prompt + * @throws IOException if the reading failed */ + public String readNextLine() throws IOException { + final String ret = out.readNextLine(); + return ret; + } + + public void sendCommand(final String cmd) throws IOException { + in.type(cmd); + } + + /** @throws IOException if the writing failed */ + public void waitAndStop() throws IOException { + in.type(ConsoleTestApplication.EXIT); + try { + th.join(); + } catch (final InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java b/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java index 008d2ca..571d5bd 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/ConsoleApplicationTest.java @@ -1,247 +1,279 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.ConsoleApplicationTest.java - * Created on: Jun 9, 2016 - */ -package fr.bigeon.gclc; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -import org.junit.Test; - -import fr.bigeon.gclc.command.ExitCommand; -import fr.bigeon.gclc.command.ICommand; -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.i18n.Messages; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.manager.PipedConsoleInput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** Test class for ConsoleApplication - * - * @author Emmanuel Bigeon */ -@SuppressWarnings({"javadoc", "nls", "static-method"}) -public class ConsoleApplicationTest { - - /** 3 seconds in milliseconds */ - protected static final long THREE_SECONDS = 3000; - - /** Test the base of a console application */ - @Test - public void testConsoleApplication() { - - try (PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final ConsoleApplication app = new ConsoleApplication(null, in, - "", ""); - app.exit(); - } catch (final IOException e) { - fail("System Console Manager failed"); - } - - } - - @Test - public void testExecution() throws IOException, InterruptedException, - InvalidCommandName { - try (CommandTestingApplication application = new CommandTestingApplication()) { - - // remove welcome - assertEquals("Header should be preserved", - application.getApplication().header, - application.readNextLine()); - // Remove first prompt - application.sendCommand(""); - application.sendCommand("test"); - assertEquals("Test should run", "Test command ran fine", - application.readNextLine()); - application.sendCommand("toto"); - assertEquals("Command fail should dispaly appropriate message", - Messages.getString("ConsoleApplication.cmd.failed", "toto"), - application.readNextLine()); - assertEquals( - "Unrecognized comment should result in a specific message.", - Messages.getString("CommandProvider.unrecognized", "toto"), - application.readNextLine()); - application.sendCommand("long"); - assertEquals("Before wait should receive message", "Waita minute", - application.readNextLine()); - assertEquals("Unexpected message", "done!", - application.readNextLine()); - - final CommandRequestListener crl = new CommandRequestListener() { - - @Override - public void commandRequest(final String command) { - // - } - }; - final CommandRequestListener crl2 = new CommandRequestListener() { - - @Override - public void commandRequest(final String command) { - // - } - }; - application.getApplication().addListener(crl); - application.getApplication().addListener(crl2); - application.sendCommand("test"); - assertEquals("Unexpected message", "Test command ran fine", - application.readNextLine()); - application.getApplication().removeListener(crl2); - application.getApplication().removeListener(crl); - application.getApplication().removeListener(crl); - - assertTrue("Unclosed application should be running", - application.getApplication().isRunning()); - - application.sendCommand("exit"); - assertEquals("Footer should be preserved", - application.getApplication().footer, - application.readNextLine()); - assertFalse("Stopped application should not be running", - application.getApplication().isRunning()); - } - - ConsoleApplication appli = null; - try (PipedConsoleOutput manager = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final ConsoleApplication app = new ConsoleApplication(manager, in, - null, null); - appli = app; - app.add(new ExitCommand("exit", app)); - - final Thread th = new Thread(new Runnable() { - - @SuppressWarnings("synthetic-access") - @Override - public void run() { - app.start(); - } - }); - th.start(); - in.type("exit"); - th.join(); - } - - assertNotNull( - "Application should still exist even if the console input and output are closed.", - appli); - appli.start(); - assertFalse( - "Application should not start on closed console input and output", - appli.isRunning()); - } - - @Test - public void testInterpretCommand() throws InvalidCommandName, IOException { - try (PipedConsoleInput test = new PipedConsoleInput(null); - PipedConsoleOutput out = new PipedConsoleOutput()) { - final ConsoleApplication appl = new ConsoleApplication(out, test, - "", ""); - - appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); - assertEquals("Specific error message expected", - "Command line cannot be parsed", out.readNextLine()); - - appl.interpretCommand(""); - - final String message = "message"; - appl.add(new ICommand() { - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. - * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, - * java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - throw new CommandRunException(CommandRunExceptionType.USAGE, - message, this); - } - - @Override - public String getCommandName() { - return "fail"; - } - - @Override - public void help(final ConsoleOutput manager, - final String... args) throws IOException { - manager.println(message); - } - - @Override - public String tip() { - return ""; - } - - }); - appl.interpretCommand("fail"); - assertEquals("Unexpected message", - Messages.getString("ConsoleApplication.cmd.failed", "fail"), - out.readNextLine()); - assertEquals("Unexpected message", message, out.readNextLine()); - assertEquals("Unexpected message", message, out.readNextLine()); - - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.ConsoleApplicationTest.java + * Created on: Jun 9, 2016 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +import fr.bigeon.gclc.command.ICommand; +import fr.bigeon.gclc.command.base.ExitCommand; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.i18n.Messages; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.utils.PipedConsoleInput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** Test class for ConsoleApplication + * + * @author Emmanuel Bigeon */ +@SuppressWarnings({"javadoc", "nls", "static-method"}) +public class ConsoleApplicationTest { + + /** 3 seconds in milliseconds */ + protected static final long THREE_SECONDS = 3000; + + /** Test the base of a console application */ + @Test + public void testConsoleApplication() { + + try (PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final ConsoleApplication app = new ConsoleApplication(null, in, + "", ""); + app.exit(); + } catch (final IOException e) { + fail("System Console Manager failed"); + } + + } + + @Test + public void testExecution() throws IOException, InterruptedException, + InvalidCommandName { + try (CommandTestingApplication application = new CommandTestingApplication()) { + + // remove welcome + assertEquals("Header should be preserved", + application.getApplication().header, + application.readNextLine()); + // Remove first prompt + application.sendCommand(""); + application.sendCommand("test"); + assertEquals("Test should run", "Test command ran fine", + application.readNextLine()); + application.sendCommand("toto"); + assertEquals("Command fail should dispaly appropriate message", + Messages.getString("ConsoleApplication.cmd.failed", "toto"), + application.readNextLine()); + assertEquals( + "Unrecognized comment should result in a specific message.", + Messages.getString("CommandProvider.unrecognized", "toto"), + application.readNextLine()); + application.sendCommand("long"); + assertEquals("Before wait should receive message", "Waita minute", + application.readNextLine()); + assertEquals("Unexpected message", "done!", + application.readNextLine()); + + final CommandRequestListener crl = new CommandRequestListener() { + + @Override + public void commandRequest(final String command) { + // + } + }; + final CommandRequestListener crl2 = new CommandRequestListener() { + + @Override + public void commandRequest(final String command) { + // + } + }; + application.getApplication().addListener(crl); + application.getApplication().addListener(crl2); + application.sendCommand("test"); + assertEquals("Unexpected message", "Test command ran fine", + application.readNextLine()); + application.getApplication().removeListener(crl2); + application.getApplication().removeListener(crl); + application.getApplication().removeListener(crl); + + assertTrue("Unclosed application should be running", + application.getApplication().isRunning()); + + application.sendCommand("exit"); + assertEquals("Footer should be preserved", + application.getApplication().footer, + application.readNextLine()); + assertFalse("Stopped application should not be running", + application.getApplication().isRunning()); + } + + ConsoleApplication appli = null; + try (PipedConsoleOutput manager = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final ConsoleApplication app = new ConsoleApplication(manager, in, + null, null); + appli = app; + app.add(new ExitCommand("exit", app)); + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + app.start(); + } + }); + th.start(); + in.type("exit"); + th.join(); + } + + assertNotNull( + "Application should still exist even if the console input and output are closed.", + appli); + appli.start(); + assertFalse( + "Application should not start on closed console input and output", + appli.isRunning()); + } + + @Test + public void testInterpretCommand() throws InvalidCommandName, IOException { + try (PipedConsoleInput test = new PipedConsoleInput(null); + PipedConsoleOutput out = new PipedConsoleOutput()) { + final ConsoleApplication appl = new ConsoleApplication(out, test, + "", ""); + + appl.interpretCommand("invalid cmd \"due to misplaced\"quote"); + assertEquals("Specific error message expected", + "Command line cannot be parsed", out.readNextLine()); + + appl.interpretCommand(""); + + final String message = "message"; + appl.add(new ICommand() { + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. + * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, + * java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + throw new CommandRunException(CommandRunExceptionType.USAGE, + message); + } + + @Override + public String getCommandName() { + return "fail"; + } + + @Override + public void help(final ConsoleOutput manager, + final String... args) throws IOException { + manager.println(message); + } + + @Override + public String tip() { + return ""; + } + + }); + appl.interpretCommand("fail"); + assertEquals("Unexpected message", + Messages.getString("ConsoleApplication.cmd.failed", "fail"), + out.readNextLine()); + assertEquals("Unexpected message", message, out.readNextLine()); + assertEquals("Unexpected message", message, out.readNextLine()); + + } + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java b/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java index bb9d655..fe8ee7f 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java +++ b/gclc/src/test/java/fr/bigeon/gclc/ConsoleTestApplication.java @@ -1,152 +1,179 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -package fr.bigeon.gclc; - -import java.io.IOException; - -import fr.bigeon.gclc.command.Command; -import fr.bigeon.gclc.command.ExitCommand; -import fr.bigeon.gclc.command.HelpExecutor; -import fr.bigeon.gclc.command.ICommandProvider; -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; - -/** A test-purpose application - * - * @author Emmanuel Bigeon */ -public class ConsoleTestApplication implements ApplicationAttachement { - - /** Exit command */ - public static final String EXIT = "exit"; //$NON-NLS-1$ - /** Two seconds in milliseconds */ - protected static final long TWO_SECONDS = 2000; - - /***/ - @Override - @SuppressWarnings("nls") - public void attach(final ICommandProvider application) { - try { - application.add(new ExitCommand(EXIT, (ConsoleApplication) application)); - application.add(new HelpExecutor("help", - ((ConsoleApplication) application).root)); - application.add(new Command("test") { - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. - * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, - * java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - try { - out.println("Test command ran fine"); - } catch (final IOException e) { - throw new CommandRunException("manager closed", e, - this); - } - } - - @Override - public String tip() { - return "A test command"; - } - - @Override - protected String usageDetail() { - return null; - } - }); - application.add(new Command("long") { - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. - * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, - * java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - try { - out.println("Waita minute"); - Thread.sleep(TWO_SECONDS); - out.println("done!"); - } catch (final IOException e) { - throw new CommandRunException("manager closed", e, - this); - } catch (final InterruptedException e) { - throw new CommandRunException("wait interrupted", e, - this); - } - } - - @Override - public String tip() { - return "A long execution command"; - } - - @Override - protected String usageDetail() { - return null; - } - }); - application.add(new Command("failingCmd") { - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. - * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, - * java.lang.String[]) */ - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - throw new CommandRunException("Failing command", this); - } - - @Override - public String tip() { - return "A long execution command"; - } - - @Override - protected String usageDetail() { - return null; - } - }); - } catch (final InvalidCommandName e) { - e.printStackTrace(); - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import java.io.IOException; + +import fr.bigeon.gclc.command.Command; +import fr.bigeon.gclc.command.HelpExecutor; +import fr.bigeon.gclc.command.ICommandProvider; +import fr.bigeon.gclc.command.base.ExitCommand; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; + +/** A test-purpose application + * + * @author Emmanuel Bigeon */ +public class ConsoleTestApplication implements ApplicationAttachement { + + /** Exit command */ + public static final String EXIT = "exit"; //$NON-NLS-1$ + /** Two seconds in milliseconds */ + protected static final long TWO_SECONDS = 2000; + + /***/ + @Override + @SuppressWarnings("nls") + public void attach(final ICommandProvider application) { + try { + application.add(new ExitCommand(EXIT, (ConsoleApplication) application)); + application.add( + new HelpExecutor("help", ((ConsoleApplication) application).root)); + application.add(new Command("test") { + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. + * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, + * java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + try { + out.println("Test command ran fine"); + } catch (final IOException e) { + throw new CommandRunException("manager closed", e); + } + } + + @Override + public String tip() { + return "A test command"; + } + + @Override + protected String usageDetail() { + return null; + } + }); + application.add(new Command("long") { + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. + * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, + * java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + try { + out.println("Waita minute"); + Thread.sleep(TWO_SECONDS); + out.println("done!"); + } catch (final IOException e) { + throw new CommandRunException("manager closed", e); + } catch (final InterruptedException e) { + throw new CommandRunException("wait interrupted", e); + } + } + + @Override + public String tip() { + return "A long execution command"; + } + + @Override + protected String usageDetail() { + return null; + } + }); + application.add(new Command("failingCmd") { + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.ICommand#execute(fr.bigeon.gclc. + * manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, + * java.lang.String[]) */ + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + throw new CommandRunException("Failing command"); + } + + @Override + public String tip() { + return "A long execution command"; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + e.printStackTrace(); + } + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java b/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java index 850c485..1abbc07 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/GCLCConstantsTest.java @@ -1,128 +1,161 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.GCLCConstantsTest.java - * Created on: Jun 8, 2016 - */ -package fr.bigeon.gclc; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.List; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandParsingException; - -/** Test class for {@link GCLCConstants} - * - * @author Emmanuel Bigeon */ -@SuppressWarnings({"nls", "static-method"}) -public class GCLCConstantsTest { - - /** Test method for - * {@link fr.bigeon.gclc.GCLCConstants#splitCommand(java.lang.String)}. - * - * @throws CommandParsingException if an error occured */ - @Test - public void testSplitCommand() throws CommandParsingException { - List res; - res = GCLCConstants.splitCommand("aCommand"); - assertTrue("single word command should have one element", - res.size() == 1); - assertTrue("Command should be preserved", - res.get(0).equals("aCommand")); - - res = GCLCConstants.splitCommand("aCommand with some arguments"); - assertEquals("Command size", 4, res.size()); - assertEquals("Elements should be preserved", "aCommand", res.get(0)); - assertTrue("Elements should be preserved", res.get(1).equals("with")); - assertTrue("Elements should be preserved", res.get(2).equals("some")); - assertTrue("Elements should be preserved", - res.get(3).equals("arguments")); - res = GCLCConstants.splitCommand("aCommand with some arguments"); - assertEquals("Command size", 4, res.size()); - assertTrue("Elements should be preserved", - res.get(0).equals("aCommand")); - assertTrue("Elements should be preserved", res.get(1).equals("with")); - assertTrue("Elements should be preserved", res.get(2).equals("some")); - assertTrue("Elements should be preserved", - res.get(3).equals("arguments")); - res = GCLCConstants.splitCommand("aCommand \"with some\" arguments"); - assertEquals("Command size", 3, res.size()); - assertTrue("Elements should be preserved", - res.get(0).equals("aCommand")); - assertTrue("Elements should be preserved", - res.get(1).equals("with some")); - assertTrue("Elements should be preserved", - res.get(2).equals("arguments")); - res = GCLCConstants.splitCommand("aCommand with\\ some arguments"); - assertEquals("Command size", 3, res.size()); - assertTrue("Elements should be preserved", - res.get(0).equals("aCommand")); - assertTrue("Elements should be preserved", - res.get(1).equals("with some")); - assertTrue("Elements should be preserved", - res.get(2).equals("arguments")); - res = GCLCConstants.splitCommand("aCommand wi\\\"th some arguments"); - assertEquals("Command size", 4, res.size()); - assertTrue("Elements should be preserved", - res.get(0).equals("aCommand")); - assertTrue("Elements should be preserved", res.get(1).equals("wi\"th")); - assertTrue("Elements should be preserved", res.get(2).equals("some")); - assertTrue("Elements should be preserved", - res.get(3).equals("arguments")); - - res = GCLCConstants.splitCommand("aCommand with \"some arguments\""); - assertEquals("Command size", 3, res.size()); - assertTrue("Elements should be preserved", - res.get(0).equals("aCommand")); - assertTrue("Elements should be preserved", res.get(1).equals("with")); - assertTrue("Elements should be preserved", - res.get(2).equals("some arguments")); - - try { - // Wrong lines? - res = GCLCConstants - .splitCommand("aCommand with \"some ar\"guments"); - fail("Misplaced quotes should fail"); - } catch (final CommandParsingException e) { - // ok - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.GCLCConstantsTest.java + * Created on: Jun 8, 2016 + */ +package fr.bigeon.gclc; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; + +import org.junit.Test; + +import fr.bigeon.gclc.exception.CommandParsingException; + +/** Test class for {@link GCLCConstants} + * + * @author Emmanuel Bigeon */ +@SuppressWarnings({"nls", "static-method"}) +public class GCLCConstantsTest { + + /** Test method for + * {@link fr.bigeon.gclc.GCLCConstants#splitCommand(java.lang.String)}. + * + * @throws CommandParsingException if an error occured */ + @Test + public void testSplitCommand() throws CommandParsingException { + List res; + res = GCLCConstants.splitCommand("aCommand"); + assertTrue("single word command should have one element", + res.size() == 1); + assertTrue("Command should be preserved", + res.get(0).equals("aCommand")); + + res = GCLCConstants.splitCommand("aCommand with some arguments"); + assertEquals("Command size", 4, res.size()); + assertEquals("Elements should be preserved", "aCommand", res.get(0)); + assertTrue("Elements should be preserved", res.get(1).equals("with")); + assertTrue("Elements should be preserved", res.get(2).equals("some")); + assertTrue("Elements should be preserved", + res.get(3).equals("arguments")); + res = GCLCConstants.splitCommand("aCommand with some arguments"); + assertEquals("Command size", 4, res.size()); + assertTrue("Elements should be preserved", + res.get(0).equals("aCommand")); + assertTrue("Elements should be preserved", res.get(1).equals("with")); + assertTrue("Elements should be preserved", res.get(2).equals("some")); + assertTrue("Elements should be preserved", + res.get(3).equals("arguments")); + res = GCLCConstants.splitCommand("aCommand \"with some\" arguments"); + assertEquals("Command size", 3, res.size()); + assertTrue("Elements should be preserved", + res.get(0).equals("aCommand")); + assertTrue("Elements should be preserved", + res.get(1).equals("with some")); + assertTrue("Elements should be preserved", + res.get(2).equals("arguments")); + res = GCLCConstants.splitCommand("aCommand with\\ some arguments"); + assertEquals("Command size", 3, res.size()); + assertTrue("Elements should be preserved", + res.get(0).equals("aCommand")); + assertTrue("Elements should be preserved", + res.get(1).equals("with some")); + assertTrue("Elements should be preserved", + res.get(2).equals("arguments")); + res = GCLCConstants.splitCommand("aCommand wi\\\"th some arguments"); + assertEquals("Command size", 4, res.size()); + assertTrue("Elements should be preserved", + res.get(0).equals("aCommand")); + assertTrue("Elements should be preserved", res.get(1).equals("wi\"th")); + assertTrue("Elements should be preserved", res.get(2).equals("some")); + assertTrue("Elements should be preserved", + res.get(3).equals("arguments")); + + res = GCLCConstants.splitCommand("aCommand with \"some arguments\""); + assertEquals("Command size", 3, res.size()); + assertTrue("Elements should be preserved", + res.get(0).equals("aCommand")); + assertTrue("Elements should be preserved", res.get(1).equals("with")); + assertTrue("Elements should be preserved", + res.get(2).equals("some arguments")); + + try { + // Wrong lines? + res = GCLCConstants + .splitCommand("aCommand with \"some ar\"guments"); + fail("Misplaced quotes should fail"); + } catch (final CommandParsingException e) { + // ok + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/CommandParametersTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/CommandParametersTest.java index 1c35de0..20fbf0d 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/CommandParametersTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/CommandParametersTest.java @@ -1,328 +1,361 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.CommandParametersTest.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandParsingException; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -@SuppressWarnings({"static-method", "nls"}) -public class CommandParametersTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. - * - * @throws CommandParsingException if an unexpected exception is thrown */ - @Test - public final void testCommandParameters() throws CommandParsingException { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - CommandParameters parameters = new CommandParameters(bools, strings, - true); - - try { - parameters.parseArgs("-ungivenFlag"); - fail("parse of unknown in strict should fail"); - } catch (final CommandParsingException e) { - // ok - } - parameters = new CommandParameters(bools, strings, false); - - parameters.parseArgs("-ungivenFlag"); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. - * - * @throws CommandParsingException if an exception occired */ - @Test - public final void testGet() throws CommandParsingException { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - final CommandParameters parameters = new CommandParameters(bools, - strings, true); - - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - try { - parameters.parseArgs("-ungiven", "val"); - fail("Missing parameter should fail for strict element"); - } catch (final CommandParsingException e) { - // ok - } - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - parameters.parseArgs("-str", "val"); - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - - try { - parameters.parseArgs("-ungiven"); - fail("Invalid argument type parsing should fail"); - } catch (final CommandParsingException e) { - // ok - } - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */ - @Test - public final void testGetAdditionals() throws CommandParsingException { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - CommandParameters parameters = new CommandParameters(bools, strings, - true); - - parameters.parseArgs("-boolFlag"); - assertTrue(parameters.getAdditionals().isEmpty()); - - try { - parameters.parseArgs("-ungiven"); - fail("Should fail"); - } catch (final CommandParsingException e) { - // ok - } - assertTrue(parameters.getAdditionals().isEmpty()); - - parameters = new CommandParameters(bools, strings, false); - - parameters.parseArgs("-boolFlag"); - assertTrue(parameters.getAdditionals().isEmpty()); - - parameters.parseArgs("ungiven"); - assertTrue(parameters.getAdditionals().contains("ungiven")); - assertEquals(1, parameters.getAdditionals().size()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. - * - * @throws CommandParsingException if a command parsing failed */ - @Test - public final void testGetBool() throws CommandParsingException { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - CommandParameters parameters = new CommandParameters(bools, strings, - true); - - assertFalse(parameters.getBool("ungiven")); - assertFalse(parameters.getBool("boolFlag")); - - parameters.parseArgs("-boolFlag"); - assertTrue(parameters.getBool("boolFlag")); - assertFalse(parameters.getBool("ungiven")); - - try { - parameters.parseArgs("-ungiven"); - fail("unknown parameter should fail"); - } catch (final CommandParsingException e) { - // ok - } - assertFalse(parameters.getBool("ungiven")); - assertTrue(parameters.getBool("boolFlag")); - - parameters = new CommandParameters(bools, strings, false); - - assertFalse(parameters.getBool("ungiven")); - assertFalse(parameters.getBool("boolFlag")); - - try { - parameters.parseArgs("-boolFlag"); - } catch (final CommandParsingException e) { - // ok - } - assertTrue(parameters.getBool("boolFlag")); - assertFalse(parameters.getBool("ungiven")); - - try { - parameters.parseArgs("-ungiven"); - } catch (final CommandParsingException e) { - // ok - } - assertFalse(parameters.getBool("ungiven")); - assertTrue(parameters.getBool("boolFlag")); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. - * - * @throws CommandParsingException if a command parsing failed */ - @Test - public final void testParseArgs() throws CommandParsingException { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - final CommandParameters parameters = new CommandParameters(bools, - strings, true); - - try { - parameters.parseArgs("-ungivenFlag"); - fail("Strict should fail with flag"); - } catch (final CommandParsingException e) { - // ok - } - try { - parameters.parseArgs("-str"); - fail("String argument without second element should fail"); - } catch (final CommandParsingException e) { - // ok - } - parameters.parseArgs("-boolFlag"); - parameters.parseArgs("-str", "-boolFlag"); - parameters.parseArgs("-boolFlag", "-str", "val"); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */ - @Test - public final void testSetStringBoolean() { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - CommandParameters parameters = new CommandParameters(bools, strings, - true); - - assertFalse(parameters.getBool("ungiven")); - assertFalse(parameters.getBool("boolFlag")); - - parameters.set("boolFlag", true); - assertTrue(parameters.getBool("boolFlag")); - assertFalse(parameters.getBool("ungiven")); - - parameters.set("ungiven", true); - assertFalse(parameters.getBool("ungiven")); - assertTrue(parameters.getBool("boolFlag")); - - parameters = new CommandParameters(bools, strings, false); - - assertFalse(parameters.getBool("ungiven")); - assertFalse(parameters.getBool("boolFlag")); - - parameters.set("boolFlag", true); - assertTrue(parameters.getBool("boolFlag")); - assertFalse(parameters.getBool("ungiven")); - - parameters.set("ungiven", true); - assertFalse(parameters.getBool("ungiven")); - assertTrue(parameters.getBool("boolFlag")); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */ - @Test - public final void testSetStringString() { - final Set strings = new HashSet<>(); - final Set bools = new HashSet<>(); - - bools.add("boolFlag"); - strings.add("str"); - - CommandParameters parameters = new CommandParameters(bools, strings, - true); - - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - parameters.set("ungiven", "val"); - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - parameters.set("str", "val"); - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - - parameters.set("ungiven", "val"); - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - - parameters = new CommandParameters(bools, strings, false); - - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - parameters.set("ungiven", "val"); - assertNull(parameters.get("ungiven")); - assertNull(parameters.get("str")); - - parameters.set("str", "val"); - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - - parameters.set("ungiven", "val"); - assertNull(parameters.get("ungiven")); - assertEquals("val", parameters.get("str")); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.CommandParametersTest.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +import fr.bigeon.gclc.exception.CommandParsingException; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +@SuppressWarnings({"static-method", "nls"}) +public class CommandParametersTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#CommandParameters(java.util.Set, java.util.Set, boolean)}. + * + * @throws CommandParsingException if an unexpected exception is thrown */ + @Test + public final void testCommandParameters() throws CommandParsingException { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + CommandParameters parameters = new CommandParameters(bools, strings, + true); + + try { + parameters.parseArgs("-ungivenFlag"); + fail("parse of unknown in strict should fail"); + } catch (final CommandParsingException e) { + // ok + } + parameters = new CommandParameters(bools, strings, false); + + parameters.parseArgs("-ungivenFlag"); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#get(java.lang.String)}. + * + * @throws CommandParsingException if an exception occired */ + @Test + public final void testGet() throws CommandParsingException { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + final CommandParameters parameters = new CommandParameters(bools, + strings, true); + + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + try { + parameters.parseArgs("-ungiven", "val"); + fail("Missing parameter should fail for strict element"); + } catch (final CommandParsingException e) { + // ok + } + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + parameters.parseArgs("-str", "val"); + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + + try { + parameters.parseArgs("-ungiven"); + fail("Invalid argument type parsing should fail"); + } catch (final CommandParsingException e) { + // ok + } + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#getAdditionals()}. */ + @Test + public final void testGetAdditionals() throws CommandParsingException { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + CommandParameters parameters = new CommandParameters(bools, strings, + true); + + parameters.parseArgs("-boolFlag"); + assertTrue(parameters.getAdditionals().isEmpty()); + + try { + parameters.parseArgs("-ungiven"); + fail("Should fail"); + } catch (final CommandParsingException e) { + // ok + } + assertTrue(parameters.getAdditionals().isEmpty()); + + parameters = new CommandParameters(bools, strings, false); + + parameters.parseArgs("-boolFlag"); + assertTrue(parameters.getAdditionals().isEmpty()); + + parameters.parseArgs("ungiven"); + assertTrue(parameters.getAdditionals().contains("ungiven")); + assertEquals(1, parameters.getAdditionals().size()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#getBool(java.lang.String)}. + * + * @throws CommandParsingException if a command parsing failed */ + @Test + public final void testGetBool() throws CommandParsingException { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + CommandParameters parameters = new CommandParameters(bools, strings, + true); + + assertFalse(parameters.getBool("ungiven")); + assertFalse(parameters.getBool("boolFlag")); + + parameters.parseArgs("-boolFlag"); + assertTrue(parameters.getBool("boolFlag")); + assertFalse(parameters.getBool("ungiven")); + + try { + parameters.parseArgs("-ungiven"); + fail("unknown parameter should fail"); + } catch (final CommandParsingException e) { + // ok + } + assertFalse(parameters.getBool("ungiven")); + assertTrue(parameters.getBool("boolFlag")); + + parameters = new CommandParameters(bools, strings, false); + + assertFalse(parameters.getBool("ungiven")); + assertFalse(parameters.getBool("boolFlag")); + + try { + parameters.parseArgs("-boolFlag"); + } catch (final CommandParsingException e) { + // ok + } + assertTrue(parameters.getBool("boolFlag")); + assertFalse(parameters.getBool("ungiven")); + + try { + parameters.parseArgs("-ungiven"); + } catch (final CommandParsingException e) { + // ok + } + assertFalse(parameters.getBool("ungiven")); + assertTrue(parameters.getBool("boolFlag")); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#parseArgs(java.lang.String[])}. + * + * @throws CommandParsingException if a command parsing failed */ + @Test + public final void testParseArgs() throws CommandParsingException { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + final CommandParameters parameters = new CommandParameters(bools, + strings, true); + + try { + parameters.parseArgs("-ungivenFlag"); + fail("Strict should fail with flag"); + } catch (final CommandParsingException e) { + // ok + } + try { + parameters.parseArgs("-str"); + fail("String argument without second element should fail"); + } catch (final CommandParsingException e) { + // ok + } + parameters.parseArgs("-boolFlag"); + parameters.parseArgs("-str", "-boolFlag"); + parameters.parseArgs("-boolFlag", "-str", "val"); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, boolean)}. */ + @Test + public final void testSetStringBoolean() { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + CommandParameters parameters = new CommandParameters(bools, strings, + true); + + assertFalse(parameters.getBool("ungiven")); + assertFalse(parameters.getBool("boolFlag")); + + parameters.set("boolFlag", true); + assertTrue(parameters.getBool("boolFlag")); + assertFalse(parameters.getBool("ungiven")); + + parameters.set("ungiven", true); + assertFalse(parameters.getBool("ungiven")); + assertTrue(parameters.getBool("boolFlag")); + + parameters = new CommandParameters(bools, strings, false); + + assertFalse(parameters.getBool("ungiven")); + assertFalse(parameters.getBool("boolFlag")); + + parameters.set("boolFlag", true); + assertTrue(parameters.getBool("boolFlag")); + assertFalse(parameters.getBool("ungiven")); + + parameters.set("ungiven", true); + assertFalse(parameters.getBool("ungiven")); + assertTrue(parameters.getBool("boolFlag")); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandParameters#set(java.lang.String, java.lang.String)}. */ + @Test + public final void testSetStringString() { + final Set strings = new HashSet<>(); + final Set bools = new HashSet<>(); + + bools.add("boolFlag"); + strings.add("str"); + + CommandParameters parameters = new CommandParameters(bools, strings, + true); + + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + parameters.set("ungiven", "val"); + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + parameters.set("str", "val"); + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + + parameters.set("ungiven", "val"); + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + + parameters = new CommandParameters(bools, strings, false); + + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + parameters.set("ungiven", "val"); + assertNull(parameters.get("ungiven")); + assertNull(parameters.get("str")); + + parameters.set("str", "val"); + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + + parameters.set("ungiven", "val"); + assertNull(parameters.get("ungiven")); + assertEquals("val", parameters.get("str")); + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/CommandProviderTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/CommandProviderTest.java index adf0755..5be6378 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/CommandProviderTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/CommandProviderTest.java @@ -1,98 +1,132 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.CommandProviderTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.fail; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.InvalidCommandName; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class CommandProviderTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}. - * - * @throws InvalidCommandName if the test failed */ - @Test - public final void testAdd() throws InvalidCommandName { - final CommandProvider provider = new CommandProvider(); - try { - provider.add(new MockCommand(null)); - fail("null name for command should be rejected"); - } catch (final InvalidCommandName e) { - // ok - } - try { - provider.add(new MockCommand("")); - fail("null name for command should be rejected"); - } catch (final InvalidCommandName e) { - // ok - } - try { - provider.add(new MockCommand("-name")); - fail("name with minus as starting character for command should be rejected"); - } catch (final InvalidCommandName e) { - // ok - } - try { - provider.add(new MockCommand("name command")); - fail("name with space for command should be rejected"); - } catch (final InvalidCommandName e) { - // ok - } - final ICommand mock = new MockCommand("name"); - provider.add(mock); - - try { - provider.add(new MockCommand(mock.getCommandName())); - fail("already existing command name should be rejected"); - } catch (final InvalidCommandName e) { - // ok - } - - provider.add(mock); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.CommandProviderTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.fail; + +import org.junit.Test; + +import fr.bigeon.gclc.command.base.MockCommand; +import fr.bigeon.gclc.exception.InvalidCommandName; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class CommandProviderTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.CommandProvider#add(fr.bigeon.gclc.command.ICommand)}. + * + * @throws InvalidCommandName if the test failed */ + @Test + public final void testAdd() throws InvalidCommandName { + final CommandProvider provider = new CommandProvider(); + try { + provider.add(new MockCommand(null)); + fail("null name for command should be rejected"); + } catch (final InvalidCommandName e) { + // ok + } + try { + provider.add(new MockCommand("")); + fail("null name for command should be rejected"); + } catch (final InvalidCommandName e) { + // ok + } + try { + provider.add(new MockCommand("-name")); + fail("name with minus as starting character for command should be rejected"); + } catch (final InvalidCommandName e) { + // ok + } + try { + provider.add(new MockCommand("name command")); + fail("name with space for command should be rejected"); + } catch (final InvalidCommandName e) { + // ok + } + final ICommand mock = new MockCommand("name"); + provider.add(mock); + + try { + provider.add(new MockCommand(mock.getCommandName())); + fail("already existing command name should be rejected"); + } catch (final InvalidCommandName e) { + // ok + } + + provider.add(mock); + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java index 3ad8b50..f71f5c8 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/CommandTest.java @@ -1,376 +1,409 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.CommandTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/**

- * TODO - * - * @author Emmanuel Bigeon */ -public class CommandTest { - - @Test - public final void testCommand() throws IOException { - try (PipedConsoleOutput test = new PipedConsoleOutput()) { - Command cmd; - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.help(test); - - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // details - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // details - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#brief() */ - @Override - protected String brief() { - return null; - } - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // details - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#brief() */ - @Override - protected String brief() { - return "brief"; - } - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // details - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @Override - protected String usageDetail() { - return null; - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // details - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @Override - protected String usageDetail() { - return "details"; - } - }; - cmd.help(test); - - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // pattern - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // details - assertEquals("Unexpected detail", "details", test.readNextLine()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @Override - protected String usageDetail() { - return "details" + System.lineSeparator(); - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // pattern - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // details - assertEquals("Unexpected detail", "details", test.readNextLine()); - assertFalse("Only 6 line should be printed", test.available()); - - cmd = new Command("name") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return "tip"; - } - - /* (non-Javadoc) - * @see fr.bigeon.gclc.command.Command#usageDetail() */ - @Override - protected String usageDetail() { - return "\n"; - } - }; - cmd.help(test); - // name - assertEquals("First line should be command name", "name", - test.readNextLine()); - // tip - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // Usage - test.readNextLine(); - // pattern - test.readNextLine(); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - // - assertTrue("Section line is empty", test.readNextLine().isEmpty()); - assertFalse("Only 6 line should be printed", test.available()); - - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.CommandTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.junit.Test; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/**

+ * TODO + * + * @author Emmanuel Bigeon */ +public class CommandTest { + + @Test + public final void testCommand() throws IOException { + try (PipedConsoleOutput test = new PipedConsoleOutput()) { + Command cmd; + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // details + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // details + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#brief() */ + @Override + protected String brief() { + return null; + } + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // details + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#brief() */ + @Override + protected String brief() { + return "brief"; + } + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // details + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return null; + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // details + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return "details"; + } + }; + cmd.help(test); + + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // pattern + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // details + assertEquals("Unexpected detail", "details", test.readNextLine()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return "details" + System.lineSeparator(); + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // pattern + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // details + assertEquals("Unexpected detail", "details", test.readNextLine()); + assertFalse("Only 6 line should be printed", test.available()); + + cmd = new Command("name") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return "tip"; + } + + /* (non-Javadoc) + * @see fr.bigeon.gclc.command.Command#usageDetail() */ + @Override + protected String usageDetail() { + return "\n"; + } + }; + cmd.help(test); + // name + assertEquals("First line should be command name", "name", + test.readNextLine()); + // tip + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // Usage + test.readNextLine(); + // pattern + test.readNextLine(); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + // + assertTrue("Section line is empty", test.readNextLine().isEmpty()); + assertFalse("Only 6 line should be printed", test.available()); + + } + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java index 8bbf59e..b4c0c03 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/HelpExecutorTest.java @@ -1,118 +1,152 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.HelpExecutorTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class HelpExecutorTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.HelpExecutor#execute(ConsoleOutput, ConsoleInput, String...)}. - * - * @throws CommandRunException if the test failed - * @throws IOException if the test failed */ - @Test - public final void testExecute() throws CommandRunException, IOException { - final PipedConsoleOutput test = new PipedConsoleOutput(); - final HelpExecutor help = new HelpExecutor("?", new Command("mock") { - - @Override - public void execute(final ConsoleOutput out, final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - - }); - - help.execute(test, null); - test.close(); - - try { - help.execute(test, null); - fail("manager closed shall provoke failure of help command execution"); - } catch (final Exception e) { - // ok - } - } - - /** Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}. - * - * @throws IOException if the test failed */ - @Test - public final void testTip() throws IOException { - try (PipedConsoleOutput test = new PipedConsoleOutput()) { - final HelpExecutor help = new HelpExecutor("?", - new MockCommand("mock")); - assertNotNull("Tip should be provided", help.tip()); - help.help(test); - } - try (PipedConsoleOutput test = new PipedConsoleOutput()) { - final HelpExecutor help = new HelpExecutor("?", - new SubedCommand("sub", new MockCommand("mock"))); - help.tip(); - help.help(test); - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.HelpExecutorTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; + +import org.junit.Test; + +import fr.bigeon.gclc.command.base.MockCommand; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class HelpExecutorTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.HelpExecutor#execute(ConsoleOutput, ConsoleInput, String...)}. + * + * @throws CommandRunException if the test failed + * @throws IOException if the test failed */ + @Test + public final void testExecute() throws CommandRunException, IOException { + final PipedConsoleOutput test = new PipedConsoleOutput(); + final HelpExecutor help = new HelpExecutor("?", new Command("mock") { + + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + + }); + + help.execute(test, null); + test.close(); + + try { + help.execute(test, null); + fail("manager closed shall provoke failure of help command execution"); + } catch (final Exception e) { + // ok + } + } + + /** Test method for {@link fr.bigeon.gclc.command.HelpExecutor#tip()}. + * + * @throws IOException if the test failed */ + @Test + public final void testTip() throws IOException { + try (PipedConsoleOutput test = new PipedConsoleOutput()) { + final HelpExecutor help = new HelpExecutor("?", + new MockCommand("mock")); + assertNotNull("Tip should be provided", help.tip()); + help.help(test); + } + try (PipedConsoleOutput test = new PipedConsoleOutput()) { + final HelpExecutor help = new HelpExecutor("?", + new SubedCommand("sub", new MockCommand("mock"))); + help.tip(); + help.help(test); + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java index a1d0ea7..d87b05c 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/ParametrizedCommandTest.java @@ -1,682 +1,714 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ParametrizedCommandTest.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidParameterException; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.manager.PipedConsoleInput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class ParametrizedCommandTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#addStringParameter(String, boolean)}. - * - * @throws InvalidParameterException if the test failed */ - @Test - public final void testAddParameter() throws InvalidParameterException { - ParametrizedCommand cmd = new ParametrizedCommand("name") { - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd = new ParametrizedCommand("name", true) { - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - // XXX Boolean flag should not be specified mandatory! They are by - // nature qualified - final String str = "str"; - assertTrue(cmd.getBooleanParameters().isEmpty()); - assertTrue(cmd.getStringParameters().isEmpty()); - cmd.addBooleanParameter("boolFlag"); - assertEquals(1, cmd.getBooleanParameters().size()); - assertTrue(cmd.getStringParameters().isEmpty()); - cmd.addStringParameter(str, false); - assertEquals(1, cmd.getBooleanParameters().size()); - assertEquals(1, cmd.getStringParameters().size()); - assertFalse(cmd.isNeeded(str)); - cmd.addBooleanParameter("boolFlag"); - assertEquals(1, cmd.getBooleanParameters().size()); - assertEquals(1, cmd.getStringParameters().size()); - cmd.addStringParameter(str, true); - assertEquals(1, cmd.getBooleanParameters().size()); - assertEquals(1, cmd.getStringParameters().size()); - assertTrue(cmd.isNeeded(str)); - cmd.addStringParameter(str, false); - assertEquals(1, cmd.getBooleanParameters().size()); - assertEquals(1, cmd.getStringParameters().size()); - assertTrue(cmd.isNeeded(str)); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(ConsoleOutput, ConsoleInput, String...)}. - * - * @throws CommandRunException if the test failed - * @throws InterruptedException if the test failed - * @throws IOException if the test failed */ - @Test - public final void testExecute() throws CommandRunException, - InterruptedException, IOException { - final String addParam = "additional"; - final String str1 = "str1"; - final String str2 = "str2"; - final String bool1 = "bool1"; - final String bool2 = "bool2"; - - // Test on command with no needed elements - ParametrizedCommand cmd = new ParametrizedCommand("name", false) { - private boolean evenCall = true; - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - assertTrue(parameters.getBooleanArgumentKeys().isEmpty()); - assertTrue(parameters.getStringArgumentKeys().isEmpty()); - if (evenCall) { - assertTrue(parameters.getAdditionals().isEmpty()); - evenCall = false; - } else { - assertEquals(1, parameters.getAdditionals().size()); - assertTrue(parameters.getAdditionals().contains(addParam)); - evenCall = true; - } - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.execute(null, null); - cmd.execute(null, null, addParam); - cmd = new ParametrizedCommand("name", false) { - private int call = 0; - { - - try { - addStringParameter(str1, false); - addStringParameter(str2, false); - addBooleanParameter(bool1); - addBooleanParameter(bool2); - } catch (final InvalidParameterException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - assertEquals(2, parameters.getBooleanArgumentKeys().size()); - assertEquals(2, parameters.getStringArgumentKeys().size()); - switch (call) { - case 0: - case 1: - case 2: - case 3: - assertNull(parameters.get(str1)); - assertNull(parameters.get(str2)); - assertFalse(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call++; - break; - case 4: - assertEquals(str2, parameters.get(str1)); - assertNull(parameters.get(str2)); - assertFalse(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call++; - break; - case 5: - assertEquals(str2, parameters.get(str1)); - assertNull(parameters.get(str2)); - assertTrue(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call = 0; - break; - default: - break; - } - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.execute(null, null); - cmd.execute(null, null, "-" + addParam); - cmd.execute(null, null, addParam); - cmd.execute(null, null, "-" + addParam, addParam); - cmd.execute(null, null, "-" + str1, str2); - cmd.execute(null, null, "-" + str1, str2, "-" + bool1); - cmd = new ParametrizedCommand("name", true) { - private int call = 0; - { - - try { - addStringParameter(str1, false); - addStringParameter(str2, false); - addBooleanParameter(bool1); - addBooleanParameter(bool2); - } catch (final InvalidParameterException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - assertEquals(2, parameters.getBooleanArgumentKeys().size()); - assertEquals(2, parameters.getStringArgumentKeys().size()); - switch (call) { - case 0: - assertNull(parameters.get(str1)); - assertNull(parameters.get(str2)); - assertFalse(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call++; - break; - case 1: - assertEquals(str2, parameters.get(str1)); - assertNull(parameters.get(str2)); - assertFalse(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call++; - break; - case 2: - assertEquals(str2, parameters.get(str1)); - assertNull(parameters.get(str2)); - assertTrue(parameters.getBool(bool1)); - assertFalse(parameters.getBool(bool2)); - call = 0; - break; - default: - break; - } - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.execute(null, null); - cmd.execute(null, null, "-" + str1, str2); - cmd.execute(null, null, "-" + str1, str2, "-" + bool1); - try { - cmd.execute(null, null, addParam); - fail("Strict should fail with unexpected argument"); - } catch (final CommandRunException e) { - // ok - } - try { - cmd.execute(null, null, "-" + addParam); - fail("Strict should fail with unexpected argument"); - } catch (final CommandRunException e) { - // ok - } - // Test on command with missing needed elements - cmd = new ParametrizedCommand("name", false) { - private final int call = 0; - { - - try { - addStringParameter(str1, true); - addStringParameter(str2, false); - addBooleanParameter(bool1); - addBooleanParameter(bool2); - } catch (final InvalidParameterException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - assertEquals(str2, parameters.get(str1)); - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.execute(null, null, "-" + str1, str2); - cmd.execute(null, null, "-" + str1, str2, "-" + bool1); - cmd.execute(null, null, "-" + str1, str2, "-" + addParam); - cmd.execute(null, null, "-" + str1, str2, addParam); - cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); - try { - cmd.execute(null, null); - fail("needed " + str1 + " not provided shall fail"); - } catch (final CommandRunException e) { - // ok - } - cmd = new ParametrizedCommand("name", true) { - private final int call = 0; - { - - try { - addStringParameter(str1, true); - addStringParameter(str2, false); - addBooleanParameter(bool1); - addBooleanParameter(bool2); - } catch (final InvalidParameterException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - assertEquals(str2, parameters.get(str1)); - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - cmd.execute(null, null, "-" + str1, str2); - cmd.execute(null, null, "-" + str1, str2, "-" + bool1); - try { - cmd.execute(null, null, "-" + str1, str2, addParam); - fail("Additional parameter should cause failure"); - } catch (final CommandRunException e) { - // ok - } - try { - cmd.execute(null, null); - fail("needed " + str1 + " not provided shall fail"); - } catch (final CommandRunException e) { - // ok - } - try { - cmd.execute(null, null, "-" + str1, str2, "-" + addParam); - fail("unepected error"); - } catch (final CommandRunException e) { - // ok - } - try { - cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); - fail("unepected error"); - } catch (final CommandRunException e) { - // ok - } - // TODO Test of interactive not providing and providing all needed - } - - @Test - public void testExecuteInteractive() throws IOException, - CommandRunException, - InterruptedException { - ParametrizedCommand cmd; - final String addParam = "additional"; - final String str1 = "str1"; - final String str2 = "str2"; - final String bool1 = "bool1"; - final String bool2 = "bool2"; - - cmd = new ParametrizedCommand("name", false) { - { - try { - addStringParameter(str1, true); - addStringParameter(str2, false); - addBooleanParameter(bool1); - addBooleanParameter(bool2); - } catch (final InvalidParameterException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) throws CommandRunException { - if (!str2.equals(parameters.get(str1))) { - throw new CommandRunException("Expected other argument", - this); - } - } - - @Override - public String tip() { - return ""; - } - - @Override - protected String usageDetail() { - return null; - } - }; - try (PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - cmd.execute(out, in, "-" + str1, str2); - cmd.execute(out, in, "-" + str1, str2, "-" + bool1); - cmd.execute(out, in, "-" + str1, str2, addParam); - cmd.execute(out, in, "-" + str1, str2, "-" + addParam); - cmd.execute(out, in, "-" + str1, str2, "-" + addParam, addParam); - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("value of " + str1 + "? ", buf.readLine()); - in.type(""); - assertEquals( - "value of " + str1 + "? (cannot be empty) ", - buf.readLine()); - in.type(""); - assertEquals( - "value of " + str1 + "? (cannot be empty) ", - buf.readLine()); - in.type(str2); - } catch (final IOException e) { - assertNull(e); - } - } - }); - th.start(); - - cmd.execute(out, in); - - th.join(); - } - try (PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("value of " + str1 + "? ", buf.readLine()); - in.type(str2); - } catch (final IOException e) { - assertNull(e); - } - } - }); - th.start(); - - cmd.execute(out, in, "-" + addParam); - - th.join(); - } - try { - final PipedConsoleOutput out = new PipedConsoleOutput(); - final PipedConsoleInput test = new PipedConsoleInput(null); - test.close(); - out.close(); - cmd.execute(out, test, "-" + str1, str2); - cmd.execute(out, test, "-" + addParam); - fail("Closed manager shall cause error"); - } catch (final CommandRunException e) { - // ok - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(String)}. */ - @Test - public final void testParametrizedCommandConsoleManagerString() { - ParametrizedCommand cmd = new ParametrizedCommand("name") { - - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertTrue(cmd.isStrict()); - cmd = new ParametrizedCommand("name") { - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertTrue(cmd.isStrict()); - cmd = new ParametrizedCommand("name") { - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertTrue(cmd.isStrict()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(java.lang.String, boolean)}. */ - @Test - public final void testParametrizedCommandConsoleManagerStringBoolean() { - ParametrizedCommand cmd = new ParametrizedCommand("name", false) { - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertFalse(cmd.isStrict()); - cmd = new ParametrizedCommand("name", false) { - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertFalse(cmd.isStrict()); - cmd = new ParametrizedCommand("name", false) { - @Override - protected void doExecute(final ConsoleOutput out, - final ConsoleInput in, - final CommandParameters parameters) { - // - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }; - assertFalse(cmd.isStrict()); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ParametrizedCommandTest.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidParameterException; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.utils.PipedConsoleInput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class ParametrizedCommandTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#addStringParameter(String, boolean)}. + * + * @throws InvalidParameterException if the test failed */ + @Test + public final void testAddParameter() throws InvalidParameterException { + ParametrizedCommand cmd = new ParametrizedCommand("name") { + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd = new ParametrizedCommand("name", true) { + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + // XXX Boolean flag should not be specified mandatory! They are by + // nature qualified + final String str = "str"; + assertTrue(cmd.getBooleanParameters().isEmpty()); + assertTrue(cmd.getStringParameters().isEmpty()); + cmd.addBooleanParameter("boolFlag"); + assertEquals(1, cmd.getBooleanParameters().size()); + assertTrue(cmd.getStringParameters().isEmpty()); + cmd.addStringParameter(str, false); + assertEquals(1, cmd.getBooleanParameters().size()); + assertEquals(1, cmd.getStringParameters().size()); + assertFalse(cmd.isNeeded(str)); + cmd.addBooleanParameter("boolFlag"); + assertEquals(1, cmd.getBooleanParameters().size()); + assertEquals(1, cmd.getStringParameters().size()); + cmd.addStringParameter(str, true); + assertEquals(1, cmd.getBooleanParameters().size()); + assertEquals(1, cmd.getStringParameters().size()); + assertTrue(cmd.isNeeded(str)); + cmd.addStringParameter(str, false); + assertEquals(1, cmd.getBooleanParameters().size()); + assertEquals(1, cmd.getStringParameters().size()); + assertTrue(cmd.isNeeded(str)); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#execute(ConsoleOutput, ConsoleInput, String...)}. + * + * @throws CommandRunException if the test failed + * @throws InterruptedException if the test failed + * @throws IOException if the test failed */ + @Test + public final void testExecute() throws CommandRunException, + InterruptedException, IOException { + final String addParam = "additional"; + final String str1 = "str1"; + final String str2 = "str2"; + final String bool1 = "bool1"; + final String bool2 = "bool2"; + + // Test on command with no needed elements + ParametrizedCommand cmd = new ParametrizedCommand("name", false) { + private boolean evenCall = true; + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + assertTrue(parameters.getBooleanArgumentKeys().isEmpty()); + assertTrue(parameters.getStringArgumentKeys().isEmpty()); + if (evenCall) { + assertTrue(parameters.getAdditionals().isEmpty()); + evenCall = false; + } else { + assertEquals(1, parameters.getAdditionals().size()); + assertTrue(parameters.getAdditionals().contains(addParam)); + evenCall = true; + } + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.execute(null, null); + cmd.execute(null, null, addParam); + cmd = new ParametrizedCommand("name", false) { + private int call = 0; + { + + try { + addStringParameter(str1, false); + addStringParameter(str2, false); + addBooleanParameter(bool1); + addBooleanParameter(bool2); + } catch (final InvalidParameterException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + assertEquals(2, parameters.getBooleanArgumentKeys().size()); + assertEquals(2, parameters.getStringArgumentKeys().size()); + switch (call) { + case 0: + case 1: + case 2: + case 3: + assertNull(parameters.get(str1)); + assertNull(parameters.get(str2)); + assertFalse(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call++; + break; + case 4: + assertEquals(str2, parameters.get(str1)); + assertNull(parameters.get(str2)); + assertFalse(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call++; + break; + case 5: + assertEquals(str2, parameters.get(str1)); + assertNull(parameters.get(str2)); + assertTrue(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call = 0; + break; + default: + break; + } + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.execute(null, null); + cmd.execute(null, null, "-" + addParam); + cmd.execute(null, null, addParam); + cmd.execute(null, null, "-" + addParam, addParam); + cmd.execute(null, null, "-" + str1, str2); + cmd.execute(null, null, "-" + str1, str2, "-" + bool1); + cmd = new ParametrizedCommand("name", true) { + private int call = 0; + { + + try { + addStringParameter(str1, false); + addStringParameter(str2, false); + addBooleanParameter(bool1); + addBooleanParameter(bool2); + } catch (final InvalidParameterException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + assertEquals(2, parameters.getBooleanArgumentKeys().size()); + assertEquals(2, parameters.getStringArgumentKeys().size()); + switch (call) { + case 0: + assertNull(parameters.get(str1)); + assertNull(parameters.get(str2)); + assertFalse(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call++; + break; + case 1: + assertEquals(str2, parameters.get(str1)); + assertNull(parameters.get(str2)); + assertFalse(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call++; + break; + case 2: + assertEquals(str2, parameters.get(str1)); + assertNull(parameters.get(str2)); + assertTrue(parameters.getBool(bool1)); + assertFalse(parameters.getBool(bool2)); + call = 0; + break; + default: + break; + } + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.execute(null, null); + cmd.execute(null, null, "-" + str1, str2); + cmd.execute(null, null, "-" + str1, str2, "-" + bool1); + try { + cmd.execute(null, null, addParam); + fail("Strict should fail with unexpected argument"); + } catch (final CommandRunException e) { + // ok + } + try { + cmd.execute(null, null, "-" + addParam); + fail("Strict should fail with unexpected argument"); + } catch (final CommandRunException e) { + // ok + } + // Test on command with missing needed elements + cmd = new ParametrizedCommand("name", false) { + private final int call = 0; + { + + try { + addStringParameter(str1, true); + addStringParameter(str2, false); + addBooleanParameter(bool1); + addBooleanParameter(bool2); + } catch (final InvalidParameterException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + assertEquals(str2, parameters.get(str1)); + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.execute(null, null, "-" + str1, str2); + cmd.execute(null, null, "-" + str1, str2, "-" + bool1); + cmd.execute(null, null, "-" + str1, str2, "-" + addParam); + cmd.execute(null, null, "-" + str1, str2, addParam); + cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); + try { + cmd.execute(null, null); + fail("needed " + str1 + " not provided shall fail"); + } catch (final CommandRunException e) { + // ok + } + cmd = new ParametrizedCommand("name", true) { + private final int call = 0; + { + + try { + addStringParameter(str1, true); + addStringParameter(str2, false); + addBooleanParameter(bool1); + addBooleanParameter(bool2); + } catch (final InvalidParameterException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + assertEquals(str2, parameters.get(str1)); + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + cmd.execute(null, null, "-" + str1, str2); + cmd.execute(null, null, "-" + str1, str2, "-" + bool1); + try { + cmd.execute(null, null, "-" + str1, str2, addParam); + fail("Additional parameter should cause failure"); + } catch (final CommandRunException e) { + // ok + } + try { + cmd.execute(null, null); + fail("needed " + str1 + " not provided shall fail"); + } catch (final CommandRunException e) { + // ok + } + try { + cmd.execute(null, null, "-" + str1, str2, "-" + addParam); + fail("unepected error"); + } catch (final CommandRunException e) { + // ok + } + try { + cmd.execute(null, null, "-" + str1, str2, "-" + addParam, addParam); + fail("unepected error"); + } catch (final CommandRunException e) { + // ok + } + // TODO Test of interactive not providing and providing all needed + } + + @Test + public void testExecuteInteractive() throws IOException, + CommandRunException, + InterruptedException { + ParametrizedCommand cmd; + final String addParam = "additional"; + final String str1 = "str1"; + final String str2 = "str2"; + final String bool1 = "bool1"; + final String bool2 = "bool2"; + + cmd = new ParametrizedCommand("name", false) { + { + try { + addStringParameter(str1, true); + addStringParameter(str2, false); + addBooleanParameter(bool1); + addBooleanParameter(bool2); + } catch (final InvalidParameterException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) throws CommandRunException { + if (!str2.equals(parameters.get(str1))) { + throw new CommandRunException("Expected other argument"); + } + } + + @Override + public String tip() { + return ""; + } + + @Override + protected String usageDetail() { + return null; + } + }; + try (PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + cmd.execute(out, in, "-" + str1, str2); + cmd.execute(out, in, "-" + str1, str2, "-" + bool1); + cmd.execute(out, in, "-" + str1, str2, addParam); + cmd.execute(out, in, "-" + str1, str2, "-" + addParam); + cmd.execute(out, in, "-" + str1, str2, "-" + addParam, addParam); + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("value of " + str1 + "? ", buf.readLine()); + in.type(""); + assertEquals( + "value of " + str1 + "? (cannot be empty) ", + buf.readLine()); + in.type(""); + assertEquals( + "value of " + str1 + "? (cannot be empty) ", + buf.readLine()); + in.type(str2); + } catch (final IOException e) { + assertNull(e); + } + } + }); + th.start(); + + cmd.execute(out, in); + + th.join(); + } + try (PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("value of " + str1 + "? ", buf.readLine()); + in.type(str2); + } catch (final IOException e) { + assertNull(e); + } + } + }); + th.start(); + + cmd.execute(out, in, "-" + addParam); + + th.join(); + } + try { + final PipedConsoleOutput out = new PipedConsoleOutput(); + final PipedConsoleInput test = new PipedConsoleInput(null); + test.close(); + out.close(); + cmd.execute(out, test, "-" + str1, str2); + cmd.execute(out, test, "-" + addParam); + fail("Closed manager shall cause error"); + } catch (final CommandRunException e) { + // ok + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(String)}. */ + @Test + public final void testParametrizedCommandConsoleManagerString() { + ParametrizedCommand cmd = new ParametrizedCommand("name") { + + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + cmd = new ParametrizedCommand("name") { + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + cmd = new ParametrizedCommand("name") { + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertTrue(cmd.isStrict()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.ParametrizedCommand#ParametrizedCommand(java.lang.String, boolean)}. */ + @Test + public final void testParametrizedCommandConsoleManagerStringBoolean() { + ParametrizedCommand cmd = new ParametrizedCommand("name", false) { + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + cmd = new ParametrizedCommand("name", false) { + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + cmd = new ParametrizedCommand("name", false) { + @Override + protected void doExecute(final ConsoleOutput out, + final ConsoleInput in, + final CommandParameters parameters) { + // + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }; + assertFalse(cmd.isStrict()); + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java index 8b4f90b..1b35f7e 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/ScriptExecutionTest.java @@ -1,181 +1,209 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.ScriptExecutionTest.java - * Created on: Jun 12, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.nio.charset.Charset; - -import org.junit.Test; - -import fr.bigeon.gclc.ConsoleApplication; -import fr.bigeon.gclc.ConsoleTestApplication; -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.CommandRunExceptionType; -import fr.bigeon.gclc.manager.PipedConsoleInput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/**

- * Test class for {@link ScriptExecution} - * - * @author Emmanuel Bigeon */ -@SuppressWarnings("static-method") -public class ScriptExecutionTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.ScriptExecution#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String...)}. */ - @Test - public void testExecute() { - PipedConsoleOutput test; - PipedConsoleInput in; - try { - in = new PipedConsoleInput(null); - test = new PipedConsoleOutput(); - } catch (final IOException e2) { - fail("creation of console manager failed"); //$NON-NLS-1$ - return; - } - final ConsoleApplication app = new ConsoleApplication( - test, in, "", ""); - new ConsoleTestApplication().attach(app); - final ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$ - Charset.forName("UTF-8")); - try { - exec.execute(test, in); - fail("execution of script command with no file should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.USAGE, e1.getType()); - } - - try { - exec.execute(test, in, - "src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$ - fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); - } - - try { - exec.execute(test, in, - "src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$ - fail("execution of script with invalid command line should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); - } - - try { - exec.execute(test, in, - "src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$ - fail("execution of script with invalid command should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); - } - - try { - exec.execute(test, in, - "src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$ - fail("execution of script with failing command should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); - } - - try { - exec.execute(test, in, - "src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$ - fail("execution of script with unexisting file should fail"); //$NON-NLS-1$ - } catch (final CommandRunException e1) { - // ok - assertEquals(exec, e1.getSource()); - assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); - } - - try { - exec.execute(test, in, "src/test/resources/script1.txt"); //$NON-NLS-1$ - exec.execute(test, in, "src/test/resources/script2.txt"); //$NON-NLS-1$ - exec.execute(test, in, "src/test/resources/script3.txt"); //$NON-NLS-1$ - exec.execute(test, in, "src/test/resources/script4.txt"); //$NON-NLS-1$ - exec.execute(test, in, "src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (final CommandRunException e) { - e.printStackTrace(); - fail("execution of wellformed script should not fail"); //$NON-NLS-1$ - } - try { - test.close(); - } catch (final IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleOutput, String...)}. */ - @Test - public void testHelp() { - final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ - Charset.forName("UTF-8")); - try (PipedConsoleOutput test = new PipedConsoleOutput()) { - exec.help(test); - exec.help(test, "ignored element"); - } catch (final IOException e) { - e.printStackTrace(); - fail("unexpected error in help invocation"); //$NON-NLS-1$ - } - } - - /** Test method for {@link fr.bigeon.gclc.command.ScriptExecution#tip()}. */ - @Test - public void testTip() { - final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ - Charset.forName("UTF-8")); - assertNotNull("Tip should not be null", exec.tip()); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.ScriptExecutionTest.java + * Created on: Jun 12, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.nio.charset.Charset; + +import org.junit.Test; + +import fr.bigeon.gclc.ConsoleApplication; +import fr.bigeon.gclc.ConsoleTestApplication; +import fr.bigeon.gclc.command.base.ScriptExecution; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.CommandRunExceptionType; +import fr.bigeon.gclc.utils.PipedConsoleInput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/**

+ * Test class for {@link ScriptExecution} + * + * @author Emmanuel Bigeon */ +@SuppressWarnings("static-method") +public class ScriptExecutionTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.base.ScriptExecution#execute(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String...)}. */ + @Test + public void testExecute() { + PipedConsoleOutput test; + PipedConsoleInput in; + try { + in = new PipedConsoleInput(null); + test = new PipedConsoleOutput(); + } catch (final IOException e2) { + fail("creation of console manager failed"); //$NON-NLS-1$ + return; + } + final ConsoleApplication app = new ConsoleApplication( + test, in, "", ""); + new ConsoleTestApplication().attach(app); + final ScriptExecution exec = new ScriptExecution("script", app, "#", //$NON-NLS-1$ //$NON-NLS-2$ + Charset.forName("UTF-8")); + try { + exec.execute(test, in); + fail("execution of script command with no file should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.USAGE, e1.getType()); + } + + try { + exec.execute(test, in, + "src/test/resources/scripts/withprependSpace.txt"); //$NON-NLS-1$ + fail("execution of script with lines begining with space should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); + } + + try { + exec.execute(test, in, + "src/test/resources/scripts/invalidCmdParse.txt"); //$NON-NLS-1$ + fail("execution of script with invalid command line should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); + } + + try { + exec.execute(test, in, + "src/test/resources/scripts/invalidCmd.txt"); //$NON-NLS-1$ + fail("execution of script with invalid command should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); + } + + try { + exec.execute(test, in, + "src/test/resources/scripts/failingCmdInvoc.txt"); //$NON-NLS-1$ + fail("execution of script with failing command should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); + } + + try { + exec.execute(test, in, + "src/test/resources/scripts/someNonExisting.file"); //$NON-NLS-1$ + fail("execution of script with unexisting file should fail"); //$NON-NLS-1$ + } catch (final CommandRunException e1) { + // ok + assertEquals(CommandRunExceptionType.EXECUTION, e1.getType()); + } + + try { + exec.execute(test, in, "src/test/resources/script1.gclc"); //$NON-NLS-1$ + exec.execute(test, in, "src/test/resources/script2.txt"); //$NON-NLS-1$ + exec.execute(test, in, "src/test/resources/script3.txt"); //$NON-NLS-1$ + exec.execute(test, in, "src/test/resources/script4.txt"); //$NON-NLS-1$ + exec.execute(test, in, "src/test/resources/script5.txt", "test"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (final CommandRunException e) { + e.printStackTrace(); + fail("execution of wellformed script should not fail"); //$NON-NLS-1$ + } + try { + test.close(); + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.base.ScriptExecution#help(fr.bigeon.gclc.manager.ConsoleOutput, String...)}. */ + @Test + public void testHelp() { + final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ + Charset.forName("UTF-8")); + try (PipedConsoleOutput test = new PipedConsoleOutput()) { + exec.help(test); + exec.help(test, "ignored element"); + } catch (final IOException e) { + e.printStackTrace(); + fail("unexpected error in help invocation"); //$NON-NLS-1$ + } + } + + /** Test method for {@link fr.bigeon.gclc.command.base.ScriptExecution#tip()}. */ + @Test + public void testTip() { + final ScriptExecution exec = new ScriptExecution("script", null, "#", //$NON-NLS-1$ //$NON-NLS-2$ + Charset.forName("UTF-8")); + assertNotNull("Tip should not be null", exec.tip()); + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java b/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java index bdb40c3..af1752b 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/command/SubedCommandTest.java @@ -1,408 +1,438 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.command.SubedCommandTest.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.command; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.junit.Test; - -import fr.bigeon.gclc.exception.CommandRunException; -import fr.bigeon.gclc.exception.InvalidCommandName; -import fr.bigeon.gclc.manager.ConsoleInput; -import fr.bigeon.gclc.manager.ConsoleOutput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -@SuppressWarnings("all") -public class SubedCommandTest { - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */ - @Test - public final void testAdd() { - final SubedCommand cmd = new SubedCommand("name"); - - try { - cmd.add(new MockCommand("id")); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - } - try { - cmd.add(new MockCommand("id")); - fail("addition of command with already used id succeeded"); - } catch (final InvalidCommandName e) { - // - } - try { - cmd.add(new MockCommand("")); - fail("addition of command with invalid id succeeded"); - } catch (final InvalidCommandName e) { - // - } - - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#execute(ConsoleOutput, ConsoleInput, String...)}. */ - @Test - public final void testExecute() { - SubedCommand cmd = new SubedCommand("name"); - - final MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - throw new CommandRunException("Failing command", null); - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.execute(null, null, "id"); - } catch (final CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.execute(null, null, "fail"); - fail("Fail command error should be re thrown"); - } catch (final CommandRunException e) { - assertNotNull(e); - assertEquals(cmd, e.getSource()); - } - try { - cmd.execute(null, null); - fail("Request for inexistent default command should fail"); - } catch (final CommandRunException e) { - assertNotNull(e); - assertEquals(cmd, e.getSource()); - } - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - throw new CommandRunException("Failing command", this); - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.execute(null, null, "id"); - } catch (final CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.execute(null, null, "fail"); - fail("Fail command error should be re thrown"); - } catch (final CommandRunException e) { - assertNotNull(e); - assertEquals(cmd.get("fail"), e.getSource()); - } - try { - cmd.execute(null, null); - } catch (final CommandRunException e) { - fail("Request for default command should execute default command"); - assertNotNull(e); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#executeSub(ConsoleOutput, ConsoleInput, String, String...)}. */ - @Test - public final void testExecuteSub() { - final SubedCommand cmd = new SubedCommand("name"); - - final MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - cmd.add(new Command("fail") { - - @Override - public void execute(final ConsoleOutput out, - final ConsoleInput in, - final String... args) throws CommandRunException { - throw new CommandRunException("Failing command", this); - } - - @Override - public String tip() { - return null; - } - - @Override - protected String usageDetail() { - return null; - } - }); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try { - cmd.executeSub(null, null,"id"); - } catch (final CommandRunException e) { - fail("Unexpected exception when running mock command"); - assertNotNull(e); - } - try { - cmd.executeSub(null, null, "fail"); - fail("Fail command error should be re thrown"); - } catch (final CommandRunException e) { - assertNotNull(e); - assertEquals(cmd.get("fail"), e.getSource()); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */ - @Test - public final void testGet() { - final SubedCommand cmd = new SubedCommand("name"); - - assertNull(cmd.get("id")); - - final MockCommand mock = new MockCommand("id"); - try { - cmd.add(mock); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - assertEquals(mock, cmd.get("id")); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */ - @Test - public final void testGetCommandName() { - SubedCommand cmd = new SubedCommand("name"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces"); - assertEquals("name with spaces", cmd.getCommandName()); - cmd = new SubedCommand("name", "some tip"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name", new MockCommand("")); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name", new MockCommand(""), "some tip"); - assertEquals("name", cmd.getCommandName()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#help(ConsoleOutput, String...)}. */ - @Test - public final void testHelp() { - SubedCommand cmd = new SubedCommand("name"); - - ICommand mock = new MockCommand("id"); - try { - cmd.add(mock); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleOutput manager = new PipedConsoleOutput()) { - cmd.help(manager); - assertEquals("\tid", manager.readNextLine()); - cmd.help(manager, "id"); - cmd.help(manager, "inexistent"); - } catch (final IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleOutput manager = new PipedConsoleOutput()) { - cmd.help(manager); - assertEquals("\tid", manager.readNextLine()); - } catch (final IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - - mock = new ICommand() { - - @Override - public void execute(final ConsoleOutput out, final ConsoleInput in, - final String... args) throws CommandRunException { - // - } - - @Override - public String getCommandName() { - return "id"; - } - - @Override - public void help(final ConsoleOutput manager, - final String... args) throws IOException { - // - } - - @Override - public String tip() { - return "tip"; - } - }; - cmd = new SubedCommand("name", mock); - - try { - cmd.add(mock); - } catch (final InvalidCommandName e) { - fail("addition of command with valid id failed"); - assertNotNull(e); - } - - try (PipedConsoleOutput manager = new PipedConsoleOutput()) { - cmd.help(manager); - assertEquals("\ttip", manager.readNextLine()); - assertEquals("\tid: tip", manager.readNextLine()); - } catch (final IOException e) { - fail("Unexpected exception when running help"); - assertNotNull(e); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */ - @Test - public final void testSubedCommandString() { - SubedCommand cmd = new SubedCommand("name"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces"); - assertNull(cmd.tip()); - assertEquals("name with spaces", cmd.getCommandName()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand)}. */ - @Test - public final void testSubedCommandStringICommand() { - SubedCommand cmd = new SubedCommand("name", new MockCommand("")); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces", new MockCommand("")); - assertNull(cmd.tip()); - assertEquals("name with spaces", cmd.getCommandName()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand, java.lang.String)}. */ - @Test - public final void testSubedCommandStringICommandString() { - SubedCommand cmd = new SubedCommand("name", new MockCommand(""), "tip"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip"); - assertEquals("name with spaces", cmd.getCommandName()); - } - - /** Test method for - * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, java.lang.String)}. */ - @Test - public final void testSubedCommandStringString() { - SubedCommand cmd = new SubedCommand("name", "tip"); - assertEquals("name", cmd.getCommandName()); - cmd = new SubedCommand("name with spaces", "tip"); - assertEquals("name with spaces", cmd.getCommandName()); - } - - /** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */ - @Test - public final void testTip() { - SubedCommand cmd = new SubedCommand("name"); - assertNull(cmd.tip()); - cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip"); - assertEquals("tip", cmd.tip()); - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.command.SubedCommandTest.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.command; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.IOException; + +import org.junit.Test; + +import fr.bigeon.gclc.command.base.MockCommand; +import fr.bigeon.gclc.exception.CommandRunException; +import fr.bigeon.gclc.exception.InvalidCommandName; +import fr.bigeon.gclc.manager.ConsoleInput; +import fr.bigeon.gclc.manager.ConsoleOutput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +@SuppressWarnings("all") +public class SubedCommandTest { + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#add(fr.bigeon.gclc.command.ICommand)}. */ + @Test + public final void testAdd() { + final SubedCommand cmd = new SubedCommand("name"); + + try { + cmd.add(new MockCommand("id")); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + } + try { + cmd.add(new MockCommand("id")); + fail("addition of command with already used id succeeded"); + } catch (final InvalidCommandName e) { + // + } + try { + cmd.add(new MockCommand("")); + fail("addition of command with invalid id succeeded"); + } catch (final InvalidCommandName e) { + // + } + + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#execute(ConsoleOutput, ConsoleInput, String...)}. */ + @Test + public final void testExecute() { + SubedCommand cmd = new SubedCommand("name"); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + throw new CommandRunException("Failing command", null); + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.execute(null, null, "id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.execute(null, null, "fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + } + try { + cmd.execute(null, null); + fail("Request for inexistent default command should fail"); + } catch (final CommandRunException e) { + assertNotNull(e); + } + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + throw new CommandRunException("Failing command"); + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.execute(null, null, "id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.execute(null, null, "fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + } + try { + cmd.execute(null, null); + } catch (final CommandRunException e) { + fail("Request for default command should execute default command"); + assertNotNull(e); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#executeSub(ConsoleOutput, ConsoleInput, String, String...)}. */ + @Test + public final void testExecuteSub() { + final SubedCommand cmd = new SubedCommand("name"); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + cmd.add(new Command("fail") { + + @Override + public void execute(final ConsoleOutput out, + final ConsoleInput in, + final String... args) throws CommandRunException { + throw new CommandRunException("Failing command"); + } + + @Override + public String tip() { + return null; + } + + @Override + protected String usageDetail() { + return null; + } + }); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try { + cmd.executeSub(null, null,"id"); + } catch (final CommandRunException e) { + fail("Unexpected exception when running mock command"); + assertNotNull(e); + } + try { + cmd.executeSub(null, null, "fail"); + fail("Fail command error should be re thrown"); + } catch (final CommandRunException e) { + assertNotNull(e); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#get(java.lang.String)}. */ + @Test + public final void testGet() { + final SubedCommand cmd = new SubedCommand("name"); + + assertNull(cmd.get("id")); + + final MockCommand mock = new MockCommand("id"); + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + assertEquals(mock, cmd.get("id")); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#getCommandName()}. */ + @Test + public final void testGetCommandName() { + SubedCommand cmd = new SubedCommand("name"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces"); + assertEquals("name with spaces", cmd.getCommandName()); + cmd = new SubedCommand("name", "some tip"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name", new MockCommand("")); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name", new MockCommand(""), "some tip"); + assertEquals("name", cmd.getCommandName()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#help(ConsoleOutput, String...)}. */ + @Test + public final void testHelp() { + SubedCommand cmd = new SubedCommand("name"); + + ICommand mock = new MockCommand("id"); + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleOutput manager = new PipedConsoleOutput()) { + cmd.help(manager); + assertEquals("\tid", manager.readNextLine()); + cmd.help(manager, "id"); + cmd.help(manager, "inexistent"); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleOutput manager = new PipedConsoleOutput()) { + cmd.help(manager); + assertEquals("\tid", manager.readNextLine()); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + + mock = new ICommand() { + + @Override + public void execute(final ConsoleOutput out, final ConsoleInput in, + final String... args) throws CommandRunException { + // + } + + @Override + public String getCommandName() { + return "id"; + } + + @Override + public void help(final ConsoleOutput manager, + final String... args) throws IOException { + // + } + + @Override + public String tip() { + return "tip"; + } + }; + cmd = new SubedCommand("name", mock); + + try { + cmd.add(mock); + } catch (final InvalidCommandName e) { + fail("addition of command with valid id failed"); + assertNotNull(e); + } + + try (PipedConsoleOutput manager = new PipedConsoleOutput()) { + cmd.help(manager); + assertEquals("\ttip", manager.readNextLine()); + assertEquals("\tid: tip", manager.readNextLine()); + } catch (final IOException e) { + fail("Unexpected exception when running help"); + assertNotNull(e); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String)}. */ + @Test + public final void testSubedCommandString() { + SubedCommand cmd = new SubedCommand("name"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces"); + assertNull(cmd.tip()); + assertEquals("name with spaces", cmd.getCommandName()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand)}. */ + @Test + public final void testSubedCommandStringICommand() { + SubedCommand cmd = new SubedCommand("name", new MockCommand("")); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces", new MockCommand("")); + assertNull(cmd.tip()); + assertEquals("name with spaces", cmd.getCommandName()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, fr.bigeon.gclc.command.ICommand, java.lang.String)}. */ + @Test + public final void testSubedCommandStringICommandString() { + SubedCommand cmd = new SubedCommand("name", new MockCommand(""), "tip"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip"); + assertEquals("name with spaces", cmd.getCommandName()); + } + + /** Test method for + * {@link fr.bigeon.gclc.command.SubedCommand#SubedCommand(java.lang.String, java.lang.String)}. */ + @Test + public final void testSubedCommandStringString() { + SubedCommand cmd = new SubedCommand("name", "tip"); + assertEquals("name", cmd.getCommandName()); + cmd = new SubedCommand("name with spaces", "tip"); + assertEquals("name with spaces", cmd.getCommandName()); + } + + /** Test method for {@link fr.bigeon.gclc.command.SubedCommand#tip()}. */ + @Test + public final void testTip() { + SubedCommand cmd = new SubedCommand("name"); + assertNull(cmd.tip()); + cmd = new SubedCommand("name with spaces", new MockCommand(""), "tip"); + assertEquals("tip", cmd.tip()); + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/exception/CommandRunExceptionTest.java b/gclc/src/test/java/fr/bigeon/gclc/exception/CommandRunExceptionTest.java index 2a29acc..5930118 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/exception/CommandRunExceptionTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/exception/CommandRunExceptionTest.java @@ -1,75 +1,107 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.exception.CommandRunExceptionTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.exception; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import fr.bigeon.gclc.command.ICommand; -import fr.bigeon.gclc.command.MockCommand; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon - * - */ -public class CommandRunExceptionTest { - - /** - * Test method for {@link fr.bigeon.gclc.exception.CommandRunException#getLocalizedMessage()}. - */ - @Test - public final void testGetLocalizedMessage() { - CommandRunException e; - ICommand cmd = new MockCommand("name"); - String messageInner = "inner"; - String message = "message"; - e = new CommandRunException(message, - new CommandRunException(messageInner, new MockCommand("name")), //$NON-NLS-1$ - cmd); - - assertEquals(message + ": " + messageInner, e.getLocalizedMessage()); - e = new CommandRunException(message, cmd); - assertEquals(message, e.getLocalizedMessage()); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.exception.CommandRunExceptionTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.exception; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import fr.bigeon.gclc.command.ICommand; +import fr.bigeon.gclc.command.base.MockCommand; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon + * + */ +public class CommandRunExceptionTest { + + /** + * Test method for {@link fr.bigeon.gclc.exception.CommandRunException#getLocalizedMessage()}. + */ + @Test + public final void testGetLocalizedMessage() { + CommandRunException e; + final ICommand cmd = new MockCommand("name"); + final String messageInner = "inner"; + final String message = "message"; + e = new CommandRunException(message, + new CommandRunException(messageInner)); + + assertEquals(message + ": " + messageInner, e.getLocalizedMessage()); + e = new CommandRunException(message); + assertEquals(message, e.getLocalizedMessage()); + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/manager/ReadingRunnableTest.java b/gclc/src/test/java/fr/bigeon/gclc/manager/ReadingRunnableTest.java index 4dfae41..da5258d 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/manager/ReadingRunnableTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/manager/ReadingRunnableTest.java @@ -1,142 +1,177 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.ReadingRunnableTest.java - * Created on: Dec 6, 2016 - */ -package fr.bigeon.gclc.manager; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.nio.charset.Charset; - -import org.junit.Before; -import org.junit.Test; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class ReadingRunnableTest { - - /** - */ - @Before - public void setUp() {} - - /** Test method for - * {@link fr.bigeon.gclc.manager.ReadingRunnable#getMessage()}. */ - @Test - public final void testGetMessage() { - final BufferedReader reader = null; - final ReadingRunnable runnable = new ReadingRunnable(reader); - runnable.setRunning(false); - - try { - runnable.getMessage(); - fail("reading from closed runnable"); - } catch (final IOException e) { - // ok - } - - } - - /** Test method for - * {@link fr.bigeon.gclc.manager.ReadingRunnable#getWaitForDelivery(java.lang.String)}. - * - * @throws InterruptedException if the test failed - * @throws IOException if the test failed */ - @Test - public final void testGetWaitForDelivery() throws InterruptedException, - IOException { - try (PipedOutputStream out = new PipedOutputStream(); - InputStream piped = new PipedInputStream(out); - BufferedReader reader = new BufferedReader( - new InputStreamReader(piped, "UTF-8"))) { - final ReadingRunnable runnable = new ReadingRunnable(reader); - final Thread th0 = new Thread(runnable, "read"); - th0.start(); - final Thread th = runnable.getWaitForDelivery("msg"); - - out.write(Charset.forName("UTF-8") - .encode("msg" + System.lineSeparator()).array()); - - final Thread th2 = new Thread(new Runnable() { - - @Override - public void run() { - try { - runnable.getMessage(); - } catch (final IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }, "get"); - th2.start(); - th.join(); - assertFalse("Runnable should have consumed every message", - runnable.hasMessage()); - runnable.setRunning(false); - out.close(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.manager.ReadingRunnable#hasMessage()}. */ - @Test - public final void testHasMessage() { - - final BufferedReader reader = null; - final ReadingRunnable runnable = new ReadingRunnable(reader); - runnable.setRunning(false); - - try { - runnable.getMessage(); - fail("reading from closed runnable"); - } catch (final IOException e) { - // ok - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.ReadingRunnableTest.java + * Created on: Dec 6, 2016 + */ +package fr.bigeon.gclc.manager; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.nio.charset.Charset; + +import org.junit.Before; +import org.junit.Test; + +import fr.bigeon.gclc.utils.ReadingRunnable; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class ReadingRunnableTest { + + /** + */ + @Before + public void setUp() {} + + /** Test method for + * {@link fr.bigeon.gclc.utils.ReadingRunnable#getMessage()}. */ + @Test + public final void testGetMessage() { + final BufferedReader reader = null; + final ReadingRunnable runnable = new ReadingRunnable(reader); + runnable.setRunning(false); + + try { + runnable.getMessage(); + fail("reading from closed runnable"); + } catch (final IOException e) { + // ok + } + + } + + /** Test method for + * {@link fr.bigeon.gclc.utils.ReadingRunnable#getWaitForDelivery(java.lang.String)}. + * + * @throws InterruptedException if the test failed + * @throws IOException if the test failed */ + @Test + public final void testGetWaitForDelivery() throws InterruptedException, + IOException { + try (PipedOutputStream out = new PipedOutputStream(); + InputStream piped = new PipedInputStream(out); + BufferedReader reader = new BufferedReader( + new InputStreamReader(piped, "UTF-8"))) { + final ReadingRunnable runnable = new ReadingRunnable(reader); + final Thread th0 = new Thread(runnable, "read"); + th0.start(); + final Thread th = runnable.getWaitForDelivery("msg"); + + out.write(Charset.forName("UTF-8") + .encode("msg" + System.lineSeparator()).array()); + + final Thread th2 = new Thread(new Runnable() { + + @Override + public void run() { + try { + runnable.getMessage(); + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }, "get"); + th2.start(); + th.join(); + assertFalse("Runnable should have consumed every message", + runnable.hasMessage()); + runnable.setRunning(false); + out.close(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.utils.ReadingRunnable#hasMessage()}. */ + @Test + public final void testHasMessage() { + + final BufferedReader reader = null; + final ReadingRunnable runnable = new ReadingRunnable(reader); + runnable.setRunning(false); + + try { + runnable.getMessage(); + fail("reading from closed runnable"); + } catch (final IOException e) { + // ok + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/manager/SystemConsoleManagerTest.java b/gclc/src/test/java/fr/bigeon/gclc/manager/SystemConsoleManagerTest.java index b8205ae..da481a4 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/manager/SystemConsoleManagerTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/manager/SystemConsoleManagerTest.java @@ -1,146 +1,181 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.manager.SystemConsoleManagerTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.manager; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.Charset; - -import org.junit.Test; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class SystemConsoleManagerTest { - - /** Test method for {@link fr.bigeon.gclc.manager.ConsoleInput#isClosed()}. - * - * @throws IOException if the test failed - * @throws InterruptedException if the test failed */ - @Test - public final void testIsClosed() throws IOException, InterruptedException { - final PipedOutputStream outStream = new PipedOutputStream(); - final InputStream in = new PipedInputStream(outStream); - final PrintStream out = new PrintStream(outStream); - final String test = "test"; - final StreamConsoleInput manager = new StreamConsoleInput(System.out, - in, Charset.forName("UTF-8")); - - final Thread th = new Thread(new Runnable() { - - @SuppressWarnings("synthetic-access") - @Override - public void run() { - out.println(test); - } - }); - - th.start(); - assertEquals(test, manager.prompt()); - assertFalse(manager.isClosed()); - manager.close(); - assertTrue(manager.isClosed()); - try { - manager.prompt(); - fail("prompt on closed manager"); - } catch (final IOException e) { - // ok - } - th.join(); - } - - /** Test method for {@link fr.bigeon.gclc.manager.ConsoleInput#prompt()}. - * - * @throws IOException if the test failed - * @throws InterruptedException if the test failed */ - @Test - public final void testPrompt() throws IOException, InterruptedException { - - final String test = "test"; - try (PipedOutputStream outStream = new PipedOutputStream(); - InputStream in = new PipedInputStream(outStream); - final PrintStream out = new PrintStream(outStream); - StreamConsoleInput manager = new StreamConsoleInput(System.out, in, - Charset.forName("UTF-8"))) { - - final Thread th = new Thread(new Runnable() { - - @SuppressWarnings("synthetic-access") - @Override - public void run() { - out.println(test); - } - }); - - th.start(); - assertEquals(test, manager.prompt()); - - th.join(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String)}. - * - * @throws IOException if the test failed */ - @Test - public final void testSetPrompt() throws IOException { - try (PipedOutputStream outStream = new PipedOutputStream(); - InputStream in = new PipedInputStream(outStream); - final PrintStream out = new PrintStream(outStream); - StreamConsoleInput manager = new StreamConsoleInput(System.out, in, - Charset.forName("UTF-8"))) { - - final String prt = "++"; - manager.setPrompt(prt); - assertEquals(prt, manager.getPrompt().apply()); - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.manager.SystemConsoleManagerTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.manager; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.Charset; + +import org.junit.Test; + +import fr.bigeon.gclc.utils.StreamConsoleInput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class SystemConsoleManagerTest { + + /** Test method for {@link fr.bigeon.gclc.manager.ConsoleInput#isClosed()}. + * + * @throws IOException if the test failed + * @throws InterruptedException if the test failed */ + @Test + public final void testIsClosed() throws IOException, InterruptedException { + final PipedOutputStream outStream = new PipedOutputStream(); + final InputStream in = new PipedInputStream(outStream); + final PrintStream out = new PrintStream(outStream); + final String test = "test"; + final StreamConsoleInput manager = new StreamConsoleInput(System.out, + in, Charset.forName("UTF-8")); + + final Thread th = new Thread(new Runnable() { + + @SuppressWarnings("synthetic-access") + @Override + public void run() { + out.println(test); + } + }); + + th.start(); + assertEquals(test, manager.prompt()); + assertFalse(manager.isClosed()); + manager.close(); + assertTrue(manager.isClosed()); + try { + manager.prompt(); + fail("prompt on closed manager"); + } catch (final IOException e) { + // ok + } + th.join(); + } + + /** Test method for {@link fr.bigeon.gclc.manager.ConsoleInput#prompt()}. + * + * @throws IOException if the test failed + * @throws InterruptedException if the test failed */ + @Test + public final void testPrompt() throws IOException, InterruptedException { + + final String test = "test"; + try (PipedOutputStream outStream = new PipedOutputStream(); + InputStream in = new PipedInputStream(outStream); + final PrintStream out = new PrintStream(outStream); + StreamConsoleInput manager = new StreamConsoleInput(System.out, in, + Charset.forName("UTF-8"))) { + + final Thread th = new Thread(new Runnable() { + + @SuppressWarnings("synthetic-access") + @Override + public void run() { + out.println(test); + } + }); + + th.start(); + assertEquals(test, manager.prompt()); + + th.join(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.manager.ConsoleInput#setPrompt(java.lang.String)}. + * + * @throws IOException if the test failed */ + @Test + public final void testSetPrompt() throws IOException { + try (PipedOutputStream outStream = new PipedOutputStream(); + InputStream in = new PipedInputStream(outStream); + final PrintStream out = new PrintStream(outStream); + StreamConsoleInput manager = new StreamConsoleInput(System.out, in, + Charset.forName("UTF-8"))) { + + final String prt = "++"; + manager.setPrompt(prt); + assertEquals(prt, manager.getPrompt().apply()); + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterMessagesTest.java b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterMessagesTest.java index 32537ef..3d92a0d 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterMessagesTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterMessagesTest.java @@ -1,67 +1,100 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.prompt.CLIPrompterMessagesTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.prompt; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon - * - */ -public class CLIPrompterMessagesTest { - - /** - * Test method for {@link fr.bigeon.gclc.prompt.CLIPrompterMessages#getString(java.lang.String, java.lang.Object[])}. - */ - @Test - public final void testGetString() { - String key = "bad.key"; - assertEquals('!' + key + '!', CLIPrompterMessages.getString(key)); - assertEquals('!' + key + '!', - CLIPrompterMessages.getString(key, "some arg")); - assertEquals('!' + key + '!', - CLIPrompterMessages.getString(key, new Object[] {})); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.prompt.CLIPrompterMessagesTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.prompt; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon + * + */ +public class CLIPrompterMessagesTest { + + /** + * Test method for {@link fr.bigeon.gclc.prompt.CLIPrompterMessages#getString(java.lang.String, java.lang.Object[])}. + */ + @Test + public final void testGetString() { + String key = "bad.key"; + assertEquals('!' + key + '!', CLIPrompterMessages.getString(key)); + assertEquals('!' + key + '!', + CLIPrompterMessages.getString(key, "some arg")); + assertEquals('!' + key + '!', + CLIPrompterMessages.getString(key, new Object[] {})); + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java index 07645c8..8ae8d6e 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/prompt/CLIPrompterTest.java @@ -1,1212 +1,1245 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.prompt.CLIPrompterTest.java - * Created on: Nov 18, 2016 - */ -package fr.bigeon.gclc.prompt; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import fr.bigeon.gclc.manager.PipedConsoleInput; -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/** - *

- * TODO - * - * @author Emmanuel Bigeon */ -public class CLIPrompterTest { - - /** @throws java.lang.Exception if there are exceptions */ - @Before - public void setUp() throws Exception { - // - } - - /** @throws java.lang.Exception if there are exceptions */ - @After - public void tearDown() throws Exception { - // - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptBoolean(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ - @Test - public final void testPromptBoolean() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertTrue(CLIPrompter.promptBoolean(out, in, - "My message")); //$NON-NLS-1$ - assertTrue(CLIPrompter.promptBoolean(out, in, - "My message")); //$NON-NLS-1$ - assertFalse(CLIPrompter.promptBoolean(out, in, - "My message")); //$NON-NLS-1$ - assertFalse(CLIPrompter.promptBoolean(out, in, - "My message")); //$NON-NLS-1$ - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type(""); //$NON-NLS-1$ - out.readNextLine(); - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("Y"); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("yes"); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("N"); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("nO"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, List, String, String)}. */ - @Test - public final void testPromptChoiceConsoleManagerListOfStringListOfUStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final List choices = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.add(new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.add("The actual other"); //$NON-NLS-1$ - final String cancel = "Cancel"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - choices.get(0), CLIPrompter.promptChoice(out, - in, keys, choices, message, cancel)); - assertEquals("Asserted provided value to be retrieved", - choices.get(0), CLIPrompter.promptChoice(out, - in, keys, choices, message, null)); - assertEquals("Asserted provided value to be retrieved", - null, CLIPrompter.promptChoice(out, in, keys, - choices, message, cancel)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size()); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - @Test - public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final Map choices = new HashMap<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.put(keys.get(0), new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ - final String cancel = "Cancel"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - choices.get(keys.get(0)), - CLIPrompter.promptChoice(out, in, keys, choices, - message, cancel)); - assertEquals("Asserted provided value to be retrieved", - choices.get(keys.get(0)), - CLIPrompter.promptChoice(out, in, keys, choices, - message, null)); - assertEquals("Asserted provided value to be retrieved", - null, CLIPrompter.promptChoice(out, in, keys, - choices, message, cancel)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size()); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - @Test - public final void testPromptChoiceConsoleManagerListOfUStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - keys.add("An other"); //$NON-NLS-1$ - final String cancel = "Cancel"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - Integer.valueOf(0), CLIPrompter.promptChoice( - out, in, keys, message, cancel)); - assertEquals("Asserted provided value to be retrieved", - Integer.valueOf(0), CLIPrompter.promptChoice( - out, in, keys, message, null)); - assertEquals("Asserted provided value to be retrieved", - Integer.valueOf(1), CLIPrompter.promptChoice( - out, in, keys, message, null)); - assertEquals("Asserted provided value to be retrieved", - null, CLIPrompter.promptChoice(out, in, keys, - message, cancel)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size()); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Success do it again - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("1"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, Map, String, String)}. */ - @Test - public final void testPromptChoiceConsoleManagerMapOfUTStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final Map choices = new HashMap<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.put(keys.get(0), new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ - final String cancel = "Cancel"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - choices.get(keys.get(0)), - CLIPrompter.promptChoice(out, in, keys, choices, - message, cancel)); - assertEquals("Asserted provided value to be retrieved", - choices.get(keys.get(0)), - CLIPrompter.promptChoice(out, in, keys, choices, - message, null)); - assertEquals("Asserted provided value to be retrieved", - null, CLIPrompter.promptChoice(out, in, keys, - choices, message, cancel)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - final String readNextLine = out.readNextLine(); - assertTrue(readNextLine + " expected to contain " + keys.get(0), - readNextLine.contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size()); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertTrue(out.readNextLine().contains(cancel)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptInteger(fr.bigeon.gclc.manager.ConsoleInput, String)}. */ - @Test - public final void testPromptInteger() { - try (PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - 10, - CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$ - assertEquals("Asserted provided value to be retrieved", - -15, - CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$ - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type(""); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("Y"); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("10"); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type("-15"); //$NON-NLS-1$ - th.join(); - - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ - @Test - public final void testPromptListConsoleManagerString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - keys.add("An other"); //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - new ArrayList(), - CLIPrompter.promptList(out, in, message)); - assertEquals("Asserted provided value to be retrieved", - keys, CLIPrompter.promptList(out, in, message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - String nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlist.exit.dispkey", CLIPrompterMessages //$NON-NLS-1$ - .getString("promptlist.exit.defaultkey")))); //$NON-NLS-1$ - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type(CLIPrompterMessages - .getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ - // enter keys list - nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlist.exit.dispkey", CLIPrompterMessages //$NON-NLS-1$ - .getString("promptlist.exit.defaultkey")))); //$NON-NLS-1$ - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - for (int i = 0; i < keys.size(); i++) { - in.type(keys.get(i)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - } - in.type(CLIPrompterMessages - .getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ - @Test - public final void testPromptListConsoleManagerStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - keys.add("An other"); //$NON-NLS-1$ - final String ender = "*"; //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - new ArrayList(), CLIPrompter - .promptList(out, in, message, ender)); - assertEquals("Asserted provided value to be retrieved", - keys, CLIPrompter.promptList(out, in, message, - ender)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - String nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlist.exit.dispkey", ender))); //$NON-NLS-1$ - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type(ender); - // enter keys list - nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlist.exit.dispkey", ender))); //$NON-NLS-1$ - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - for (int i = 0; i < keys.size(); i++) { - in.type(keys.get(i)); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - } - in.type(ender); - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ - @Test - public final void testPromptLongTextConsoleManagerString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final String message = "My message"; - final String longText = "Some text with" + System.lineSeparator() + - "line feeds and other" + - System.lineSeparator() + - System.lineSeparator() + - " \tspecial characters"; - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", - "", - CLIPrompter.promptLongText(out, in, message)); - assertEquals("Asserted provided value to be retrieved", - longText + System.lineSeparator(), - CLIPrompter.promptLongText(out, in, message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - String nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages.getString( - "promptlongtext.exit.dispkey", CLIPrompterMessages - .getString("promptlongtext.exit.defaultkey")))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - in.type(CLIPrompterMessages - .getString("promptlongtext.exit.defaultkey")); - // enter long text - nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages.getString( - "promptlongtext.exit.dispkey", CLIPrompterMessages - .getString("promptlongtext.exit.defaultkey")))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - final String[] text = longText.split(System.lineSeparator()); - for (final String element : text) { - in.type(element); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - } - in.type(CLIPrompterMessages - .getString("promptlongtext.exit.defaultkey")); - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ - @Test - public final void testPromptLongTextConsoleManagerStringString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final String message = "My message"; - final String ender = "\\quit"; - final String[] text = new String[] {"Some text with", - "feeds and other", " \tspecial characters"}; - final String longText = text[0] + System.lineSeparator() + text[1] + - System.lineSeparator() + text[2]; - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Asserted provided value to be retrieved", //$NON-NLS-1$ - "", CLIPrompter.promptLongText(out, in, message, - ender)); - assertEquals("Asserted provided value to be retrieved", - longText + System.lineSeparator(), - CLIPrompter.promptLongText(out, in, message, - ender)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - String nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", ender))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - in.type(ender); - // enter long text - nLine = out.readNextLine(); - assertTrue(nLine.startsWith(message)); - assertTrue(nLine.endsWith(CLIPrompterMessages - .getString("promptlongtext.exit.dispkey", ender))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - for (final String element : text) { - in.type(element); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), - buf.readLine()); - } - in.type(ender); - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, List, String)}. */ - @Test - public final void testPromptMultiChoiceConsoleManagerListOfStringListOfUString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final List choices = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.add(new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.add("The actual other"); //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertTrue("Asserted provided value to be retrieved", - CLIPrompter.promptMultiChoice(out, in, keys, - choices, message).isEmpty()); - final ArrayList l = new ArrayList<>(); - l.add(choices.get(0)); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - l.add(choices.get(1)); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size() - 1); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type(""); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0))); - assertTrue(out.readNextLine().contains(keys.get(1))); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0 1"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, Map, String)}. */ - @Test - public final void testPromptMultiChoiceConsoleManagerListOfUMapOfUTString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final Map choices = new HashMap<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.put(keys.get(0), new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertTrue("Asserted provided value to be retrieved", - CLIPrompter.promptMultiChoice(out, in, keys, - choices, message).isEmpty()); - final ArrayList l = new ArrayList<>(); - l.add(choices.get(keys.get(0))); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - l.add(choices.get(keys.get(1))); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size() - 1); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type(""); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0 1"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, String)}. */ - @Test - public final void testPromptMultiChoiceConsoleManagerListOfUString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - keys.add("A choice"); //$NON-NLS-1$ - keys.add("An other"); //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertTrue("Asserted provided value to be retrieved", - CLIPrompter.promptMultiChoice(out, in, keys, - message).isEmpty()); - final ArrayList l = new ArrayList<>(); - l.add(0); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - message)); - l.add(1); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size() - 1); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type(""); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ - buf.readLine()); - in.type("0 1"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, Map, String)}. */ - @Test - public final void testPromptMultiChoiceConsoleManagerMapOfUTString() { - try (final PipedConsoleOutput out = new PipedConsoleOutput(); - PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final List keys = new ArrayList<>(); - final Map choices = new HashMap<>(); - keys.add("A choice"); //$NON-NLS-1$ - choices.put(keys.get(0), new Integer(25)); - keys.add("An other"); //$NON-NLS-1$ - choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ - final String message = "My message"; //$NON-NLS-1$ - - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertTrue("Asserted provided value to be retrieved", - CLIPrompter.promptMultiChoice(out, in, keys, - choices, message).isEmpty()); - final ArrayList l = new ArrayList<>(); - l.add(choices.get(keys.get(0))); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - l.add(choices.get(keys.get(1))); - assertEquals("Asserted provided value to be retrieved", - l, CLIPrompter.promptMultiChoice(out, in, keys, - choices, message)); - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(out.readNextLine().startsWith(message)); - final String readNextLine = out.readNextLine(); - assertTrue(readNextLine + " expected to contain " + keys.get(0), - readNextLine.contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - in.type("yoyo"); //$NON-NLS-1$ - // fail, reprompt - final String msg = CLIPrompterMessages.getString( - "promptchoice.formaterr", //$NON-NLS-1$ - 0, keys.size() - 1); - for (final String line : msg.split(System.lineSeparator())) { - assertEquals(line, out.readNextLine()); - } - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - in.type(""); //$NON-NLS-1$ - // Sucess, reprompt without cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - in.type("2"); //$NON-NLS-1$ - // fail, reprompt - assertEquals( - CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ - keys.size() - 1), - out.readNextLine()); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - in.type("0"); //$NON-NLS-1$ - // Sucess, prompt with cancel - assertTrue(out.readNextLine().startsWith(message)); - assertTrue(out.readNextLine().contains(keys.get(0).toString())); - assertTrue(out.readNextLine().contains(keys.get(1).toString())); - in.type("0 1"); //$NON-NLS-1$ - th.join(); - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion, the other thread probably failed"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - - /** Test method for - * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptNonEmpty(fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ - @Test - public final void testPromptNonEmpty() { - try (PipedOutputStream pout = new PipedOutputStream(); - PipedInputStream pis = new PipedInputStream(pout); - BufferedReader buf = new BufferedReader( - new InputStreamReader(pis, StandardCharsets.UTF_8)); - PipedConsoleInput in = new PipedConsoleInput( - new PrintStream(pout))) { - final String res = "some content"; //$NON-NLS-1$ - final Thread th = new Thread(new Runnable() { - - @Override - public void run() { - try { - assertEquals("Expected provided message to be returned", - res, CLIPrompter.promptNonEmpty(in, - "My message", "my reprompt")); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (final IOException e) { - fail("Unexpected io excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - }); - th.start(); - assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ - in.type(""); //$NON-NLS-1$ - assertTrue(buf.readLine().startsWith("my reprompt")); //$NON-NLS-1$ - in.type(res); - th.join(); - - } catch (IOException | InterruptedException e) { - fail("Unexpected excpetion"); //$NON-NLS-1$ - e.printStackTrace(); - } - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.prompt.CLIPrompterTest.java + * Created on: Nov 18, 2016 + */ +package fr.bigeon.gclc.prompt; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import fr.bigeon.gclc.utils.PipedConsoleInput; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/** + *

+ * TODO + * + * @author Emmanuel Bigeon */ +public class CLIPrompterTest { + + /** @throws java.lang.Exception if there are exceptions */ + @Before + public void setUp() throws Exception { + // + } + + /** @throws java.lang.Exception if there are exceptions */ + @After + public void tearDown() throws Exception { + // + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptBoolean(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ + @Test + public final void testPromptBoolean() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertTrue(CLIPrompter.promptBoolean(out, in, + "My message")); //$NON-NLS-1$ + assertTrue(CLIPrompter.promptBoolean(out, in, + "My message")); //$NON-NLS-1$ + assertFalse(CLIPrompter.promptBoolean(out, in, + "My message")); //$NON-NLS-1$ + assertFalse(CLIPrompter.promptBoolean(out, in, + "My message")); //$NON-NLS-1$ + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type(""); //$NON-NLS-1$ + out.readNextLine(); + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("Y"); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("yes"); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("N"); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("nO"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, List, String, String)}. */ + @Test + public final void testPromptChoiceConsoleManagerListOfStringListOfUStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final List choices = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.add(new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.add("The actual other"); //$NON-NLS-1$ + final String cancel = "Cancel"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + choices.get(0), CLIPrompter.promptChoice(out, + in, keys, choices, message, cancel)); + assertEquals("Asserted provided value to be retrieved", + choices.get(0), CLIPrompter.promptChoice(out, + in, keys, choices, message, null)); + assertEquals("Asserted provided value to be retrieved", + null, CLIPrompter.promptChoice(out, in, keys, + choices, message, cancel)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size()); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + @Test + public final void testPromptChoiceConsoleManagerListOfUMapOfUTStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final Map choices = new HashMap<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.put(keys.get(0), new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ + final String cancel = "Cancel"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + choices.get(keys.get(0)), + CLIPrompter.promptChoice(out, in, keys, choices, + message, cancel)); + assertEquals("Asserted provided value to be retrieved", + choices.get(keys.get(0)), + CLIPrompter.promptChoice(out, in, keys, choices, + message, null)); + assertEquals("Asserted provided value to be retrieved", + null, CLIPrompter.promptChoice(out, in, keys, + choices, message, cancel)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size()); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + @Test + public final void testPromptChoiceConsoleManagerListOfUStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + keys.add("An other"); //$NON-NLS-1$ + final String cancel = "Cancel"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + Integer.valueOf(0), CLIPrompter.promptChoice( + out, in, keys, message, cancel)); + assertEquals("Asserted provided value to be retrieved", + Integer.valueOf(0), CLIPrompter.promptChoice( + out, in, keys, message, null)); + assertEquals("Asserted provided value to be retrieved", + Integer.valueOf(1), CLIPrompter.promptChoice( + out, in, keys, message, null)); + assertEquals("Asserted provided value to be retrieved", + null, CLIPrompter.promptChoice(out, in, keys, + message, cancel)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size()); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Success do it again + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("1"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, Map, String, String)}. */ + @Test + public final void testPromptChoiceConsoleManagerMapOfUTStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final Map choices = new HashMap<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.put(keys.get(0), new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ + final String cancel = "Cancel"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + choices.get(keys.get(0)), + CLIPrompter.promptChoice(out, in, keys, choices, + message, cancel)); + assertEquals("Asserted provided value to be retrieved", + choices.get(keys.get(0)), + CLIPrompter.promptChoice(out, in, keys, choices, + message, null)); + assertEquals("Asserted provided value to be retrieved", + null, CLIPrompter.promptChoice(out, in, keys, + choices, message, cancel)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + final String readNextLine = out.readNextLine(); + assertTrue(readNextLine + " expected to contain " + keys.get(0), + readNextLine.contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size()); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertTrue(out.readNextLine().contains(cancel)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptInteger(fr.bigeon.gclc.manager.ConsoleInput, String)}. */ + @Test + public final void testPromptInteger() { + try (PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + 10, + CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$ + assertEquals("Asserted provided value to be retrieved", + -15, + CLIPrompter.promptInteger(in, "My message")); //$NON-NLS-1$ + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type(""); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("Y"); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("10"); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type("-15"); //$NON-NLS-1$ + th.join(); + + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ + @Test + public final void testPromptListConsoleManagerString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + keys.add("An other"); //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + new ArrayList(), + CLIPrompter.promptList(out, in, message)); + assertEquals("Asserted provided value to be retrieved", + keys, CLIPrompter.promptList(out, in, message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + String nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlist.exit.dispkey", CLIPrompterMessages //$NON-NLS-1$ + .getString("promptlist.exit.defaultkey")))); //$NON-NLS-1$ + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type(CLIPrompterMessages + .getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ + // enter keys list + nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlist.exit.dispkey", CLIPrompterMessages //$NON-NLS-1$ + .getString("promptlist.exit.defaultkey")))); //$NON-NLS-1$ + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + for (int i = 0; i < keys.size(); i++) { + in.type(keys.get(i)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + } + in.type(CLIPrompterMessages + .getString("promptlist.exit.defaultkey")); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptList(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ + @Test + public final void testPromptListConsoleManagerStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + keys.add("An other"); //$NON-NLS-1$ + final String ender = "*"; //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + new ArrayList(), CLIPrompter + .promptList(out, in, message, ender)); + assertEquals("Asserted provided value to be retrieved", + keys, CLIPrompter.promptList(out, in, message, + ender)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + String nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlist.exit.dispkey", ender))); //$NON-NLS-1$ + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type(ender); + // enter keys list + nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlist.exit.dispkey", ender))); //$NON-NLS-1$ + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + for (int i = 0; i < keys.size(); i++) { + in.type(keys.get(i)); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + } + in.type(ender); + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String)}. */ + @Test + public final void testPromptLongTextConsoleManagerString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final String message = "My message"; + final String longText = "Some text with" + System.lineSeparator() + + "line feeds and other" + + System.lineSeparator() + + System.lineSeparator() + + " \tspecial characters"; + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", + "", + CLIPrompter.promptLongText(out, in, message)); + assertEquals("Asserted provided value to be retrieved", + longText + System.lineSeparator(), + CLIPrompter.promptLongText(out, in, message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + String nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages.getString( + "promptlongtext.exit.dispkey", CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + in.type(CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")); + // enter long text + nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages.getString( + "promptlongtext.exit.dispkey", CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + final String[] text = longText.split(System.lineSeparator()); + for (final String element : text) { + in.type(element); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + } + in.type(CLIPrompterMessages + .getString("promptlongtext.exit.defaultkey")); + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptLongText(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ + @Test + public final void testPromptLongTextConsoleManagerStringString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final String message = "My message"; + final String ender = "\\quit"; + final String[] text = new String[] {"Some text with", + "feeds and other", " \tspecial characters"}; + final String longText = text[0] + System.lineSeparator() + text[1] + + System.lineSeparator() + text[2]; + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Asserted provided value to be retrieved", //$NON-NLS-1$ + "", CLIPrompter.promptLongText(out, in, message, + ender)); + assertEquals("Asserted provided value to be retrieved", + longText + System.lineSeparator(), + CLIPrompter.promptLongText(out, in, message, + ender)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + String nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlongtext.exit.dispkey", ender))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + in.type(ender); + // enter long text + nLine = out.readNextLine(); + assertTrue(nLine.startsWith(message)); + assertTrue(nLine.endsWith(CLIPrompterMessages + .getString("promptlongtext.exit.dispkey", ender))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + for (final String element : text) { + in.type(element); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), + buf.readLine()); + } + in.type(ender); + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, List, String)}. */ + @Test + public final void testPromptMultiChoiceConsoleManagerListOfStringListOfUString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final List choices = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.add(new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.add("The actual other"); //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertTrue("Asserted provided value to be retrieved", + CLIPrompter.promptMultiChoice(out, in, keys, + choices, message).isEmpty()); + final ArrayList l = new ArrayList<>(); + l.add(choices.get(0)); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + l.add(choices.get(1)); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size() - 1); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type(""); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0))); + assertTrue(out.readNextLine().contains(keys.get(1))); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0 1"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, Map, String)}. */ + @Test + public final void testPromptMultiChoiceConsoleManagerListOfUMapOfUTString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final Map choices = new HashMap<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.put(keys.get(0), new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertTrue("Asserted provided value to be retrieved", + CLIPrompter.promptMultiChoice(out, in, keys, + choices, message).isEmpty()); + final ArrayList l = new ArrayList<>(); + l.add(choices.get(keys.get(0))); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + l.add(choices.get(keys.get(1))); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size() - 1); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type(""); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0 1"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, List, String)}. */ + @Test + public final void testPromptMultiChoiceConsoleManagerListOfUString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + keys.add("A choice"); //$NON-NLS-1$ + keys.add("An other"); //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertTrue("Asserted provided value to be retrieved", + CLIPrompter.promptMultiChoice(out, in, keys, + message).isEmpty()); + final ArrayList l = new ArrayList<>(); + l.add(0); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + message)); + l.add(1); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size() - 1); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type(""); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + assertEquals(CLIPrompterMessages.getString("prompt.lineprompt"), //$NON-NLS-1$ + buf.readLine()); + in.type("0 1"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptMultiChoice(fr.bigeon.gclc.manager.ConsoleOutput, fr.bigeon.gclc.manager.ConsoleInput, Map, String)}. */ + @Test + public final void testPromptMultiChoiceConsoleManagerMapOfUTString() { + try (final PipedConsoleOutput out = new PipedConsoleOutput(); + PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final List keys = new ArrayList<>(); + final Map choices = new HashMap<>(); + keys.add("A choice"); //$NON-NLS-1$ + choices.put(keys.get(0), new Integer(25)); + keys.add("An other"); //$NON-NLS-1$ + choices.put(keys.get(1), "The actual other"); //$NON-NLS-1$ + final String message = "My message"; //$NON-NLS-1$ + + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertTrue("Asserted provided value to be retrieved", + CLIPrompter.promptMultiChoice(out, in, keys, + choices, message).isEmpty()); + final ArrayList l = new ArrayList<>(); + l.add(choices.get(keys.get(0))); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + l.add(choices.get(keys.get(1))); + assertEquals("Asserted provided value to be retrieved", + l, CLIPrompter.promptMultiChoice(out, in, keys, + choices, message)); + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(out.readNextLine().startsWith(message)); + final String readNextLine = out.readNextLine(); + assertTrue(readNextLine + " expected to contain " + keys.get(0), + readNextLine.contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + in.type("yoyo"); //$NON-NLS-1$ + // fail, reprompt + final String msg = CLIPrompterMessages.getString( + "promptchoice.formaterr", //$NON-NLS-1$ + 0, keys.size() - 1); + for (final String line : msg.split(System.lineSeparator())) { + assertEquals(line, out.readNextLine()); + } + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + in.type(""); //$NON-NLS-1$ + // Sucess, reprompt without cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + in.type("2"); //$NON-NLS-1$ + // fail, reprompt + assertEquals( + CLIPrompterMessages.getString("promptchoice.outofbounds", 0, //$NON-NLS-1$ + keys.size() - 1), + out.readNextLine()); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + in.type("0"); //$NON-NLS-1$ + // Sucess, prompt with cancel + assertTrue(out.readNextLine().startsWith(message)); + assertTrue(out.readNextLine().contains(keys.get(0).toString())); + assertTrue(out.readNextLine().contains(keys.get(1).toString())); + in.type("0 1"); //$NON-NLS-1$ + th.join(); + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion, the other thread probably failed"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + + /** Test method for + * {@link fr.bigeon.gclc.prompt.CLIPrompter#promptNonEmpty(fr.bigeon.gclc.manager.ConsoleInput, String, String)}. */ + @Test + public final void testPromptNonEmpty() { + try (PipedOutputStream pout = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(pout); + BufferedReader buf = new BufferedReader( + new InputStreamReader(pis, StandardCharsets.UTF_8)); + PipedConsoleInput in = new PipedConsoleInput( + new PrintStream(pout))) { + final String res = "some content"; //$NON-NLS-1$ + final Thread th = new Thread(new Runnable() { + + @Override + public void run() { + try { + assertEquals("Expected provided message to be returned", + res, CLIPrompter.promptNonEmpty(in, + "My message", "my reprompt")); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (final IOException e) { + fail("Unexpected io excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + }); + th.start(); + assertTrue(buf.readLine().startsWith("My message")); //$NON-NLS-1$ + in.type(""); //$NON-NLS-1$ + assertTrue(buf.readLine().startsWith("my reprompt")); //$NON-NLS-1$ + in.type(res); + th.join(); + + } catch (IOException | InterruptedException e) { + fail("Unexpected excpetion"); //$NON-NLS-1$ + e.printStackTrace(); + } + } + +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/tools/AOutputForwardRunnableTest.java b/gclc/src/test/java/fr/bigeon/gclc/tools/AOutputForwardRunnableTest.java index 6672011..05bc0d6 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/tools/AOutputForwardRunnableTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/tools/AOutputForwardRunnableTest.java @@ -1,140 +1,174 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.tools.AOutputForwardRunnableTest.java - * Created on: Dec 3, 2016 - */ -package fr.bigeon.gclc.tools; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.junit.Test; - -import fr.bigeon.gclc.manager.PipedConsoleOutput; - -/**

- * TODO - * - * @author Emmanuel Bigeon */ -public class AOutputForwardRunnableTest { - - /**

- * TODO - * - * @author Emmanuel Bigeon */ - private final class AOutputForwardTestRunnable - extends AOutputForwardRunnable { - private int count = 2; - private String message; - - private AOutputForwardTestRunnable(final PipedConsoleOutput manager) { - super(manager); - } - - @Override - protected void forwardLine(final String m) { - // Do nothing - message = m; - synchronized (this) { - notify(); - try { - wait(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - /** @return the message */ - public String getMessage() { - if (message == null) { - synchronized (this) { - try { - wait(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - final String m = message; - count--; - message = null; - synchronized (this) { - notify(); - } - return m; - } - - @Override - protected boolean isRunning() { - return count != 0; - } - } - - /** Test method for - * {@link fr.bigeon.gclc.tools.AOutputForwardRunnable#run()}. */ - @Test - public final void testRun() { - try (PipedConsoleOutput manager = new PipedConsoleOutput()) { - final AOutputForwardTestRunnable runnable = new AOutputForwardTestRunnable( - manager); - - final Thread th = new Thread(runnable, "forward"); - manager.println("before"); - th.start(); - - assertEquals("before", runnable.getMessage()); - - synchronized (this) { - wait(3000); - } - manager.println("after"); - assertEquals("after", runnable.getMessage()); - synchronized (this) { - wait(3000); - } - - th.join(); - - } catch (IOException | InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.tools.AOutputForwardRunnableTest.java + * Created on: Dec 3, 2016 + */ +package fr.bigeon.gclc.tools; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +import fr.bigeon.gclc.utils.AOutputForwardRunnable; +import fr.bigeon.gclc.utils.PipedConsoleOutput; + +/**

+ * TODO + * + * @author Emmanuel Bigeon */ +public class AOutputForwardRunnableTest { + + /**

+ * TODO + * + * @author Emmanuel Bigeon */ + private final class AOutputForwardTestRunnable + extends AOutputForwardRunnable { + private int count = 2; + private String message; + + private AOutputForwardTestRunnable(final PipedConsoleOutput manager) { + super(manager); + } + + @Override + protected void forwardLine(final String m) { + // Do nothing + message = m; + synchronized (this) { + notify(); + try { + wait(); + } catch (final InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + /** @return the message */ + public String getMessage() { + if (message == null) { + synchronized (this) { + try { + wait(); + } catch (final InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + final String m = message; + count--; + message = null; + synchronized (this) { + notify(); + } + return m; + } + + @Override + protected boolean isRunning() { + return count != 0; + } + } + + /** Test method for + * {@link fr.bigeon.gclc.utils.AOutputForwardRunnable#run()}. */ + @Test + public final void testRun() { + try (PipedConsoleOutput manager = new PipedConsoleOutput()) { + final AOutputForwardTestRunnable runnable = new AOutputForwardTestRunnable( + manager); + + final Thread th = new Thread(runnable, "forward"); + manager.println("before"); + th.start(); + + assertEquals("before", runnable.getMessage()); + + synchronized (this) { + wait(3000); + } + manager.println("after"); + assertEquals("after", runnable.getMessage()); + synchronized (this) { + wait(3000); + } + + th.join(); + + } catch (IOException | InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java b/gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java index a593f49..d5d2776 100644 --- a/gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java +++ b/gclc/src/test/java/fr/bigeon/gclc/tools/PrintUtilsTest.java @@ -1,94 +1,127 @@ -/* - * Copyright Bigeon Emmanuel (2014) - * - * emmanuel@bigeon.fr - * - * This software is a computer program whose purpose is to - * provide a generic framework for console applications. - * - * This software is governed by the CeCILL license under French law and - * abiding by the rules of distribution of free software. You can use, - * modify and/or redistribute the software under the terms of the CeCILL - * license as circulated by CEA, CNRS and INRIA at the following URL - * "http://www.cecill.info". - * - * As a counterpart to the access to the source code and rights to copy, - * modify and redistribute granted by the license, users are provided only - * with a limited warranty and the software's author, the holder of the - * economic rights, and the successive licensors have only limited - * liability. - * - * In this respect, the user's attention is drawn to the risks associated - * with loading, using, modifying and/or developing or reproducing the - * software by the user in light of its specific status of free software, - * that may mean that it is complicated to manipulate, and that also - * therefore means that it is reserved for developers and experienced - * professionals having in-depth computer knowledge. Users are therefore - * encouraged to load and test the software's suitability as regards their - * requirements in conditions enabling the security of their systems and/or - * data to be ensured and, more generally, to use and operate it in the - * same conditions as regards security. - * - * The fact that you are presently reading this means that you have had - * knowledge of the CeCILL license and that you accept its terms. - */ -/** - * gclc:fr.bigeon.gclc.tools.PrintUtilsTest.java - * Created on: Nov 19, 2016 - */ -package fr.bigeon.gclc.tools; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; - -import org.junit.Test; - -/**

- * TODO - * - * @author Emmanuel Bigeon */ -public class PrintUtilsTest { - - /** Test method for - * {@link fr.bigeon.gclc.tools.PrintUtils#print(java.lang.String, int, boolean)}. */ - @Test - public final void testPrint() { - String text = "Some text"; - String longText = text + " that may be abbreviated"; - assertEquals(text, PrintUtils.print(text, text.length(), true)); - assertEquals(text, PrintUtils.print(text, text.length(), false)); - assertEquals(text + " ", - PrintUtils.print(text, text.length() + 3, false)); - assertEquals(text + " ", - PrintUtils.print(text, text.length() + 3, true)); - assertEquals(text, PrintUtils.print(longText, text.length(), false)); - assertEquals(text + "...", - PrintUtils.print(longText, text.length() + 3, true)); - } - - /** Test method for - * {@link fr.bigeon.gclc.tools.PrintUtils#wrap(java.lang.String, int)}. */ - @Test - public final void testWrap() { - String[] line = {"A text separated", "on several lines", "with cuts at", - "whitespace", "characters"}; - String text = line[0] + " " + line[1] + " " + line[2] + " " + line[3] + - " " + line[4]; - assertEquals(Arrays.asList(line), - PrintUtils.wrap(text, line[0].length() + 1)); - assertEquals(Arrays.asList(line), - PrintUtils.wrap(text, line[0].length())); - - // test with split word - line = new String[] {"A text separated", "on several lines", "", - "with cuts at", "whitespacecharac", "ters"}; - text = line[0] + " " + line[1] + System.lineSeparator() + line[3] + - " " + line[4] + line[5]; - assertEquals(Arrays.asList(line), - PrintUtils.wrap(text, line[0].length())); - assertEquals(Arrays.asList(""), - PrintUtils.wrap("", line[0].length())); - } - -} +/* + * Copyright Bigeon Emmanuel (2014) + * + * emmanuel@bigeon.fr + * + * This software is a computer program whose purpose is to + * provide a generic framework for console applications. + * + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + */ +/** + * gclc:fr.bigeon.gclc.tools.PrintUtilsTest.java + * Created on: Nov 19, 2016 + */ +package fr.bigeon.gclc.tools; + +/*- + * #%L + * Generic Command Ligne console + * %% + * Copyright (C) 2014 - 2018 bigeon.fr + * %% + * This software is governed by the CeCILL license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * As a counterpart to the access to the source code and rights to copy, + * modify and redistribute granted by the license, users are provided only + * with a limited warranty and the software's author, the holder of the + * economic rights, and the successive licensors have only limited + * liability. + * + * In this respect, the user's attention is drawn to the risks associated + * with loading, using, modifying and/or developing or reproducing the + * software by the user in light of its specific status of free software, + * that may mean that it is complicated to manipulate, and that also + * therefore means that it is reserved for developers and experienced + * professionals having in-depth computer knowledge. Users are therefore + * encouraged to load and test the software's suitability as regards their + * requirements in conditions enabling the security of their systems and/or + * data to be ensured and, more generally, to use and operate it in the + * same conditions as regards security. + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL license and that you accept its terms. + * #L% + */ +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.Test; + +/**

+ * TODO + * + * @author Emmanuel Bigeon */ +public class PrintUtilsTest { + + /** Test method for + * {@link fr.bigeon.gclc.tools.PrintUtils#print(java.lang.String, int, boolean)}. */ + @Test + public final void testPrint() { + String text = "Some text"; + String longText = text + " that may be abbreviated"; + assertEquals(text, PrintUtils.print(text, text.length(), true)); + assertEquals(text, PrintUtils.print(text, text.length(), false)); + assertEquals(text + " ", + PrintUtils.print(text, text.length() + 3, false)); + assertEquals(text + " ", + PrintUtils.print(text, text.length() + 3, true)); + assertEquals(text, PrintUtils.print(longText, text.length(), false)); + assertEquals(text + "...", + PrintUtils.print(longText, text.length() + 3, true)); + } + + /** Test method for + * {@link fr.bigeon.gclc.tools.PrintUtils#wrap(java.lang.String, int)}. */ + @Test + public final void testWrap() { + String[] line = {"A text separated", "on several lines", "with cuts at", + "whitespace", "characters"}; + String text = line[0] + " " + line[1] + " " + line[2] + " " + line[3] + + " " + line[4]; + assertEquals(Arrays.asList(line), + PrintUtils.wrap(text, line[0].length() + 1)); + assertEquals(Arrays.asList(line), + PrintUtils.wrap(text, line[0].length())); + + // test with split word + line = new String[] {"A text separated", "on several lines", "", + "with cuts at", "whitespacecharac", "ters"}; + text = line[0] + " " + line[1] + System.lineSeparator() + line[3] + + " " + line[4] + line[5]; + assertEquals(Arrays.asList(line), + PrintUtils.wrap(text, line[0].length())); + assertEquals(Arrays.asList(""), + PrintUtils.wrap("", line[0].length())); + } + +} diff --git a/gclc/src/test/resources/script1.gclc b/gclc/src/test/resources/script1.gclc new file mode 100644 index 0000000..c3905ca --- /dev/null +++ b/gclc/src/test/resources/script1.gclc @@ -0,0 +1,33 @@ +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 bigeon.fr +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### diff --git a/gclc/src/test/resources/script1.txt b/gclc/src/test/resources/script1.txt deleted file mode 100644 index e69de29..0000000 diff --git a/gclc/src/test/resources/script2.txt b/gclc/src/test/resources/script2.txt index 5bafb5f..faabb82 100644 --- a/gclc/src/test/resources/script2.txt +++ b/gclc/src/test/resources/script2.txt @@ -1 +1,34 @@ -# test only comment \ No newline at end of file +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# test only comment diff --git a/gclc/src/test/resources/script3.txt b/gclc/src/test/resources/script3.txt index 30d74d2..abec884 100644 --- a/gclc/src/test/resources/script3.txt +++ b/gclc/src/test/resources/script3.txt @@ -1 +1,34 @@ -test \ No newline at end of file +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +test diff --git a/gclc/src/test/resources/script4.txt b/gclc/src/test/resources/script4.txt index ece2ab2..e873546 100644 --- a/gclc/src/test/resources/script4.txt +++ b/gclc/src/test/resources/script4.txt @@ -1,7 +1,40 @@ -# Test file with commands -test -# and comments -long -# interwined - -# with empty line too +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# Test file with commands +test +# and comments +long +# interwined + +# with empty line too diff --git a/gclc/src/test/resources/script5.txt b/gclc/src/test/resources/script5.txt index 6bf36ac..6b9c705 100644 --- a/gclc/src/test/resources/script5.txt +++ b/gclc/src/test/resources/script5.txt @@ -1,2 +1,35 @@ -# A script with arguments -{0} +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# A script with arguments +{0} diff --git a/gclc/src/test/resources/scripts/failingCmdInvoc.txt b/gclc/src/test/resources/scripts/failingCmdInvoc.txt index 092889f..a924e6d 100644 --- a/gclc/src/test/resources/scripts/failingCmdInvoc.txt +++ b/gclc/src/test/resources/scripts/failingCmdInvoc.txt @@ -1,2 +1,35 @@ -# a script invoking a failing command -failingCmd +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# a script invoking a failing command +failingCmd diff --git a/gclc/src/test/resources/scripts/invalidCmd.txt b/gclc/src/test/resources/scripts/invalidCmd.txt index e3793f3..e07044d 100644 --- a/gclc/src/test/resources/scripts/invalidCmd.txt +++ b/gclc/src/test/resources/scripts/invalidCmd.txt @@ -1,2 +1,35 @@ -# a script with invalid commands -invalid +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# a script with invalid commands +invalid diff --git a/gclc/src/test/resources/scripts/invalidCmdParse.txt b/gclc/src/test/resources/scripts/invalidCmdParse.txt index ca3f1a9..7c82287 100644 --- a/gclc/src/test/resources/scripts/invalidCmdParse.txt +++ b/gclc/src/test/resources/scripts/invalidCmdParse.txt @@ -1,2 +1,35 @@ -# a script with invalid commands -test "po"m +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# a script with invalid commands +test "po"m diff --git a/gclc/src/test/resources/scripts/withprependSpace.txt b/gclc/src/test/resources/scripts/withprependSpace.txt index e640bf3..1015cd4 100644 --- a/gclc/src/test/resources/scripts/withprependSpace.txt +++ b/gclc/src/test/resources/scripts/withprependSpace.txt @@ -1,3 +1,36 @@ -# a script with space in begining - test - should never be reached \ No newline at end of file +### +# #%L +# Generic Command Ligne console +# %% +# Copyright (C) 2014 - 2018 Bigeon +# %% +# This software is governed by the CeCILL license under French law and +# abiding by the rules of distribution of free software. You can use, +# modify and/ or redistribute the software under the terms of the CeCILL +# license as circulated by CEA, CNRS and INRIA at the following URL +# "http://www.cecill.info". +# +# As a counterpart to the access to the source code and rights to copy, +# modify and redistribute granted by the license, users are provided only +# with a limited warranty and the software's author, the holder of the +# economic rights, and the successive licensors have only limited +# liability. +# +# In this respect, the user's attention is drawn to the risks associated +# with loading, using, modifying and/or developing or reproducing the +# software by the user in light of its specific status of free software, +# that may mean that it is complicated to manipulate, and that also +# therefore means that it is reserved for developers and experienced +# professionals having in-depth computer knowledge. Users are therefore +# encouraged to load and test the software's suitability as regards their +# requirements in conditions enabling the security of their systems and/or +# data to be ensured and, more generally, to use and operate it in the +# same conditions as regards security. +# +# The fact that you are presently reading this means that you have had +# knowledge of the CeCILL license and that you accept its terms. +# #L% +### +# a script with space in begining + test + should never be reached