Repository: DomHeal/JavaFX-Chat Branch: master Commit: 43afdec30d4e Files: 46 Total size: 145.0 KB Directory structure: gitextract_e98itcgw/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── client/ │ ├── pom.xml │ └── src/ │ └── main/ │ ├── java/ │ │ └── com/ │ │ ├── client/ │ │ │ ├── chatwindow/ │ │ │ │ ├── CellRenderer.java │ │ │ │ ├── ChatController.java │ │ │ │ └── Listener.java │ │ │ ├── login/ │ │ │ │ ├── LoginController.java │ │ │ │ └── MainLauncher.java │ │ │ └── util/ │ │ │ ├── ResizeHelper.java │ │ │ ├── VoicePlayback.java │ │ │ ├── VoiceRecorder.java │ │ │ └── VoiceUtil.java │ │ ├── messages/ │ │ │ ├── Message.java │ │ │ ├── MessageType.java │ │ │ ├── Status.java │ │ │ ├── User.java │ │ │ └── bubble/ │ │ │ ├── Bubble.java │ │ │ ├── BubbleSpec.java │ │ │ └── BubbledLabel.java │ │ └── traynotifications/ │ │ ├── animations/ │ │ │ ├── AnimationProvider.java │ │ │ ├── AnimationType.java │ │ │ ├── FadeAnimation.java │ │ │ ├── PopupAnimation.java │ │ │ ├── SlideAnimation.java │ │ │ └── TrayAnimation.java │ │ ├── models/ │ │ │ ├── CustomStage.java │ │ │ └── Location.java │ │ └── notification/ │ │ ├── NotificationType.java │ │ └── TrayNotification.java │ └── resources/ │ ├── styles/ │ │ ├── ButtonStyle.css │ │ ├── ChatViewStyle.css │ │ ├── ComboBox.css │ │ ├── ListViewStyle.css │ │ └── Login.css │ └── views/ │ ├── ChatView.fxml │ ├── LoginView.fxml │ └── TrayNotification.fxml ├── pom.xml └── server/ ├── pom.xml └── src/ └── main/ └── java/ └── com/ ├── exception/ │ └── DuplicateUsernameException.java ├── messages/ │ ├── Message.java │ ├── MessageType.java │ ├── Status.java │ └── User.java └── server/ └── Server.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) ### Java template # Compiled class file *.class # Log file *.log # BlueJ files *.ctxt # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ### JetBrains template # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff: .idea/**/workspace.xml .idea/**/tasks.xml .idea/dictionaries # Sensitive or high-churn files: .idea/**/dataSources/ .idea/**/dataSources.ids .idea/**/dataSources.xml .idea/**/dataSources.local.xml .idea/**/sqlDataSources.xml .idea/**/dynamic.xml .idea/**/uiDesigner.xml # Gradle: .idea/**/gradle.xml .idea/**/libraries # CMake cmake-build-debug/ # Mongo Explorer plugin: .idea/**/mongoSettings.xml ## File-based project format: *.iws ## Plugin-specific files: # IntelliJ out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Cursive Clojure plugin .idea/replstate.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties ### Eclipse template .metadata bin/ tmp/ *.tmp *.bak *.swp *~.nib local.properties .settings/ .loadpath .recommenders # External tool builders .externalToolBuilders/ # Locally stored "Eclipse launch configurations" *.launch # PyDev specific (Python IDE for Eclipse) *.pydevproject # CDT-specific (C/C++ Development Tooling) .cproject # Java annotation processor (APT) .factorypath # PDT-specific (PHP Development Tools) .buildpath # sbteclipse plugin .target # Tern plugin .tern-project # TeXlipse plugin .texlipse # STS (Spring Tool Suite) .springBeans # Code Recommenders .recommenders/ # Scala IDE specific (Scala & Java development for Eclipse) .cache-main .scala_dependencies .worksheet /client/target/ /server/target/ .idea/ JavaFx.iml /server/server.iml /client/client.iml ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS JavaFX-Chat - A Java FX Chat Client which communicates via sockets Copyright (C) 2016 Dominic Heal www.dominicheal.com - www.github.com/DomHeal This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ================================================ FILE: README.md ================================================ # JavaFx-SocketChat A small application which using JavaFX for a GUI chat application. Currently in Development.


Notifications using Tray-Notifications Library

To-Do

New Features! - Voice Messages

================================================ FILE: client/pom.xml ================================================ 4.0.0 groupId JavaFx 1.0-SNAPSHOT client jar org.apache.maven.plugins maven-jar-plugin true com.client.login.MainLauncher org.apache.maven.plugins maven-assembly-plugin 2.4.1 jar-with-dependencies com.client.login.MainLauncher make-assembly package single 1.6.1 org.fxmisc.richtext richtextfx 0.6.10 org.controlsfx controlsfx 8.40.10 org.slf4j slf4j-api 1.5.6 jar org.slf4j slf4j-simple 1.5.6 ================================================ FILE: client/src/main/java/com/client/chatwindow/CellRenderer.java ================================================ package com.client.chatwindow; import com.messages.User; import javafx.geometry.Pos; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.util.Callback; /** * A Class for Rendering users images / name on the userlist. */ class CellRenderer implements Callback,ListCell>{ @Override public ListCell call(ListView p) { ListCell cell = new ListCell(){ @Override protected void updateItem(User user, boolean bln) { super.updateItem(user, bln); setGraphic(null); setText(null); if (user != null) { HBox hBox = new HBox(); Text name = new Text(user.getName()); ImageView statusImageView = new ImageView(); Image statusImage = new Image(getClass().getClassLoader().getResource("images/" + user.getStatus().toString().toLowerCase() + ".png").toString(), 16, 16,true,true); statusImageView.setImage(statusImage); ImageView pictureImageView = new ImageView(); Image image = new Image(getClass().getClassLoader().getResource("images/" + user.getPicture().toLowerCase() + ".png").toString(),50,50,true,true); pictureImageView.setImage(image); hBox.getChildren().addAll(statusImageView, pictureImageView, name); hBox.setAlignment(Pos.CENTER_LEFT); setGraphic(hBox); } } }; return cell; } } ================================================ FILE: client/src/main/java/com/client/chatwindow/ChatController.java ================================================ package com.client.chatwindow; import com.client.login.MainLauncher; import com.client.util.VoicePlayback; import com.client.util.VoiceRecorder; import com.client.util.VoiceUtil; import com.messages.Message; import com.messages.MessageType; import com.messages.Status; import com.messages.User; import com.messages.bubble.BubbleSpec; import com.messages.bubble.BubbledLabel; import com.traynotifications.animations.AnimationType; import com.traynotifications.notification.TrayNotification; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.stage.Stage; import javafx.util.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ChatController implements Initializable { @FXML private TextArea messageBox; @FXML private Label usernameLabel; @FXML private Label onlineCountLabel; @FXML private ListView userList; @FXML private ImageView userImageView; @FXML private Button recordBtn; @FXML ListView chatPane; @FXML ListView statusList; @FXML BorderPane borderPane; @FXML ComboBox statusComboBox; @FXML ImageView microphoneImageView; Image microphoneActiveImage = new Image(getClass().getClassLoader().getResource("images/microphone-active.png").toString()); Image microphoneInactiveImage = new Image(getClass().getClassLoader().getResource("images/microphone.png").toString()); private double xOffset; private double yOffset; Logger logger = LoggerFactory.getLogger(ChatController.class); public void sendButtonAction() throws IOException { String msg = messageBox.getText(); if (!messageBox.getText().isEmpty()) { Listener.send(msg); messageBox.clear(); } } public void recordVoiceMessage() throws IOException { if (VoiceUtil.isRecording()) { Platform.runLater(() -> { microphoneImageView.setImage(microphoneInactiveImage); } ); VoiceUtil.setRecording(false); } else { Platform.runLater(() -> { microphoneImageView.setImage(microphoneActiveImage); } ); VoiceRecorder.captureAudio(); } } public synchronized void addToChat(Message msg) { Task othersMessages = new Task() { @Override public HBox call() throws Exception { Image image = new Image(getClass().getClassLoader().getResource("images/" + msg.getPicture().toLowerCase() + ".png").toString()); ImageView profileImage = new ImageView(image); profileImage.setFitHeight(32); profileImage.setFitWidth(32); BubbledLabel bl6 = new BubbledLabel(); if (msg.getType() == MessageType.VOICE){ ImageView imageview = new ImageView(new Image(getClass().getClassLoader().getResource("images/sound.png").toString())); bl6.setGraphic(imageview); bl6.setText("Sent a voice message!"); VoicePlayback.playAudio(msg.getVoiceMsg()); }else { bl6.setText(msg.getName() + ": " + msg.getMsg()); } bl6.setBackground(new Background(new BackgroundFill(Color.WHITE,null, null))); HBox x = new HBox(); bl6.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER); x.getChildren().addAll(profileImage, bl6); logger.debug("ONLINE USERS: " + Integer.toString(msg.getUserlist().size())); setOnlineLabel(Integer.toString(msg.getOnlineCount())); return x; } }; othersMessages.setOnSucceeded(event -> { chatPane.getItems().add(othersMessages.getValue()); }); Task yourMessages = new Task() { @Override public HBox call() throws Exception { Image image = userImageView.getImage(); ImageView profileImage = new ImageView(image); profileImage.setFitHeight(32); profileImage.setFitWidth(32); BubbledLabel bl6 = new BubbledLabel(); if (msg.getType() == MessageType.VOICE){ bl6.setGraphic(new ImageView(new Image(getClass().getClassLoader().getResource("images/sound.png").toString()))); bl6.setText("Sent a voice message!"); VoicePlayback.playAudio(msg.getVoiceMsg()); }else { bl6.setText(msg.getMsg()); } bl6.setBackground(new Background(new BackgroundFill(Color.LIGHTGREEN, null, null))); HBox x = new HBox(); x.setMaxWidth(chatPane.getWidth() - 20); x.setAlignment(Pos.TOP_RIGHT); bl6.setBubbleSpec(BubbleSpec.FACE_RIGHT_CENTER); x.getChildren().addAll(bl6, profileImage); setOnlineLabel(Integer.toString(msg.getOnlineCount())); return x; } }; yourMessages.setOnSucceeded(event -> chatPane.getItems().add(yourMessages.getValue())); if (msg.getName().equals(usernameLabel.getText())) { Thread t2 = new Thread(yourMessages); t2.setDaemon(true); t2.start(); } else { Thread t = new Thread(othersMessages); t.setDaemon(true); t.start(); } } public void setUsernameLabel(String username) { this.usernameLabel.setText(username); } public void setImageLabel() throws IOException { this.userImageView.setImage(new Image(getClass().getClassLoader().getResource("images/dominic.png").toString())); } public void setOnlineLabel(String usercount) { Platform.runLater(() -> onlineCountLabel.setText(usercount)); } public void setUserList(Message msg) { logger.info("setUserList() method Enter"); Platform.runLater(() -> { ObservableList users = FXCollections.observableList(msg.getUsers()); userList.setItems(users); userList.setCellFactory(new CellRenderer()); setOnlineLabel(String.valueOf(msg.getUserlist().size())); }); logger.info("setUserList() method Exit"); } /* Displays Notification when a user joins */ public void newUserNotification(Message msg) { Platform.runLater(() -> { Image profileImg = new Image(getClass().getClassLoader().getResource("images/" + msg.getPicture().toLowerCase() +".png").toString(),50,50,false,false); TrayNotification tray = new TrayNotification(); tray.setTitle("A new user has joined!"); tray.setMessage(msg.getName() + " has joined the JavaFX Chatroom!"); tray.setRectangleFill(Paint.valueOf("#2C3E50")); tray.setAnimationType(AnimationType.POPUP); tray.setImage(profileImg); tray.showAndDismiss(Duration.seconds(5)); try { Media hit = new Media(getClass().getClassLoader().getResource("sounds/notification.wav").toString()); MediaPlayer mediaPlayer = new MediaPlayer(hit); mediaPlayer.play(); } catch (Exception e) { e.printStackTrace(); } }); } public void sendMethod(KeyEvent event) throws IOException { if (event.getCode() == KeyCode.ENTER) { sendButtonAction(); } } @FXML public void closeApplication() { Platform.exit(); System.exit(0); } /* Method to display server messages */ public synchronized void addAsServer(Message msg) { Task task = new Task() { @Override public HBox call() throws Exception { BubbledLabel bl6 = new BubbledLabel(); bl6.setText(msg.getMsg()); bl6.setBackground(new Background(new BackgroundFill(Color.ALICEBLUE, null, null))); HBox x = new HBox(); bl6.setBubbleSpec(BubbleSpec.FACE_BOTTOM); x.setAlignment(Pos.CENTER); x.getChildren().addAll(bl6); return x; } }; task.setOnSucceeded(event -> { chatPane.getItems().add(task.getValue()); }); Thread t = new Thread(task); t.setDaemon(true); t.start(); } @Override public void initialize(URL location, ResourceBundle resources) { try { setImageLabel(); } catch (IOException e) { e.printStackTrace(); } /* Drag and Drop */ borderPane.setOnMousePressed(event -> { xOffset = MainLauncher.getPrimaryStage().getX() - event.getScreenX(); yOffset = MainLauncher.getPrimaryStage().getY() - event.getScreenY(); borderPane.setCursor(Cursor.CLOSED_HAND); }); borderPane.setOnMouseDragged(event -> { MainLauncher.getPrimaryStage().setX(event.getScreenX() + xOffset); MainLauncher.getPrimaryStage().setY(event.getScreenY() + yOffset); }); borderPane.setOnMouseReleased(event -> { borderPane.setCursor(Cursor.DEFAULT); }); statusComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { public void changed(ObservableValue observable, String oldValue, String newValue) { try { Listener.sendStatusUpdate(Status.valueOf(newValue.toUpperCase())); } catch (IOException e) { e.printStackTrace(); } } }); /* Added to prevent the enter from adding a new line to inputMessageBox */ messageBox.addEventFilter(KeyEvent.KEY_PRESSED, ke -> { if (ke.getCode().equals(KeyCode.ENTER)) { try { sendButtonAction(); } catch (IOException e) { e.printStackTrace(); } ke.consume(); } }); } public void setImageLabel(String selectedPicture) { switch (selectedPicture) { case "Dominic": this.userImageView.setImage(new Image(getClass().getClassLoader().getResource("images/dominic.png").toString())); break; case "Sarah": this.userImageView.setImage(new Image(getClass().getClassLoader().getResource("images/sarah.png").toString())); break; case "Default": this.userImageView.setImage(new Image(getClass().getClassLoader().getResource("images/default.png").toString())); break; } } public void logoutScene() { Platform.runLater(() -> { FXMLLoader fmxlLoader = new FXMLLoader(getClass().getResource("/views/LoginView.fxml")); Parent window = null; try { window = (Pane) fmxlLoader.load(); } catch (IOException e) { e.printStackTrace(); } Stage stage = MainLauncher.getPrimaryStage(); Scene scene = new Scene(window); stage.setMaxWidth(350); stage.setMaxHeight(420); stage.setResizable(false); stage.setScene(scene); stage.centerOnScreen(); }); } } ================================================ FILE: client/src/main/java/com/client/chatwindow/Listener.java ================================================ package com.client.chatwindow; import com.client.login.LoginController; import com.messages.Message; import com.messages.MessageType; import com.messages.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.Socket; import static com.messages.MessageType.CONNECTED; public class Listener implements Runnable{ private static final String HASCONNECTED = "has connected"; private static String picture; private Socket socket; public String hostname; public int port; public static String username; public ChatController controller; private static ObjectOutputStream oos; private InputStream is; private ObjectInputStream input; private OutputStream outputStream; Logger logger = LoggerFactory.getLogger(Listener.class); public Listener(String hostname, int port, String username, String picture, ChatController controller) { this.hostname = hostname; this.port = port; Listener.username = username; Listener.picture = picture; this.controller = controller; } public void run() { try { socket = new Socket(hostname, port); LoginController.getInstance().showScene(); outputStream = socket.getOutputStream(); oos = new ObjectOutputStream(outputStream); is = socket.getInputStream(); input = new ObjectInputStream(is); } catch (IOException e) { LoginController.getInstance().showErrorDialog("Could not connect to server"); logger.error("Could not Connect"); } logger.info("Connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); try { connect(); logger.info("Sockets in and out ready!"); while (socket.isConnected()) { Message message = null; message = (Message) input.readObject(); if (message != null) { logger.debug("Message recieved:" + message.getMsg() + " MessageType:" + message.getType() + "Name:" + message.getName()); switch (message.getType()) { case USER: controller.addToChat(message); break; case VOICE: controller.addToChat(message); break; case NOTIFICATION: controller.newUserNotification(message); break; case SERVER: controller.addAsServer(message); break; case CONNECTED: controller.setUserList(message); break; case DISCONNECTED: controller.setUserList(message); break; case STATUS: controller.setUserList(message); break; } } } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); controller.logoutScene(); } } /* This method is used for sending a normal Message * @param msg - The message which the user generates */ public static void send(String msg) throws IOException { Message createMessage = new Message(); createMessage.setName(username); createMessage.setType(MessageType.USER); createMessage.setStatus(Status.AWAY); createMessage.setMsg(msg); createMessage.setPicture(picture); oos.writeObject(createMessage); oos.flush(); } /* This method is used for sending a voice Message * @param msg - The message which the user generates */ public static void sendVoiceMessage(byte[] audio) throws IOException { Message createMessage = new Message(); createMessage.setName(username); createMessage.setType(MessageType.VOICE); createMessage.setStatus(Status.AWAY); createMessage.setVoiceMsg(audio); createMessage.setPicture(picture); oos.writeObject(createMessage); oos.flush(); } /* This method is used for sending a normal Message * @param msg - The message which the user generates */ public static void sendStatusUpdate(Status status) throws IOException { Message createMessage = new Message(); createMessage.setName(username); createMessage.setType(MessageType.STATUS); createMessage.setStatus(status); createMessage.setPicture(picture); oos.writeObject(createMessage); oos.flush(); } /* This method is used to send a connecting message */ public static void connect() throws IOException { Message createMessage = new Message(); createMessage.setName(username); createMessage.setType(CONNECTED); createMessage.setMsg(HASCONNECTED); createMessage.setPicture(picture); oos.writeObject(createMessage); } } ================================================ FILE: client/src/main/java/com/client/login/LoginController.java ================================================ package com.client.login; import com.client.chatwindow.ChatController; import com.client.chatwindow.Listener; import com.client.util.ResizeHelper; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Cursor; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Duration; import java.io.IOException; import java.net.URL; import java.util.Random; import java.util.ResourceBundle; /** * Created by Dominic on 12-Nov-15. */ public class LoginController implements Initializable { @FXML private ImageView Defaultview; @FXML private ImageView Sarahview; @FXML private ImageView Dominicview; @FXML public TextField hostnameTextfield; @FXML private TextField portTextfield; @FXML private TextField usernameTextfield; @FXML private ChoiceBox imagePicker; @FXML private Label selectedPicture; public static ChatController con; @FXML private BorderPane borderPane; private double xOffset; private double yOffset; private Scene scene; private static LoginController instance; public LoginController() { instance = this; } public static LoginController getInstance() { return instance; } public void loginButtonAction() throws IOException { String hostname = hostnameTextfield.getText(); int port = Integer.parseInt(portTextfield.getText()); String username = usernameTextfield.getText(); String picture = selectedPicture.getText(); FXMLLoader fmxlLoader = new FXMLLoader(getClass().getResource("/views/ChatView.fxml")); Parent window = (Pane) fmxlLoader.load(); con = fmxlLoader.getController(); Listener listener = new Listener(hostname, port, username, picture, con); Thread x = new Thread(listener); x.start(); this.scene = new Scene(window); } public void showScene() throws IOException { Platform.runLater(() -> { Stage stage = (Stage) hostnameTextfield.getScene().getWindow(); stage.setResizable(true); stage.setWidth(1040); stage.setHeight(620); stage.setOnCloseRequest((WindowEvent e) -> { Platform.exit(); System.exit(0); }); stage.setScene(this.scene); stage.setMinWidth(800); stage.setMinHeight(300); ResizeHelper.addResizeListener(stage); stage.centerOnScreen(); con.setUsernameLabel(usernameTextfield.getText()); con.setImageLabel(selectedPicture.getText()); }); } @Override public void initialize(URL location, ResourceBundle resources) { imagePicker.getSelectionModel().selectFirst(); selectedPicture.textProperty().bind(imagePicker.getSelectionModel().selectedItemProperty()); selectedPicture.setVisible(false); /* Drag and Drop */ borderPane.setOnMousePressed(event -> { xOffset = MainLauncher.getPrimaryStage().getX() - event.getScreenX(); yOffset = MainLauncher.getPrimaryStage().getY() - event.getScreenY(); borderPane.setCursor(Cursor.CLOSED_HAND); }); borderPane.setOnMouseDragged(event -> { MainLauncher.getPrimaryStage().setX(event.getScreenX() + xOffset); MainLauncher.getPrimaryStage().setY(event.getScreenY() + yOffset); }); borderPane.setOnMouseReleased(event -> { borderPane.setCursor(Cursor.DEFAULT); }); imagePicker.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue selected, String oldPicture, String newPicture) { if (oldPicture != null) { switch (oldPicture) { case "Default": Defaultview.setVisible(false); break; case "Dominic": Dominicview.setVisible(false); break; case "Sarah": Sarahview.setVisible(false); break; } } if (newPicture != null) { switch (newPicture) { case "Default": Defaultview.setVisible(true); break; case "Dominic": Dominicview.setVisible(true); break; case "Sarah": Sarahview.setVisible(true); break; } } } }); int numberOfSquares = 30; while (numberOfSquares > 0){ generateAnimation(); numberOfSquares--; } } /* This method is used to generate the animation on the login window, It will generate random ints to determine * the size, speed, starting points and direction of each square. */ public void generateAnimation(){ Random rand = new Random(); int sizeOfSqaure = rand.nextInt(50) + 1; int speedOfSqaure = rand.nextInt(10) + 5; int startXPoint = rand.nextInt(420); int startYPoint = rand.nextInt(350); int direction = rand.nextInt(5) + 1; KeyValue moveXAxis = null; KeyValue moveYAxis = null; Rectangle r1 = null; switch (direction){ case 1 : // MOVE LEFT TO RIGHT r1 = new Rectangle(0,startYPoint,sizeOfSqaure,sizeOfSqaure); moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure); break; case 2 : // MOVE TOP TO BOTTOM r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure); moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure); break; case 3 : // MOVE LEFT TO RIGHT, TOP TO BOTTOM r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure); moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure); moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure); break; case 4 : // MOVE BOTTOM TO TOP r1 = new Rectangle(startXPoint,420-sizeOfSqaure ,sizeOfSqaure,sizeOfSqaure); moveYAxis = new KeyValue(r1.xProperty(), 0); break; case 5 : // MOVE RIGHT TO LEFT r1 = new Rectangle(420-sizeOfSqaure,startYPoint,sizeOfSqaure,sizeOfSqaure); moveXAxis = new KeyValue(r1.xProperty(), 0); break; case 6 : //MOVE RIGHT TO LEFT, BOTTOM TO TOP r1 = new Rectangle(startXPoint,0,sizeOfSqaure,sizeOfSqaure); moveXAxis = new KeyValue(r1.xProperty(), 350 - sizeOfSqaure); moveYAxis = new KeyValue(r1.yProperty(), 420 - sizeOfSqaure); break; default: System.out.println("default"); } r1.setFill(Color.web("#F89406")); r1.setOpacity(0.1); KeyFrame keyFrame = new KeyFrame(Duration.millis(speedOfSqaure * 1000), moveXAxis, moveYAxis); Timeline timeline = new Timeline(); timeline.setCycleCount(Timeline.INDEFINITE); timeline.setAutoReverse(true); timeline.getKeyFrames().add(keyFrame); timeline.play(); borderPane.getChildren().add(borderPane.getChildren().size()-1,r1); } /* Terminates Application */ public void closeSystem(){ Platform.exit(); System.exit(0); } public void minimizeWindow(){ MainLauncher.getPrimaryStage().setIconified(true); } /* This displays an alert message to the user */ public void showErrorDialog(String message) { Platform.runLater(()-> { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning!"); alert.setHeaderText(message); alert.setContentText("Please check for firewall issues and check if the server is running."); alert.showAndWait(); }); } } ================================================ FILE: client/src/main/java/com/client/login/MainLauncher.java ================================================ package com.client.login; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.StageStyle; public class MainLauncher extends Application { private static Stage primaryStageObj; @Override public void start(Stage primaryStage) throws Exception { primaryStageObj = primaryStage; Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("views/LoginView.fxml")); primaryStage.initStyle(StageStyle.UNDECORATED); primaryStage.setTitle("Socket Chat : Client version 0.3"); primaryStage.getIcons().add(new Image(getClass().getClassLoader().getResource("images/plug.png").toString())); Scene mainScene = new Scene(root, 350, 420); mainScene.setRoot(root); primaryStage.setResizable(false); primaryStage.setScene(mainScene); primaryStage.show(); primaryStage.setOnCloseRequest(e -> Platform.exit()); } public static void main(String[] args) { launch(args); } public static Stage getPrimaryStage() { return primaryStageObj; } } ================================================ FILE: client/src/main/java/com/client/util/ResizeHelper.java ================================================ package com.client.util; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; //created by Alexander Berg public class ResizeHelper { public static void addResizeListener(Stage stage) { ResizeListener resizeListener = new ResizeListener(stage); stage.getScene().addEventHandler(MouseEvent.MOUSE_MOVED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_PRESSED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_DRAGGED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, resizeListener); ObservableList children = stage.getScene().getRoot().getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, resizeListener); } } public static void addListenerDeeply(Node node, EventHandler listener) { node.addEventHandler(MouseEvent.MOUSE_MOVED, listener); node.addEventHandler(MouseEvent.MOUSE_PRESSED, listener); node.addEventHandler(MouseEvent.MOUSE_DRAGGED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, listener); if (node instanceof Parent) { Parent parent = (Parent) node; ObservableList children = parent.getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, listener); } } } static class ResizeListener implements EventHandler { private Stage stage; private Cursor cursorEvent = Cursor.DEFAULT; private int border = 4; private double startX = 0; private double startY = 0; public ResizeListener(Stage stage) { this.stage = stage; } @Override public void handle(MouseEvent mouseEvent) { EventType mouseEventType = mouseEvent.getEventType(); Scene scene = stage.getScene(); double mouseEventX = mouseEvent.getSceneX(), mouseEventY = mouseEvent.getSceneY(), sceneWidth = scene.getWidth(), sceneHeight = scene.getHeight(); if (MouseEvent.MOUSE_MOVED.equals(mouseEventType)) { if (mouseEventX < border && mouseEventY < border) { cursorEvent = Cursor.NW_RESIZE; } else if (mouseEventX < border && mouseEventY > sceneHeight - border) { cursorEvent = Cursor.SW_RESIZE; } else if (mouseEventX > sceneWidth - border && mouseEventY < border) { cursorEvent = Cursor.NE_RESIZE; } else if (mouseEventX > sceneWidth - border && mouseEventY > sceneHeight - border) { cursorEvent = Cursor.SE_RESIZE; } else if (mouseEventX < border) { cursorEvent = Cursor.W_RESIZE; } else if (mouseEventX > sceneWidth - border) { cursorEvent = Cursor.E_RESIZE; } else if (mouseEventY < border) { cursorEvent = Cursor.N_RESIZE; } else if (mouseEventY > sceneHeight - border) { cursorEvent = Cursor.S_RESIZE; } else { cursorEvent = Cursor.DEFAULT; } scene.setCursor(cursorEvent); } else if(MouseEvent.MOUSE_EXITED.equals(mouseEventType) || MouseEvent.MOUSE_EXITED_TARGET.equals(mouseEventType)){ scene.setCursor(Cursor.DEFAULT); } else if (MouseEvent.MOUSE_PRESSED.equals(mouseEventType)) { startX = stage.getWidth() - mouseEventX; startY = stage.getHeight() - mouseEventY; } else if (MouseEvent.MOUSE_DRAGGED.equals(mouseEventType)) { if (Cursor.DEFAULT.equals(cursorEvent) == false) { if (Cursor.W_RESIZE.equals(cursorEvent) == false && Cursor.E_RESIZE.equals(cursorEvent) == false) { double minHeight = stage.getMinHeight() > (border*2) ? stage.getMinHeight() : (border*2); if (Cursor.NW_RESIZE.equals(cursorEvent) == true || Cursor.N_RESIZE.equals(cursorEvent) == true || Cursor.NE_RESIZE.equals(cursorEvent) == true) { if (stage.getHeight() > minHeight || mouseEventY < 0) { stage.setHeight(stage.getY() - mouseEvent.getScreenY() + stage.getHeight()); stage.setY(mouseEvent.getScreenY()); } } else { if (stage.getHeight() > minHeight || mouseEventY + startY - stage.getHeight() > 0) { stage.setHeight(mouseEventY + startY); } } } if (Cursor.N_RESIZE.equals(cursorEvent) == false && Cursor.S_RESIZE.equals(cursorEvent) == false) { double minWidth = stage.getMinWidth() > (border*2) ? stage.getMinWidth() : (border*2); if (Cursor.NW_RESIZE.equals(cursorEvent) == true || Cursor.W_RESIZE.equals(cursorEvent) == true || Cursor.SW_RESIZE.equals(cursorEvent) == true) { if (stage.getWidth() > minWidth || mouseEventX < 0) { stage.setWidth(stage.getX() - mouseEvent.getScreenX() + stage.getWidth()); stage.setX(mouseEvent.getScreenX()); } } else { if (stage.getWidth() > minWidth || mouseEventX + startX - stage.getWidth() > 0) { stage.setWidth(mouseEventX + startX); } } } } } } } } ================================================ FILE: client/src/main/java/com/client/util/VoicePlayback.java ================================================ package com.client.util; import javax.sound.sampled.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * @author Dominic * @since 16-Oct-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public class VoicePlayback extends VoiceUtil { public static void playAudio(byte[] audio) { try { InputStream input = new ByteArrayInputStream(audio); final AudioFormat format = getAudioFormat(); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { int bufferSize = (int) format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { try { int count; while ((count = ais.read( buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } } catch (IOException e) { System.err.println("I/O problems: " + e); } finally { line.drain(); line.close(); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } } ================================================ FILE: client/src/main/java/com/client/util/VoiceRecorder.java ================================================ package com.client.util; import com.client.chatwindow.Listener; import javax.sound.sampled.*; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * @author Dominic * @since 16-Oct-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public class VoiceRecorder extends VoiceUtil { public static void captureAudio() { try { final AudioFormat format = getAudioFormat(); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { int bufferSize = (int)format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { out = new ByteArrayOutputStream(); isRecording = true; try { while (isRecording) { int count = line.read(buffer, 0, buffer.length); if (count > 0) { out.write(buffer, 0, count); } } } finally { try { out.close(); out.flush(); line.close(); line.flush(); Listener.sendVoiceMessage(out.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } } }; Thread captureThread = new Thread(runner); captureThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " ); e.printStackTrace(); } } } ================================================ FILE: client/src/main/java/com/client/util/VoiceUtil.java ================================================ package com.client.util; import javax.sound.sampled.AudioFormat; import java.io.ByteArrayOutputStream; /** * @author Dominic * @since 16-Oct-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public class VoiceUtil { public static void setRecording(boolean flag){ isRecording = flag; } public static boolean isRecording() { return isRecording; } protected static boolean isRecording = false; static ByteArrayOutputStream out; /** * Defines an audio format */ static AudioFormat getAudioFormat() { float sampleRate = 16000; int sampleSizeInBits = 8; int channels = 2; boolean signed = true; boolean bigEndian = true; AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); return format; } } ================================================ FILE: client/src/main/java/com/messages/Message.java ================================================ package com.messages; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; public class Message implements Serializable { private String name; private MessageType type; private String msg; private int count; private ArrayList list; private ArrayList users; private Status status; public byte[] getVoiceMsg() { return voiceMsg; } private byte[] voiceMsg; public String getPicture() { return picture; } private String picture; public Message() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public MessageType getType() { return type; } public void setType(MessageType type) { this.type = type; } public ArrayList getUserlist() { return list; } public void setUserlist(HashMap userList) { this.list = new ArrayList<>(userList.values()); } public void setOnlineCount(int count){ this.count = count; } public int getOnlineCount(){ return this.count; } public void setPicture(String picture) { this.picture = picture; } public ArrayList getUsers() { return users; } public void setUsers(ArrayList users) { this.users = users; } public void setStatus(Status status) { this.status = status; } public Status getStatus() { return status; } public void setVoiceMsg(byte[] voiceMsg) { this.voiceMsg = voiceMsg; } } ================================================ FILE: client/src/main/java/com/messages/MessageType.java ================================================ package com.messages; /** * @author Dominic * @since 03-Sep-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public enum MessageType { DISCONNECTED, CONNECTED, STATUS, USER, SERVER, NOTIFICATION, VOICE } ================================================ FILE: client/src/main/java/com/messages/Status.java ================================================ package com.messages; /** * @author Dominic * @since 03-Sep-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public enum Status { ONLINE, AWAY, BUSY } ================================================ FILE: client/src/main/java/com/messages/User.java ================================================ package com.messages; import java.io.Serializable; /** * Created by Dominic on 01-May-16. */ public class User implements Serializable { public String getName() { return name; } public void setName(String name) { this.name = name; } String name; public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } String picture; Status status; } ================================================ FILE: client/src/main/java/com/messages/bubble/Bubble.java ================================================ package com.messages.bubble; import javafx.scene.shape.HLineTo; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.VLineTo; public class Bubble extends Path{ /*Copyright {2015} {Terah Laweh} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public Bubble(BubbleSpec bubbleSpec) { super(); switch (bubbleSpec) { case FACE_BOTTOM: break; case FACE_LEFT_BOTTOM: drawRectBubbleLeftBaselineIndicator(); break; case FACE_LEFT_CENTER: drawRectBubbleLeftCenterIndicator(); break; case FACE_RIGHT_BOTTOM: drawRectBubbleRightBaselineIndicator(); break; case FACE_RIGHT_CENTER: drawRectBubbleRightCenterIndicator(); break; case FACE_TOP: drawRectBubbleToplineIndicator(); break; default: break; } } private void drawRectBubbleToplineIndicator() { getElements().addAll(new MoveTo(1.0f, 1.2f), new HLineTo(2.5f), new LineTo(2.7f, 1.0f), new LineTo(2.9f, 1.2f), new HLineTo(4.4f), new VLineTo(4f), new HLineTo(1.0f), new VLineTo(1.2f) ); } private void drawRectBubbleRightBaselineIndicator() { getElements().addAll(new MoveTo(3.0f, 1.0f), new HLineTo(0f), new VLineTo(4f), new HLineTo(3.0f), new LineTo(2.8f, 3.8f), new VLineTo(1f) ); } private void drawRectBubbleLeftBaselineIndicator() { getElements().addAll(new MoveTo(1.2f, 1.0f), new HLineTo(3f), new VLineTo(4f), new HLineTo(1.0f), new LineTo(1.2f, 3.8f), new VLineTo(1f) ); } private void drawRectBubbleRightCenterIndicator() { getElements().addAll(new MoveTo(3.0f, 2.5f), new LineTo(2.8f, 2.4f), new VLineTo(1f), new HLineTo(0f), new VLineTo(4f), new HLineTo(2.8f), new VLineTo(2.7f), new LineTo(3.0f, 2.5f) ); } protected double drawRectBubbleIndicatorRule = 0.2; private void drawRectBubbleLeftCenterIndicator() { getElements().addAll(new MoveTo(1.0f, 2.5f), new LineTo(1.2f, 2.4f), new VLineTo(1f), new HLineTo(2.9f), new VLineTo(4f), new HLineTo(1.2f), new VLineTo(2.7f), new LineTo(1.0f, 2.5f) ); } } ================================================ FILE: client/src/main/java/com/messages/bubble/BubbleSpec.java ================================================ package com.messages.bubble; public enum BubbleSpec { /*Copyright {2015} {Terah Laweh} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ FACE_TOP, FACE_BOTTOM, FACE_LEFT_BOTTOM, FACE_LEFT_CENTER, FACE_RIGHT_BOTTOM, FACE_RIGHT_CENTER; } ================================================ FILE: client/src/main/java/com/messages/bubble/BubbledLabel.java ================================================ package com.messages.bubble; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.paint.Color; import javafx.scene.shape.Shape; public class BubbledLabel extends Label { /*Copyright {2015} {Terah Laweh} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ private BubbleSpec bs = BubbleSpec.FACE_LEFT_CENTER; private double pading = 5.0; private boolean systemCall = false; public BubbledLabel() { super(); init(); } public BubbledLabel(String arg0, Node arg1) { super(arg0, arg1); init(); } public BubbledLabel(String arg0) { super(arg0); init(); } public BubbledLabel(BubbleSpec bubbleSpec) { super(); this.bs = bubbleSpec; init(); } public BubbledLabel(String arg0, Node arg1,BubbleSpec bubbleSpec) { super(arg0, arg1); this.bs = bubbleSpec; init(); } public BubbledLabel(String arg0,BubbleSpec bubbleSpec) { super(arg0); this.bs = bubbleSpec; init(); } private void init(){ DropShadow ds = new DropShadow(); ds.setOffsetX(1.3); ds.setOffsetY(1.3); ds.setColor(Color.DARKGRAY); setPrefSize(Label.USE_COMPUTED_SIZE, Label.USE_COMPUTED_SIZE); shapeProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue arg0, Shape arg1, Shape arg2) { if(systemCall){ systemCall = false; }else{ shapeIt(); } } }); heightProperty().addListener(new InvalidationListener() { @Override public void invalidated(Observable arg0) { if(!systemCall) setPrefHeight(Label.USE_COMPUTED_SIZE); } }); widthProperty().addListener(new InvalidationListener() { @Override public void invalidated(Observable observable) { if(!systemCall) setPrefHeight(Label.USE_COMPUTED_SIZE); } }); shapeIt(); } @Override protected void updateBounds() { super.updateBounds(); //top right bottom left switch (bs) { case FACE_LEFT_BOTTOM: setPadding(new Insets(pading,pading, (this.getBoundsInLocal().getWidth()*((Bubble)getShape()).drawRectBubbleIndicatorRule)/2 +pading, pading)); break; case FACE_LEFT_CENTER: setPadding(new Insets(pading,pading,pading, (this.getBoundsInLocal().getWidth()*((Bubble)getShape()).drawRectBubbleIndicatorRule)/2 +pading )); break; case FACE_RIGHT_BOTTOM: setPadding(new Insets(pading, (this.getBoundsInLocal().getWidth()*((Bubble)getShape()).drawRectBubbleIndicatorRule)/2 +pading ,pading,pading)); break; case FACE_RIGHT_CENTER: setPadding(new Insets(pading, (this.getBoundsInLocal().getWidth()*((Bubble)getShape()).drawRectBubbleIndicatorRule)/2 +pading ,pading,pading)); break; case FACE_TOP: setPadding(new Insets( (this.getBoundsInLocal().getWidth()*((Bubble)getShape()).drawRectBubbleIndicatorRule)/2 +pading, pading,pading,pading)); break; default: break; } } public final double getPading() { return pading; } public void setPading(double pading) { if(pading > 25.0) return; this.pading = pading; } public BubbleSpec getBubbleSpec() { return bs; } public void setBubbleSpec(BubbleSpec bubbleSpec) { this.bs = bubbleSpec; shapeIt(); } private final void shapeIt(){ systemCall = true; setShape(new Bubble(bs)); System.gc(); } } ================================================ FILE: client/src/main/java/com/traynotifications/animations/AnimationProvider.java ================================================ package com.traynotifications.animations; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * A provider class that houses all animation objects that implement TrayAnimation * This makes it easier to lookup any existing animations and retrieve them * This means the user can easily switch animations, and in the background all possible animation types * Are stores in here, so when a user selects an animation type, this class will return the TrayAnimation that satisfies that request * It's much like a mini database */ public class AnimationProvider { private List animationsList; public AnimationProvider(TrayAnimation... animations) { animationsList = new ArrayList<>(); Collections.addAll(animationsList, animations); } public void addAll(TrayAnimation... animations) { Collections.addAll(animationsList, animations); } public TrayAnimation get(int index) { return animationsList.get(index); } public TrayAnimation findFirstWhere(Predicate predicate) { return animationsList.stream().filter(predicate).findFirst().orElse(null); } public List where(Predicate predicate) { return animationsList.stream().filter(predicate).collect(Collectors.toList()); } } ================================================ FILE: client/src/main/java/com/traynotifications/animations/AnimationType.java ================================================ package com.traynotifications.animations; public enum AnimationType { FADE, SLIDE, POPUP } ================================================ FILE: client/src/main/java/com/traynotifications/animations/FadeAnimation.java ================================================ package com.traynotifications.animations; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.util.Duration; import com.traynotifications.models.CustomStage; public class FadeAnimation implements TrayAnimation { private final Timeline showAnimation, dismissAnimation; private final SequentialTransition sq; private final CustomStage stage; private boolean trayIsShowing; /** * Initializes a fade type animation on a stage * @param customStage The stage associate the fade animation with */ public FadeAnimation(CustomStage customStage) { this.stage = customStage; //It wouldn't allow me to play embedded animations so I had to create two separate //Instances so I could play sequentially and individually. showAnimation = setupShowAnimation(); dismissAnimation = setupDismissAnimation(); sq = new SequentialTransition(setupShowAnimation(), setupDismissAnimation()); } /** * * @return a constructed instance of a show fade animation */ private Timeline setupShowAnimation() { Timeline tl = new Timeline(); //Sets opacity to 0.0 instantly which is pretty much invisible KeyValue kvOpacity = new KeyValue(stage.opacityProperty(), 0.0); KeyFrame frame1 = new KeyFrame(Duration.ZERO, kvOpacity); //Sets opacity to 1.0 (fully visible) over the time of 3000 milliseconds. KeyValue kvOpacity2 = new KeyValue(stage.opacityProperty(), 1.0); KeyFrame frame2 = new KeyFrame(Duration.millis(3000), kvOpacity2); tl.getKeyFrames().addAll(frame1, frame2); tl.setOnFinished(e -> trayIsShowing = true); return tl; } /** * * @return a constructed instance of a dismiss fade animation */ private Timeline setupDismissAnimation() { Timeline tl = new Timeline(); //At this stage the opacity is already at 1.0 //Lowers the opacity to 0.0 within 2000 milliseconds KeyValue kv1 = new KeyValue(stage.opacityProperty(), 0.0); KeyFrame kf1 = new KeyFrame(Duration.millis(2000), kv1); tl.getKeyFrames().addAll(kf1); //Action to be performed when the animation has finished tl.setOnFinished(e -> { trayIsShowing = false; stage.close(); stage.setLocation(stage.getBottomRight()); }); return tl; } /** * The type of animation this class plays * * @return The type of animation this class plays */ @Override public AnimationType getAnimationType() { return AnimationType.FADE; } /** * Plays both the show and dismiss animation using a sequential transition object * * @param dismissDelay How long to delay the start of the dismiss animation */ @Override public void playSequential(Duration dismissDelay) { sq.getChildren().get(1).setDelay(dismissDelay); sq.play(); } /** * Plays the implemented show animation */ @Override public void playShowAnimation() { showAnimation.play(); } /** * Plays the implemented dismiss animation */ @Override public void playDismissAnimation() { dismissAnimation.play(); } /** * Signifies if the tray is current showing * * @return boolean resultant */ @Override public boolean isShowing() { return trayIsShowing; } } ================================================ FILE: client/src/main/java/com/traynotifications/animations/PopupAnimation.java ================================================ package com.traynotifications.animations; import javafx.animation.*; import com.traynotifications.models.CustomStage; import javafx.util.Duration; public class PopupAnimation implements TrayAnimation { private final Timeline showAnimation, dismissAnimation; private final SequentialTransition sq; private final CustomStage stage; private boolean trayIsShowing; public PopupAnimation(CustomStage s) { this.stage = s; showAnimation = setupShowAnimation(); dismissAnimation = setupDismissAnimation(); sq = new SequentialTransition(setupShowAnimation(), setupDismissAnimation()); } private Timeline setupDismissAnimation() { Timeline tl = new Timeline(); KeyValue kv1 = new KeyValue(stage.yLocationProperty(), stage.getY() + stage.getWidth()); KeyFrame kf1 = new KeyFrame(Duration.millis(2000), kv1); KeyValue kv2 = new KeyValue(stage.opacityProperty(), 0.0); KeyFrame kf2 = new KeyFrame(Duration.millis(2000), kv2); tl.getKeyFrames().addAll(kf1, kf2); tl.setOnFinished(e -> { trayIsShowing = false; stage.close(); stage.setLocation(stage.getBottomRight()); }); return tl; } private Timeline setupShowAnimation() { Timeline tl = new Timeline(); KeyValue kv1 = new KeyValue(stage.yLocationProperty(), stage.getBottomRight().getY() + stage.getWidth()); KeyFrame kf1 = new KeyFrame(Duration.ZERO, kv1); KeyValue kv2 = new KeyValue(stage.yLocationProperty(), stage.getBottomRight().getY()); KeyFrame kf2 = new KeyFrame(Duration.millis(1000), kv2); KeyValue kv3 = new KeyValue(stage.opacityProperty(), 0.0); KeyFrame kf3 = new KeyFrame(Duration.ZERO, kv3); KeyValue kv4 = new KeyValue(stage.opacityProperty(), 1.0); KeyFrame kf4 = new KeyFrame(Duration.millis(2000), kv4); tl.getKeyFrames().addAll(kf1, kf2, kf3, kf4); tl.setOnFinished(e -> trayIsShowing = true); return tl; } /** * The type of animation this class plays * * @return The type of animation this class plays */ @Override public AnimationType getAnimationType() { return AnimationType.POPUP; } /** * Plays both the show and dismiss animation using a sequential transition object * * @param dismissDelay How long to delay the start of the dismiss animation */ @Override public void playSequential(Duration dismissDelay) { sq.getChildren().get(1).setDelay(dismissDelay); sq.play(); } /** * Plays the implemented show animation */ @Override public void playShowAnimation() { showAnimation.play(); } /** * Plays the implemented dismiss animation */ @Override public void playDismissAnimation() { dismissAnimation.play(); } /** * Signifies if the tray is current showing * * @return boolean resultant */ @Override public boolean isShowing() { return trayIsShowing; } } ================================================ FILE: client/src/main/java/com/traynotifications/animations/SlideAnimation.java ================================================ package com.traynotifications.animations; import javafx.animation.*; import javafx.util.Duration; import com.traynotifications.models.CustomStage; public class SlideAnimation implements TrayAnimation { private final Timeline showAnimation, dismissAnimation; private final SequentialTransition sq; private final CustomStage stage; private boolean trayIsShowing; public SlideAnimation(CustomStage customStage) { this.stage = customStage; showAnimation = setupShowAnimation(); dismissAnimation = setupDismissAnimation(); //It wouldn't allow me to play embedded animations so I had to create two separate //Instances so I could play sequentially and individually. sq = new SequentialTransition(setupShowAnimation(), setupDismissAnimation()); } private Timeline setupShowAnimation() { Timeline tl = new Timeline(); //Sets the x location of the tray off the screen double offScreenX = stage.getOffScreenBounds().getX(); KeyValue kvX = new KeyValue(stage.xLocationProperty(), offScreenX); KeyFrame frame1 = new KeyFrame(Duration.ZERO, kvX); //Animates the Tray onto the screen and interpolates at a tangent for 300 millis Interpolator interpolator = Interpolator.TANGENT(Duration.millis(300), 50); KeyValue kvInter = new KeyValue(stage.xLocationProperty(), stage.getBottomRight().getX(), interpolator); KeyFrame frame2 = new KeyFrame(Duration.millis(1300), kvInter); //Sets opacity to 0 instantly KeyValue kvOpacity = new KeyValue(stage.opacityProperty(), 0.0); KeyFrame frame3 = new KeyFrame(Duration.ZERO, kvOpacity); //Increases the opacity to fully visible whilst moving in the space of 1000 millis KeyValue kvOpacity2 = new KeyValue(stage.opacityProperty(), 1.0); KeyFrame frame4 = new KeyFrame(Duration.millis(1000), kvOpacity2); tl.getKeyFrames().addAll(frame1, frame2, frame3, frame4); tl.setOnFinished(e -> trayIsShowing = true); return tl; } private Timeline setupDismissAnimation() { Timeline tl = new Timeline(); double offScreenX = stage.getOffScreenBounds().getX(); Interpolator interpolator = Interpolator.TANGENT(Duration.millis(300), 50); double trayPadding = 3; //The destination X location for the stage. Which is off the users screen //Since the tray has some padding, we want to hide that too KeyValue kvX = new KeyValue(stage.xLocationProperty(), offScreenX + trayPadding, interpolator); KeyFrame frame1 = new KeyFrame(Duration.millis(1400), kvX); //Change the opacity level to 0.4 over the duration of 2000 millis KeyValue kvOpacity = new KeyValue(stage.opacityProperty(), 0.4); KeyFrame frame2 = new KeyFrame(Duration.millis(2000), kvOpacity); tl.getKeyFrames().addAll(frame1, frame2); tl.setOnFinished(e -> { trayIsShowing = false; stage.close(); stage.setLocation(stage.getBottomRight()); }); return tl; } /** * The type of animation this class plays * * @return The type of animation this class plays */ @Override public AnimationType getAnimationType() { return AnimationType.SLIDE; } /** * Plays both the show and dismiss animation using a sequential transition object * * @param dismissDelay How long to delay the start of the dismiss animation */ @Override public void playSequential(Duration dismissDelay) { sq.getChildren().get(1).setDelay(dismissDelay); sq.play(); } /** * Plays the implemented show animation */ @Override public void playShowAnimation() { showAnimation.play(); } /** * Plays the implemented dismiss animation */ @Override public void playDismissAnimation() { dismissAnimation.play(); } /** * Signifies if the tray is current showing * * @return boolean resultant */ @Override public boolean isShowing() { return trayIsShowing; } } ================================================ FILE: client/src/main/java/com/traynotifications/animations/TrayAnimation.java ================================================ package com.traynotifications.animations; import javafx.util.Duration; //All tray animations must implement TrayAnimation public interface TrayAnimation { /** * The type of animation this class plays * @return The type of animation this class plays */ AnimationType getAnimationType(); /** * Plays both the show and dismiss animation using a sequential transition object * @param dismissDelay How long to delay the start of the dismiss animation */ void playSequential(Duration dismissDelay); /** * Plays the implemented show animation */ void playShowAnimation(); /** * Plays the implemented dismiss animation */ void playDismissAnimation(); /** * Signifies if the tray is current showing * @return boolean resultant */ boolean isShowing(); } ================================================ FILE: client/src/main/java/com/traynotifications/models/CustomStage.java ================================================ package com.traynotifications.models; import javafx.beans.property.SimpleDoubleProperty; import javafx.geometry.Rectangle2D; import javafx.scene.layout.AnchorPane; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; public class CustomStage extends Stage { private final Location bottomRight; public CustomStage(AnchorPane ap, StageStyle style) { initStyle(style); setSize(ap.getPrefWidth(), ap.getPrefHeight()); Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); double x = screenBounds.getMinX() + screenBounds.getWidth() - ap.getPrefWidth() - 2; double y = screenBounds.getMinY() + screenBounds.getHeight() - ap.getPrefHeight() - 2; bottomRight = new Location(x,y); } public Location getBottomRight() { return bottomRight; } public void setSize(double width, double height) { setWidth(width); setHeight(height); } public Location getOffScreenBounds() { Location loc = getBottomRight(); return new Location(loc.getX() + this.getWidth(), loc.getY()); } public void setLocation(Location loc) { setX(loc.getX()); setY(loc.getY()); } private SimpleDoubleProperty xLocationProperty = new SimpleDoubleProperty() { @Override public void set(double newValue) { setX(newValue); } @Override public double get() { return getX(); } }; public SimpleDoubleProperty xLocationProperty() { return xLocationProperty; } private SimpleDoubleProperty yLocationProperty = new SimpleDoubleProperty() { @Override public void set(double newValue) { setY(newValue); } @Override public double get() { return getY(); } }; public SimpleDoubleProperty yLocationProperty() { return yLocationProperty; } } ================================================ FILE: client/src/main/java/com/traynotifications/models/Location.java ================================================ package com.traynotifications.models; public class Location { private double x, y; public Location(double xLoc, double yLoc) { this.x = xLoc; this.y = yLoc; } public double getX() { return x; } public double getY() { return y; } } ================================================ FILE: client/src/main/java/com/traynotifications/notification/NotificationType.java ================================================ package com.traynotifications.notification; public enum NotificationType { INFORMATION, NOTICE, SUCCESS, WARNING, ERROR, CUSTOM } ================================================ FILE: client/src/main/java/com/traynotifications/notification/TrayNotification.java ================================================ package com.traynotifications.notification; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Paint; import javafx.scene.shape.Rectangle; import javafx.stage.StageStyle; import javafx.util.Duration; import com.traynotifications.animations.*; import com.traynotifications.models.CustomStage; import java.io.IOException; import java.net.URL; public final class TrayNotification { @FXML private Label lblTitle, lblMessage, lblClose; @FXML private ImageView imageIcon; @FXML private Rectangle rectangleColor; @FXML private AnchorPane rootNode; private CustomStage stage; private NotificationType notificationType; private AnimationType animationType; private EventHandler onDismissedCallBack, onShownCallback; private TrayAnimation animator; private AnimationProvider animationProvider; /** * Initializes an instance of the tray notification object * @param title The title text to assign to the tray * @param body The body text to assign to the tray * @param img The image to show on the tray * @param rectangleFill The fill for the rectangle */ public TrayNotification(String title, String body, Image img, Paint rectangleFill) { initTrayNotification(title, body, NotificationType.CUSTOM); setImage(img); setRectangleFill(rectangleFill); } /** * Initializes an instance of the tray notification object * @param title The title text to assign to the tray * @param body The body text to assign to the tray * @param notificationType The notification type to assign to the tray */ public TrayNotification(String title, String body, NotificationType notificationType ) { initTrayNotification(title, body, notificationType); } /** * Initializes an empty instance of the tray notification */ public TrayNotification() { initTrayNotification("", "", NotificationType.CUSTOM); } private void initTrayNotification(String title, String message, NotificationType type) { try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/views/TrayNotification.fxml")); fxmlLoader.setController(this); fxmlLoader.load(); initStage(); initAnimations(); setTray(title, message, type); } catch (IOException e) { e.printStackTrace(); } } private void initAnimations() { animationProvider = new AnimationProvider(new FadeAnimation(stage), new SlideAnimation(stage), new PopupAnimation(stage)); //Default animation type setAnimationType(AnimationType.SLIDE); } private void initStage() { stage = new CustomStage(rootNode, StageStyle.UNDECORATED); stage.setScene(new Scene(rootNode)); stage.setAlwaysOnTop(true); stage.setLocation(stage.getBottomRight()); lblClose.setOnMouseClicked(e -> dismiss()); } public void setNotificationType(NotificationType nType) { notificationType = nType; URL imageLocation = null; String paintHex = null; switch (nType) { case INFORMATION: imageLocation = getClass().getResource("/tray/resources/info.png"); paintHex = "#2C54AB"; break; case NOTICE: imageLocation = getClass().getResource("/tray/resources/notice.png"); paintHex = "#8D9695"; break; case SUCCESS: imageLocation = getClass().getResource("/tray/resources/success.png"); paintHex = "#009961"; break; case WARNING: imageLocation = getClass().getResource("/tray/resources/warning.png"); paintHex = "#E23E0A"; break; case ERROR: imageLocation = getClass().getResource("/tray/resources/error.png"); paintHex = "#CC0033"; break; case CUSTOM: return; } setRectangleFill(Paint.valueOf(paintHex)); setImage(new Image(imageLocation.toString())); setTrayIcon(imageIcon.getImage()); } public NotificationType getNotificationType() { return notificationType; } public void setTray(String title, String message, NotificationType type) { setTitle(title); setMessage(message); setNotificationType(type); } public void setTray(String title, String message, Image img, Paint rectangleFill, AnimationType animType) { setTitle(title); setMessage(message); setImage(img); setRectangleFill(rectangleFill); setAnimationType(animType); } public boolean isTrayShowing() { return animator.isShowing(); } /** * Shows and dismisses the tray notification * @param dismissDelay How long to delay the start of the dismiss animation */ public void showAndDismiss(Duration dismissDelay) { if (isTrayShowing()) { dismiss(); } else { stage.show(); onShown(); animator.playSequential(dismissDelay); } onDismissed(); } /** * Displays the notification tray */ public void showAndWait() { if (! isTrayShowing()) { stage.show(); animator.playShowAnimation(); onShown(); } } /** * Dismisses the notifcation tray */ public void dismiss() { if (isTrayShowing()) { animator.playDismissAnimation(); onDismissed(); } } private void onShown() { if (onShownCallback != null) onShownCallback.handle(new ActionEvent()); } private void onDismissed() { if (onDismissedCallBack != null) onDismissedCallBack.handle(new ActionEvent()); } /** * Sets an action event for when the tray has been dismissed * @param event The event to occur when the tray has been dismissed */ public void setOnDismiss(EventHandler event) { onDismissedCallBack = event; } /** * Sets an action event for when the tray has been shown * @param event The event to occur after the tray has been shown */ public void setOnShown(EventHandler event) { onShownCallback = event; } /** * Sets a new task bar image for the tray * @param img The image to assign */ public void setTrayIcon(Image img) { stage.getIcons().clear(); stage.getIcons().add(img); } public Image getTrayIcon() { return stage.getIcons().get(0); } /** * Sets a title to the tray * @param txt The text to assign to the tray icon */ public void setTitle(String txt) { lblTitle.setText(txt); } public String getTitle() { return lblTitle.getText(); } /** * Sets the message for the tray notification * @param txt The text to assign to the body of the tray notification */ public void setMessage(String txt) { lblMessage.setText(txt); } public String getMessage() { return lblMessage.getText(); } public void setImage (Image img) { imageIcon.setImage(img); setTrayIcon(img); } public Image getImage() { return imageIcon.getImage(); } public void setRectangleFill(Paint value) { rectangleColor.setFill(value); } public Paint getRectangleFill() { return rectangleColor.getFill(); } public void setAnimationType(AnimationType type) { animator = animationProvider.findFirstWhere(a -> a.getAnimationType() == type); animationType = type; } public AnimationType getAnimationType() { return animationType; } } ================================================ FILE: client/src/main/resources/styles/ButtonStyle.css ================================================ .button { -fx-opacity: 1.0; } .button:hover { -fx-opacity: 0.6; } ================================================ FILE: client/src/main/resources/styles/ChatViewStyle.css ================================================ .vbox { -fx-border-color: #2e8b57; -fx-border-width: 2px; -fx-padding: 10; -fx-spacing: 8; } ================================================ FILE: client/src/main/resources/styles/ComboBox.css ================================================ .comboTextField { -fx-background-color: -fx-text-box-border, -fx-control-inner-background; -fx-background-insets: 0, 1 0 1 1; -fx-padding: 1 3 1 3; -fx-background-radius: 0; -fx-cursor: hand; } .comboTextField:focused { -fx-background-color: -fx-text-box-border, -fx-control-inner-background; -fx-background-insets: 0, 1 0 1 1; } .comboButton { -fx-background-color: -fx-outer-border, -fx-inner-border, -fx-body-color; -fx-background-insets: 0, 1, 2; -fx-background-radius: 0 5 5 0, 0 4 4 0, 0 3 3 0; } .comboButton:focused { -fx-color: -fx-focused-base; -fx-background-color: -fx-outer-border, -fx-inner-border, -fx-body-color; -fx-background-insets: 0, 1, 2; -fx-background-radius: 0 5 5 0, 0 4 4 0, 0 3 3 0; } .comboFocus{ -fx-border-color:-fx-focus-color; -fx-border-insets: -1; -fx-border-radius: 0 5 5 0 } .comboFocusOut{ -fx-border-color:transparent; -fx-border-insets: 0; -fx-border-radius: 0 5 5 0 } ================================================ FILE: client/src/main/resources/styles/ListViewStyle.css ================================================ .list-cell { -fx-cell-size: 50 ; -fx-animated: true; -fx-padding: 1px; } .list-cell:hover{ -fx-background-color: #dbdbdb; } .list-view { -fx-border-image-width: 0; } #statusList { -fx-box-border: transparent; } #userList { -fx-box-border: transparent; } #listHbox { -fx-background-color: #d5d5d5; -fx-padding: 0.2; -fx-spacing: -2; } #onlineUsersHbox { -fx-border-color: #d5d5d5; -fx-border-width: 1px; -fx-padding: 0.2; -fx-spacing: -2; } ================================================ FILE: client/src/main/resources/styles/Login.css ================================================ #CloseBtn { -fx-graphic: url("../images/cross.png"); -fx-background-color:transparent; -fx-opacity: 1; } #CloseBtn:hover { -fx-opacity: 0.5; } #CloseBtn:pressed { -fx-opacity: 0.2; } #MinimizedBtn { -fx-graphic: url("../images/line.png"); -fx-background-color: transparent; -fx-opacity: 1; } #MinimizedBtn:hover { -fx-opacity: 0.5; } #connectBtn{ -fx-color: #ffffff; -fx-padding: 5px 20px; -fx-background-color: linear-gradient(to bottom, #ffe49e 0%,#ffb700 3%,#ffad00 35%,#ff9000 97%,#e27f00 100%); -fx-font-family: 'Open Sans', sans-serif; -fx-font-size: 12px; border-radius: 3px; cursor: pointer; -fx-opacity: 1; } #connectBtn:hover{ -fx-cursor: hand; -fx-opacity: 0.5; } #connectBtn:pressed{ -fx-opacity: 1; -fx-padding: 5px 20px; -fx-spacing: 10px; -fx-start-margin: 10px; -fx-background-color: linear-gradient(to bottom, #ffe49e 0%,#ffb700 3%,#ffad00 35%,#ff9000 97%,#e27f00 100%); -fx-font-family: 'Open Sans', sans-serif; -fx-cursor: hand; } ================================================ FILE: client/src/main/resources/views/ChatView.fxml ================================================
================================================ FILE: client/src/main/resources/views/LoginView.fxml ================================================
================================================ FILE: client/src/main/resources/views/TrayNotification.fxml ================================================ ================================================ FILE: pom.xml ================================================ 4.0.0 groupId JavaFx pom 1.0-SNAPSHOT JavaFX-Chat server client org.apache.maven.plugins maven-compiler-plugin 3.6.1 1.8 1.8 org.apache.maven.plugins maven-jar-plugin 3.0.2 ================================================ FILE: server/pom.xml ================================================ 4.0.0 groupId JavaFx 1.0-SNAPSHOT server jar org.apache.maven.plugins maven-jar-plugin true com.server.Server org.apache.maven.plugins maven-assembly-plugin 2.4.1 jar-with-dependencies com.server.Server make-assembly package single org.slf4j slf4j-api 1.5.6 jar org.slf4j slf4j-simple 1.5.6 ================================================ FILE: server/src/main/java/com/exception/DuplicateUsernameException.java ================================================ package com.exception; /** * @author Dominic * @since 23-Oct-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public class DuplicateUsernameException extends Exception { public DuplicateUsernameException(String message){ super(message); } } ================================================ FILE: server/src/main/java/com/messages/Message.java ================================================ package com.messages; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; public class Message implements Serializable { private String name; private MessageType type; private String msg; private int count; private ArrayList list; private ArrayList users; private Status status; private byte[] voiceMsg; public byte[] getVoiceMsg() { return voiceMsg; } public String getPicture() { return picture; } private String picture; public Message() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public MessageType getType() { return type; } public void setType(MessageType type) { this.type = type; } public ArrayList getUserlist() { return list; } public void setUserlist(HashMap userList) { this.list = new ArrayList<>(userList.values()); } public void setOnlineCount(int count){ this.count = count; } public int getOnlineCount(){ return this.count; } public void setPicture(String picture) { this.picture = picture; } public ArrayList getUsers() { return users; } public void setUsers(ArrayList users) { this.users = users; } public void setStatus(Status status) { this.status = status; } public Status getStatus() { return status; } public void setVoiceMsg(byte[] voiceMsg) { this.voiceMsg = voiceMsg; } } ================================================ FILE: server/src/main/java/com/messages/MessageType.java ================================================ package com.messages; /** * @author Dominic * @since 03-Sep-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public enum MessageType { DISCONNECTED, CONNECTED, STATUS, USER, SERVER, NOTIFICATION, VOICE } ================================================ FILE: server/src/main/java/com/messages/Status.java ================================================ package com.messages; /** * @author Dominic * @since 03-Sep-16 * Website: www.dominicheal.com * Github: www.github.com/DomHeal */ public enum Status { ONLINE, AWAY, BUSY } ================================================ FILE: server/src/main/java/com/messages/User.java ================================================ package com.messages; import java.io.Serializable; /** * Created by Dominic on 01-May-16. */ public class User implements Serializable { public String getName() { return name; } public void setName(String name) { this.name = name; } String name; public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } String picture; Status status; } ================================================ FILE: server/src/main/java/com/server/Server.java ================================================ package com.server; import com.exception.DuplicateUsernameException; import com.messages.Message; import com.messages.MessageType; import com.messages.Status; import com.messages.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class Server { /* Setting up variables */ private static final int PORT = 9001; private static final HashMap names = new HashMap<>(); private static HashSet writers = new HashSet<>(); private static ArrayList users = new ArrayList<>(); static Logger logger = LoggerFactory.getLogger(Server.class); public static void main(String[] args) throws Exception { logger.info("The chat server is running."); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new Handler(listener.accept()).start(); } } catch (Exception e) { e.printStackTrace(); } finally { listener.close(); } } private static class Handler extends Thread { private String name; private Socket socket; private Logger logger = LoggerFactory.getLogger(Handler.class); private User user; private ObjectInputStream input; private OutputStream os; private ObjectOutputStream output; private InputStream is; public Handler(Socket socket) throws IOException { this.socket = socket; } public void run() { logger.info("Attempting to connect a user..."); try { is = socket.getInputStream(); input = new ObjectInputStream(is); os = socket.getOutputStream(); output = new ObjectOutputStream(os); Message firstMessage = (Message) input.readObject(); checkDuplicateUsername(firstMessage); writers.add(output); sendNotification(firstMessage); addToList(); while (socket.isConnected()) { Message inputmsg = (Message) input.readObject(); if (inputmsg != null) { logger.info(inputmsg.getType() + " - " + inputmsg.getName() + ": " + inputmsg.getMsg()); switch (inputmsg.getType()) { case USER: write(inputmsg); break; case VOICE: write(inputmsg); break; case CONNECTED: addToList(); break; case STATUS: changeStatus(inputmsg); break; } } } } catch (SocketException socketException) { logger.error("Socket Exception for user " + name); } catch (DuplicateUsernameException duplicateException){ logger.error("Duplicate Username : " + name); } catch (Exception e){ logger.error("Exception in run() method for user: " + name, e); } finally { closeConnections(); } } private Message changeStatus(Message inputmsg) throws IOException { logger.debug(inputmsg.getName() + " has changed status to " + inputmsg.getStatus()); Message msg = new Message(); msg.setName(user.getName()); msg.setType(MessageType.STATUS); msg.setMsg(""); User userObj = names.get(name); userObj.setStatus(inputmsg.getStatus()); write(msg); return msg; } private synchronized void checkDuplicateUsername(Message firstMessage) throws DuplicateUsernameException { logger.info(firstMessage.getName() + " is trying to connect"); if (!names.containsKey(firstMessage.getName())) { this.name = firstMessage.getName(); user = new User(); user.setName(firstMessage.getName()); user.setStatus(Status.ONLINE); user.setPicture(firstMessage.getPicture()); users.add(user); names.put(name, user); logger.info(name + " has been added to the list"); } else { logger.error(firstMessage.getName() + " is already connected"); throw new DuplicateUsernameException(firstMessage.getName() + " is already connected"); } } private Message sendNotification(Message firstMessage) throws IOException { Message msg = new Message(); msg.setMsg("has joined the chat."); msg.setType(MessageType.NOTIFICATION); msg.setName(firstMessage.getName()); msg.setPicture(firstMessage.getPicture()); write(msg); return msg; } private Message removeFromList() throws IOException { logger.debug("removeFromList() method Enter"); Message msg = new Message(); msg.setMsg("has left the chat."); msg.setType(MessageType.DISCONNECTED); msg.setName("SERVER"); msg.setUserlist(names); write(msg); logger.debug("removeFromList() method Exit"); return msg; } /* * For displaying that a user has joined the server */ private Message addToList() throws IOException { Message msg = new Message(); msg.setMsg("Welcome, You have now joined the server! Enjoy chatting!"); msg.setType(MessageType.CONNECTED); msg.setName("SERVER"); write(msg); return msg; } /* * Creates and sends a Message type to the listeners. */ private void write(Message msg) throws IOException { for (ObjectOutputStream writer : writers) { msg.setUserlist(names); msg.setUsers(users); msg.setOnlineCount(names.size()); writer.writeObject(msg); writer.reset(); } } /* * Once a user has been disconnected, we close the open connections and remove the writers */ private synchronized void closeConnections() { logger.debug("closeConnections() method Enter"); logger.info("HashMap names:" + names.size() + " writers:" + writers.size() + " usersList size:" + users.size()); if (name != null) { names.remove(name); logger.info("User: " + name + " has been removed!"); } if (user != null){ users.remove(user); logger.info("User object: " + user + " has been removed!"); } if (output != null){ writers.remove(output); logger.info("Writer object: " + user + " has been removed!"); } if (is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (input != null){ try { input.close(); } catch (IOException e) { e.printStackTrace(); } } try { removeFromList(); } catch (Exception e) { e.printStackTrace(); } logger.info("HashMap names:" + names.size() + " writers:" + writers.size() + " usersList size:" + users.size()); logger.debug("closeConnections() method Exit"); } } }