├── .gitignore ├── .travis.yml ├── ARM.Dockerfile ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── config.json.example ├── docker-compose.node-java.yml ├── docker-compose.yml ├── pbft.iml ├── pom.xml └── src ├── main └── java │ └── de │ ├── luckydonald │ └── utils │ │ ├── ObjectWithLogger.java │ │ ├── Streams.java │ │ ├── UserInput.java │ │ ├── dockerus │ │ ├── Dockerus.java │ │ ├── DockerusAuto.java │ │ ├── DockerusDummy.java │ │ ├── DockerusFile.java │ │ └── IDoNotWantThisException.java │ │ └── mockups │ │ ├── ServerSocketMockup.java │ │ └── SocketMockup.java │ └── teamproject16 │ ├── DS1820Reader.java │ └── pbft │ ├── CancelableLinkedBlockingMessageQueue.java │ ├── CancelableLinkedBlockingQueue.java │ ├── Main.java │ ├── Median.java │ ├── Messages │ ├── Acknowledge.java │ ├── InitMessage.java │ ├── LeaderChangeMessage.java │ ├── Message.java │ ├── PrevoteMessage.java │ ├── ProposeMessage.java │ ├── Types.java │ └── VoteMessage.java │ ├── Network │ ├── CloseConnectionPlease.java │ ├── Database │ │ └── Dumper.java │ ├── MessageQueue.java │ ├── Receiver.java │ └── Sender.java │ ├── NormalCase.java │ └── Sensor │ ├── FakeSensor.java │ ├── RealSensor.java │ └── SensorSelector.java └── test └── java └── de └── teamproject16 └── pbft ├── MedianTest.java ├── Messages └── TestMessage.java ├── Network └── ReceiverTest.java └── NormalCaseTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Maven template 3 | target/ 4 | pom.xml.tag 5 | pom.xml.releaseBackup 6 | pom.xml.versionsBackup 7 | pom.xml.next 8 | release.properties 9 | dependency-reduced-pom.xml 10 | buildNumber.properties 11 | .mvn/timing.properties 12 | ### JetBrains template 13 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 14 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 15 | 16 | # User-specific stuff: 17 | .idea/workspace.xml 18 | .idea/tasks.xml 19 | .idea/dictionaries 20 | .idea/vcs.xml 21 | .idea/jsLibraryMappings.xml 22 | 23 | # Sensitive or high-churn files: 24 | .idea/dataSources.ids 25 | .idea/dataSources.xml 26 | .idea/dataSources.local.xml 27 | .idea/sqlDataSources.xml 28 | .idea/dynamic.xml 29 | .idea/uiDesigner.xml 30 | 31 | # Gradle: 32 | .idea/gradle.xml 33 | .idea/libraries 34 | 35 | # Mongo Explorer plugin: 36 | .idea/mongoSettings.xml 37 | 38 | ## File-based project format: 39 | *.iws 40 | 41 | ## Plugin-specific files: 42 | 43 | # IntelliJ 44 | /out/ 45 | 46 | # mpeltonen/sbt-idea plugin 47 | .idea_modules/ 48 | 49 | # JIRA plugin 50 | atlassian-ide-plugin.xml 51 | 52 | # Crashlytics plugin (for Android Studio and IntelliJ) 53 | com_crashlytics_export_strings.xml 54 | crashlytics.properties 55 | crashlytics-build.properties 56 | fabric.properties 57 | ### JDeveloper template 58 | # default application storage directory used by the IDE Performance Cache feature 59 | .data/ 60 | 61 | # used for ADF styles caching 62 | temp/ 63 | 64 | # default output directories 65 | classes/ 66 | deploy/ 67 | javadoc/ 68 | 69 | # lock file, a part of Oracle Credential Store Framework 70 | cwallet.sso.lck### Eclipse template 71 | 72 | .metadata 73 | bin/ 74 | tmp/ 75 | *.tmp 76 | *.bak 77 | *.swp 78 | *~.nib 79 | local.properties 80 | .settings/ 81 | .loadpath 82 | .recommenders 83 | 84 | # Eclipse Core 85 | .project 86 | 87 | # External tool builders 88 | .externalToolBuilders/ 89 | 90 | # Locally stored "Eclipse launch configurations" 91 | *.launch 92 | 93 | # PyDev specific (Python IDE for Eclipse) 94 | *.pydevproject 95 | 96 | # CDT-specific (C/C++ Development Tooling) 97 | .cproject 98 | 99 | # JDT-specific (Eclipse Java Development Tools) 100 | .classpath 101 | 102 | # Java annotation processor (APT) 103 | .factorypath 104 | 105 | # PDT-specific (PHP Development Tools) 106 | .buildpath 107 | 108 | # sbteclipse plugin 109 | .target 110 | 111 | # Tern plugin 112 | .tern-project 113 | 114 | # TeXlipse plugin 115 | .texlipse 116 | 117 | # STS (Spring Tool Suite) 118 | .springBeans 119 | 120 | # Code Recommenders 121 | .recommenders/ 122 | ### Java template 123 | *.class 124 | 125 | # Mobile Tools for Java (J2ME) 126 | .mtj.tmp/ 127 | 128 | # Package Files # 129 | *.jar 130 | *.war 131 | *.ear 132 | 133 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 134 | hs_err_pid* -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | before_cache: 7 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 8 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 9 | 10 | cache: 11 | directories: 12 | - $HOME/.gradle/caches/ 13 | - $HOME/.gradle/wrapper/ 14 | 15 | after_success: 16 | - mvn test jacoco:report coveralls:report -DrepoToken=$COVERALLS_TOKEN 17 | 18 | notifications: 19 | # https://docs.travis-ci.com/user/notifications#Notifications 20 | webhooks: 21 | urls: 22 | - "https://bot.proxy.bronies.link/travis/webhook/eBsj4azkOk9Au40rnAb9OmVqi0WWH3bcYalWzZGYs1Q" 23 | on_success: always # default: always 24 | on_failure: always # default: always 25 | on_start: always # default: never 26 | # [always|never|change] # change means to notify when the build status changes. 27 | -------------------------------------------------------------------------------- /ARM.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM hypriot/rpi-java 2 | 3 | # Install maven 4 | RUN apt-get update 5 | RUN apt-get install -y maven 6 | 7 | WORKDIR /code 8 | 9 | # Prepare by downloading dependencies 10 | ADD pom.xml /code/pom.xml 11 | RUN ["mvn", "dependency:resolve", "-U"] 12 | RUN ["mvn", "verify"] 13 | 14 | # Adding source, compile and package into a fat jar 15 | ADD src /code/src 16 | RUN ["mvn", "package", "-DskipTest=True", "-Dmaven.javadoc.skip=true", "-Dmaven.test.skip=true", "--offline"] 17 | 18 | EXPOSE 4458 19 | # CMD ["ls", "-la", "target/"] 20 | ENTRYPOINT ["/usr/lib/jvm/java-8-openjdk-armhf/bin/java", "-jar", "target/pbft-jar-with-dependencies.jar"] -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-jdk 2 | 3 | # Install maven 4 | RUN apt-get update 5 | RUN apt-get install -y maven 6 | 7 | WORKDIR /code 8 | 9 | # Prepare by downloading dependencies 10 | ADD pom.xml /code/pom.xml 11 | RUN ["mvn", "dependency:resolve", "-U"] 12 | RUN ["mvn", "verify"] 13 | 14 | # Adding source, compile and package into a fat jar 15 | ADD src /code/src 16 | RUN ["mvn", "package", "-DskipTest=True", "-Dmaven.javadoc.skip=true", "-Dmaven.test.skip=true", "--offline"] 17 | 18 | EXPOSE 4458 19 | # CMD ["ls", "-la", "target/"] 20 | ENTRYPOINT ["/usr/lib/jvm/java-8-openjdk-amd64/bin/java", "-jar", "target/pbft-jar-with-dependencies.jar"] 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | offline: 2 | mvn package -DskipTest=True -Dmaven.javadoc.skip=true -Dmaven.test.skip=true --offline 3 | 4 | run: 5 | java -jar target/pbft-jar-with-dependencies.jar 6 | 7 | it: offline run 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PBFT 2 | ==== 3 | [![Build Status](https://travis-ci.org/luckydonald/PBFT-JAVA.svg?branch=master)](https://travis-ci.org/luckydonald/PBFT-JAVA) [![Coverage Status](https://coveralls.io/repos/github/luckydonald/PBFT-JAVA/badge.svg?branch=master)](https://coveralls.io/github/luckydonald/PBFT-JAVA?branch=master) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/ee3937a213e447a79d36f5cc0597d046)](https://www.codacy.com/app/luckydonald/PBFT-JAVA?utm_source=github.com&utm_medium=referral&utm_content=KathrynJaneway/PBFT-JAVA&utm_campaign=Badge_Grade) 4 | 5 | 6 | Node configuration 7 | ================== 8 | This offers different ways to load configuration and information about the other nodes. 9 | 10 | It will try to load the information in the following order: 11 | 12 | 1. [Configuration file](#configuration-file) 13 | 2. [Docker & Environment variables](#docker--environment-variables) 14 | 3. [Dummy Configuration](#dummy-configuration) 15 | 16 | The detection is made in class `DockerusAuto`. 17 | 18 | Docker & Environment variables 19 | ------------------------------ 20 | If this is launched via docker-compose, and is multiplied using `scale`, 21 | it will already grab all needed info from docker, and the following **Environment variables** 22 | 23 | - `HOSTNAME` own host name (should be given from the system) 24 | - `API_HOST` where the api node is. _Example: `http://localhost:8080/api`_ 25 | - `SENSOR_SIMULATE` set to `1` to enable reading from the `DS1820` sensor (tested on Raspberry Pi) 26 | 27 | This happens in the class `Dockerus`. 28 | 29 | 30 | Configuration file 31 | ------------------ 32 | If you specify a `config.json` file however, that one will be used: 33 | 34 | ```python 35 | { 36 | "node_hosts": ["192.168.2.8", "192.168.2.9", "192.168.2.10", "192.168.2.11"], 37 | "own_host": "192.168.2.8", # If not given: Falls back to the local socket ip address, which might be wrong! 38 | "api_host": "http://example.com/" # If you have this entry, it overwrites $API_HOST env variable. Or set to null, to disable. 39 | "sensor_simulate": false # If you have this entry, it overwrites $SENSOR_SIMULATE env variable. 40 | } 41 | ``` 42 | This is handled in the class `DockerusFile`. 43 | 44 | 45 | Dummy Configuration 46 | ------------------- 47 | It is not possible to use the PBFT algorithm with this. 48 | This is the fallback so unit tests can still be executed. 49 | See the class `DockerusDummy`. 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /config.json.example: -------------------------------------------------------------------------------- 1 | # nano Desktop/PBFT-JAVA/config.json 2 | { 3 | "node_hosts": ["192.168.2.8", "192.168.2.9", "192.168.2.10", "192.168.2.11"], 4 | "own_host": "192.168.2.8", 5 | "api_host": "http://example.com/", 6 | "simulate_sensor": true 7 | } -------------------------------------------------------------------------------- /docker-compose.node-java.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | node: 4 | build: . 5 | environment: 6 | NODE_PORT: 4458 7 | command: ["-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"] 8 | # restart: "unless-stopped" 9 | # stdin_open: true 10 | node-pi: 11 | build: 12 | context: . 13 | dockerfile: ARM.Dockerfile 14 | environment: 15 | NODE_PORT: 4458 -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | node_java: 4 | extends: 5 | file: docker-compose.node-java.yml 6 | service: node 7 | volumes: 8 | - /var/run/docker.sock:/var/run/docker.sock 9 | environment: 10 | NODE_DEBUG: "False" -------------------------------------------------------------------------------- /pbft.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | de.tu-bs.teamproject16 8 | pbft 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | jitpack.io 14 | https://jitpack.io 15 | 16 | 17 | 18 | 19 | 20 | 21 | org.json 22 | json 23 | 20090211 24 | 25 | 26 | 27 | 28 | org.slf4j 29 | slf4j-api 30 | 1.7.21 31 | 32 | 33 | 34 | 35 | org.slf4j 36 | slf4j-simple 37 | 1.7.21 38 | 39 | 40 | 41 | 42 | com.spotify 43 | docker-client 44 | 3.5.12 45 | 46 | 47 | 48 | 49 | com.github.luckydonald 50 | luckydonald-java-utils 51 | master-SNAPSHOT 52 | 53 | 54 | junit 55 | junit 56 | 4.12 57 | test 58 | 59 | 60 | 61 | 62 | javax.cache 63 | cache-api 64 | 0.3 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.apache.maven.plugins 74 | maven-jar-plugin 75 | 2.4 76 | 77 | pbft 78 | 79 | 80 | true 81 | de.teamproject16.pbft.Main 82 | dependency-jars/ 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-compiler-plugin 90 | 3.1 91 | 92 | 1.8 93 | 1.8 94 | 95 | 96 | 97 | org.apache.maven.plugins 98 | maven-assembly-plugin 99 | 100 | 101 | 102 | attached 103 | 104 | package 105 | 106 | pbft 107 | 108 | jar-with-dependencies 109 | 110 | 111 | 112 | de.teamproject16.pbft.Main 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | org.jacoco 121 | jacoco-maven-plugin 122 | 0.7.2.201409121644 123 | 124 | 125 | prepare-agent 126 | 127 | prepare-agent 128 | 129 | 130 | 131 | 132 | 133 | *at/HexLib/library/*.java 134 | **/*Gui.java 135 | **/Gui*.java 136 | 137 | 138 | 139 | 140 | org.eluder.coveralls 141 | coveralls-maven-plugin 142 | 4.3.0 143 | 144 | 147 | utf-8 148 | 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/ObjectWithLogger.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils; 2 | 3 | import java.util.logging.ConsoleHandler; 4 | import java.util.logging.Handler; 5 | import java.util.logging.Level; 6 | import java.util.logging.Logger; 7 | 8 | /** 9 | * Adds a logger ready to use. 10 | * @author luckydonald 11 | */ 12 | public class ObjectWithLogger { 13 | private Logger logger = null; 14 | private static Logger staticLogger = null; 15 | public Logger getLogger() { 16 | if (logger == null) { 17 | logger = Logger.getLogger(this.getClass().getCanonicalName()); 18 | } 19 | logger.setLevel(Level.FINE); 20 | return logger; 21 | } 22 | public static Logger getStaticLogger() { 23 | if (staticLogger == null) { 24 | staticLogger = Logger.getLogger(new Throwable().getStackTrace()[1].getClassName()); 25 | } 26 | return staticLogger; 27 | } 28 | 29 | public Handler addLogConsoleHandler() { 30 | return addLogConsoleHandler(null); 31 | } 32 | public Handler addLogConsoleHandler(Level l) { 33 | if (l == null) { 34 | return addLogConsoleHandler(Level.ALL); 35 | } 36 | // Create and set handler 37 | Handler systemOut = new ConsoleHandler(); 38 | systemOut.setLevel( l ); 39 | getLogger().addHandler( systemOut ); 40 | getLogger().setLevel( l ); 41 | 42 | // Prevent logs from processed by default Console handler. 43 | getLogger().setUseParentHandlers( false ); // Solution 1 44 | return systemOut; 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/Streams.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils; 2 | 3 | import de.luckydonald.utils.ObjectWithLogger; 4 | 5 | import java.util.ArrayList; 6 | import java.util.stream.Collector; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | * Collector + ObjectWithLogger 11 | * 12 | * @author luckydonald 13 | * @since 07.11.2016 14 | **/ 15 | public class Streams extends ObjectWithLogger { 16 | public static Collector> toArrayList() { 17 | return Collectors.toCollection(ArrayList::new); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/UserInput.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils; 2 | 3 | import de.luckydonald.utils.ObjectWithLogger; 4 | 5 | /** 6 | * Shortcuts for user IO. 7 | * 8 | * @author luckydonald 9 | * @since 30.03.2017 10 | **/ 11 | public class UserInput extends ObjectWithLogger { 12 | 13 | public static boolean stringIsTrue(String input) { 14 | switch ( input.toLowerCase()) { 15 | case "yes": 16 | case "y": 17 | case "ja": 18 | case "j": 19 | case "true": 20 | case "t": 21 | case "1": 22 | return true; 23 | default: 24 | return false; 25 | } 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/dockerus/Dockerus.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.dockerus; 2 | 3 | import com.spotify.docker.client.DefaultDockerClient; 4 | import com.spotify.docker.client.DockerCertificateException; 5 | import com.spotify.docker.client.DockerClient; 6 | import com.spotify.docker.client.DockerException; 7 | import com.spotify.docker.client.messages.Container; 8 | import de.luckydonald.utils.UserInput; 9 | 10 | import java.util.List; 11 | import java.util.stream.Collectors; 12 | 13 | // import static de.luckydonald.utils.lambdas.LambdaUtils.uncheckCall; 14 | 15 | /** 16 | * @author luckydonald 17 | */ 18 | public class Dockerus { 19 | String LABEL_COMPOSE_CONTAINER_NUMBER = "com.docker.compose.container-number"; 20 | String LABEL_COMPOSE_PROJECT = "com.docker.compose.project"; 21 | String LABEL_COMPOSE_SERVICE = "com.docker.compose.service"; 22 | 23 | final DockerClient docker; 24 | 25 | //CACHING_TIME = timedelta(seconds=60); 26 | 27 | static private Dockerus instance = null; 28 | 29 | static public Dockerus getInstance() throws IDoNotWantThisException { 30 | if (Dockerus.instance == null) { 31 | Dockerus.instance = new Dockerus(); 32 | try { 33 | Dockerus.instance.me(); 34 | } catch (DockerException | InterruptedException e) { 35 | //e.printStackTrace(); 36 | throw new IDoNotWantThisException(e); 37 | } 38 | } 39 | return Dockerus.instance; 40 | } 41 | 42 | Dockerus() throws IDoNotWantThisException { 43 | // Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars 44 | try { 45 | docker = DefaultDockerClient.fromEnv().build(); 46 | } catch (DockerCertificateException e) { 47 | e.printStackTrace(); 48 | throw new IDoNotWantThisException(e); 49 | } 50 | // docker.listContainers(DockerClient.ListContainersParam.withLabel("")) 51 | } 52 | 53 | 54 | public DockerClient getCLI() { 55 | return docker; 56 | } 57 | 58 | public String getEnvHostname() { 59 | return System.getenv("HOSTNAME"); 60 | } 61 | 62 | public Container me() throws DockerException, InterruptedException { 63 | return this.getCLI().listContainers().stream().filter(this::filterIsIdEqualHostname).limit(1).collect(Collectors.toList()).get(0); 64 | } 65 | 66 | public int getId() throws DockerException, InterruptedException { 67 | return Integer.parseInt(this.me().id()); 68 | } 69 | 70 | public String getService() throws DockerException, InterruptedException { 71 | return this.getService(this.me()); 72 | } 73 | public String getService(Container container) throws DockerException, InterruptedException { 74 | return container.labels().get(this.LABEL_COMPOSE_SERVICE); 75 | } 76 | 77 | public String getName() throws DockerException, InterruptedException { 78 | return this.getService(); 79 | } 80 | public String getName(Container container) throws DockerException, InterruptedException { 81 | return this.getService(container); 82 | } 83 | 84 | public String getProject() throws DockerException, InterruptedException { 85 | return this.getProject(this.me()); 86 | } 87 | public String getProject(Container container) throws DockerException, InterruptedException { 88 | return container.labels().get(this.LABEL_COMPOSE_PROJECT); 89 | } 90 | 91 | public int getNumber() throws DockerException, InterruptedException { 92 | return this.getNumber(this.me()); 93 | } 94 | public int getNumber(Container container) throws DockerException, InterruptedException { 95 | return Integer.parseInt(container.labels().get(this.LABEL_COMPOSE_CONTAINER_NUMBER)); 96 | } 97 | 98 | public List getContainers(boolean excludeSelf) throws DockerException, InterruptedException { 99 | Container me = me(); 100 | return this.getCLI().listContainers( 101 | DockerClient.ListContainersParam.withLabel(this.LABEL_COMPOSE_PROJECT, this.getProject(me)), 102 | DockerClient.ListContainersParam.withLabel(this.LABEL_COMPOSE_SERVICE, this.getService(me)) 103 | ).stream() 104 | .filter(c -> !excludeSelf || this.filterIsIdEqualHostname(c)) 105 | .filter(c -> { try { 106 | return this.getService(me).equals(c.labels().get(this.LABEL_COMPOSE_SERVICE)); 107 | } catch (InterruptedException | DockerException e) {return false;}}) 108 | //.filter(this::output) 109 | .collect(Collectors.toList()); 110 | } 111 | 112 | public int getTotal(boolean excludeSelf) { 113 | try { 114 | return this.getContainers(false).size(); 115 | } catch (DockerException | InterruptedException e) { 116 | return 0; 117 | } 118 | } 119 | 120 | public String getHostname() throws DockerException, InterruptedException { 121 | return this.getHostname(this.me()); 122 | } 123 | 124 | String getHostname(Container container) throws DockerException, InterruptedException { 125 | return "" + this.getProject(container) + "_" + this.getService(container) + "_" + this.getNumber(container); 126 | } 127 | 128 | public List getHostnames(boolean excludeSelf) throws DockerException, InterruptedException { 129 | return this.getContainers(excludeSelf).stream().map(c -> { try { return this.getHostname(c); } catch (InterruptedException | DockerException e) { e.printStackTrace(); return null; } }).filter(c -> c != null).collect(Collectors.toList()); 130 | // #java_sucks http://stackoverflow.com/a/19757456/3423324 131 | } 132 | 133 | boolean filterIsIdEqualHostname(Container c) { 134 | return c.id().substring(0, 12).equals(this.getEnvHostname().substring(0, 12)); 135 | } 136 | 137 | boolean output(Object o) { 138 | System.out.println("LIST STREAM ELEMENT: " + o.toString()); 139 | return true; 140 | } 141 | 142 | public String getApiHost() { 143 | return System.getenv("API_HOST"); 144 | } 145 | 146 | public boolean getSensorSimulate() { 147 | return UserInput.stringIsTrue(System.getenv("SENSOR_SIMULATE")); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/dockerus/DockerusAuto.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.dockerus; 2 | 3 | import com.spotify.docker.client.DockerCertificateException; 4 | import com.spotify.docker.client.DockerException; 5 | 6 | import java.util.InvalidPropertiesFormatException; 7 | 8 | /** 9 | * This selects a best fitting way to load config. See the other Dockerus* classes. 10 | * @author luckydonald 11 | */ 12 | public class DockerusAuto extends Dockerus { 13 | DockerusAuto() throws IDoNotWantThisException { 14 | } 15 | 16 | private static Dockerus instance; 17 | 18 | static public Dockerus getInstance() throws IDoNotWantThisException { 19 | if(DockerusAuto.instance != null) { 20 | return DockerusAuto.instance; 21 | } 22 | 23 | // Config file 24 | try { 25 | DockerusAuto.instance = DockerusFile.getInstance(); 26 | System.out.println("DockerFile"); 27 | } catch (IDoNotWantThisException e) { 28 | e.printStackTrace(); 29 | } 30 | if(DockerusAuto.instance != null) { 31 | return DockerusAuto.instance; 32 | } 33 | 34 | // Docker instance 35 | try { 36 | DockerusAuto.instance = Dockerus.getInstance(); 37 | System.out.println("Docker"); 38 | } catch (IDoNotWantThisException e) { 39 | e.printStackTrace(); 40 | } 41 | if(DockerusAuto.instance != null) { 42 | return DockerusAuto.instance; 43 | } 44 | 45 | // Dummy (Travis, etc.) 46 | try { 47 | DockerusAuto.instance = DockerusDummy.getInstance(); 48 | System.out.println("DockerDummy"); 49 | } catch (IDoNotWantThisException e) { 50 | e.printStackTrace(); 51 | } 52 | 53 | if(DockerusAuto.instance != null) { 54 | return DockerusAuto.instance; 55 | } 56 | 57 | // Nothing is working 58 | System.err.println("LOL THIS SHOULDN'T FAIL BECAUSE FAILING IS NOT IMPLEMENTED!!!111"); 59 | System.err.println("The config file, docker and the dummy class failed. At least the dummy class should have be successful."); 60 | throw new IDoNotWantThisException(new InvalidPropertiesFormatException("pfft!")); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/dockerus/DockerusDummy.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.dockerus; 2 | 3 | import com.spotify.docker.client.DockerCertificateException; 4 | import com.spotify.docker.client.DockerClient; 5 | import com.spotify.docker.client.DockerException; 6 | import com.spotify.docker.client.messages.Container; 7 | import org.apache.commons.lang.NotImplementedException; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public class DockerusDummy extends Dockerus{ 13 | 14 | private DockerusDummy() throws IDoNotWantThisException { 15 | System.out.println("Project probably not loaded in docker-compose..."); 16 | } 17 | 18 | static private DockerusDummy instance = null; 19 | 20 | static public DockerusDummy getInstance() throws IDoNotWantThisException { 21 | if (DockerusDummy.instance == null) { 22 | DockerusDummy.instance = new DockerusDummy(); 23 | } 24 | return DockerusDummy.instance; 25 | } 26 | 27 | @Override 28 | public List getHostnames(boolean excludeSelf) throws DockerException, InterruptedException { 29 | List foo = new ArrayList<>(); 30 | foo.add("localhost"); 31 | return foo; 32 | } 33 | 34 | @Override 35 | public String getHostname() throws DockerException, InterruptedException { 36 | return "localhost"; 37 | } 38 | 39 | @Override 40 | public DockerClient getCLI() { 41 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 42 | } 43 | 44 | @Override 45 | public String getEnvHostname() { 46 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 47 | } 48 | 49 | @Override 50 | public Container me() throws DockerException, InterruptedException { 51 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 52 | } 53 | 54 | @Override 55 | public int getId() throws DockerException, InterruptedException { 56 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 57 | } 58 | 59 | @Override 60 | public String getService() throws DockerException, InterruptedException { 61 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 62 | } 63 | 64 | @Override 65 | public String getService(Container container) throws DockerException, InterruptedException { 66 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 67 | } 68 | 69 | @Override 70 | public String getName() throws DockerException, InterruptedException { 71 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 72 | } 73 | 74 | @Override 75 | public String getName(Container container) throws DockerException, InterruptedException { 76 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 77 | } 78 | 79 | @Override 80 | public String getProject() throws DockerException, InterruptedException { 81 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 82 | } 83 | 84 | @Override 85 | public String getProject(Container container) throws DockerException, InterruptedException { 86 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 87 | } 88 | 89 | @Override 90 | public int getNumber() throws DockerException, InterruptedException { 91 | return 1; 92 | } 93 | 94 | @Override 95 | public int getNumber(Container container) throws DockerException, InterruptedException { 96 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 97 | } 98 | 99 | @Override 100 | public List getContainers(boolean excludeSelf) throws DockerException, InterruptedException { 101 | throw new NotImplementedException("Project probably not loaded in docker-compose..."); 102 | } 103 | private int total = 0; 104 | 105 | @Override 106 | public int getTotal(boolean excludeSelf) { 107 | return (excludeSelf ? total -1 : total); // stored not excluded 108 | } 109 | 110 | public void setTotal(int total) { 111 | this.setTotal(total, false); 112 | } 113 | public void setTotal(int total, boolean excludeSelf) { 114 | if (excludeSelf) { 115 | total++; // store not excluded 116 | } 117 | this.total = total; 118 | } 119 | 120 | @Override 121 | public boolean getSensorSimulate() { 122 | return true; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/dockerus/DockerusFile.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.dockerus; 2 | 3 | import com.spotify.docker.client.DockerException; 4 | import org.json.JSONArray; 5 | import org.json.JSONException; 6 | import org.json.JSONObject; 7 | 8 | import java.io.*; 9 | import java.net.InetAddress; 10 | import java.net.UnknownHostException; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * This loads the configuration from a config.json file. 16 | */ 17 | public class DockerusFile extends Dockerus { 18 | 19 | public static final String NODE_HOSTS_KEY = "node_hosts"; 20 | public static final String JSON_FILENAME = "config.json"; 21 | public static final String API_HOST_KEY = "api_host"; 22 | public static final String OWN_HOST_KEY = "own_host"; 23 | public static final String SENSOR_SIMULATE_KEY = "sensor_simulate"; 24 | private ArrayList hostnames = new ArrayList<>(); 25 | private String api_host = null; 26 | private String own_host = null; 27 | private Boolean sensor_simulate = true; 28 | 29 | public DockerusFile() throws IDoNotWantThisException { 30 | try { 31 | read_json_file(); 32 | } catch (IOException e) { 33 | System.err.println("File \"" + JSON_FILENAME + "\" could not be accessed. \n" + 34 | "If you need to create one, have a look at the \"" + JSON_FILENAME + ".example\" file."); 35 | throw new IDoNotWantThisException(e); 36 | } catch (JSONException e) { 37 | System.err.println("File \"" + JSON_FILENAME + "\" seems to be no valid json."); 38 | throw new IDoNotWantThisException(e); 39 | } 40 | } 41 | static private Dockerus instance = null; 42 | 43 | static public Dockerus getInstance() throws IDoNotWantThisException { 44 | if (DockerusFile.instance == null) { 45 | DockerusFile.instance = new DockerusFile(); 46 | } 47 | return DockerusFile.instance; 48 | } 49 | 50 | 51 | @Override 52 | public List getHostnames(boolean excludeSelf) throws DockerException, InterruptedException { 53 | return hostnames; 54 | } 55 | 56 | @Override 57 | public int getTotal(boolean excludeSelf) { 58 | return hostnames.size(); 59 | } 60 | 61 | @Override 62 | public int getNumber() throws DockerException, InterruptedException { 63 | return hostnames.indexOf(this.getHostname()); // find ourself in the list and return index. 64 | } 65 | 66 | @Override 67 | public String getHostname() throws DockerException, InterruptedException { 68 | try { 69 | if (this.own_host!=null && this.own_host.length() > 0) { 70 | return this.own_host; 71 | } 72 | return "" + InetAddress.getLocalHost().getHostAddress(); // get IP from socket/OS 73 | } catch (UnknownHostException e) { 74 | e.printStackTrace(); 75 | } 76 | return null; 77 | } 78 | 79 | @Override 80 | public String getName() throws DockerException, InterruptedException { 81 | return null; 82 | } 83 | @Override 84 | public String getProject() throws DockerException, InterruptedException { 85 | return null; 86 | } 87 | 88 | public void read_json_file() throws JSONException, IOException, IDoNotWantThisException { 89 | String jsonData = readFile(JSON_FILENAME); 90 | JSONObject root = new JSONObject(jsonData); 91 | JSONArray hostnames_json = new JSONArray(root.getJSONArray(NODE_HOSTS_KEY).toString()); 92 | for (int i = 0; i < hostnames_json.length(); i++) { 93 | String elem = hostnames_json.getString(i); 94 | this.hostnames.add(elem); 95 | } 96 | // api host (dumper) 97 | if (root.has(API_HOST_KEY) && !root.isNull(API_HOST_KEY)) { 98 | this.api_host = root.getString(API_HOST_KEY); 99 | } else { 100 | this.api_host = super.getApiHost(); 101 | } 102 | if (root.has(SENSOR_SIMULATE_KEY) && !root.isNull(SENSOR_SIMULATE_KEY)) { 103 | this.sensor_simulate = root.getBoolean(SENSOR_SIMULATE_KEY); 104 | } else { 105 | this.api_host = super.getApiHost(); 106 | } 107 | if (root.has(OWN_HOST_KEY) && !root.isNull(OWN_HOST_KEY)) { 108 | this.own_host = root.getString(OWN_HOST_KEY); 109 | if (this.hostnames.indexOf(this.own_host) < 0) { 110 | throw new IDoNotWantThisException( 111 | "Specified '"+OWN_HOST_KEY+"' ("+this.own_host+") " + 112 | "is not contained in '"+NODE_HOSTS_KEY+"("+hostnames_json+")'!" 113 | ); 114 | } 115 | } 116 | } 117 | public static String readFile(String filename) throws IOException { 118 | return readFile(new File(filename)); 119 | } 120 | public static String readFile(File filename) throws IOException { 121 | String result = ""; 122 | try { 123 | BufferedReader br = new BufferedReader(new FileReader(filename)); 124 | StringBuilder sb = new StringBuilder(); 125 | String line = br.readLine(); 126 | while (line != null) { 127 | sb.append(line); 128 | line = br.readLine(); 129 | } 130 | result = sb.toString(); 131 | } catch(Exception e) { 132 | e.printStackTrace(); 133 | throw e; 134 | } 135 | return result; 136 | } 137 | 138 | @Override 139 | public String getApiHost() { 140 | if (this.api_host != null ) { 141 | return this.api_host; 142 | } else { 143 | return super.getApiHost(); 144 | } 145 | } 146 | 147 | @Override 148 | public boolean getSensorSimulate() { 149 | if (this.sensor_simulate != null ) { 150 | return this.sensor_simulate; 151 | } else { 152 | return super.getSensorSimulate(); 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/dockerus/IDoNotWantThisException.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.dockerus; 2 | 3 | import com.spotify.docker.client.DockerCertificateException; 4 | 5 | /** 6 | * This can be raised if something should be raised and we want to catch something. 7 | * 8 | * @author luckydonald 9 | **/ 10 | public class IDoNotWantThisException extends Exception { 11 | 12 | public IDoNotWantThisException(Exception e) { 13 | super(e.getMessage(), e); 14 | } 15 | public IDoNotWantThisException(final String message) { 16 | super(message); 17 | } 18 | 19 | public IDoNotWantThisException(final String message, final Throwable cause) { 20 | super(message, cause); 21 | } 22 | 23 | public IDoNotWantThisException(final Throwable cause) { 24 | super(cause); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/mockups/ServerSocketMockup.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.mockups; 2 | 3 | import java.io.IOException; 4 | import java.net.*; 5 | import java.nio.channels.ServerSocketChannel; 6 | 7 | 8 | /** 9 | * @author luckydonald 10 | * @since 26.10.2016 11 | **/ 12 | public class ServerSocketMockup extends ServerSocket { 13 | SocketMockup socket = null; 14 | public ServerSocketMockup(SocketMockup s) throws IOException { 15 | System.out.println("Mock ServerSocket"); 16 | this.socket = s; 17 | } 18 | 19 | public ServerSocketMockup(int port) throws IOException { 20 | throw new UnsupportedOperationException("Not implemented."); // super(port); 21 | } 22 | 23 | public ServerSocketMockup(int port, int backlog) throws IOException { 24 | throw new UnsupportedOperationException("Not implemented."); // super(port, backlog); 25 | } 26 | 27 | public ServerSocketMockup(int port, int backlog, InetAddress bindAddr) throws IOException { 28 | throw new UnsupportedOperationException("Not implemented."); // super(port, backlog, bindAddr); 29 | } 30 | 31 | @Override 32 | public void bind(SocketAddress endpoint) throws IOException { 33 | throw new UnsupportedOperationException("Not implemented."); // super.bind(endpoint); 34 | } 35 | 36 | @Override 37 | public void bind(SocketAddress endpoint, int backlog) throws IOException { 38 | throw new UnsupportedOperationException("Not implemented."); // super.bind(endpoint, backlog); 39 | } 40 | 41 | @Override 42 | public InetAddress getInetAddress() { 43 | throw new UnsupportedOperationException("Not implemented."); // return super.getInetAddress(); 44 | } 45 | 46 | @Override 47 | public int getLocalPort() { 48 | throw new UnsupportedOperationException("Not implemented."); // return super.getLocalPort(); 49 | } 50 | 51 | @Override 52 | public SocketAddress getLocalSocketAddress() { 53 | throw new UnsupportedOperationException("Not implemented."); // return super.getLocalSocketAddress(); 54 | } 55 | 56 | @Override 57 | public Socket accept() throws IOException { 58 | System.out.println("accept()"); 59 | return new SocketMockup(); 60 | } 61 | 62 | @Override 63 | public void close() throws IOException { 64 | super.close(); 65 | } 66 | 67 | @Override 68 | public ServerSocketChannel getChannel() { 69 | throw new UnsupportedOperationException("Not implemented."); // return super.getChannel(); 70 | } 71 | 72 | @Override 73 | public boolean isBound() { 74 | throw new UnsupportedOperationException("Not implemented."); // return super.isBound(); 75 | } 76 | 77 | @Override 78 | public boolean isClosed() { 79 | throw new UnsupportedOperationException("Not implemented."); // return super.isClosed(); 80 | } 81 | 82 | @Override 83 | public synchronized void setSoTimeout(int timeout) throws SocketException { 84 | super.setSoTimeout(timeout); 85 | } 86 | 87 | @Override 88 | public synchronized int getSoTimeout() throws IOException { 89 | throw new UnsupportedOperationException("Not implemented."); // return super.getSoTimeout(); 90 | } 91 | 92 | @Override 93 | public void setReuseAddress(boolean on) throws SocketException { 94 | super.setReuseAddress(on); 95 | } 96 | 97 | public boolean getReuseAddress() throws SocketException { 98 | throw new UnsupportedOperationException("Not implemented."); // return super.getReuseAddress(); 99 | } 100 | 101 | @Override 102 | public String toString() { 103 | throw new UnsupportedOperationException("Not implemented."); // return super.toString(); 104 | } 105 | 106 | @Override 107 | public synchronized void setReceiveBufferSize(int size) throws SocketException { 108 | super.setReceiveBufferSize(size); 109 | } 110 | 111 | @Override 112 | public synchronized int getReceiveBufferSize() throws SocketException { 113 | throw new UnsupportedOperationException("Not implemented."); // return super.getReceiveBufferSize(); 114 | } 115 | 116 | @Override 117 | public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { 118 | super.setPerformancePreferences(connectionTime, latency, bandwidth); 119 | } 120 | } -------------------------------------------------------------------------------- /src/main/java/de/luckydonald/utils/mockups/SocketMockup.java: -------------------------------------------------------------------------------- 1 | package de.luckydonald.utils.mockups; 2 | 3 | import de.luckydonald.utils.ObjectWithLogger; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.net.*; 9 | import java.nio.channels.SocketChannel; 10 | 11 | /** 12 | * Mocks a socket. For testing. 13 | **/ 14 | public class SocketMockup extends Socket { 15 | public InputStream in = null; 16 | public SocketMockup() { 17 | System.out.print("Mock Socket"); 18 | } 19 | 20 | public SocketMockup(Proxy proxy) { 21 | throw new UnsupportedOperationException("Not implemented."); // super(proxy); 22 | } 23 | 24 | protected SocketMockup(SocketImpl impl) throws SocketException { 25 | throw new UnsupportedOperationException("Not implemented."); // super(impl); 26 | } 27 | 28 | public SocketMockup(String host, int port) throws UnknownHostException, IOException { 29 | throw new UnsupportedOperationException("Not implemented."); // super(host, port); 30 | } 31 | 32 | public SocketMockup(InetAddress address, int port) throws IOException { 33 | throw new UnsupportedOperationException("Not implemented."); // super(address, port); 34 | } 35 | 36 | public SocketMockup(String host, int port, InetAddress localAddr, int localPort) throws IOException { 37 | throw new UnsupportedOperationException("Not implemented."); // super(host, port, localAddr, localPort); 38 | } 39 | 40 | public SocketMockup(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException { 41 | throw new UnsupportedOperationException("Not implemented."); // super(address, port, localAddr, localPort); 42 | } 43 | 44 | public SocketMockup(String host, int port, boolean stream) throws IOException { 45 | throw new UnsupportedOperationException("Not implemented."); // super(host, port, stream); 46 | } 47 | 48 | public SocketMockup(InetAddress host, int port, boolean stream) throws IOException { 49 | throw new UnsupportedOperationException("Not implemented."); // super(host, port, stream); 50 | } 51 | 52 | @Override 53 | public void connect(SocketAddress endpoint) throws IOException { 54 | throw new UnsupportedOperationException("Not implemented."); // super.connect(endpoint); 55 | } 56 | 57 | @Override 58 | public void connect(SocketAddress endpoint, int timeout) throws IOException { 59 | throw new UnsupportedOperationException("Not implemented."); // super.connect(endpoint, timeout); 60 | } 61 | 62 | @Override 63 | public void bind(SocketAddress bindpoint) throws IOException { 64 | throw new UnsupportedOperationException("Not implemented."); // super.bind(bindpoint); 65 | } 66 | 67 | @Override 68 | public InetAddress getInetAddress() { 69 | throw new UnsupportedOperationException("Not implemented."); // return super.getInetAddress(); 70 | } 71 | 72 | @Override 73 | public InetAddress getLocalAddress() { 74 | throw new UnsupportedOperationException("Not implemented."); // return super.getLocalAddress(); 75 | } 76 | 77 | @Override 78 | public int getPort() { 79 | throw new UnsupportedOperationException("Not implemented."); // return super.getPort(); 80 | } 81 | 82 | @Override 83 | public int getLocalPort() { 84 | throw new UnsupportedOperationException("Not implemented."); // return super.getLocalPort(); 85 | } 86 | 87 | @Override 88 | public SocketAddress getRemoteSocketAddress() { 89 | throw new UnsupportedOperationException("Not implemented."); // return super.getRemoteSocketAddress(); 90 | } 91 | 92 | @Override 93 | public SocketAddress getLocalSocketAddress() { 94 | throw new UnsupportedOperationException("Not implemented."); // return super.getLocalSocketAddress(); 95 | } 96 | 97 | @Override 98 | public SocketChannel getChannel() { 99 | throw new UnsupportedOperationException("Not implemented."); // return super.getChannel(); 100 | } 101 | 102 | @Override 103 | public InputStream getInputStream() throws IOException { 104 | System.out.println("getInputStream()"); 105 | return in; 106 | } 107 | 108 | @Override 109 | public OutputStream getOutputStream() throws IOException { 110 | throw new UnsupportedOperationException("Not implemented."); // return super.getOutputStream(); 111 | } 112 | 113 | @Override 114 | public void setTcpNoDelay(boolean on) throws SocketException { 115 | throw new UnsupportedOperationException("Not implemented."); // super.setTcpNoDelay(on); 116 | } 117 | 118 | @Override 119 | public boolean getTcpNoDelay() throws SocketException { 120 | throw new UnsupportedOperationException("Not implemented."); // return super.getTcpNoDelay(); 121 | } 122 | 123 | @Override 124 | public void setSoLinger(boolean on, int linger) throws SocketException { 125 | throw new UnsupportedOperationException("Not implemented."); // super.setSoLinger(on, linger); 126 | } 127 | 128 | @Override 129 | public int getSoLinger() throws SocketException { 130 | throw new UnsupportedOperationException("Not implemented."); // return super.getSoLinger(); 131 | } 132 | 133 | @Override 134 | public void sendUrgentData(int data) throws IOException { 135 | throw new UnsupportedOperationException("Not implemented."); // super.sendUrgentData(data); 136 | } 137 | 138 | @Override 139 | public void setOOBInline(boolean on) throws SocketException { 140 | throw new UnsupportedOperationException("Not implemented."); // super.setOOBInline(on); 141 | } 142 | 143 | @Override 144 | public boolean getOOBInline() throws SocketException { 145 | throw new UnsupportedOperationException("Not implemented."); // return super.getOOBInline(); 146 | } 147 | 148 | @Override 149 | public synchronized void setSoTimeout(int timeout) throws SocketException { 150 | throw new UnsupportedOperationException("Not implemented."); // super.setSoTimeout(timeout); 151 | } 152 | 153 | @Override 154 | public synchronized int getSoTimeout() throws SocketException { 155 | throw new UnsupportedOperationException("Not implemented."); // return super.getSoTimeout(); 156 | } 157 | 158 | @Override 159 | public synchronized void setSendBufferSize(int size) throws SocketException { 160 | throw new UnsupportedOperationException("Not implemented."); // super.setSendBufferSize(size); 161 | } 162 | 163 | @Override 164 | public synchronized int getSendBufferSize() throws SocketException { 165 | throw new UnsupportedOperationException("Not implemented."); // return super.getSendBufferSize(); 166 | } 167 | 168 | @Override 169 | public synchronized void setReceiveBufferSize(int size) throws SocketException { 170 | throw new UnsupportedOperationException("Not implemented."); // super.setReceiveBufferSize(size); 171 | } 172 | 173 | @Override 174 | public synchronized int getReceiveBufferSize() throws SocketException { 175 | throw new UnsupportedOperationException("Not implemented."); // return super.getReceiveBufferSize(); 176 | } 177 | 178 | @Override 179 | public void setKeepAlive(boolean on) throws SocketException { 180 | throw new UnsupportedOperationException("Not implemented."); // super.setKeepAlive(on); 181 | } 182 | 183 | @Override 184 | public boolean getKeepAlive() throws SocketException { 185 | throw new UnsupportedOperationException("Not implemented."); // return super.getKeepAlive(); 186 | } 187 | 188 | @Override 189 | public void setTrafficClass(int tc) throws SocketException { 190 | throw new UnsupportedOperationException("Not implemented."); // super.setTrafficClass(tc); 191 | } 192 | 193 | @Override 194 | public int getTrafficClass() throws SocketException { 195 | throw new UnsupportedOperationException("Not implemented."); // return super.getTrafficClass(); 196 | } 197 | 198 | @Override 199 | public void setReuseAddress(boolean on) throws SocketException { 200 | throw new UnsupportedOperationException("Not implemented."); // super.setReuseAddress(on); 201 | } 202 | 203 | @Override 204 | public boolean getReuseAddress() throws SocketException { 205 | throw new UnsupportedOperationException("Not implemented."); // return super.getReuseAddress(); 206 | } 207 | 208 | @Override 209 | public synchronized void close() throws IOException { 210 | System.out.println("close()"); 211 | } 212 | 213 | @Override 214 | public void shutdownInput() throws IOException { 215 | throw new UnsupportedOperationException("Not implemented."); // super.shutdownInput(); 216 | } 217 | 218 | @Override 219 | public void shutdownOutput() throws IOException { 220 | throw new UnsupportedOperationException("Not implemented."); // super.shutdownOutput(); 221 | } 222 | 223 | @Override 224 | public String toString() { 225 | throw new UnsupportedOperationException("Not implemented."); // return super.toString(); 226 | } 227 | 228 | @Override 229 | public boolean isConnected() { 230 | throw new UnsupportedOperationException("Not implemented."); // return super.isConnected(); 231 | } 232 | 233 | @Override 234 | public boolean isBound() { 235 | throw new UnsupportedOperationException("Not implemented."); // return super.isBound(); 236 | } 237 | 238 | @Override 239 | public boolean isClosed() { 240 | throw new UnsupportedOperationException("Not implemented."); // return super.isClosed(); 241 | } 242 | 243 | @Override 244 | public boolean isInputShutdown() { 245 | throw new UnsupportedOperationException("Not implemented."); // return super.isInputShutdown(); 246 | } 247 | 248 | @Override 249 | public boolean isOutputShutdown() { 250 | throw new UnsupportedOperationException("Not implemented."); // return super.isOutputShutdown(); 251 | } 252 | 253 | @Override 254 | public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { 255 | throw new UnsupportedOperationException("Not implemented."); // super.setPerformancePreferences(connectionTime, latency, bandwidth); 256 | } 257 | } -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/DS1820Reader.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.nio.file.FileSystems; 3 | import java.nio.file.Files; 4 | import java.nio.file.Path; 5 | import java.util.List; 6 | 7 | public class DS1820Reader { 8 | 9 | ///sys/bus/w1/devices/XX-XXXX..../w1_slave 10 | /* path to search for devices in filesystem */ 11 | private static String devicesPath = "/sys/bus/w1/devices"; 12 | 13 | /* file of the measured values */ 14 | private static String valueFile = "w1_slave"; 15 | 16 | /* id of sensor */ 17 | private static String id = null; 18 | 19 | 20 | public static double read() { 21 | // if id is null, search for sensor and take the first 22 | if (id==null) { 23 | findSensorID(); 24 | if (id == null) 25 | return Double.MAX_VALUE; 26 | } 27 | 28 | Path path = FileSystems.getDefault().getPath(devicesPath, id, valueFile); 29 | List lines; 30 | 31 | int attempts = 3; 32 | boolean crcOK = false; 33 | 34 | while (attempts > 0) { 35 | try { 36 | lines = Files.readAllLines(path); 37 | for(String line: lines) { 38 | if (line.endsWith("YES")) 39 | crcOK = true; 40 | else if (line.matches(".*t=[0-9]+") && crcOK) 41 | return Integer.valueOf(line.substring(line.indexOf("=")+1))/1000.0; 42 | } 43 | } catch (Exception e) { 44 | e.printStackTrace(); 45 | continue; 46 | } 47 | attempts--; 48 | } 49 | 50 | return Double.MAX_VALUE; 51 | } 52 | 53 | 54 | public static String findSensorID() { 55 | File searchPath = new File(devicesPath); 56 | if (searchPath.listFiles()!=null) { 57 | for (File f: searchPath.listFiles()) { 58 | if (f.isDirectory() && !f.getName().startsWith("w1_bus_master")) 59 | id = f.getName(); 60 | 61 | } 62 | } 63 | return id; 64 | } 65 | 66 | public static void main(String[] args) { 67 | System.out.println("DS1820 Temperature Sensor Tool"); 68 | System.out.println("------------------------------"); 69 | if(findSensorID() != null){ 70 | System.out.println(" found sensor: " + id); 71 | System.out.print(" read sensor " + id + " ..."); 72 | double t = DS1820Reader.read(); 73 | System.out.println(" --> temp: " + t); 74 | } 75 | 76 | } 77 | 78 | 79 | } 80 | 81 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/CancelableLinkedBlockingMessageQueue.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | 4 | import de.teamproject16.pbft.Messages.Message; 5 | 6 | import java.util.concurrent.CancellationException; 7 | import java.util.concurrent.LinkedBlockingQueue; 8 | 9 | /** 10 | * //TODO: Here are many original funcions which don't respect the cancel() command. 11 | * A class which allows to abort the waiting for new entries by calling {@link #cancel()}. 12 | * Also has {@link #isCanceled()} and {@link #uncancel()}. 13 | * 14 | * Currently only {@link #put(Object)} and {@link #take()} are save to access and use the underlaying {@link LinkedBlockingQueue}. 15 | * 16 | * @author luckydonald 17 | * @since 26.10.2016 18 | * @see LinkedBlockingQueue 19 | **/ 20 | public class CancelableLinkedBlockingMessageQueue extends CancelableLinkedBlockingQueue { 21 | private static final long serialVersionUID = 0x1L; 22 | 23 | /** 24 | * May return null if producer ends the production after consumer 25 | * has entered the element-await state. 26 | * @param current_sequence_no: it will skip (discard) all omessages with a sequence_no below that. 27 | * 28 | * @throws CancellationException when .cancel() was called somewhere. 29 | */ 30 | public T take(long current_sequence_no) throws InterruptedException, CancellationException { 31 | T el; 32 | while (((el = super.poll()) == null || el.sequence_no < current_sequence_no) && !this.isCanceled()) { // while has no next element and is not canceled. 33 | synchronized (this) { 34 | wait(); 35 | } 36 | } 37 | if (this.isCanceled()) { 38 | throw new CancellationException("Done."); 39 | } 40 | return el; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/CancelableLinkedBlockingQueue.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | 4 | import java.util.concurrent.CancellationException; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | 7 | /** 8 | * //TODO: Here are many original funcions which don't respect the cancel() command. 9 | * A class which allows to abort the waiting for new entries by calling {@link #cancel()}. 10 | * Also has {@link #isCanceled()} and {@link #uncancel()}. 11 | * 12 | * Currently only {@link #put(Object)} and {@link #take()} are save to access and use the underlaying {@link LinkedBlockingQueue}. 13 | * 14 | * @author luckydonald 15 | * @since 26.10.2016 16 | * @see LinkedBlockingQueue 17 | **/ 18 | public class CancelableLinkedBlockingQueue extends LinkedBlockingQueue { 19 | private static final long serialVersionUID = 1L; 20 | private boolean canceled = false; 21 | 22 | public CancelableLinkedBlockingQueue() { super(); } 23 | 24 | /** 25 | * Cancels any blocking {@link #take()} calls. 26 | * Any calls to {@link #take()} (blocking or new) will throw a {@link CancellationException}. 27 | */ 28 | public void cancel() { 29 | canceled = true; 30 | synchronized (this) { 31 | notifyAll(); 32 | } 33 | } 34 | 35 | public boolean isCanceled() { 36 | return canceled; 37 | } 38 | 39 | public void uncancel() { 40 | canceled = false; 41 | } 42 | 43 | /** 44 | * Inserts the specified element at the tail of this queue, waiting if 45 | * necessary for space to become available. 46 | * @param element Element to append. 47 | * @throws InterruptedException {@inheritDoc} 48 | * @throws NullPointerException {@inheritDoc} 49 | */ 50 | @Override 51 | public void put(T element) throws InterruptedException { 52 | super.put(element); 53 | synchronized (this) { 54 | notify(); 55 | } 56 | } 57 | 58 | 59 | /** 60 | * May return null if producer ends the production after consumer 61 | * has entered the element-await state. 62 | * 63 | * @throws CancellationException when .cancel() was called somewhere. 64 | */ 65 | public T take() throws InterruptedException, CancellationException { 66 | T el; 67 | while ((el = super.poll()) == null && !canceled) { // while has no next element and is not canceled. 68 | synchronized (this) { 69 | wait(); 70 | } 71 | } 72 | if (canceled) { 73 | throw new CancellationException("Done."); 74 | } 75 | return el; 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Main.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | import de.luckydonald.utils.dockerus.DockerusAuto; 4 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 5 | import de.teamproject16.pbft.Network.Receiver; 6 | import de.teamproject16.pbft.Sensor.FakeSensor; 7 | import de.teamproject16.pbft.Sensor.SensorSelector; 8 | 9 | import java.net.ConnectException; 10 | import java.util.concurrent.TimeoutException; 11 | import java.util.logging.ConsoleHandler; 12 | import java.util.logging.Handler; 13 | import java.util.logging.Level; 14 | import java.util.logging.Logger; 15 | 16 | /** 17 | * Main class of the program. Starting stuff. 18 | */ 19 | public class Main { 20 | public static void main(String[] args) throws Exception { 21 | Handler consoleHandler = new ConsoleHandler(); 22 | consoleHandler.setLevel(Level.ALL); 23 | Logger.getAnonymousLogger().addHandler(consoleHandler); 24 | Logger.getGlobal().addHandler(consoleHandler); 25 | Logger.getAnonymousLogger(); 26 | System.out.println("HalloMain"); 27 | Receiver receiver = new Receiver(); 28 | receiver.start(); 29 | NormalCase algo = new NormalCase(receiver); 30 | StringBuilder sb = new StringBuilder("[Environment] \n"); 31 | sb.append("Node container: ").append(DockerusAuto.getInstance().getEnvHostname()).append("\n"); 32 | sb.append("Node hostname: ").append(DockerusAuto.getInstance().getHostname()).append("\n"); 33 | sb.append("Node number: ").append(DockerusAuto.getInstance().getNumber()).append("\n"); 34 | sb.append("Node name: ").append(DockerusAuto.getInstance().getName()).append("\n"); 35 | sb.append("Node project: ").append(DockerusAuto.getInstance().getProject()).append("\n"); 36 | sb.append("API Host: ").append(DockerusAuto.getInstance().getApiHost()).append("\n"); 37 | sb.append("\n[Other nodes]\n"); 38 | for (String n : DockerusAuto.getInstance().getHostnames(false)) { 39 | sb.append(" - ").append(n).append("\n"); 40 | } 41 | System.out.println(sb.toString()); 42 | 43 | while(true) { 44 | System.out.println("### STARTING ROUND ###"); 45 | try { 46 | double measurement = SensorSelector.getSensorValue(); 47 | System.out.println("### NEW MEASUREMENT: " + measurement); 48 | double result = algo.normalFunction(measurement); 49 | System.out.println("### MEASURED: " + measurement); 50 | System.out.println("### RESULT: " + result); 51 | if (false) { 52 | throw new ConnectException(); 53 | // java complained that ConnectException would never be raised in here, BUT IT IS! 54 | // This sh*t is why java is so ugly. 55 | } 56 | } catch (TimeoutException | ConnectException | IDoNotWantThisException e) { 57 | System.out.println("### Round Abort ###"); 58 | } finally { 59 | algo.cleanUp(); 60 | } 61 | 62 | } 63 | 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Median.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | import de.teamproject16.pbft.Messages.InitMessage; 4 | 5 | import java.util.Collections; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.stream.Stream; 9 | 10 | /** 11 | * Created on 29.09.16. 12 | */ 13 | public class Median { 14 | 15 | /** calculates the median of a given initStore list. This list has to only contain the current sequence number. **/ 16 | public static double calculateMedian(List initStore) throws InterruptedException { 17 | return calculateMedian(initStore.stream()); 18 | } 19 | 20 | public static double calculateMedian(Stream initMessageStream) { 21 | //TODO: Start Locking 22 | List floatStore = new LinkedList<>(); 23 | initMessageStream.forEach(msg -> floatStore.add(msg.value)); 24 | //TODO: End lock 25 | Collections.sort(floatStore); 26 | int calculate = (floatStore.size()-1)/2; 27 | return floatStore.get(calculate); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/Acknowledge.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.apache.commons.lang.NotImplementedException; 4 | import org.json.JSONException; 5 | import org.json.JSONObject; 6 | 7 | import static de.teamproject16.pbft.Messages.Types.ACKNOWLEDGE; 8 | 9 | /** 10 | * This is just to notify the API server that we got a message. 11 | */ 12 | public class Acknowledge extends Message { 13 | //public int node; 14 | public int sender; 15 | public JSONObject raw; 16 | 17 | /** 18 | *InitMessage 19 | * @param sequence_no of tries 20 | * @param node the id of the current node 21 | * @param sender the id of the other node, the sender 22 | */ 23 | public Acknowledge(long sequence_no, int node, int sender) { 24 | super(node, ACKNOWLEDGE, sequence_no); 25 | //this.node = node; 26 | this.sender = sender; 27 | } 28 | 29 | /** 30 | *InitMessage 31 | * @param sequence_no of tries 32 | * @param node the id of the current node 33 | * @param sender the id of the other node, the sender 34 | * @param raw json which was received 35 | */ 36 | public Acknowledge(long sequence_no, int node, int sender, JSONObject raw) { 37 | super(node, ACKNOWLEDGE, sequence_no); 38 | //this.node = node; 39 | this.sender = sender; 40 | this.raw = raw; 41 | } 42 | 43 | /** 44 | * Create a initmessage object from the data out JSONObject. 45 | * @param data JSONObject 46 | * @return a new InitMessage object with the specific data. 47 | * @throws JSONException 48 | */ 49 | public static Acknowledge messageDecipher(JSONObject data) throws JSONException { 50 | throw new NotImplementedException(); 51 | } 52 | 53 | /** 54 | * Create JSONObject for the network. 55 | * @return data JSONObject 56 | * @throws JSONException 57 | */ 58 | public JSONObject messageEncode() throws JSONException { 59 | JSONObject data = super.messageEncode(); 60 | //data.put("node", this.node); 61 | data.put("sender", this.sender); 62 | data.put("raw", this.raw); 63 | return data; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/InitMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | import static de.teamproject16.pbft.Messages.Types.INIT; 6 | 7 | /** 8 | * Json serializable Init message 9 | */ 10 | public class InitMessage extends Message { 11 | public double value; 12 | //public int node; 13 | 14 | /** 15 | *InitMessage 16 | * @param sequence_no of tries 17 | * @param node the id of the sender 18 | * @param value the value of the sensor from the node 19 | */ 20 | public InitMessage(long sequence_no, int node, double value) { 21 | super(node, INIT, sequence_no); 22 | //this.node = node; 23 | this.value = value; 24 | } 25 | 26 | /** 27 | * Create a initmessage object from the data out JSONObject. 28 | * @param data JSONObject 29 | * @return a new InitMessage object with the specific data. 30 | * @throws JSONException 31 | */ 32 | public static InitMessage messageDecipher(JSONObject data) throws JSONException { 33 | return new InitMessage(data.getLong("sequence_no"), data.getInt("node"), 34 | data.getDouble("value")); 35 | } 36 | 37 | /** 38 | * Create JSONObject for the network. 39 | * @return data JSONObject 40 | * @throws JSONException 41 | */ 42 | public JSONObject messageEncode() throws JSONException { 43 | JSONObject data = super.messageEncode(); 44 | data.put("value", this.value); 45 | return data; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/LeaderChangeMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONObject; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static de.teamproject16.pbft.Messages.Types.LEADER_CHANGE; 8 | 9 | /** 10 | * Json serializable LoaderChangeMessage message. 11 | * Not implemented. 12 | */ 13 | public class LeaderChangeMessage extends Message { 14 | 15 | //public int node; 16 | public int leader; 17 | public ArrayList prevoteList; 18 | 19 | public LeaderChangeMessage(long sequence_no, int node, int leader, ArrayList prevoteList) { 20 | super(node, LEADER_CHANGE, sequence_no); 21 | //this.node = node; 22 | this.leader = leader; 23 | this.prevoteList = prevoteList; 24 | } 25 | 26 | public static LeaderChangeMessage messageDecipher(JSONObject data) { 27 | return null; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/Message.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | /** 7 | * A json serializable message. The base type. 8 | **/ 9 | public class Message { 10 | public int node; 11 | 12 | public int getType() { 13 | return type; 14 | } 15 | public String getTypeString() { 16 | return Types._NAMES_.get(this.getType()); 17 | } 18 | 19 | private int type; 20 | public long sequence_no; 21 | 22 | /** 23 | * Create the basic type of message. 24 | * @param type messagetype 25 | * @param sequence_no of tries 26 | */ 27 | public Message(int node, int type, long sequence_no){ 28 | this.node = node; 29 | this.type = type; 30 | this.sequence_no = sequence_no; 31 | } 32 | 33 | /** 34 | * 35 | * @return String with basic data from this message. 36 | */ 37 | public String toString(){ 38 | try { 39 | return this.messageEncode().toString(); 40 | } catch (JSONException e) { 41 | e.printStackTrace(); 42 | return "Error toString/de.teamproject16.pbft.Messages.Message"; 43 | } 44 | } 45 | 46 | /** 47 | * Encode the basic data for the network. 48 | * @return JSONObject data 49 | * @throws JSONException 50 | */ 51 | public JSONObject messageEncode () throws JSONException { 52 | JSONObject data = new JSONObject(); 53 | data.put("node", this.node); 54 | data.put("type", this.type); 55 | data.put("sequence_no", this.sequence_no); 56 | return data; 57 | } 58 | 59 | /** 60 | * Create a specific message from the received message. 61 | * @param data received message 62 | * @return specific message object 63 | * @throws JSONException 64 | */ 65 | public static Message messageConvert(JSONObject data) throws JSONException { 66 | int type = 0; 67 | try { 68 | type = data.getInt("type"); 69 | } catch (JSONException e) { 70 | e.printStackTrace(); 71 | } 72 | if (Types.INIT == type){ 73 | return InitMessage.messageDecipher(data); 74 | } 75 | 76 | if (Types.LEADER_CHANGE == type){ 77 | return LeaderChangeMessage.messageDecipher(data); 78 | } 79 | if (Types.PROPOSE == type){ 80 | return ProposeMessage.messageDecipher(data); 81 | } 82 | if (Types.PREVOTE == type){ 83 | return PrevoteMessage.messageDecipher(data); 84 | } 85 | if (Types.VOTE == type){ 86 | return VoteMessage.messageDecipher(data); 87 | } 88 | return new Message(data.getInt("node"), data.getInt("type"), data.getLong("sequence_no")); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/PrevoteMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | import static de.teamproject16.pbft.Messages.Types.PREVOTE; 6 | 7 | /** 8 | * Json serializable Prevote message 9 | */ 10 | public class PrevoteMessage extends Message { 11 | 12 | //public int node; 13 | public int leader; 14 | public double value; 15 | 16 | /** 17 | * Prevote message 18 | * @param sequence_no of tries 19 | * @param node the id of the sender 20 | * @param leader the leading node 21 | * @param value from the node 22 | */ 23 | public PrevoteMessage(long sequence_no, int node, int leader, double value) { 24 | super(node, PREVOTE, sequence_no); 25 | //this.node = node; 26 | this.leader = leader; 27 | this.value = value; 28 | } 29 | 30 | /** 31 | * Create a prevote message object from the data out JSONObject. 32 | * @param data JSONObject 33 | * @return a new prevote message object with the specific data. 34 | * @throws JSONException 35 | */ 36 | public static PrevoteMessage messageDecipher(JSONObject data) throws JSONException { 37 | return new PrevoteMessage(data.getLong("sequence_no"), data.getInt("node"), 38 | data.getInt("leader"), data.getDouble("value")); 39 | } 40 | 41 | /** 42 | * Create JSONObject for the network. 43 | * @return data JSONObject 44 | * @throws JSONException 45 | */ 46 | public JSONObject messageEncode() throws JSONException { 47 | JSONObject data = super.messageEncode(); 48 | //data.put("node", this.node); 49 | data.put("leader", this.leader); 50 | data.put("value", this.value); 51 | return data; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/ProposeMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONException; 5 | import org.json.JSONObject; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static de.teamproject16.pbft.Messages.Types.PROPOSE; 11 | 12 | 13 | /** 14 | * Json serializable Propose message 15 | */ 16 | public class ProposeMessage extends Message { 17 | 18 | //public int node; 19 | public int leader; 20 | public double proposal; 21 | public List value_store; 22 | 23 | /** 24 | * Propose message 25 | * @param sequence_no of tries 26 | * @param node the id of the sender 27 | * @param leader 28 | * @param proposal 29 | * @param value_store values from all nodes in the network 30 | */ 31 | public ProposeMessage(long sequence_no, int node, int leader, double proposal, List value_store) { 32 | super(node, PROPOSE, sequence_no); 33 | //this.node = node; 34 | this.leader = leader; 35 | this.proposal = proposal; 36 | this.value_store = value_store; 37 | } 38 | 39 | /** 40 | * Create a propose message object from the data out JSONObject. 41 | * @param data JSONObject 42 | * @return a new propose message object with the specific data. 43 | * @throws JSONException 44 | */ 45 | public static ProposeMessage messageDecipher(JSONObject data) throws JSONException { 46 | int len = data.getJSONArray("value_store").length(); 47 | ArrayList tmp_value_store = new ArrayList<>(len); 48 | for(int i=0; i < len; i++) { 49 | JSONObject obj = data.getJSONArray("value_store").getJSONObject(i); 50 | tmp_value_store.add(InitMessage.messageDecipher(obj)); 51 | } 52 | return new ProposeMessage( 53 | data.getLong("sequence_no"), data.getInt("node"), data.getInt("leader"), 54 | data.getDouble("proposal"), tmp_value_store 55 | ); 56 | } 57 | 58 | /** 59 | * Create JSONObject for the network. 60 | * @return data JSONObject 61 | * @throws JSONException 62 | */ 63 | public JSONObject messageEncode() throws JSONException { 64 | JSONObject data = super.messageEncode(); 65 | data.put("leader", this.leader); 66 | data.put("proposal", this.proposal); 67 | JSONArray value_store_temp = new JSONArray(); 68 | for (InitMessage msg : this.value_store) { 69 | value_store_temp.put(msg.messageEncode()); 70 | } 71 | data.put("value_store", value_store_temp); 72 | return data; 73 | } 74 | } 75 | 76 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/Types.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | /** 8 | * Enum class for the message types. 9 | */ 10 | public class Types { 11 | public static final int INIT = 1; // Broadcasting the initial values. 12 | public static final int PROPOSE = 2; // Only Leader sends this. 13 | public static final int PREVOTE = 3; // Our median we calculated all by our self! 14 | public static final int VOTE = 4; 15 | public static final int LEADER_CHANGE = 5; 16 | public static final int ACKNOWLEDGE = -1; 17 | 18 | public static final Map _NAMES_ = new HashMap(){ 19 | { 20 | put(INIT, "init"); 21 | put(PROPOSE, "propose"); 22 | put(PREVOTE, "prevote"); 23 | put(VOTE, "vote"); 24 | put(LEADER_CHANGE, "leader_change"); 25 | 26 | put(ACKNOWLEDGE, "acknowledge"); 27 | } 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Messages/VoteMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | import static de.teamproject16.pbft.Messages.Types.VOTE; 6 | 7 | 8 | /** 9 | * Json serializable Vote message 10 | */ 11 | public class VoteMessage extends Message { 12 | 13 | //public int node; 14 | public int leader; 15 | public double value; 16 | 17 | /** 18 | * Vote message 19 | * @param sequence_no of tries 20 | * @param node the id of the sender 21 | * @param leader the leader node 22 | * @param value of the sensor 23 | */ 24 | public VoteMessage(long sequence_no, int node, int leader, double value) { 25 | super(node, VOTE, sequence_no); 26 | //this.node = node; 27 | this.leader = leader; 28 | this.value = value; 29 | } 30 | 31 | /** 32 | * Create a vote message object from the data out JSONObject. 33 | * @param data JSONObject 34 | * @return a new vote message object with the specific data. 35 | * @throws JSONException 36 | */ 37 | public static VoteMessage messageDecipher(JSONObject data) throws JSONException { 38 | return new VoteMessage(data.getInt("sequence_no"), data.getInt("node"), 39 | data.getInt("leader"), data.getDouble("value")); 40 | } 41 | 42 | /** 43 | * Create JSONObject for the network. 44 | * @return data JSONObject 45 | * @throws JSONException 46 | */ 47 | public JSONObject messageEncode() throws JSONException { 48 | JSONObject data = super.messageEncode(); 49 | //data.put("node", this.node); 50 | data.put("leader", this.leader); 51 | data.put("value", this.value); 52 | return data; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Network/CloseConnectionPlease.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network; 2 | 3 | /** 4 | * Raised if the connection should be closed. 5 | */ 6 | public class CloseConnectionPlease extends Exception { 7 | public CloseConnectionPlease(String msg) { 8 | super(msg); 9 | } 10 | public CloseConnectionPlease() { 11 | super(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Network/Database/Dumper.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network.Database; 2 | 3 | import de.luckydonald.utils.ObjectWithLogger; 4 | import de.luckydonald.utils.dockerus.Dockerus; 5 | import de.luckydonald.utils.dockerus.DockerusAuto; 6 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 7 | 8 | import java.io.IOException; 9 | import java.io.OutputStreamWriter; 10 | import java.net.HttpURLConnection; 11 | import java.net.MalformedURLException; 12 | import java.net.ProtocolException; 13 | import java.net.URL; 14 | 15 | /** 16 | * For throwing the sending json to the database. 17 | * 18 | * @author luckydonald 19 | * @since 31.10.2016 20 | **/ 21 | public class Dumper extends ObjectWithLogger { 22 | public static void send(String json) { 23 | String host_to_post = getApiHost(); 24 | if (host_to_post == null || host_to_post.length() < 1) { 25 | return; 26 | } 27 | try { 28 | URL url = new URL(host_to_post + "/dump/"); // TODO: env 29 | HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 30 | httpCon.setDoOutput(true); 31 | httpCon.setRequestMethod("PUT"); 32 | OutputStreamWriter out = new OutputStreamWriter( 33 | httpCon.getOutputStream()); 34 | out.write(json); 35 | out.close(); 36 | httpCon.getInputStream().close(); 37 | System.out.println("PUT " + url + ": "+ httpCon.getResponseCode() + " - " + httpCon.getResponseMessage()); 38 | } catch (IOException e) { 39 | System.out.println("Sending message to API failed: " + e.toString()); 40 | } 41 | 42 | } 43 | 44 | public static String getApiHost() { 45 | try { 46 | return DockerusAuto.getInstance().getApiHost(); 47 | } catch (IDoNotWantThisException e) { 48 | e.printStackTrace(); 49 | } 50 | return null; 51 | } 52 | } -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Network/MessageQueue.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network; 2 | 3 | import de.teamproject16.pbft.CancelableLinkedBlockingQueue; 4 | import de.teamproject16.pbft.Messages.*; 5 | 6 | /** 7 | * Enqueue all them messages, in one queue for each type. 8 | * Like channels. 9 | */ 10 | public class MessageQueue { 11 | public static CancelableLinkedBlockingQueue leaderChangeM = new CancelableLinkedBlockingQueue(); 12 | public static CancelableLinkedBlockingQueue initM = new CancelableLinkedBlockingQueue(); 13 | public static CancelableLinkedBlockingQueue prevoteM = new CancelableLinkedBlockingQueue(); 14 | public static CancelableLinkedBlockingQueue proposeM = new CancelableLinkedBlockingQueue(); 15 | public static CancelableLinkedBlockingQueue voteM = new CancelableLinkedBlockingQueue(); 16 | 17 | public static void messageQueue(Message message){ 18 | try { 19 | if (message instanceof InitMessage){ 20 | initM.put(message); 21 | } 22 | if (message instanceof LeaderChangeMessage) { 23 | leaderChangeM.put(message); 24 | } 25 | if (message instanceof PrevoteMessage) { 26 | prevoteM.put(message); 27 | } 28 | if (message instanceof ProposeMessage){ 29 | proposeM.put(message); 30 | } 31 | if (message instanceof VoteMessage){ 32 | voteM.put(message); 33 | } 34 | } catch (InterruptedException e) { 35 | e.printStackTrace(); 36 | } 37 | } 38 | 39 | public static void cancelAll() { 40 | initM.cancel(); 41 | leaderChangeM.cancel(); 42 | prevoteM.cancel(); 43 | proposeM.cancel(); 44 | voteM.cancel(); 45 | } 46 | } 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Network/Receiver.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network; 2 | 3 | import de.luckydonald.utils.dockerus.DockerusAuto; 4 | import de.teamproject16.pbft.Messages.Acknowledge; 5 | import de.teamproject16.pbft.Messages.Message; 6 | import de.teamproject16.pbft.Network.Database.Dumper; 7 | import org.json.JSONException; 8 | import org.json.JSONObject; 9 | 10 | import java.io.BufferedInputStream; 11 | import java.io.IOException; 12 | import java.net.ServerSocket; 13 | import java.net.Socket; 14 | import java.nio.ByteBuffer; 15 | import java.nio.charset.Charset; 16 | import java.util.logging.Level; 17 | import java.util.logging.Logger; 18 | 19 | /* Test with netcat in terminal: 20 | * $ nc localhost 4458 21 | * ANSWER 19 22 | * {"hello": "world"} 23 | */ 24 | 25 | 26 | /** 27 | * Class to which will receive Messages. 28 | * It will call {@link Receiver#addMessage(String) this.addMessage(String messageContent)} to process incoming messages. 29 | **/ 30 | public class Receiver extends Thread { 31 | private static String ANSWER_SYNTAX = "ANSWER "; 32 | private Logger logger = null; 33 | private long current_sequence_no = Long.MAX_VALUE; 34 | 35 | public Receiver() { 36 | this.setName("Receiver"); 37 | } 38 | 39 | public void receiver() throws IOException { 40 | this.receiver(this.newServerSocket()); 41 | } 42 | public boolean do_quit = false; 43 | 44 | public void receiver(ServerSocket server) { 45 | while (!do_quit) { // For each connection do // TODO: self.do_quit or similar 46 | Socket socket; 47 | try { 48 | socket = server.accept(); // throws IOException 49 | } catch (IOException e) { 50 | this.getLogger().finest("Could not accept server client: " + e.getLocalizedMessage()); 51 | continue; 52 | } 53 | try { 54 | String received = this.receiveFromSocket(socket); 55 | this.addMessage(received); 56 | // now the client would close the sockets. We do, too, in the finally statement. 57 | } catch (CloseConnectionPlease e) { 58 | this.getLogger().finest("Requested to close connection prematurely: " + e.getLocalizedMessage()); 59 | } catch (IOException e){ 60 | this.getLogger().warning("IOException"); 61 | e.printStackTrace(); 62 | } finally { 63 | // in case it should close prematurely (by throwing CloseConnectionPlease) 64 | // in case of normal operation after a received message. 65 | try { 66 | socket.close(); // throws IOException 67 | } catch (IOException e) { 68 | this.getLogger().warning("Ignored failed socket closing."); 69 | } 70 | } 71 | } 72 | } 73 | 74 | String receiveFromSocket(Socket socket) throws IOException, CloseConnectionPlease { 75 | BufferedInputStream input = new BufferedInputStream(socket.getInputStream()); // throws IOException 76 | 77 | int completed = -ANSWER_SYNTAX.length(); 78 | /** 79 | -7 = ^ANSWER 123\n 80 | -6 = A^NSWER 123\n 81 | -1 = ANSWER^ 123\n 82 | 0 = ANSWER ^123\n => ready to read the number 83 | **/ 84 | 85 | ByteBuffer buff = null; 86 | // buff.put(ANSWER_SYNTAX.getBytes()); // TODO: Unit test :D 87 | long length_of_answer = -1; 88 | buff = ByteBuffer.allocate(520); // ANSWER \n 89 | while (length_of_answer == -1) { // Length detection: "ANSWER 123\n" 90 | int char_ = input.read(); // throws IOException 91 | if (char_ == -1) { 92 | // Client disconnected prematurely: Close connection; connect to next incoming client. 93 | throw new CloseConnectionPlease("Client disconnected."); 94 | } 95 | if (completed < 0) { 96 | // must be inside ANSWER_SYNTAX 97 | if ((char) char_ != ANSWER_SYNTAX.charAt(ANSWER_SYNTAX.length() + completed)) { 98 | // if the received character not as expected of the ANSWER_SYNTAX header. 99 | //Wrong ANSWER_SYNTAX => Close (abort) connection; connect to next incoming client. 100 | throw new CloseConnectionPlease("Syntax error in ANSWER header."); 101 | } 102 | completed++; 103 | } else { 104 | if ((char) char_ != '\n') { // not end yet. // line breaks in json strings should be "\\" and "n". 105 | // put it into our number buffer. 106 | buff.put((byte) char_); 107 | } else { // end of ANSWER_SYNTAX+number+\n, after number 108 | // linebreak: we have the ending. 109 | // http://stackoverflow.com/a/22717246 110 | byte[] str_bytes = new byte[buff.position()]; 111 | buff.rewind(); 112 | buff.get(str_bytes); 113 | // http://stackoverflow.com/a/17355227 114 | String str = new String(str_bytes, Charset.forName("UTF-8")); 115 | this.getLogger().finest("\"ANSWER \\n\" header read: " + buff + "> " + str); 116 | length_of_answer = Integer.parseInt(str); 117 | break; // (while should end anyway) 118 | } 119 | } 120 | } 121 | // prepare content reading 122 | this.getLogger().finer("Waiting to receive " + length_of_answer + " bytes."); 123 | buff = ByteBuffer.allocate((int) length_of_answer); 124 | int bytes_read = 0; 125 | while (bytes_read < length_of_answer) { 126 | int char_ = input.read(); // throws IOException 127 | getLogger().finest("READ: "+ Character.toString((char)char_) + ", " + bytes_read + "<" + length_of_answer); 128 | if (char_ == -1) { 129 | // Client disconnected prematurely: Close connection; connect to next incoming client. 130 | throw new CloseConnectionPlease("Client disconnected."); 131 | } 132 | if (bytes_read+1 >= length_of_answer) { 133 | if (bytes_read+1 > length_of_answer) { 134 | // moved inside other if to have less to checks on normal execution -> performance 135 | throw new CloseConnectionPlease("Read to much."); 136 | } 137 | if (char_ == '\n') { 138 | // last char should be '\n' 139 | getLogger().finer("Skipping ending linebreak."); 140 | } else { 141 | getLogger().warning("Message did not end with '\\n', ignoring!"); 142 | throw new CloseConnectionPlease("Not ending with '\\n'"); 143 | } 144 | } 145 | bytes_read++; 146 | buff.put((byte) char_); 147 | } 148 | String result = new String(buff.array(), Charset.forName("UTF-8")); 149 | this.getLogger().fine("Received: " + result); 150 | return result; 151 | // Now the client would close the sockets. 152 | // We do, too, in the finally statement, of the method `receiver()` calling this. 153 | } 154 | 155 | public Logger getLogger() { 156 | if (logger == null) { 157 | logger = Logger.getLogger(this.getClass().getCanonicalName()); 158 | } 159 | logger.setLevel(Level.ALL); 160 | return logger; 161 | } 162 | 163 | 164 | ServerSocket newServerSocket() throws IOException { 165 | ServerSocket s = new ServerSocket(4458); // throws IOException 166 | s.setReuseAddress(true); 167 | return s; 168 | } 169 | 170 | @Override 171 | public void run() { 172 | try { 173 | this.receiver(); 174 | } catch (IOException e) { 175 | e.printStackTrace(); 176 | } 177 | } 178 | 179 | private void addMessage(String json_string) { 180 | synchronized (this) { 181 | try { 182 | JSONObject json = new JSONObject(json_string); 183 | Message msg = Message.messageConvert(json); 184 | try { 185 | Acknowledge ack = new Acknowledge(msg.sequence_no, DockerusAuto.getInstance().getNumber(), msg.node, json); 186 | Dumper.send(ack.messageEncode().toString()); 187 | } catch(Exception ignore) { 188 | // pass 189 | } 190 | if (msg.sequence_no < this.current_sequence_no) { 191 | System.out.println( 192 | "Dropped old " + msg.getTypeString() + " message from node " + 193 | msg.node + " with sequence_no " + msg.sequence_no + ". Delay: " + 194 | (this.current_sequence_no - msg.sequence_no) 195 | ); 196 | return; 197 | } 198 | MessageQueue.messageQueue(msg); 199 | } catch (JSONException e) { 200 | System.out.println("Convert the String to JSONObject failed."); 201 | e.printStackTrace(); 202 | } 203 | this.notifyAll(); // In case someone is waiting for new messages. 204 | } 205 | } 206 | 207 | public long getCurrentSequenceNo() { 208 | return current_sequence_no; 209 | } 210 | 211 | public void setCurrentSequenceNo(long current_sequence_no) { 212 | this.current_sequence_no = current_sequence_no; 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Network/Sender.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network; 2 | 3 | import com.spotify.docker.client.DockerCertificateException; 4 | import com.spotify.docker.client.DockerException; 5 | import de.luckydonald.utils.dockerus.DockerusAuto; 6 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 7 | import de.teamproject16.pbft.Messages.Message; 8 | import de.teamproject16.pbft.Network.Database.Dumper; 9 | import org.json.JSONException; 10 | 11 | import java.io.DataOutputStream; 12 | import java.io.IOException; 13 | import java.io.UnsupportedEncodingException; 14 | import java.net.Socket; 15 | import java.util.List; 16 | 17 | /** 18 | * This handles sending messages. 19 | */ 20 | public class Sender { 21 | 22 | /** 23 | * Make the message object to a string and give it to the method broadcast. 24 | * @param msg object from message with specific data. 25 | * @throws UnsupportedEncodingException 26 | * @throws InterruptedException 27 | * @throws DockerException 28 | * @throws DockerCertificateException 29 | */ 30 | public void sendMessage(Message msg) throws JSONException, InterruptedException, IDoNotWantThisException, DockerException, UnsupportedEncodingException { 31 | String json = msg.messageEncode().toString(); 32 | Dumper.send(json); 33 | broadcast(json); 34 | } 35 | 36 | /** 37 | * Send broadcast messages in the network of registered nodes. 38 | * @param message String with the specific message (init, void...). 39 | * @throws UnsupportedEncodingException 40 | * @throws DockerCertificateException 41 | * @throws DockerException 42 | * @throws InterruptedException 43 | */ 44 | public void broadcast(String message) throws IDoNotWantThisException, DockerException, InterruptedException, UnsupportedEncodingException { 45 | List otherHostnames = DockerusAuto.getInstance().getHostnames(false); 46 | message += "\n"; 47 | String msg = "ANSWER " + message.length() + "\n" + message; 48 | byte[] msgBytes = msg.getBytes("UTF-8"); 49 | for (String nodeHost: otherHostnames){ 50 | Boolean sent = false; 51 | while(!sent){ 52 | try { 53 | Socket socket = new Socket(nodeHost, 4458); //open a socket port 4458, and the nodeHost names of the other hosts 54 | DataOutputStream dataStream = new DataOutputStream(socket.getOutputStream()); //to send messages 55 | dataStream.write(msgBytes); //write the messages at the datastream 56 | sent = true; 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/NormalCase.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | import com.spotify.docker.client.DockerCertificateException; 4 | import com.spotify.docker.client.DockerException; 5 | import de.luckydonald.utils.dockerus.DockerusAuto; 6 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 7 | import de.teamproject16.pbft.Messages.*; 8 | import de.teamproject16.pbft.Network.MessageQueue; 9 | import de.teamproject16.pbft.Network.Receiver; 10 | import de.teamproject16.pbft.Network.Sender; 11 | import org.json.JSONException; 12 | 13 | import java.io.UnsupportedEncodingException; 14 | import java.util.ArrayList; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.concurrent.TimeoutException; 19 | 20 | import static de.luckydonald.utils.Streams.toArrayList; 21 | import static java.util.stream.Collectors.groupingBy; 22 | 23 | public class NormalCase { 24 | public int sequenceLength = 5000; 25 | 26 | int leader = 1; 27 | 28 | ArrayList initStore = null; 29 | ArrayList prevoteStore = null; 30 | ArrayList leaderchangeStore = null; 31 | 32 | Receiver r = null; 33 | Sender sender = null; 34 | private long sequenceNo; 35 | 36 | public NormalCase(Receiver receiver) { 37 | this.r = receiver; 38 | this.sender = new Sender(); 39 | } 40 | 41 | /** 42 | * The row 15 to 27 from the algorithm given in the pdf over pbft. 43 | * @throws DockerException 44 | * @throws InterruptedException 45 | * @throws UnsupportedEncodingException 46 | * @throws DockerCertificateException 47 | */ 48 | public double normalFunction(double measurement) throws DockerException, InterruptedException, UnsupportedEncodingException, 49 | DockerCertificateException, JSONException, TimeoutException, IDoNotWantThisException { 50 | cleanUp(); 51 | long newSeq = calculateSequenceNumber(); 52 | if (this.sequenceNo >= newSeq) { 53 | o("Sequence number is equal. Old " + this.sequenceNo + " and new " + newSeq); 54 | } 55 | while (this.sequenceNo >= newSeq) { 56 | synchronized (this) { 57 | long waitMs = Math.min(((this.sequenceNo + 1) * sequenceLength)-System.currentTimeMillis(), 0); 58 | System.out.println("Waiting " + waitMs + "ms."); 59 | if(waitMs != 0) { 60 | this.wait(waitMs); 61 | } 62 | newSeq = calculateSequenceNumber(); 63 | } 64 | } 65 | r.setCurrentSequenceNo(this.sequenceNo); 66 | o("Changed sequence " + this.sequenceNo + " to " + newSeq); 67 | this.sequenceNo = newSeq; 68 | System.out.println("NODE ID: " + getNumber() + " SEQ_NO: " + sequenceNo); 69 | 70 | sender.sendMessage(new InitMessage(this.sequenceNo, getNumber(), measurement)); 71 | //prevoteStore = new ArrayList<>(); 72 | ArrayList voteStore = new ArrayList<>(); 73 | int state = 0; 74 | // prevoteDone = false; 75 | while(true){ 76 | if((System.currentTimeMillis()/ sequenceLength) > this.sequenceNo){ 77 | throw new TimeoutException(); 78 | } 79 | synchronized (this.r) { 80 | if(!MessageQueue.initM.isEmpty()) { 81 | System.out.println("Got InitMessage"); 82 | this.initStore.add((InitMessage) MessageQueue.initM.take()); 83 | } 84 | if(state == 0) { 85 | if(this.leader == getNumber()) { // are we the leader? 86 | // remove old sequence numbers 87 | System.out.println("LEADER! Checking messages."); 88 | long valid_size = this.initStore.stream().filter(m -> m.sequence_no == this.sequenceNo).count(); 89 | System.out.println("LEADER! Got " + valid_size + " messages. " + (this.initStore.size() - valid_size) + " messages were ignored."); 90 | if (valid_size >= (getTotalNodeCount() - getFaultyNodeCount())) { // <--- 91 | o("ENOUGH INIT"); 92 | sender.sendMessage( 93 | new ProposeMessage( 94 | this.sequenceNo, 95 | getNumber(), 96 | this.leader, 97 | Median.calculateMedian(this.initStore.stream().filter(m -> m.sequence_no == this.sequenceNo)), 98 | initStore 99 | ) 100 | ); 101 | state = 1; // we send da message. 102 | o("state = 1"); 103 | } 104 | } else { 105 | state = 1; 106 | o("state = 1"); 107 | } 108 | } 109 | if (state == 1 && !MessageQueue.proposeM.isEmpty() && verifyProposal((ProposeMessage) MessageQueue.proposeM.take())) { 110 | o("Got ProposeMessage"); 111 | sender.sendMessage( 112 | new PrevoteMessage( 113 | this.sequenceNo, getNumber(), this.leader, Median.calculateMedian(this.initStore) 114 | ) 115 | ); 116 | state = 2; 117 | o("state = 2"); 118 | } 119 | if (state == 2 && !MessageQueue.prevoteM.isEmpty()) { 120 | o("Got PrevoteMessage"); 121 | prevoteStore.add((PrevoteMessage) MessageQueue.prevoteM.take()); 122 | VerifyAgreementResult agreement = checkAgreement(prevoteStore.stream().collect(toArrayList())); 123 | if (agreement.bool) { 124 | sender.sendMessage(new VoteMessage(this.sequenceNo, 125 | getNumber(), 126 | this.leader, agreement.value)); 127 | state=3; 128 | o("state = "+ state); 129 | } else { 130 | o("checkAgreement failed."); 131 | } 132 | } 133 | if ((state == 2 || state == 3) && !MessageQueue.voteM.isEmpty()) {//abfrage dessen das der median bei genügend node gleich ist und sequenznr stimmt fehlt 134 | o("Got VoteMessage"); 135 | voteStore.add((VoteMessage) MessageQueue.voteM.take()); 136 | VerifyAgreementResult agreement = checkAgreement(voteStore); 137 | if (agreement.bool) { 138 | o("state = DONE! (now doing cleanup)"); 139 | this.cleanUp(); 140 | return agreement.value; 141 | } 142 | } else { 143 | this.r.wait(1000); // waits for a new message to allow all 3 ifs to check, but otherwise block. 144 | } 145 | } 146 | } 147 | } 148 | 149 | /** 150 | * Removes old messages from this.initStore. 151 | */ 152 | private void initStoreRemoveOldMessages() { 153 | boolean has_new = false; 154 | for (InitMessage msg : this.initStore) { 155 | if (msg.sequence_no < this.sequenceNo) { 156 | has_new = true; 157 | break; 158 | } 159 | } 160 | if (!has_new) { 161 | return; // don't copy the array if nothing needs to be changed. 162 | } 163 | this.initStore = this.initStore.stream() 164 | .filter(i-> i.sequence_no >= this.sequenceNo) 165 | .collect(toArrayList()); 166 | } 167 | 168 | private long calculateSequenceNumber() { 169 | return System.currentTimeMillis() / sequenceLength; 170 | } 171 | 172 | /** 173 | * Verify the calculated median for the result. 174 | * @param store 175 | * @return a tuple as VerifyAgreementResult 176 | * @throws DockerException 177 | * @throws InterruptedException 178 | * @throws UnsupportedEncodingException 179 | * @throws DockerCertificateException 180 | */ 181 | public VerifyAgreementResult checkAgreement(List store) throws DockerException, InterruptedException, UnsupportedEncodingException, DockerCertificateException, IDoNotWantThisException { 182 | double value = 0.0; 183 | for (Message e : store){ 184 | if (e instanceof PrevoteMessage) { 185 | value = ((PrevoteMessage) e).value; 186 | } else 187 | if (e instanceof VoteMessage) { 188 | value = ((VoteMessage) e).value; 189 | } else { 190 | throw new IllegalArgumentException("Needs type PrevoteMessage or VoteMessage."); 191 | } 192 | int count = 0; 193 | for (Message i : store){ 194 | if (((i instanceof PrevoteMessage && value == ((PrevoteMessage)i).value) 195 | || (i instanceof VoteMessage && value == ((VoteMessage) i).value))){ 196 | count++; 197 | } 198 | } 199 | if (count > muchMoreThenHalf()){ 200 | return new VerifyAgreementResult(true, value); 201 | } 202 | } 203 | return new VerifyAgreementResult(false, value); 204 | } 205 | 206 | /** 207 | * Check that more than the half of the group members approve the result. 208 | * @return 209 | * @throws DockerException 210 | * @throws InterruptedException 211 | * @throws IDoNotWantThisException 212 | */ 213 | double muchMoreThenHalf() throws DockerException, InterruptedException, IDoNotWantThisException { 214 | //System.out.println((this.getTotalNodeCount() + getFaultyNodeCount())/2); 215 | return (this.getTotalNodeCount() + getFaultyNodeCount())/2; 216 | } 217 | 218 | /** 219 | * We have a timeout for it. But here you can change it. 220 | * @throws DockerException 221 | * @throws InterruptedException 222 | * @throws JSONException 223 | * @throws UnsupportedEncodingException 224 | * @throws DockerCertificateException 225 | * @throws IDoNotWantThisException 226 | */ 227 | public void leaderChange() throws DockerException, InterruptedException, JSONException, UnsupportedEncodingException, DockerCertificateException, IDoNotWantThisException { 228 | this.incrementLeader(); 229 | sender.sendMessage(new LeaderChangeMessage(this.sequenceNo, getNumber(), this.leader, prevoteStore)); 230 | if(this.leader == getNumber()) { 231 | if(this.leaderchangeStore.size() > muchMoreThenHalf()) { 232 | // DO STUFF 233 | } 234 | } 235 | } 236 | 237 | /** 238 | * We have a timeout for it. But here you can change it. 239 | * @param leaderChangeMessageList 240 | */ 241 | public void getLastPrepared(List leaderChangeMessageList) { 242 | LeaderChangeMessage lastPreparedTemp = null; 243 | // Tuple: Round number, prevoted value 244 | int roundNumber; 245 | double prevoteValue; 246 | for (LeaderChangeMessage msg : leaderChangeMessageList) { 247 | Map> tmp = msg.prevoteList.stream().collect(groupingBy(prev_msg -> prev_msg.leader)); 248 | // leader: [PrevoteMessage, PrevoteMessage, PrevoteMessage] 249 | for (Integer leader : tmp.keySet()) { 250 | Map count_map = new HashMap<>(); 251 | //Map tmp2 = tmp.get(leader).stream().flatMapToLong(); 252 | // value: [PrevoteMessage, PrevoteMessage, PrevoteMessage] 253 | //for (Double value : tmp2.keySet()) { 254 | // count = 255 | //} 256 | 257 | } 258 | // value: list of messages 259 | for (PrevoteMessage pre : msg.prevoteList) { 260 | 261 | } 262 | } 263 | 264 | } 265 | 266 | public PrevoteMessage getMostValue(List list) { 267 | return list.stream().sorted((a, b)->Double.compare(a.value, b.value)).collect(groupingBy(m -> m.value)).entrySet().stream().reduce((l1, l2) -> l1.getValue().size() > l2.getValue().size() ? l1 : l2).get().getValue().stream().findAny().orElseGet(null); 268 | } 269 | 270 | /** 271 | * Retrieves the number this node has. 272 | * @return number of the node 273 | * @throws DockerException 274 | * @throws InterruptedException 275 | */ 276 | int getNumber() throws DockerException, InterruptedException, IDoNotWantThisException { 277 | return DockerusAuto.getInstance().getNumber(); 278 | } 279 | 280 | /** 281 | * Selects the next leader. 282 | * @throws DockerException 283 | * @throws InterruptedException 284 | */ 285 | public void incrementLeader() throws DockerException, InterruptedException, IDoNotWantThisException { 286 | this.leader = (int) ((this.leader + 1) % this.getTotalNodeCount()); 287 | } 288 | 289 | /** 290 | * Verify the propose message. 291 | * @return 292 | * @throws InterruptedException 293 | */ 294 | public static boolean verifyProposal(ProposeMessage msg) throws InterruptedException { 295 | double medianS = Median.calculateMedian(msg.value_store); 296 | return msg.proposal == medianS; 297 | } 298 | 299 | /** 300 | * Calculates the faulty nodes. 301 | * @return count of possible faulty nodes. 302 | * @throws DockerException 303 | * @throws InterruptedException 304 | */ 305 | public double getFaultyNodeCount() throws DockerException, InterruptedException, IDoNotWantThisException { 306 | return (this.getTotalNodeCount() - 1)/3; 307 | } 308 | 309 | /** 310 | * Retrieves the total amount of nodes. 311 | * @return count of total nodes in the system. 312 | * @throws DockerException 313 | * @throws InterruptedException 314 | */ 315 | public double getTotalNodeCount() throws DockerException, InterruptedException, IDoNotWantThisException { 316 | return DockerusAuto.getInstance().getTotal(false); 317 | } 318 | 319 | /** 320 | * Clean the memory for a new sequence number. 321 | */ 322 | public void cleanUp() { 323 | this.sequenceNo = calculateSequenceNumber(); 324 | if(this.initStore != null) { 325 | this.initStoreRemoveOldMessages(); 326 | } else { 327 | this.initStore = new ArrayList<>(); 328 | } 329 | if (this.prevoteStore != null) { 330 | this.prevoteStore = this.prevoteStore.stream() 331 | .filter(i -> i.sequence_no >= this.sequenceNo) 332 | .collect(toArrayList()); 333 | } else { 334 | this.prevoteStore = new ArrayList<>(); 335 | } 336 | } 337 | 338 | 339 | 340 | /** 341 | * A class for return tuple in java. 342 | */ 343 | class VerifyAgreementResult { 344 | public final double value; 345 | public final boolean bool; 346 | 347 | public VerifyAgreementResult(boolean bool, double value) { 348 | this.bool = bool; 349 | this.value = value; 350 | } 351 | } 352 | static void o(String s) { 353 | System.out.println(s); 354 | } 355 | } 356 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Sensor/FakeSensor.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Sensor; 2 | 3 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 4 | 5 | /** 6 | * This emulates sensor data. 7 | */ 8 | public class FakeSensor { 9 | public double getSensorValue() throws IDoNotWantThisException { 10 | return Math.random()*10; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Sensor/RealSensor.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Sensor; 2 | 3 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 4 | 5 | import java.io.File; 6 | import java.nio.file.FileSystems; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.util.List; 10 | 11 | /** 12 | * This emulates sensor data. 13 | */ 14 | public class RealSensor extends FakeSensor { 15 | // /sys/bus/w1/devices/XX-XXXX..../w1_slave 16 | /* path to search for devices in filesystem */ 17 | private static String devicesPath = "/sys/bus/w1/devices"; 18 | 19 | /* file of the measured values */ 20 | private static String valueFile = "w1_slave"; 21 | 22 | /* id of sensor */ 23 | private static String id = null; 24 | 25 | public double value; 26 | 27 | public RealSensor() { 28 | File searchPath = new File(devicesPath); 29 | if (searchPath.listFiles()!=null) { 30 | for (File f: searchPath.listFiles()) { 31 | if (f.isDirectory() && !f.getName().startsWith("w1_bus_master")) 32 | id = f.getName(); 33 | } 34 | } 35 | this.id = id; 36 | } 37 | 38 | @Override 39 | public double getSensorValue() throws IDoNotWantThisException { 40 | Path path = FileSystems.getDefault().getPath(devicesPath, id, valueFile); 41 | List lines; 42 | 43 | int attempts = 3; 44 | boolean crcOK = false; 45 | 46 | while (attempts > 0) { 47 | try { 48 | lines = Files.readAllLines(path); 49 | for (String line : lines) { 50 | if (line.endsWith("YES")) 51 | crcOK = true; 52 | else if (line.matches(".*t=[0-9]+") && crcOK) 53 | return Integer.valueOf(line.substring(line.indexOf("=") + 1)) / 1000.0; 54 | } 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | continue; 58 | } 59 | attempts--; 60 | } 61 | 62 | throw new IDoNotWantThisException(""); 63 | } 64 | } -------------------------------------------------------------------------------- /src/main/java/de/teamproject16/pbft/Sensor/SensorSelector.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Sensor; 2 | 3 | import de.luckydonald.utils.ObjectWithLogger; 4 | import de.luckydonald.utils.dockerus.DockerusAuto; 5 | import de.luckydonald.utils.dockerus.IDoNotWantThisException; 6 | 7 | /** 8 | * Created by on 9 | * 10 | * @author luckydonald 11 | * @since 30.03.2017 12 | **/ 13 | public class SensorSelector extends ObjectWithLogger { 14 | private static FakeSensor instance = null; 15 | 16 | static public FakeSensor getInstance() { 17 | if(SensorSelector.instance != null) { 18 | return SensorSelector.instance; 19 | } 20 | try { 21 | if (DockerusAuto.getInstance().getSensorSimulate()) { 22 | throw new IDoNotWantThisException("Plz use fake."); 23 | } 24 | SensorSelector.instance = new RealSensor(); 25 | } catch (IDoNotWantThisException e) { 26 | System.out.println("Using simulated sensor because " + e.toString()); 27 | SensorSelector.instance = new FakeSensor(); 28 | } 29 | return SensorSelector.instance; 30 | } 31 | 32 | static public double getSensorValue() throws IDoNotWantThisException { 33 | return SensorSelector.getInstance().getSensorValue(); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/de/teamproject16/pbft/MedianTest.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | import de.teamproject16.pbft.Messages.InitMessage; 4 | import org.junit.Test; 5 | 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * Tests the median calculation. 13 | * 14 | * @author luckydonald 15 | **/ 16 | public class MedianTest { 17 | 18 | @Test 19 | public void testCalculateMedian() throws Exception { 20 | List initStore = new LinkedList<>(); 21 | InitMessage init1 = new InitMessage(1,1,0.4); 22 | InitMessage init2 = new InitMessage(1,2,0.3); 23 | InitMessage init3 = new InitMessage(1,3,0.3); 24 | InitMessage init4 = new InitMessage(1,4,0.5); 25 | initStore.add(init1); 26 | initStore.add(init2); 27 | initStore.add(init3); 28 | initStore.add(init4); 29 | assertEquals(0.3, Median.calculateMedian(initStore), 0); 30 | } 31 | 32 | @Test 33 | public void moreTestCalculateMedian() throws Exception { 34 | List initStore = new LinkedList<>(); 35 | InitMessage init1 = new InitMessage(1,1,0.9); 36 | InitMessage init2 = new InitMessage(1,2,0.4); 37 | InitMessage init3 = new InitMessage(1,3,0.2); 38 | InitMessage init4 = new InitMessage(1,4,0.0); 39 | initStore.add(init1); 40 | initStore.add(init2); 41 | initStore.add(init3); 42 | initStore.add(init4); 43 | assertEquals(0.2, Median.calculateMedian(initStore), 0); 44 | } 45 | 46 | @Test 47 | public void moarTestCalculateMedian() throws Exception { 48 | List initStore = new LinkedList<>(); 49 | InitMessage init1 = new InitMessage(1,1,1.8079927); 50 | InitMessage init2 = new InitMessage(1,2,7.1203556); 51 | InitMessage init3 = new InitMessage(1,3,6.654901); 52 | InitMessage init4 = new InitMessage(1,4,5.485434); 53 | initStore.add(init1); 54 | initStore.add(init2); 55 | initStore.add(init3); 56 | initStore.add(init4); 57 | assertEquals(5.485434, Median.calculateMedian(initStore), 0); 58 | } 59 | 60 | @Test 61 | public void evunMoarTestCalculateMedian() throws Exception { 62 | List initStore = new LinkedList<>(); 63 | InitMessage init1 = new InitMessage(1,1,0); 64 | InitMessage init2 = new InitMessage(1,2,0.4458); 65 | InitMessage init3 = new InitMessage(1,3,2); 66 | initStore.add(init1); 67 | initStore.add(init2); 68 | initStore.add(init3); 69 | assertEquals(0.4458, Median.calculateMedian(initStore), 0); 70 | } 71 | } -------------------------------------------------------------------------------- /src/test/java/de/teamproject16/pbft/Messages/TestMessage.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Messages; 2 | 3 | import org.json.JSONObject; 4 | import org.junit.Test; 5 | 6 | import static de.teamproject16.pbft.Messages.Types.PROPOSE; 7 | import static org.hamcrest.CoreMatchers.instanceOf; 8 | import static org.hamcrest.MatcherAssert.assertThat; 9 | import static org.junit.Assert.assertEquals; 10 | 11 | /** 12 | * Unit tests for json serializable Test message 13 | */ 14 | public class TestMessage { 15 | @Test 16 | public void testInitMessageConvert() throws Exception{ 17 | String json = "{\"node\": 1, \"value\": 5.3, \"type\": 1, \"sequence_no\": 3}"; 18 | JSONObject jsonObj = new JSONObject(json); 19 | Message te = Message.messageConvert(jsonObj); 20 | System.out.println(te.toString()); 21 | assertThat("InitMessage instance", te, instanceOf(InitMessage.class)); 22 | assertEquals("InitMessage messageEncode()", jsonObj.toString(), te.messageEncode().toString()); 23 | } 24 | 25 | @Test 26 | public void testProposeMessageConvert() throws Exception{ 27 | String json = "{\"type\": "+ PROPOSE + ", \"sequence_no\": 3, \"node\": 1, " + 28 | "\"leader\": 2, \"proposal\": 3.5, \"value_store\": [" + 29 | "{\"node\": 2, \"value\": 0.4, \"type\": 1, \"sequence_no\": 1}, " + 30 | "{\"node\": 1, \"value\": 0.6, \"type\": 1, \"sequence_no\": 1}, " + 31 | "{\"node\": 3, \"value\": 0.3, \"type\": 1, \"sequence_no\": 1}, " + 32 | "{\"node\": 4, \"value\": 0.3, \"type\": 1, \"sequence_no\": 1}" + 33 | "]}"; 34 | JSONObject jsonObj = new JSONObject(json); 35 | Message te = Message.messageConvert(jsonObj); 36 | System.out.println(te.toString()); 37 | assertThat("ProposeMessage instance", te, instanceOf(ProposeMessage.class)); 38 | assertEquals("ProposeMessage messageEncode()", jsonObj.toString(), te.messageEncode().toString()); 39 | } 40 | 41 | @Test 42 | public void testPrevoteMessage() throws Exception{ 43 | String json = "{\"node\": 1, \"value\": 5.3, \"type\": 3, \"leader\": 2, \"sequence_no\": 3}"; 44 | JSONObject jsonObj = new JSONObject(json); 45 | Message te = Message.messageConvert(jsonObj); 46 | System.out.println(te.toString()); 47 | assertThat("PrevoteMessage instance", te, instanceOf(PrevoteMessage.class)); 48 | assertEquals("PrevoteMessage messageEncode()", jsonObj.toString(), te.messageEncode().toString()); 49 | } 50 | 51 | @Test 52 | public void testVoteMessage() throws Exception{ 53 | String json = "{\"node\": 1, \"value\": 5.3, \"type\": 4, \"leader\": 2, \"sequence_no\": 3}"; 54 | JSONObject jsonObj = new JSONObject(json); 55 | Message te = Message.messageConvert(jsonObj); 56 | System.out.println(te.toString()); 57 | assertThat("VoteMessage instance", te, instanceOf(VoteMessage.class)); 58 | assertEquals("VoteMessage messageEncode()", jsonObj.toString(), te.messageEncode().toString()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/de/teamproject16/pbft/Network/ReceiverTest.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft.Network; 2 | 3 | import de.luckydonald.utils.mockups.SocketMockup; 4 | import org.junit.After; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import static org.junit.Assert.*; 8 | import de.luckydonald.utils.mockups.ServerSocketMockup; 9 | 10 | import java.io.InputStream; 11 | import java.io.ByteArrayInputStream; 12 | 13 | /** 14 | * @author luckydonald 15 | * @since 26.10.2016 16 | **/ 17 | public class ReceiverTest { 18 | Receiver r = null; 19 | ServerSocketMockup s = null; 20 | InputStream is = null; 21 | 22 | @Before 23 | public void setUp() throws Exception { 24 | 25 | 26 | } 27 | 28 | @After 29 | public void tearDown() throws Exception { 30 | 31 | } 32 | 33 | @Test 34 | public void testReceiver() throws Exception { 35 | String expected = "{'node':1,'type':1,'value':5.3,'sequence_no':3}\n".replace("'", "\""); 36 | String send = "ANSWER 48\n" + expected; 37 | 38 | SocketMockup s = new SocketMockup(); 39 | s.in = new ByteArrayInputStream(send.getBytes()); 40 | 41 | Receiver r = new Receiver(); 42 | String result = r.receiveFromSocket(s); 43 | 44 | assertEquals("Socket Read", expected, result); 45 | } 46 | 47 | @Test 48 | public void testAddMessage() throws Exception { 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /src/test/java/de/teamproject16/pbft/NormalCaseTest.java: -------------------------------------------------------------------------------- 1 | package de.teamproject16.pbft; 2 | 3 | import de.luckydonald.utils.dockerus.DockerusAuto; 4 | import de.luckydonald.utils.dockerus.DockerusDummy; 5 | import de.teamproject16.pbft.Messages.Message; 6 | import de.teamproject16.pbft.Messages.PrevoteMessage; 7 | import de.teamproject16.pbft.Messages.ProposeMessage; 8 | import de.teamproject16.pbft.Network.Receiver; 9 | import org.json.JSONObject; 10 | import org.junit.Test; 11 | 12 | import java.util.ArrayList; 13 | 14 | import static de.teamproject16.pbft.Messages.Types.PROPOSE; 15 | import static org.junit.Assert.assertEquals; 16 | 17 | /** 18 | * Created on 31.10.16. 19 | */ 20 | public class NormalCaseTest { 21 | @Test 22 | public void testVerifyProposal() throws Exception { 23 | String json = "{\"type\": "+ PROPOSE + ", \"sequence_no\": 3, \"node\": 1, " + 24 | "\"leader\": 2, \"proposal\": 3.5, \"value_store\": [" + 25 | "{\"node\": 2, \"value\": 0.4, \"type\": 1, \"sequence_no\": 1}, " + 26 | "{\"node\": 1, \"value\": 0.6, \"type\": 1, \"sequence_no\": 1}, " + 27 | "{\"node\": 3, \"value\": 0.3, \"type\": 1, \"sequence_no\": 1}, " + 28 | "{\"node\": 4, \"value\": 0.3, \"type\": 1, \"sequence_no\": 1}" + 29 | "]}"; 30 | JSONObject json_obj = new JSONObject(json); 31 | ProposeMessage te = (ProposeMessage) Message.messageConvert(json_obj); 32 | assertEquals("VerifyProposal", NormalCase.verifyProposal(te), false); 33 | } 34 | 35 | @Test 36 | public void testCheckAgreement() throws Exception { 37 | ArrayList store = new ArrayList<>(); 38 | PrevoteMessage pM1 = new PrevoteMessage(3,1,2,0.3); 39 | PrevoteMessage pM2 = new PrevoteMessage(3,2,2,0.3); 40 | PrevoteMessage pm3 = new PrevoteMessage(3,3,2,0.2); 41 | PrevoteMessage pm4 = new PrevoteMessage(3,4,2,0.3); 42 | store.add(pM1); 43 | store.add(pM2); 44 | store.add(pm3); 45 | store.add(pm4); 46 | NormalCase normalCase = new NormalCase(new Receiver()); 47 | NormalCase.VerifyAgreementResult lol = normalCase.checkAgreement(store); 48 | if (DockerusAuto.getInstance() instanceof DockerusDummy) { 49 | ((DockerusDummy) DockerusAuto.getInstance()).setTotal(4); 50 | } 51 | 52 | assertEquals("checkAgreement", lol.bool, true); 53 | assertEquals(0.3, lol.value, 0.0); 54 | 55 | ArrayList store1 = new ArrayList<>(); 56 | PrevoteMessage pM11 = new PrevoteMessage(3,1,2,0.3); 57 | PrevoteMessage pM21 = new PrevoteMessage(3,2,2,0.4); 58 | PrevoteMessage pm31 = new PrevoteMessage(3,3,2,0.2); 59 | PrevoteMessage pm41 = new PrevoteMessage(3,4,2,0.3); 60 | store1.add(pM11); 61 | store1.add(pM21); 62 | store1.add(pm31); 63 | store1.add(pm41); 64 | NormalCase normalCase1 = new NormalCase(new Receiver()); 65 | NormalCase.VerifyAgreementResult lol1 = normalCase1.checkAgreement(store1); 66 | assertEquals("checkAgreement did agree", lol1.bool, false); 67 | //assertEquals(0.3, lol1.value, 0.0); 68 | } 69 | 70 | } --------------------------------------------------------------------------------