aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2012-05-29 23:26:46 +0000
committerFlorian Dold <florian.dold@gmail.com>2012-05-29 23:26:46 +0000
commit718ba0b662c61c1c993f43660cfa5ec393468aed (patch)
treedb4180e7f2a03f41b8fd4e910d11a4118bab72a4
parent0314ed2e7ebb2d362f25a79ce5fa689203e0e9e8 (diff)
downloadgnunet-java-718ba0b662c61c1c993f43660cfa5ec393468aed.tar.gz
gnunet-java-718ba0b662c61c1c993f43660cfa5ec393468aed.zip
implemented core with the RequestQueue API, implemented tests for most service APIs, updated shell-scripts for running tests / coverage.
-rw-r--r--COPYING674
-rw-r--r--ISSUES69
-rw-r--r--lib/guava-12.0.jarbin0 -> 1781208 bytes
-rw-r--r--src/org/gnunet/construct/MsgMap.txt4
-rw-r--r--src/org/gnunet/core/Core.java385
-rw-r--r--src/org/gnunet/core/InitMessage.java9
-rw-r--r--src/org/gnunet/core/NotifyInboundTrafficMessage.java10
-rw-r--r--src/org/gnunet/core/NotifyOutboundTrafficMessage.java10
-rw-r--r--src/org/gnunet/statistics/Statistics.java8
-rw-r--r--src/org/gnunet/util/Client.java6
-rw-r--r--src/org/gnunet/util/Configuration.java148
-rw-r--r--src/org/gnunet/util/Connection.java29
-rw-r--r--src/org/gnunet/util/Program.java31
-rw-r--r--src/org/gnunet/util/RequestQueue.java17
-rw-r--r--src/org/gnunet/util/RunaboutUtil.java56
-rw-r--r--src/org/gnunet/util/Scheduler.java30
-rw-r--r--src/org/gnunet/util/Server.java35
-rw-r--r--src/org/gnunet/util/Service.java8
-rw-r--r--src/org/grothoff/Runabout.java4
-rw-r--r--test/org/gnunet/construct/ConstructTest.java191
-rw-r--r--test/org/gnunet/construct/UnionTest.java70
-rw-r--r--test/org/gnunet/construct/parsers/IntegerParserTest.java88
-rw-r--r--test/org/gnunet/core/CoreTest.java100
-rw-r--r--test/org/gnunet/dht/DHTTest.java49
-rw-r--r--test/org/gnunet/statistics/StatisticsTest.java161
-rw-r--r--test/org/gnunet/statistics/statistics-test.conf18
-rw-r--r--test/org/gnunet/util/Assertion.java42
-rw-r--r--test/org/gnunet/util/AssertionList.java30
-rw-r--r--test/org/gnunet/util/ResolverTest.java84
-rw-r--r--test/org/gnunet/util/ServerTest.java27
-rw-r--r--test/org/gnunet/util/TestingSetup.java28
-rw-r--r--test/org/gnunet/util/Wrapper.java43
-rw-r--r--test/org/gnunet/util/getopt/GetoptTest.java (renamed from test/org/gnunet/util/GetoptTest.java)5
-rw-r--r--test/org/grothoff/RunaboutBenchmark.java5
-rw-r--r--test/org/org/gnunet/nse/NSETest.java53
-rwxr-xr-xtools/build2
-rwxr-xr-xtools/coverage10
-rwxr-xr-xtools/run-tests9
38 files changed, 1797 insertions, 751 deletions
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
1 GNU GENERAL PUBLIC LICENSE
2 Version 3, 29 June 2007
3
4 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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
11software and other kinds of works.
12
13 The licenses for most software and other practical works are designed
14to take away your freedom to share and change the works. By contrast,
15the GNU General Public License is intended to guarantee your freedom to
16share and change all versions of a program--to make sure it remains free
17software for all its users. We, the Free Software Foundation, use the
18GNU General Public License for most of our software; it applies also to
19any other work released this way by its authors. You can apply it to
20your programs, too.
21
22 When we speak of free software, we are referring to freedom, not
23price. Our General Public Licenses are designed to make sure that you
24have the freedom to distribute copies of free software (and charge for
25them if you wish), that you receive source code or can get it if you
26want it, that you can change the software or use pieces of it in new
27free programs, and that you know you can do these things.
28
29 To protect your rights, we need to prevent others from denying you
30these rights or asking you to surrender the rights. Therefore, you have
31certain responsibilities if you distribute copies of the software, or if
32you modify it: responsibilities to respect the freedom of others.
33
34 For example, if you distribute copies of such a program, whether
35gratis or for a fee, you must pass on to the recipients the same
36freedoms that you received. You must make sure that they, too, receive
37or can get the source code. And you must show them these terms so they
38know 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
42giving you legal permission to copy, distribute and/or modify it.
43
44 For the developers' and authors' protection, the GPL clearly explains
45that there is no warranty for this free software. For both users' and
46authors' sake, the GPL requires that modified versions be marked as
47changed, so that their problems will not be attributed erroneously to
48authors of previous versions.
49
50 Some devices are designed to deny users access to install or run
51modified versions of the software inside them, although the manufacturer
52can do so. This is fundamentally incompatible with the aim of
53protecting users' freedom to change the software. The systematic
54pattern of such abuse occurs in the area of products for individuals to
55use, which is precisely where it is most unacceptable. Therefore, we
56have designed this version of the GPL to prohibit the practice for those
57products. If such problems arise substantially in other domains, we
58stand ready to extend this provision to those domains in future versions
59of the GPL, as needed to protect the freedom of users.
60
61 Finally, every program is threatened constantly by software patents.
62States should not allow patents to restrict development and use of
63software on general-purpose computers, but in those that do, we wish to
64avoid the special danger that patents applied to a free program could
65make it effectively proprietary. To prevent this, the GPL assures that
66patents cannot be used to render the program non-free.
67
68 The precise terms and conditions for copying, distribution and
69modification 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
78works, such as semiconductor masks.
79
80 "The Program" refers to any copyrightable work licensed under this
81License. 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
85in a fashion requiring copyright permission, other than the making of an
86exact copy. The resulting work is called a "modified version" of the
87earlier work or a work "based on" the earlier work.
88
89 A "covered work" means either the unmodified Program or a work based
90on the Program.
91
92 To "propagate" a work means to do anything with it that, without
93permission, would make you directly or secondarily liable for
94infringement under applicable copyright law, except executing it on a
95computer or modifying a private copy. Propagation includes copying,
96distribution (with or without modification), making available to the
97public, and in some countries other activities as well.
98
99 To "convey" a work means any kind of propagation that enables other
100parties to make or receive copies. Mere interaction with a user through
101a computer network, with no transfer of a copy, is not conveying.
102
103 An interactive user interface displays "Appropriate Legal Notices"
104to the extent that it includes a convenient and prominently visible
105feature that (1) displays an appropriate copyright notice, and (2)
106tells the user that there is no warranty for the work (except to the
107extent that warranties are provided), that licensees may convey the
108work under this License, and how to view a copy of this License. If
109the interface presents a list of user commands or options, such as a
110menu, 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
115for making modifications to it. "Object code" means any non-source
116form of a work.
117
118 A "Standard Interface" means an interface that either is an official
119standard defined by a recognized standards body, or, in the case of
120interfaces specified for a particular programming language, one that
121is widely used among developers working in that language.
122
123 The "System Libraries" of an executable work include anything, other
124than the work as a whole, that (a) is included in the normal form of
125packaging a Major Component, but which is not part of that Major
126Component, and (b) serves only to enable use of the work with that
127Major Component, or to implement a Standard Interface for which an
128implementation 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
132produce 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
135the source code needed to generate, install, and (for an executable
136work) run the object code and to modify the work, including scripts to
137control those activities. However, it does not include the work's
138System Libraries, or general-purpose tools or generally available free
139programs which are used unmodified in performing those activities but
140which are not part of the work. For example, Corresponding Source
141includes interface definition files associated with source files for
142the work, and the source code for shared libraries and dynamically
143linked subprograms that the work is specifically designed to require,
144such as by intimate data communication or control flow between those
145subprograms and other parts of the work.
146
147 The Corresponding Source need not include anything that users
148can regenerate automatically from other parts of the Corresponding
149Source.
150
151 The Corresponding Source for a work in source code form is that
152same work.
153
154 2. Basic Permissions.
155
156 All rights granted under this License are granted for the term of
157copyright on the Program, and are irrevocable provided the stated
158conditions are met. This License explicitly affirms your unlimited
159permission to run the unmodified Program. The output from running a
160covered work is covered by this License only if the output, given its
161content, constitutes a covered work. This License acknowledges your
162rights 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
165convey, without conditions so long as your license otherwise remains
166in force. You may convey covered works to others for the sole purpose
167of having them make modifications exclusively for you, or provide you
168with facilities for running those works, provided that you comply with
169the terms of this License in conveying all material for which you do
170not control copyright. Those thus making or running the covered works
171for you must do so exclusively on your behalf, under your direction
172and control, on terms that prohibit them from making any copies of
173your copyrighted material outside their relationship with you.
174
175 Conveying under any other circumstances is permitted solely under
176the conditions stated below. Sublicensing is not allowed; section 10
177makes 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
182measure under any applicable law fulfilling obligations under article
18311 of the WIPO copyright treaty adopted on 20 December 1996, or
184similar laws prohibiting or restricting circumvention of such
185measures.
186
187 When you convey a covered work, you waive any legal power to forbid
188circumvention of technological measures to the extent such circumvention
189is effected by exercising rights under this License with respect to
190the covered work, and you disclaim any intention to limit operation or
191modification of the work as a means of enforcing, against the work's
192users, your or third parties' legal rights to forbid circumvention of
193technological measures.
194
195 4. Conveying Verbatim Copies.
196
197 You may convey verbatim copies of the Program's source code as you
198receive it, in any medium, provided that you conspicuously and
199appropriately publish on each copy an appropriate copyright notice;
200keep intact all notices stating that this License and any
201non-permissive terms added in accord with section 7 apply to the code;
202keep intact all notices of the absence of any warranty; and give all
203recipients 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,
206and 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
211produce it from the Program, in the form of source code under the
212terms 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
236works, which are not by their nature extensions of the covered work,
237and which are not combined with it such as to form a larger program,
238in or on a volume of a storage or distribution medium, is called an
239"aggregate" if the compilation and its resulting copyright are not
240used to limit the access or legal rights of the compilation's users
241beyond what the individual works permit. Inclusion of a covered work
242in an aggregate does not cause this License to apply to the other
243parts 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
248of sections 4 and 5, provided that you also convey the
249machine-readable Corresponding Source under the terms of this License,
250in 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
294from the Corresponding Source as a System Library, need not be
295included in conveying the object code work.
296
297 A "User Product" is either (1) a "consumer product", which means any
298tangible personal property which is normally used for personal, family,
299or household purposes, or (2) anything designed or sold for incorporation
300into a dwelling. In determining whether a product is a consumer product,
301doubtful cases shall be resolved in favor of coverage. For a particular
302product received by a particular user, "normally used" refers to a
303typical or common use of that class of product, regardless of the status
304of the particular user or of the way in which the particular user
305actually uses, or expects or is expected to use, the product. A product
306is a consumer product regardless of whether the product has substantial
307commercial, industrial or non-consumer uses, unless such uses represent
308the only significant mode of use of the product.
309
310 "Installation Information" for a User Product means any methods,
311procedures, authorization keys, or other information required to install
312and execute modified versions of a covered work in that User Product from
313a modified version of its Corresponding Source. The information must
314suffice to ensure that the continued functioning of the modified object
315code is in no case prevented or interfered with solely because
316modification has been made.
317
318 If you convey an object code work under this section in, or with, or
319specifically for use in, a User Product, and the conveying occurs as
320part of a transaction in which the right of possession and use of the
321User Product is transferred to the recipient in perpetuity or for a
322fixed term (regardless of how the transaction is characterized), the
323Corresponding Source conveyed under this section must be accompanied
324by the Installation Information. But this requirement does not apply
325if neither you nor any third party retains the ability to install
326modified object code on the User Product (for example, the work has
327been installed in ROM).
328
329 The requirement to provide Installation Information does not include a
330requirement to continue to provide support service, warranty, or updates
331for a work that has been modified or installed by the recipient, or for
332the User Product in which it has been modified or installed. Access to a
333network may be denied when the modification itself materially and
334adversely affects the operation of the network or violates the rules and
335protocols for communication across the network.
336
337 Corresponding Source conveyed, and Installation Information provided,
338in accord with this section must be in a format that is publicly
339documented (and with an implementation available to the public in
340source code form), and must require no special password or key for
341unpacking, reading or copying.
342
343 7. Additional Terms.
344
345 "Additional permissions" are terms that supplement the terms of this
346License by making exceptions from one or more of its conditions.
347Additional permissions that are applicable to the entire Program shall
348be treated as though they were included in this License, to the extent
349that they are valid under applicable law. If additional permissions
350apply only to part of the Program, that part may be used separately
351under those permissions, but the entire Program remains governed by
352this License without regard to the additional permissions.
353
354 When you convey a copy of a covered work, you may at your option
355remove any additional permissions from that copy, or from any part of
356it. (Additional permissions may be written to require their own
357removal in certain cases when you modify the work.) You may place
358additional permissions on material, added by you to a covered work,
359for which you have or can give appropriate copyright permission.
360
361 Notwithstanding any other provision of this License, for material you
362add to a covered work, you may (if authorized by the copyright holders of
363that 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
389restrictions" within the meaning of section 10. If the Program as you
390received it, or any part of it, contains a notice stating that it is
391governed by this License along with a term that is a further
392restriction, you may remove that term. If a license document contains
393a further restriction but permits relicensing or conveying under this
394License, you may add to a covered work material governed by the terms
395of that license document, provided that the further restriction does
396not survive such relicensing or conveying.
397
398 If you add terms to a covered work in accord with this section, you
399must place, in the relevant source files, a statement of the
400additional terms that apply to those files, or a notice indicating
401where to find the applicable terms.
402
403 Additional terms, permissive or non-permissive, may be stated in the
404form of a separately written license, or stated as exceptions;
405the above requirements apply either way.
406
407 8. Termination.
408
409 You may not propagate or modify a covered work except as expressly
410provided under this License. Any attempt otherwise to propagate or
411modify it is void, and will automatically terminate your rights under
412this License (including any patent licenses granted under the third
413paragraph of section 11).
414
415 However, if you cease all violation of this License, then your
416license from a particular copyright holder is reinstated (a)
417provisionally, unless and until the copyright holder explicitly and
418finally terminates your license, and (b) permanently, if the copyright
419holder fails to notify you of the violation by some reasonable means
420prior to 60 days after the cessation.
421
422 Moreover, your license from a particular copyright holder is
423reinstated permanently if the copyright holder notifies you of the
424violation by some reasonable means, this is the first time you have
425received notice of violation of this License (for any work) from that
426copyright holder, and you cure the violation prior to 30 days after
427your receipt of the notice.
428
429 Termination of your rights under this section does not terminate the
430licenses of parties who have received copies or rights from you under
431this License. If your rights have been terminated and not permanently
432reinstated, you do not qualify to receive new licenses for the same
433material 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
438run a copy of the Program. Ancillary propagation of a covered work
439occurring solely as a consequence of using peer-to-peer transmission
440to receive a copy likewise does not require acceptance. However,
441nothing other than this License grants you permission to propagate or
442modify any covered work. These actions infringe copyright if you do
443not accept this License. Therefore, by modifying or propagating a
444covered 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
449receives a license from the original licensors, to run, modify and
450propagate that work, subject to this License. You are not responsible
451for enforcing compliance by third parties with this License.
452
453 An "entity transaction" is a transaction transferring control of an
454organization, or substantially all assets of one, or subdividing an
455organization, or merging organizations. If propagation of a covered
456work results from an entity transaction, each party to that
457transaction who receives a copy of the work also receives whatever
458licenses to the work the party's predecessor in interest had or could
459give under the previous paragraph, plus a right to possession of the
460Corresponding Source of the work from the predecessor in interest, if
461the predecessor has it or can get it with reasonable efforts.
462
463 You may not impose any further restrictions on the exercise of the
464rights granted or affirmed under this License. For example, you may
465not impose a license fee, royalty, or other charge for exercise of
466rights granted under this License, and you may not initiate litigation
467(including a cross-claim or counterclaim in a lawsuit) alleging that
468any patent claim is infringed by making, using, selling, offering for
469sale, 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
474License of the Program or a work on which the Program is based. The
475work thus licensed is called the contributor's "contributor version".
476
477 A contributor's "essential patent claims" are all patent claims
478owned or controlled by the contributor, whether already acquired or
479hereafter acquired, that would be infringed by some manner, permitted
480by this License, of making, using, or selling its contributor version,
481but do not include claims that would be infringed only as a
482consequence of further modification of the contributor version. For
483purposes of this definition, "control" includes the right to grant
484patent sublicenses in a manner consistent with the requirements of
485this License.
486
487 Each contributor grants you a non-exclusive, worldwide, royalty-free
488patent license under the contributor's essential patent claims, to
489make, use, sell, offer for sale, import and otherwise run, modify and
490propagate the contents of its contributor version.
491
492 In the following three paragraphs, a "patent license" is any express
493agreement or commitment, however denominated, not to enforce a patent
494(such as an express permission to practice a patent or covenant not to
495sue for patent infringement). To "grant" such a patent license to a
496party means to make such an agreement or commitment not to enforce a
497patent against the party.
498
499 If you convey a covered work, knowingly relying on a patent license,
500and the Corresponding Source of the work is not available for anyone
501to copy, free of charge and under the terms of this License, through a
502publicly available network server or other readily accessible means,
503then you must either (1) cause the Corresponding Source to be so
504available, or (2) arrange to deprive yourself of the benefit of the
505patent license for this particular work, or (3) arrange, in a manner
506consistent with the requirements of this License, to extend the patent
507license to downstream recipients. "Knowingly relying" means you have
508actual knowledge that, but for the patent license, your conveying the
509covered work in a country, or your recipient's use of the covered work
510in a country, would infringe one or more identifiable patents in that
511country that you have reason to believe are valid.
512
513 If, pursuant to or in connection with a single transaction or
514arrangement, you convey, or propagate by procuring conveyance of, a
515covered work, and grant a patent license to some of the parties
516receiving the covered work authorizing them to use, propagate, modify
517or convey a specific copy of the covered work, then the patent license
518you grant is automatically extended to all recipients of the covered
519work and works based on it.
520
521 A patent license is "discriminatory" if it does not include within
522the scope of its coverage, prohibits the exercise of, or is
523conditioned on the non-exercise of one or more of the rights that are
524specifically granted under this License. You may not convey a covered
525work if you are a party to an arrangement with a third party that is
526in the business of distributing software, under which you make payment
527to the third party based on the extent of your activity of conveying
528the work, and under which the third party grants, to any of the
529parties who would receive the covered work from you, a discriminatory
530patent license (a) in connection with copies of the covered work
531conveyed by you (or copies made from those copies), or (b) primarily
532for and in connection with specific products or compilations that
533contain the covered work, unless you entered into that arrangement,
534or that patent license was granted, prior to 28 March 2007.
535
536 Nothing in this License shall be construed as excluding or limiting
537any implied license or other defenses to infringement that may
538otherwise 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
543otherwise) that contradict the conditions of this License, they do not
544excuse you from the conditions of this License. If you cannot convey a
545covered work so as to satisfy simultaneously your obligations under this
546License and any other pertinent obligations, then as a consequence you may
547not convey it at all. For example, if you agree to terms that obligate you
548to collect a royalty for further conveying from those to whom you convey
549the Program, the only way you could satisfy both those terms and this
550License 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
555permission to link or combine any covered work with a work licensed
556under version 3 of the GNU Affero General Public License into a single
557combined work, and to convey the resulting work. The terms of this
558License will continue to apply to the part which is the covered work,
559but the special requirements of the GNU Affero General Public License,
560section 13, concerning interaction through a network will apply to the
561combination as such.
562
563 14. Revised Versions of this License.
564
565 The Free Software Foundation may publish revised and/or new versions of
566the GNU General Public License from time to time. Such new versions will
567be similar in spirit to the present version, but may differ in detail to
568address new problems or concerns.
569
570 Each version is given a distinguishing version number. If the
571Program specifies that a certain numbered version of the GNU General
572Public License "or any later version" applies to it, you have the
573option of following the terms and conditions either of that numbered
574version or of any later version published by the Free Software
575Foundation. If the Program does not specify a version number of the
576GNU General Public License, you may choose any version ever published
577by the Free Software Foundation.
578
579 If the Program specifies that a proxy can decide which future
580versions of the GNU General Public License can be used, that proxy's
581public statement of acceptance of a version permanently authorizes you
582to choose that version for the Program.
583
584 Later license versions may give you additional or different
585permissions. However, no additional obligations are imposed on any
586author or copyright holder as a result of your choosing to follow a
587later version.
588
589 15. Disclaimer of Warranty.
590
591 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598ALL 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
603WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610SUCH DAMAGES.
611
612 17. Interpretation of Sections 15 and 16.
613
614 If the disclaimer of warranty and limitation of liability provided
615above cannot be given local legal effect according to their terms,
616reviewing courts shall apply local law that most closely approximates
617an absolute waiver of all civil liability in connection with the
618Program, unless a warranty or assumption of liability accompanies a
619copy 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
626possible use to the public, the best way to achieve this is to make it
627free 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
630to attach them to the start of each source file to most effectively
631state the exclusion of warranty; and each file should have at least
632the "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 <http://www.gnu.org/licenses/>.
649
650Also 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
653notice like this when it starts in an interactive mode:
654
655 <program> Copyright (C) <year> <name of author>
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
660The hypothetical commands `show w' and `show c' should show the appropriate
661parts of the General Public License. Of course, your program's commands
662might 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,
665if any, to sign a "copyright disclaimer" for the program, if necessary.
666For more information on this, and how to apply and follow the GNU GPL, see
667<http://www.gnu.org/licenses/>.
668
669 The GNU General Public License does not permit incorporating your program
670into proprietary programs. If your program is a subroutine library, you
671may consider it more useful to permit linking proprietary applications with
672the library. If this is what you want to do, use the GNU Lesser General
673Public License instead of this License. But first, please read
674<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/ISSUES b/ISSUES
index 5d0e379..8052420 100644
--- a/ISSUES
+++ b/ISSUES
@@ -58,3 +58,72 @@ fi
58java -jar $GNUNET_JAVA_PREFIX/lib/gnunet.jar 58java -jar $GNUNET_JAVA_PREFIX/lib/gnunet.jar
59 59
60 60
61
62===========================================================
63
64* @UNIXONLY@ PORT = 2089 in src/util/resolver.conf.on
65 * what's the purpose? we also need this line to be enabled on JAVAPORT
66
67* something I didn't think through from the beginning:
68 how should unknown message types be handled by message handlers?
69 * sometimes we want to see the message (e.g. in server), sometimes it is an error
70 * alternative 1: signal an error to the message handler, somehow pass the original message
71 * alternative 2: pass a special UnknownMessage to the message handler, filter it for higher-level
72 APIs and signal an error.
73
74* finally core/statistics/dht/resolver/... have unit tests!
75 (and coverage works again, but i can't access the cobertura via ssh yet)
76 * currently most test rely on a running gnunet, and use the default configuration
77 * alternative approach:
78 * configuration is copied from resource (may be in a jar!) to a temp file, then passed on the command
79 line to gunet-service-*
80 * useful to test behavior on disconnects
81 * problem: java sucks at managing processes, processes stay alive if we abort a test
82 * dht get: can we assume that "our" peer immediately stores the value?
83
84* naming: when do we use destroy, when do we use disconnect, or is this arbitrary?
85
86* implications of using exceptions in callbacks
87 * esp. when the exception is non-fatal, i.e. the exception is caught, handled, and the program continues
88 * java exceptions have no restarts, may leave gnunet-java in inconsistent state
89
90* how to test callbacks? we do not only need to test for the right values, but also check that callback has actually
91 been called.
92 * first approach: thow a TestSuccess exception, discarded (see above)
93 * current approach: build a list of assertions, check assertions after scheduler is done.
94 * each assertion stores whether it already succeeded and a message
95
96
97* finalziers: used to destroy object. lead to heisenbug/double disconnect. now policy: check if object
98 has been disposed of properly, otherwise log a warning.
99 * cannot guarantee cleanup anyway
100 (java behavior: run finalizers iff unreachabla during gc, may never happen, finalizers on jvm shutdown deprecated)
101
102
103* regarding peerinfo
104 * i don't fully understand how HELLOs work.
105
106* what are the next important services to implement? (probably mesh, peerinfo, transport)
107
108
109* i'm currently considering to use the google guava library
110 * Apache License 2.0
111 * con: large (1.8MB jar)
112 * but: unused class files could be stripped from the jar, e.g. using ProGuard
113 * would replace the apache commons io library
114 * contains collections used throughout gnunet
115 * bloomfilter
116 * multimap, alleviates the boilerplate code when dealing with hashmaps of lists
117 * methods to deal with "signed" primitives
118 * dealing with files (e.g. copying)
119 * redirecting i/o streams from/to files (when issuing external commands)
120 * hashing utilities
121 * tables (mapping from key pair to value), would replace nested Maps in e.g. Configurations
122 * ...
123
124
125
126
127* long-term todos:
128 * refactor the Construct implementation, implement the "nicer" syntax
129 * refactor the getopt implementation \ No newline at end of file
diff --git a/lib/guava-12.0.jar b/lib/guava-12.0.jar
new file mode 100644
index 0000000..c990f00
--- /dev/null
+++ b/lib/guava-12.0.jar
Binary files differ
diff --git a/src/org/gnunet/construct/MsgMap.txt b/src/org/gnunet/construct/MsgMap.txt
index 3e3178f..71d95d7 100644
--- a/src/org/gnunet/construct/MsgMap.txt
+++ b/src/org/gnunet/construct/MsgMap.txt
@@ -1,5 +1,3 @@
1org.gnunet.construct.UnionTest$TestUnion|0=org.gnunet.construct.UnionTest$TestUnionCase0
2org.gnunet.construct.UnionTest$TestUnion|1=org.gnunet.construct.UnionTest$TestUnionCase1
3org.gnunet.util.Resolver$Address|0=org.gnunet.util.Resolver$TextualAddress 1org.gnunet.util.Resolver$Address|0=org.gnunet.util.Resolver$TextualAddress
4org.gnunet.util.Resolver$Address|1=org.gnunet.util.Resolver$NumericAddress 2org.gnunet.util.Resolver$Address|1=org.gnunet.util.Resolver$NumericAddress
5org.gnunet.util.GnunetMessage$Body|68=org.gnunet.core.DisconnectNotifyMessage 3org.gnunet.util.GnunetMessage$Body|68=org.gnunet.core.DisconnectNotifyMessage
@@ -31,4 +29,4 @@ org.gnunet.util.GnunetMessage$Body|169=org.gnunet.statistics.GetMessage
31org.gnunet.util.GnunetMessage$Body|168=org.gnunet.statistics.SetMessage 29org.gnunet.util.GnunetMessage$Body|168=org.gnunet.statistics.SetMessage
32org.gnunet.util.GnunetMessage$Body|173=org.gnunet.statistics.WatchResponseMessage 30org.gnunet.util.GnunetMessage$Body|173=org.gnunet.statistics.WatchResponseMessage
33org.gnunet.util.GnunetMessage$Body|172=org.gnunet.statistics.WatchMessage 31org.gnunet.util.GnunetMessage$Body|172=org.gnunet.statistics.WatchMessage
34# generated 2012/05/12 12:08:13 32# generated 2012/05/29 19:00:30
diff --git a/src/org/gnunet/core/Core.java b/src/org/gnunet/core/Core.java
index e51f040..ed163af 100644
--- a/src/org/gnunet/core/Core.java
+++ b/src/org/gnunet/core/Core.java
@@ -20,16 +20,14 @@
20 20
21package org.gnunet.core; 21package org.gnunet.core;
22 22
23import org.gnunet.construct.*; 23import org.gnunet.construct.Construct;
24import org.gnunet.construct.MessageLoader;
24import org.gnunet.util.*; 25import org.gnunet.util.*;
25import org.grothoff.Runabout; 26import org.grothoff.Runabout;
26import org.slf4j.Logger; 27import org.slf4j.Logger;
27import org.slf4j.LoggerFactory; 28import org.slf4j.LoggerFactory;
28 29
29import java.lang.reflect.Method;
30import java.util.ArrayList;
31import java.util.HashMap; 30import java.util.HashMap;
32import java.util.LinkedList;
33import java.util.Map; 31import java.util.Map;
34 32
35 33
@@ -42,23 +40,15 @@ public class Core {
42 private static final Logger logger = LoggerFactory 40 private static final Logger logger = LoggerFactory
43 .getLogger(Core.class); 41 .getLogger(Core.class);
44 42
45
46 private final static int
47 CORE_OPTION_FULL_INBOUND = 8,
48 CORE_OPTION_HDR_INBOUND = 16,
49 CORE_OPTION_FULL_OUTBOUND = 32,
50 CORE_OPTION_HDR_OUTBOUND = 64;
51
52
53 private final Client client; 43 private final Client client;
54 44
55 /** 45 private final RequestQueue requestQueue;
46
47 /*
56 * set to null once connected for the first time 48 * set to null once connected for the first time
57 */ 49 */
58 private InitCallback initCallback; 50 private InitCallback initCallback;
59 51
60 private final RequestQueue requestQueue;
61
62 /* 52 /*
63 * Callbacks for traffic notifications. null if not used. 53 * Callbacks for traffic notifications. null if not used.
64 */ 54 */
@@ -68,64 +58,111 @@ public class Core {
68 private MessageNotify notifyInboundMessages; 58 private MessageNotify notifyInboundMessages;
69 59
70 60
61 /*
62 * Callbacks for connect/disconnect events
63 */
71 private ConnectHandler connectHandler; 64 private ConnectHandler connectHandler;
72 private DisconnectHandler disconnectHandler; 65 private DisconnectHandler disconnectHandler;
73 66
74 private final CoreReceiver coreReceiver = new CoreReceiver();
75 67
76 // per default we are interested in all messages => specific interest set is empty 68 // per default we are interested in all messages => specific interest set is empty
77 private int[] interested = new int[0]; 69 private int[] interested = new int[0];
70 /**
71 * Handler for the messages we are interested in.
72 */
78 private Runabout messageHandler; 73 private Runabout messageHandler;
79 74
80 HashMap<PeerIdentity, ConnectedPeerInfo> connectedPeers = new HashMap<PeerIdentity, ConnectedPeerInfo>(10);
81
82 LinkedList<TransmitHandle> pending = new LinkedList<TransmitHandle>();
83 75
84 LinkedList<SendMessage> approvedSendMessages = new LinkedList<SendMessage>(); 76 /**
85 77 * All currently connected peers with information about them attached
86 private Cancelable currentClientTransmitHandle; 78 */
79 HashMap<PeerIdentity, ConnectedPeerInfo> connectedPeers = new HashMap<PeerIdentity, ConnectedPeerInfo>(10);
87 80
88 81
89 /** 82 /**
90 * Represents a request for transmission. 83 * Information about the requests on connected peers.
91 */ 84 */
92 public class TransmitHandle {
93 private PeerIdentity peerIdentity;
94 private MessageTransmitter transmitter;
95 private int smrId;
96 private Cancelable timeoutHandle;
97 private int size;
98 public AbsoluteTime deadline;
99 }
100
101 private class ConnectedPeerInfo { 85 private class ConnectedPeerInfo {
102 public Map<Integer, TransmitHandle> requestsToPeer = new HashMap<Integer, TransmitHandle>(1); 86 public Map<Integer, NotifyTransmitReadyRequest> requestsToPeer = new HashMap<Integer,
87 NotifyTransmitReadyRequest>(1);
103 public int nextSmrId; 88 public int nextSmrId;
104 } 89 }
105 90
106 public Core(Configuration cfg) {
107 client = new Client("core", cfg);
108 requestQueue = new RequestQueue(client, new CoreReceiver());
109 }
110 91
111 public void init(InitCallback initCallback) { 92 /**
112 this.initCallback = initCallback; 93 * Request to transmit a message, sent after the corresponding NotifyTransmitRequest has been
113 reconnect(); 94 * approved by core.
95 */
96 private class TransmitRequest extends RequestQueue.Request {
97 public NotifyTransmitReadyRequest origin;
98 public GnunetMessage message;
99
100 @Override
101 public AbsoluteTime getDeadline() {
102 return origin.deadline;
103 }
104
105 @Override
106 public void transmit(Connection.MessageSink sink) {
107 SendMessage sm = new SendMessage();
108 sm.cork = 0;
109 sm.deadline = origin.deadline.asMessage();
110 sm.peer = origin.target;
111 sm.priority = origin.priority;
112 sm.payloadMessage = message;
113
114 sink.send(sm);
115 }
114 } 116 }
115 117
116 void reconnect() { 118 /**
117 InitMessage initMessage = new InitMessage(); 119 * Sent after we get a SendMessageReady
120 */
121 private class NotifyTransmitReadyRequest extends RequestQueue.Request {
122 public AbsoluteTime deadline;
123 public int size;
124 public int priority;
125 public PeerIdentity target;
126 public MessageTransmitter transmitter;
127 public int smrId;
128
129 @Override
130 public AbsoluteTime getDeadline() {
131 return deadline;
132 }
118 133
119 initMessage.interested = interested; 134 @Override
120 initMessage.options = 0; 135 public void transmit(Connection.MessageSink sink) {
136 SendMessageRequest smr = new SendMessageRequest();
137 smr.queueSize = 0;
138 smr.priority = priority;
139 smr.deadline = deadline.asMessage();
140 smr.smrId = smrId;
141 smr.peer = target;
142
143 sink.send(smr);
144 }
145 }
121 146
122 for (int i : interested) { 147 private class InitRequest extends RequestQueue.Request {
123 logger.info("we are interested in " + i); 148 @Override
149 public AbsoluteTime getDeadline() {
150 return AbsoluteTime.FOREVER;
124 } 151 }
125 152
126 //requestQueue.sendNext(); 153 @Override
154 public void transmit(Connection.MessageSink sink) {
155 InitMessage initMessage = new InitMessage();
156
157 initMessage.interested = interested;
158 initMessage.options = 0;
127 159
128 client.transmitAndGetResponse(initMessage, RelativeTime.FOREVER, true, new CoreReceiver()); 160 for (int i : interested) {
161 logger.info("we are interested in " + i);
162 }
163
164 sink.send(initMessage);
165 }
129 } 166 }
130 167
131 public class CoreReceiver extends RunaboutMessageReceiver { 168 public class CoreReceiver extends RunaboutMessageReceiver {
@@ -137,21 +174,29 @@ public class Core {
137 initCallback.onInit(m.myIdentity); 174 initCallback.onInit(m.myIdentity);
138 initCallback = null; 175 initCallback = null;
139 } 176 }
140
141 client.receive(RelativeTime.FOREVER, this);
142 } 177 }
143 178
144
145 public void visit(ConnectNotifyMessage m) { 179 public void visit(ConnectNotifyMessage m) {
146 if (connectHandler != null) { 180 if (connectHandler != null) {
147 connectHandler.onConnect(m.peer); 181 connectHandler.onConnect(m.peer);
148 } 182 }
183 }
149 184
150 client.receive(RelativeTime.FOREVER, this); 185 public void visit(DisconnectNotifyMessage m) {
186 if (disconnectHandler != null) {
187 disconnectHandler.onDisconnect(m.peer);
188 }
151 } 189 }
152 190
153 public void visit(NotifyInboundTrafficMessage m) { 191 public void visit(NotifyInboundTrafficMessage m) {
154 boolean found = false; 192 boolean found = false;
193 if (notifyInboundHeaders != null) {
194 notifyInboundHeaders.notify(m.payloadHeader);
195 }
196 if (notifyInboundMessages != null) {
197 // todo: call corresponding notify on notifyInboundMessages
198 }
199
155 for (int i : interested) { 200 for (int i : interested) {
156 if (i == m.payloadHeader.messageType) { 201 if (i == m.payloadHeader.messageType) {
157 found = true; 202 found = true;
@@ -159,61 +204,51 @@ public class Core {
159 } 204 }
160 } 205 }
161 if (found) { 206 if (found) {
162 messageHandler.visitAppropriate(m.payloadBody); 207 Class bodyClass = MessageLoader.getUnionClass(GnunetMessage.Body.class, m.payloadHeader.messageType);
163 } else { 208 @SuppressWarnings("unchecked")
164 // do stuff 209 GnunetMessage.Body b = (GnunetMessage.Body) Construct.parseAs(m.payloadBody, bodyClass);
210 messageHandler.visitAppropriate(b);
165 } 211 }
166
167 client.receive(RelativeTime.FOREVER, this);
168 } 212 }
169 213
170 public void visit(NotifyOutboundTrafficMessage m) { 214 public void visit(NotifyOutboundTrafficMessage m) {
171 215 if (notifyOutboundHeaders != null) {
172 client.receive(RelativeTime.FOREVER, this); 216 notifyOutboundHeaders.notify(m.payloadHeader);
217 }
218 if (notifyOutboundMessages != null) {
219 // todo
220 }
173 } 221 }
174 222
175 public void visit(SendMessageReady m) { 223 public void visit(SendMessageReady m) {
176 ConnectedPeerInfo targetPeerInfo = connectedPeers.get(m.peer);
177 224
178 if (targetPeerInfo == null) { 225 System.out.println("got smr");
179 logger.error("SendMessage ready received for unconnected peer " + m.peer);
180 226
181 client.receive(RelativeTime.FOREVER, this); 227 ConnectedPeerInfo cpi = connectedPeers.get(m.peer);
182 return; 228 NotifyTransmitReadyRequest req = cpi.requestsToPeer.get(m.smrId);
183 }
184 229
185 TransmitHandle transmitHandle = targetPeerInfo.requestsToPeer.get(m.smrId); 230 final TransmitRequest transmitRequest = new TransmitRequest();
231 transmitRequest.origin = req;
186 232
187 final SendMessage sendMessage = new SendMessage();
188 233
189 234 req.transmitter.transmit(new Connection.MessageSink() {
190 sendMessage.deadline = transmitHandle.deadline.asMessage(); 235 boolean sent;
191 sendMessage.cork = 0;
192 sendMessage.peer = transmitHandle.peerIdentity;
193 sendMessage.priority = 0;
194
195 transmitHandle.transmitter.transmit(new Connection.MessageSink() {
196 @Override 236 @Override
197 public void send(GnunetMessage.Body m) { 237 public void send(GnunetMessage.Body m) {
198 if (sendMessage.payloadMessage != null) { 238 if (sent) {
199 throw new AssertionError("can only send one payload message"); 239 throw new AssertionError("sending multiple messages not supported");
200 } 240 }
201 logger.info("sink called"); 241 transmitRequest.message = GnunetMessage.fromBody(m);
202 sendMessage.payloadMessage = GnunetMessage.fromBody(m); 242 sent = true;
203 } 243 }
204 }); 244 });
205 245
206 approvedSendMessages.add(sendMessage); 246 requestQueue.add(transmitRequest);
207
208 transmitPending();
209
210 client.receive(RelativeTime.FOREVER, this);
211 } 247 }
212 248
213 @Override 249 @Override
214 public void visitDefault(Object o) { 250 public void visitDefault(Object o) {
215 logger.warn("received unexpected message from core: {}", o.getClass()); 251 logger.warn("received unexpected message from core: {}", o.getClass());
216 client.receive(RelativeTime.FOREVER, this);
217 } 252 }
218 253
219 @Override 254 @Override
@@ -222,6 +257,16 @@ public class Core {
222 } 257 }
223 } 258 }
224 259
260 public Core(Configuration cfg) {
261 client = new Client("core", cfg);
262 requestQueue = new RequestQueue(client, new CoreReceiver());
263 }
264
265 public void init(InitCallback initCallback) {
266 this.initCallback = initCallback;
267 requestQueue.sendNext(new InitRequest());
268 }
269
225 /** 270 /**
226 * Ask the core to call "notify" once it is ready to transmit the 271 * Ask the core to call "notify" once it is ready to transmit the
227 * given number of bytes to the specified "target". Must only be 272 * given number of bytes to the specified "target". Must only be
@@ -229,171 +274,89 @@ public class Core {
229 * established (and the client has been informed about this). 274 * established (and the client has been informed about this).
230 * 275 *
231 * @param priority how important is the message? 276 * @param priority how important is the message?
232 * @param maxdelay maximum time until transmitter gets called 277 * @param maxdelay how long can the message wait?
233 * @param target the identity of the receiver 278 * @param target the identity of the receiver
234 * @param size the size of the message we want to transmit 279 * @param size the size of the message we want to transmit
235 * @param transmitter called once the core service is ready to send message 280 * @param transmitter called once the core service is ready to send message
236 * @return a handle to cancel the notification 281 * @return a handle to cancel the notification
237 */ 282 */
238 public Cancelable notifyTransmitReady(long priority, RelativeTime maxdelay, 283 public Cancelable notifyTransmitReady(int priority, RelativeTime maxdelay,
239 PeerIdentity target, int size, final MessageTransmitter transmitter) { 284 PeerIdentity target, int size, final MessageTransmitter transmitter) {
240 if (!connectedPeers.containsKey(target)) { 285 NotifyTransmitReadyRequest notifyRequest = new NotifyTransmitReadyRequest();
241 throw new AssertionError("trying to send message to unconnected peer"); 286 notifyRequest.priority = priority;
242 } 287 notifyRequest.deadline = maxdelay.toAbsolute();
288 notifyRequest.size = size;
289 notifyRequest.target = target;
290 notifyRequest.transmitter = transmitter;
243 291
244 ConnectedPeerInfo cpi = connectedPeers.get(target); 292 ConnectedPeerInfo cpi = connectedPeers.get(target);
245 293 if (cpi == null) {
246 final TransmitHandle transmitHandle = new TransmitHandle(); 294 throw new AssertionError("notifyTransmitReady called for unconnected peer");
247
248 transmitHandle.peerIdentity = target;
249 // add space for the header
250 transmitHandle.size = size + 4;
251 transmitHandle.smrId = cpi.nextSmrId;
252 transmitHandle.transmitter = transmitter;
253 cpi.nextSmrId += 1;
254 transmitHandle.deadline = maxdelay.toAbsolute();
255
256 cpi.requestsToPeer.put(transmitHandle.smrId, transmitHandle);
257
258 if (!maxdelay.isForever()) {
259 transmitHandle.timeoutHandle = Scheduler.addDelayed(maxdelay, new Scheduler.Task() {
260 @Override
261 public void run(Scheduler.RunContext ctx) {
262 transmitter.handleError();
263 }
264 });
265 } 295 }
266 296
267 // todo: add so that 'pending' is ordered by maxdelay 297 notifyRequest.smrId = cpi.nextSmrId;
268 pending.add(transmitHandle); 298 cpi.nextSmrId++;
269 299
270 transmitPending(); 300 cpi.requestsToPeer.put(notifyRequest.smrId, notifyRequest);
271 301
272 return new Cancelable() { 302 System.out.println("core notifyTransmitReady");
273 @Override
274 public void cancel() {
275 pending.remove(transmitHandle);
276 if (transmitHandle.timeoutHandle != null) {
277 transmitHandle.timeoutHandle.cancel();
278 }
279 }
280 };
281 303
282 304
305 return requestQueue.add(notifyRequest);
283 } 306 }
284 307
285 /**
286 * Send the next message to core.
287 */
288 private void transmitPending() {
289 // todo: check if not connected, connect then first!
290 if (currentClientTransmitHandle != null) {
291 logger.info("returning");
292 return;
293 }
294
295 final TransmitHandle transmitHandle = pending.poll();
296 if (transmitHandle != null) {
297 currentClientTransmitHandle = client.notifyTransmitReady(RelativeTime.FOREVER, false,
298 0, new MessageTransmitter() {
299 @Override
300 public void transmit(Connection.MessageSink sink) {
301 currentClientTransmitHandle = null;
302
303 SendMessageRequest request = new SendMessageRequest();
304 request.peer = transmitHandle.peerIdentity;
305 request.priority = 0;
306 request.queueSize = 5;
307 request.smrId = transmitHandle.smrId;
308 request.size = transmitHandle.size;
309
310 request.deadline = transmitHandle.deadline.asMessage();
311
312 sink.send(request);
313
314 transmitPending();
315 }
316
317 @Override
318 public void handleError() {
319 logger.error("error in SendMessageTransmitter");
320 transmitPending();
321 }
322 });
323
324 return;
325 }
326 308
327 final SendMessage sm = approvedSendMessages.poll(); 309 public void observeOutboundHeaders(HeaderNotify h) {
328 if (sm != null) { 310 this.notifyOutboundHeaders = h;
329 currentClientTransmitHandle = client.notifyTransmitReady(RelativeTime.FOREVER, false, 311 }
330 0, new MessageTransmitter() {
331 @Override
332 public void transmit(Connection.MessageSink sink) {
333 currentClientTransmitHandle = null;
334 sink.send(sm);
335 logger.info("transmitted SendMessage!");
336 transmitPending();
337 }
338 312
339 @Override 313 public void observeInboundHeaders(HeaderNotify h) {
340 public void handleError() { 314 this.notifyInboundHeaders = h;
341 throw new AssertionError("unexpected");
342 }
343 });
344 return;
345 }
346 logger.info("transmitPending did nothing");
347 } 315 }
348 316
317 public void observeInboundMessages(MessageNotify h) {
318 this.notifyInboundMessages = h;
319 }
349 320
350 public void observeOutboundHeaders(HeaderNotify h) { 321 public void observeOutboundMessages(MessageNotify h) {
322 this.notifyOutboundMessages = h;
351 } 323 }
352 324
353 public void observeConnect(ConnectHandler connectHandler) { 325 public void observeConnect(ConnectHandler connectHandler) {
354 this.connectHandler = connectHandler; 326 this.connectHandler = connectHandler;
355 } 327 }
356 328
329 public void observeDisconnect(DisconnectHandler disconnectHandler) {
330 this.disconnectHandler = disconnectHandler;
331 }
357 332
358 public void handleMessages(Runabout runabout) { 333 /**
334 * Handle all incoming messages with the specified runabout.
335 * Has to be called before init.
336 */
337 public void setMessageHandler(Runabout runabout) {
359 if (messageHandler != null) { 338 if (messageHandler != null) {
360 throw new AssertionError("Core can have only on message handler"); 339 throw new AssertionError("Core can have only on message handler");
361 } 340 }
341 if (client.isConnected()) {
342 // todo: shouldn't we just reconnect?
343 throw new AssertionError("can set message handler only if not yet connected");
344 }
362 messageHandler = runabout; 345 messageHandler = runabout;
363 interested = getRunaboutMessageTypes(runabout); 346 interested = RunaboutUtil.getRunaboutMessageTypes(runabout);
347 System.out.println("message types:");
348 for (int i : interested) {
349 System.out.println(i);
350 }System.out.println("message types end");
364 } 351 }
365 352
366 /** 353 /**
367 * Disconnect from the core service. This function can only 354 * Disconnect from the core service. This function can only
368 * be called *after* all pending notifyTransmitReady 355 * be called *after* all pending notifyTransmitReady
369 * requests have been explicitly cancelled. 356 * requests have been explicitly cancelled.
370 */ 357 */
371 public void disconnect() { 358 public void disconnect() {
372 359 requestQueue.destroy();
373 } 360 client.disconnect();
374
375
376 private static ArrayList<Class> getRunaboutVisitees(Runabout r) {
377 Class rc = r.getClass();
378 ArrayList<Class> ret = new ArrayList<Class>(5);
379 for (Method m : rc.getMethods()) {
380 if (!(m.getName().equals("visit") && m.getParameterTypes().length == 1)) {
381 continue;
382 }
383 ret.add(m.getParameterTypes()[0]);
384 }
385 return ret;
386 }
387
388
389 @SuppressWarnings("unchecked")
390 // todo: where to put this?
391 private static int[] getRunaboutMessageTypes(Runabout r) {
392 ArrayList<Class> visitees = getRunaboutVisitees(r);
393 int[] msgtypes = new int[visitees.size()];
394 for (int i = 0; i < visitees.size(); ++i) {
395 msgtypes[i] = MessageLoader.getUnionTag(GnunetMessage.Body.class, visitees.get(i));
396 }
397 return msgtypes;
398 } 361 }
399} 362}
diff --git a/src/org/gnunet/core/InitMessage.java b/src/org/gnunet/core/InitMessage.java
index f76d043..5546088 100644
--- a/src/org/gnunet/core/InitMessage.java
+++ b/src/org/gnunet/core/InitMessage.java
@@ -28,6 +28,15 @@ import org.gnunet.util.GnunetMessage;
28 28
29@UnionCase(64) 29@UnionCase(64)
30public class InitMessage implements GnunetMessage.Body { 30public class InitMessage implements GnunetMessage.Body {
31 /*
32 * Options used to tell core what kind of traffic notify messages we are interested in.
33 */
34 private final static int
35 OPTION_FULL_INBOUND = 8,
36 OPTION_HDR_INBOUND = 16,
37 OPTION_FULL_OUTBOUND = 32,
38 OPTION_HDR_OUTBOUND = 64;
39
31 @UInt32 40 @UInt32
32 public long options; 41 public long options;
33 42
diff --git a/src/org/gnunet/core/NotifyInboundTrafficMessage.java b/src/org/gnunet/core/NotifyInboundTrafficMessage.java
index 970a4ff..24df262 100644
--- a/src/org/gnunet/core/NotifyInboundTrafficMessage.java
+++ b/src/org/gnunet/core/NotifyInboundTrafficMessage.java
@@ -44,9 +44,15 @@ public class NotifyInboundTrafficMessage implements GnunetMessage.Body {
44 @VariableSizeArray(lengthField = "ats_count") 44 @VariableSizeArray(lengthField = "ats_count")
45 public ATSInformation[] atsRest; 45 public ATSInformation[] atsRest;
46 46
47
47 @NestedMessage(newFrame = true) 48 @NestedMessage(newFrame = true)
48 public GnunetMessage.Header payloadHeader; 49 public GnunetMessage.Header payloadHeader;
49 50
50 @Union(tag = "payloadHeader.messageType", optional = true) 51 /**
51 public GnunetMessage.Body payloadBody; 52 * The (optional) message body corresponding to payloadHeader.
53 * Not typed as GnunetMessage.Body because the message type may not be known by this
54 * peer.
55 */
56 @ByteFill
57 public byte[] payloadBody;
52} 58}
diff --git a/src/org/gnunet/core/NotifyOutboundTrafficMessage.java b/src/org/gnunet/core/NotifyOutboundTrafficMessage.java
index 3e66685..f2080e6 100644
--- a/src/org/gnunet/core/NotifyOutboundTrafficMessage.java
+++ b/src/org/gnunet/core/NotifyOutboundTrafficMessage.java
@@ -47,6 +47,12 @@ public class NotifyOutboundTrafficMessage implements GnunetMessage.Body {
47 @NestedMessage(newFrame = true) 47 @NestedMessage(newFrame = true)
48 public GnunetMessage.Header payloadHeader; 48 public GnunetMessage.Header payloadHeader;
49 49
50 @Union(tag = "payloadHeader.messageType", optional = true) 50 /**
51 public GnunetMessage.Body payloadBody; 51 * The (optional) message body corresponding to payloadHeader.
52 * Not typed as GnunetMessage.Body because the message type may not be known by this
53 * peer.
54 */
55 @ByteFill
56 public byte[] payloadBody;
57
52} 58}
diff --git a/src/org/gnunet/statistics/Statistics.java b/src/org/gnunet/statistics/Statistics.java
index a657053..5f3af59 100644
--- a/src/org/gnunet/statistics/Statistics.java
+++ b/src/org/gnunet/statistics/Statistics.java
@@ -48,7 +48,7 @@ public class Statistics {
48 /** 48 /**
49 * Time after we give up on setting values in statistics 49 * Time after we give up on setting values in statistics
50 */ 50 */
51 private static final RelativeTime SET_TIMEOUT = RelativeTime.SECOND.multiply(5); 51 private static final RelativeTime SET_TIMEOUT = RelativeTime.SECOND.multiply(10);
52 52
53 private final static int SETFLAG_RELATIVE = 1; 53 private final static int SETFLAG_RELATIVE = 1;
54 private final static int SETFLAG_PERSIST = 2; 54 private final static int SETFLAG_PERSIST = 2;
@@ -69,7 +69,7 @@ public class Statistics {
69 /** 69 /**
70 * List of all watch requests, canceled watch requests are null (but stay due to protocol limitations) 70 * List of all watch requests, canceled watch requests are null (but stay due to protocol limitations)
71 */ 71 */
72 ArrayList<StatisticsWatchRequest> watchRequests = new ArrayList<StatisticsWatchRequest>(); 72 private ArrayList<StatisticsWatchRequest> watchRequests = new ArrayList<StatisticsWatchRequest>();
73 73
74 /** 74 /**
75 * A request to the statistics service. 75 * A request to the statistics service.
@@ -199,7 +199,9 @@ public class Statistics {
199 199
200 public class StatisticsMessageReceiver extends RunaboutMessageReceiver { 200 public class StatisticsMessageReceiver extends RunaboutMessageReceiver {
201 public void visit(GetResponseMessage m) { 201 public void visit(GetResponseMessage m) {
202 currentGetReceiver.onReceive(m.subsystemName, m.statisticName, m.value); 202 StatisticsReceiver tmp = currentGetReceiver;
203 currentGetReceiver = null;
204 tmp.onReceive(m.subsystemName, m.statisticName, m.value);
203 } 205 }
204 206
205 public void visit(GetResponseEndMessage m) { 207 public void visit(GetResponseEndMessage m) {
diff --git a/src/org/gnunet/util/Client.java b/src/org/gnunet/util/Client.java
index 70f7eaa..4964e4e 100644
--- a/src/org/gnunet/util/Client.java
+++ b/src/org/gnunet/util/Client.java
@@ -175,9 +175,7 @@ public class Client {
175 connection.disconnect(); 175 connection.disconnect();
176 } 176 }
177 177
178 @Override 178 public boolean isConnected() {
179 protected void finalize() throws Throwable { 179 return connection.isConnected();
180 super.finalize();
181 disconnect();
182 } 180 }
183} 181}
diff --git a/src/org/gnunet/util/Configuration.java b/src/org/gnunet/util/Configuration.java
index 737802a..bd2c545 100644
--- a/src/org/gnunet/util/Configuration.java
+++ b/src/org/gnunet/util/Configuration.java
@@ -20,8 +20,9 @@
20 20
21package org.gnunet.util; 21package org.gnunet.util;
22 22
23import org.apache.commons.io.FileUtils; 23import com.google.common.collect.HashBasedTable;
24import org.apache.commons.io.LineIterator; 24import com.google.common.collect.Table;
25import com.google.common.io.Files;
25import org.slf4j.Logger; 26import org.slf4j.Logger;
26import org.slf4j.LoggerFactory; 27import org.slf4j.LoggerFactory;
27 28
@@ -29,6 +30,7 @@ import java.io.BufferedWriter;
29import java.io.File; 30import java.io.File;
30import java.io.FileWriter; 31import java.io.FileWriter;
31import java.io.IOException; 32import java.io.IOException;
33import java.nio.charset.Charset;
32import java.util.*; 34import java.util.*;
33import java.util.regex.Matcher; 35import java.util.regex.Matcher;
34import java.util.regex.Pattern; 36import java.util.regex.Pattern;
@@ -56,8 +58,9 @@ public class Configuration {
56 private static Pattern tag = Pattern.compile("(\\S+?)\\s*=(.*?)"); 58 private static Pattern tag = Pattern.compile("(\\S+?)\\s*=(.*?)");
57 private static Pattern whitspace = Pattern.compile("\\s*"); 59 private static Pattern whitspace = Pattern.compile("\\s*");
58 60
59 private final Map<String, Map<String, String>> sections = new LinkedHashMap<String, Map<String, String>>(100); 61 // rows are sections, colums are options
60 62 private final Table<String, String, String> sections = HashBasedTable.create();
63
61 private final Map<String, Set<String>> sectionSources = new HashMap<String, Set<String>>(20); 64 private final Map<String, Set<String>> sectionSources = new HashMap<String, Set<String>>(20);
62 65
63 /** 66 /**
@@ -81,11 +84,8 @@ public class Configuration {
81 orig = orig.replace("$" + e.getKey(), e.getValue()); 84 orig = orig.replace("$" + e.getKey(), e.getValue());
82 } 85 }
83 86
84 if (sections.containsKey("PATHS")) { 87 for (final Map.Entry<String, String> e : sections.row("PATHS").entrySet()) {
85 for (final Map.Entry<String, String> e : sections.get("PATHS") 88 orig = orig.replace("$" + e.getKey(), e.getValue());
86 .entrySet()) {
87 orig = orig.replace("$" + e.getKey(), e.getValue());
88 }
89 } 89 }
90 return orig; 90 return orig;
91 } 91 }
@@ -97,10 +97,7 @@ public class Configuration {
97 * @return an unmodifiable view of the section. 97 * @return an unmodifiable view of the section.
98 */ 98 */
99 public Map<String, String> getSection(String s) { 99 public Map<String, String> getSection(String s) {
100 Map<String, String> m = sections.get(s); 100 Map<String, String> m = sections.row(s);
101 if (m == null) {
102 throw new ParsingError("configuration section not found");
103 }
104 return Collections.unmodifiableMap(m); 101 return Collections.unmodifiableMap(m);
105 } 102 }
106 103
@@ -110,7 +107,7 @@ public class Configuration {
110 * @return set of non-empty section names 107 * @return set of non-empty section names
111 */ 108 */
112 public Set<String> getSections() { 109 public Set<String> getSections() {
113 return sections.keySet(); 110 return sections.rowKeySet();
114 } 111 }
115 112
116 /** 113 /**
@@ -120,10 +117,9 @@ public class Configuration {
120 * @param option option of interest 117 * @param option option of interest
121 * @param choices list of legal values 118 * @param choices list of legal values
122 * @return matching value from choices 119 * @return matching value from choices
123 * @throws ParsingError
124 */ 120 */
125 public String getValueChoice(String section, String option, 121 public String getValueChoice(String section, String option,
126 Iterable<String> choices) { 122 Iterable<String> choices) {
127 String value = getValueString(section, option); 123 String value = getValueString(section, option);
128 if (value == null) { 124 if (value == null) {
129 throw new ParsingError(String.format( 125 throw new ParsingError(String.format(
@@ -144,7 +140,7 @@ public class Configuration {
144 * Get a configuration value that should be a number 140 * Get a configuration value that should be a number
145 * 141 *
146 * @param section section of interest 142 * @param section section of interest
147 * @param option option of interest 143 * @param option option of interest
148 * @return null if value not in configuration, the option's value otherwise 144 * @return null if value not in configuration, the option's value otherwise
149 */ 145 */
150 public long getValueNumer(String section, String option) { 146 public long getValueNumer(String section, String option) {
@@ -161,7 +157,7 @@ public class Configuration {
161 + section + " option " + option + ": " + e.getMessage(), e); 157 + section + " option " + option + ": " + e.getMessage(), e);
162 } 158 }
163 } 159 }
164 160
165 private void logSectionSources(String section) { 161 private void logSectionSources(String section) {
166 Set<String> sources = sectionSources.get(section); 162 Set<String> sources = sectionSources.get(section);
167 if (sources == null) { 163 if (sources == null) {
@@ -175,14 +171,14 @@ public class Configuration {
175 * Set an option to a string value in a section. 171 * Set an option to a string value in a section.
176 * 172 *
177 * @param section section of interest 173 * @param section section of interest
178 * @param option option of interest 174 * @param option option of interest
179 * @throws ParsingError
180 * @return value 175 * @return value
181 */ 176 */
182 public String getValueString(String section, String option) { 177 public String getValueString(String section, String option) {
183 ensureSectionExists(section); 178 ensureSectionExists(section);
184 return sections.get(section).get(option); 179 return sections.get(section, option);
185 } 180 }
181
186 /** 182 /**
187 * Gets a configuration value that should be in a set of {"YES","NO"}. 183 * Gets a configuration value that should be in a set of {"YES","NO"}.
188 * 184 *
@@ -213,7 +209,6 @@ public class Configuration {
213 throw new ParsingError( 209 throw new ParsingError(
214 "Configuration error: value not recognized as YES or NO"); 210 "Configuration error: value not recognized as YES or NO");
215 } 211 }
216
217 212
218 /** 213 /**
219 * Tests if we have a value for a particular option. 214 * Tests if we have a value for a particular option.
@@ -223,8 +218,7 @@ public class Configuration {
223 * @return true if so, false of not 218 * @return true if so, false of not
224 */ 219 */
225 public boolean haveValue(String section, String option) { 220 public boolean haveValue(String section, String option) {
226 return sections.containsKey(section) 221 return sections.contains(section, option);
227 && sections.get(section).containsKey(option);
228 } 222 }
229 223
230 /** 224 /**
@@ -232,59 +226,57 @@ public class Configuration {
232 * configuration environment. 226 * configuration environment.
233 * 227 *
234 * @param filename name of the configuration file 228 * @param filename name of the configuration file
235 * @throws ParsingError
236 */ 229 */
237 public void parse(String filename) { 230 public void parse(String filename) {
238 filename = replaceHome(filename); 231 filename = replaceHome(filename);
239 232
240 String current_section = ""; 233 String current_section = "";
241 234
242 LineIterator it; 235 Iterator<String> it;
236
243 try { 237 try {
244 it = FileUtils.lineIterator(new File(filename)); 238 List<String> lines = Files.readLines(new File(filename), Charset.defaultCharset());
239 it = lines.iterator();
245 } catch (IOException e) { 240 } catch (IOException e) {
246 throw new ParsingError("Cannot read configuration file '" + filename+ "'"); 241 throw new ParsingError("Cannot read configuration file '" + filename + "'");
247 } 242 }
248 243
249 int lineNumer = 1; 244 int lineNumer = 1;
250 245
251 try { 246 while (it.hasNext()) {
252 while (it.hasNext()) { 247 String line = it.next();
253 String line = it.nextLine(); 248 // strip comment
254 // strip comment 249 line = line.split("#")[0];
255 line = line.split("#")[0]; 250 Matcher m;
256 Matcher m; 251
257 252 if ((m = tag.matcher(line)).matches()) {
258 if ((m=tag.matcher(line)).matches()) { 253 String option = m.group(1).trim();
259 String option = m.group(1).trim(); 254 String value = m.group(2).trim();
260 String value = m.group(2).trim(); 255
261 256 if (value.length() != 0 && value.charAt(0) == '"') {
262 if (value.length() != 0 && value.charAt(0) == '"') { 257 int pos = value.indexOf('"', 1);
263 int pos = value.indexOf('"', 1); 258 if (pos == -1) {
264 if (pos == -1) { 259 logger.warn("incorrecly quoted config value");
265 logger.warn("incorrecly quoted config value"); 260 continue;
266 continue;
267 }
268 value = value.substring(1, pos);
269 } 261 }
270 setValueString(current_section, option, value); 262 value = value.substring(1, pos);
271 } else if ((m=section.matcher(line)).matches()) { 263 }
272 current_section = m.group(1).trim(); 264 setValueString(current_section, option, value);
273 if (sectionSources.containsKey(current_section)) { 265 } else if ((m = section.matcher(line)).matches()) {
274 sectionSources.get(current_section).add(filename); 266 current_section = m.group(1).trim();
275 } else { 267 if (sectionSources.containsKey(current_section)) {
276 sectionSources.put(current_section, new HashSet<String>(Collections.singleton(filename))); 268 sectionSources.get(current_section).add(filename);
277 }
278 } else if (whitspace.matcher(line).matches()) {
279 // whitespace is ok
280 } else { 269 } else {
281 logger.warn(String.format("skipped unreadable line %s in configuration file '%s': '%s'", lineNumer, filename, line)); 270 sectionSources.put(current_section, new HashSet<String>(Collections.singleton(filename)));
282 } 271 }
283 272 } else if (whitspace.matcher(line).matches()) {
284 lineNumer++; 273 // whitespace is ok
274 } else {
275 logger.warn(String.format("skipped unreadable line %s in configuration file '%s': '%s'", lineNumer,
276 filename, line));
285 } 277 }
286 } finally { 278
287 it.close(); 279 lineNumer++;
288 } 280 }
289 } 281 }
290 282
@@ -297,16 +289,15 @@ public class Configuration {
297 * Remove the given section and all options in it. 289 * Remove the given section and all options in it.
298 */ 290 */
299 public void removeSection(String section) { 291 public void removeSection(String section) {
300 sections.remove(section); 292 sections.row(section).clear();
301 } 293 }
302 294
303
304 /** 295 /**
305 * Set an option to a string value in a section. 296 * Set an option to a string value in a section.
306 * 297 *
307 * @param section section of interest 298 * @param section section of interest
308 * @param option option of interest 299 * @param option option of interest
309 * @param value value to set 300 * @param value value to set
310 */ 301 */
311 public void setValueNumber(String section, String option, 302 public void setValueNumber(String section, String option,
312 long value) { 303 long value) {
@@ -317,33 +308,26 @@ public class Configuration {
317 * Set an option to a string value in a section. 308 * Set an option to a string value in a section.
318 * 309 *
319 * @param section section of interest 310 * @param section section of interest
320 * @param option option of interest 311 * @param option option of interest
321 * @param value value to set 312 * @param value value to set
322 */ 313 */
323 public void setValueString(String section, String option, 314 public void setValueString(String section, String option,
324 String value) { 315 String value) {
325 Map<String, String> table = sections.get(section); 316 sections.put(section, option, value);
326 if (table == null) {
327 table = new LinkedHashMap<String, String>();
328 sections.put(section, table);
329 }
330 table.put(option, value);
331 } 317 }
332 318
333 /** 319 /**
334 * Write configuration file. 320 * Write configuration file.
335 * 321 *
336 * @param filename where to write the configuration 322 * @param filename where to write the configuration
337 * @throws IOException
338 */ 323 */
339 public void write(String filename) throws IOException { 324 public void write(String filename) throws IOException {
340 BufferedWriter w = new BufferedWriter(new FileWriter(new File( 325 BufferedWriter w = new BufferedWriter(new FileWriter(new File(
341 filename))); 326 filename)));
342 for (Map.Entry<String, Map<String, String>> s : sections 327 for (String section : sections.rowKeySet()) {
343 .entrySet()) { 328 w.write("["+section+"]");
344 w.write(s.getKey());
345 w.newLine(); 329 w.newLine();
346 for (Map.Entry<String, String> e : s.getValue().entrySet()) { 330 for (Map.Entry<String,String> e : sections.row(section).entrySet()) {
347 w.write(e.getKey() + " = " + e.getValue()); 331 w.write(e.getKey() + " = " + e.getValue());
348 w.newLine(); 332 w.newLine();
349 } 333 }
@@ -370,10 +354,10 @@ public class Configuration {
370 } 354 }
371 } 355 }
372 } 356 }
373 357
374 private void ensureSectionExists(String section) { 358 private void ensureSectionExists(String section) {
375 if (!sections.containsKey(section)) { 359 if (!sections.containsRow(section)) {
376 throw new ConfigurationException("Required section '"+section+"' not in configuration"); 360 throw new ConfigurationException("Required section '" + section + "' not in configuration");
377 } 361 }
378 } 362 }
379 363
diff --git a/src/org/gnunet/util/Connection.java b/src/org/gnunet/util/Connection.java
index f78101b..602c81e 100644
--- a/src/org/gnunet/util/Connection.java
+++ b/src/org/gnunet/util/Connection.java
@@ -49,7 +49,6 @@ public class Connection {
49 49
50 private Iterable<AddressProbe> addressProbes = null; 50 private Iterable<AddressProbe> addressProbes = null;
51 51
52
53 /** 52 /**
54 * The task that is currently used by the resolve mechanism. 53 * The task that is currently used by the resolve mechanism.
55 */ 54 */
@@ -169,16 +168,6 @@ public class Connection {
169 receiver.handleError(); 168 receiver.handleError();
170 return; 169 return;
171 } 170 }
172 // todo: this was most probably wrong, revise it!
173 /*
174 if (n == 0) {
175 logger.info("service gracefully disconnected us");
176 connectionChannel.close();
177 connectionChannel = null;
178 receiver.handleError();
179 return;
180 }
181 */
182 logger.debug(String.format("connectionChannel read %s bytes", n)); 171 logger.debug(String.format("connectionChannel read %s bytes", n));
183 } catch (IOException e) { 172 } catch (IOException e) {
184 logger.error("read failed with exception:", e); 173 logger.error("read failed with exception:", e);
@@ -267,6 +256,7 @@ public class Connection {
267 256
268 @Override 257 @Override
269 public void run(Scheduler.RunContext ctx) { 258 public void run(Scheduler.RunContext ctx) {
259 this.transmitTask = null;
270 try { 260 try {
271 int n = connectionChannel.write(transmitBuffer); 261 int n = connectionChannel.write(transmitBuffer);
272 logger.debug("connectionChannel has written " + n + " bytes"); 262 logger.debug("connectionChannel has written " + n + " bytes");
@@ -279,8 +269,11 @@ public class Connection {
279 currentTransmitHelper = null; 269 currentTransmitHelper = null;
280 } else { 270 } else {
281 currentTransmitHelper = nextTransmitHelper; 271 currentTransmitHelper = nextTransmitHelper;
282 nextTransmitHelper.start(); 272 // we need to to this so the transmit callback can do notifyTransmitReady
273 TransmitHelper tmpTransmitHelper = nextTransmitHelper;
283 nextTransmitHelper = null; 274 nextTransmitHelper = null;
275 tmpTransmitHelper.start();
276
284 } 277 }
285 } else { 278 } else {
286 schedule(); 279 schedule();
@@ -297,7 +290,6 @@ public class Connection {
297 transmitter.transmit(TransmitHelper.this); 290 transmitter.transmit(TransmitHelper.this);
298 transmitBuffer.flip(); 291 transmitBuffer.flip();
299 schedule(); 292 schedule();
300
301 } 293 }
302 294
303 private void schedule() { 295 private void schedule() {
@@ -528,6 +520,7 @@ public class Connection {
528 public void disconnect() { 520 public void disconnect() {
529 if (disconnected) { 521 if (disconnected) {
530 logger.warn("disconnect called twice"); 522 logger.warn("disconnect called twice");
523 Thread.dumpStack();
531 } 524 }
532 disconnected = true; 525 disconnected = true;
533 526
@@ -536,6 +529,11 @@ public class Connection {
536 nextTransmitHelper.cancel(); 529 nextTransmitHelper.cancel();
537 nextTransmitHelper = null; 530 nextTransmitHelper = null;
538 } 531 }
532 if (currentTransmitHelper != null) {
533 currentTransmitHelper.cancel();
534 currentTransmitHelper = null;
535 }
536
539 if (currentReceiveHelper != null) { 537 if (currentReceiveHelper != null) {
540 currentReceiveHelper.cancel(); 538 currentReceiveHelper.cancel();
541 currentReceiveHelper = null; 539 currentReceiveHelper = null;
@@ -560,9 +558,4 @@ public class Connection {
560 558
561 } 559 }
562 560
563 @Override
564 protected void finalize() throws Throwable {
565 super.finalize();
566 disconnect();
567 }
568} 561}
diff --git a/src/org/gnunet/util/Program.java b/src/org/gnunet/util/Program.java
index 9892fd3..b638ac9 100644
--- a/src/org/gnunet/util/Program.java
+++ b/src/org/gnunet/util/Program.java
@@ -91,11 +91,21 @@ public abstract class Program {
91 optParser = new Parser(this); 91 optParser = new Parser(this);
92 unprocessedArgs = optParser.parse(args); 92 unprocessedArgs = optParser.parse(args);
93 93
94 org.apache.log4j.Logger rootLogger = LogManager.getRootLogger(); 94 configureLogging(logLevel, logFile);
95
96 cfg.loadDefaults();
97
98 if (cfgFileName != null) {
99 cfg.parse(cfgFileName);
100 }
101
102 Resolver.getInstance().setConfiguration(cfg);
103 }
95 104
105 public static void configureLogging(String logLevel, String logFile) {
106 org.apache.log4j.Logger rootLogger = LogManager.getRootLogger();
96 107
97 // category: 2 levels 108 // %c{2}: category 2 levels
98 //
99 Layout layout = new PatternLayout("%d{dd MMM yyyy HH:mm:ss-SSS} %c{2} %p: %m%n"); 109 Layout layout = new PatternLayout("%d{dd MMM yyyy HH:mm:ss-SSS} %c{2} %p: %m%n");
100 110
101 if (logFile == null) { 111 if (logFile == null) {
@@ -112,7 +122,6 @@ public abstract class Program {
112 rootLogger.addAppender(appender); 122 rootLogger.addAppender(appender);
113 } 123 }
114 } 124 }
115
116 if (logLevel == null) { 125 if (logLevel == null) {
117 rootLogger.setLevel(Level.INFO); 126 rootLogger.setLevel(Level.INFO);
118 } else if (logLevel.equalsIgnoreCase("debug")) { 127 } else if (logLevel.equalsIgnoreCase("debug")) {
@@ -129,18 +138,6 @@ public abstract class Program {
129 rootLogger.setLevel(Level.INFO); 138 rootLogger.setLevel(Level.INFO);
130 logger.info("unknown log level '{}'; defaulting to INFO", logLevel); 139 logger.info("unknown log level '{}'; defaulting to INFO", logLevel);
131 } 140 }
132
133
134
135 cfg.loadDefaults();
136
137 if (cfgFileName != null) {
138 logger.debug("loading extra config file");
139 cfg.parse(cfgFileName);
140 }
141
142
143 Resolver.getInstance().setConfiguration(cfg);
144 } 141 }
145 142
146 /** 143 /**
@@ -164,7 +161,7 @@ public abstract class Program {
164 /** 161 /**
165 * Start the Program as the initial task of the Scheduler. 162 * Start the Program as the initial task of the Scheduler.
166 */ 163 */
167 public void start() { 164 public final void start() {
168 if (showVersion) { 165 if (showVersion) {
169 System.out.println(makeVersionDescription()); 166 System.out.println(makeVersionDescription());
170 } else if (printHelp) { 167 } else if (printHelp) {
diff --git a/src/org/gnunet/util/RequestQueue.java b/src/org/gnunet/util/RequestQueue.java
index fc22e88..2ee0e8d 100644
--- a/src/org/gnunet/util/RequestQueue.java
+++ b/src/org/gnunet/util/RequestQueue.java
@@ -26,6 +26,7 @@ import java.util.LinkedList;
26 * Generic queues for Requests to be sent to the service. 26 * Generic queues for Requests to be sent to the service.
27 */ 27 */
28public class RequestQueue { 28public class RequestQueue {
29 // todo: implement more efficiently (attributes instead of multiple queues)
29 30
30 /** 31 /**
31 * Requests to be transmitted to the service. 32 * Requests to be transmitted to the service.
@@ -139,7 +140,7 @@ public class RequestQueue {
139 } 140 }
140 141
141 private void handleReceive() { 142 private void handleReceive() {
142 if (currentReceive != null || destroyed) { 143 if (currentReceive != null || destroyed || !client.isConnected()) {
143 return; 144 return;
144 } 145 }
145 currentReceive = client.receive(RelativeTime.FOREVER, new MessageReceiver() { 146 currentReceive = client.receive(RelativeTime.FOREVER, new MessageReceiver() {
@@ -188,12 +189,20 @@ public class RequestQueue {
188 189
189 /** 190 /**
190 * Add a message to the queue that will be sent before all other messages in the queue. 191 * Add a message to the queue that will be sent before all other messages in the queue.
191 * @return
192 */ 192 */
193 // should this really be cancelable? 193 // should this really be cancelable?
194 public Cancelable sendNext(final Request request) { 194 public Cancelable sendNext(final Request request) {
195 // todo 195 requestsAwaitingTransmit.addFirst(request);
196 return null; 196 handleNextTransmit();
197 return new Cancelable() {
198 @Override
199 public void cancel() {
200 RequestQueue.this.requestsAwaitingTransmit.remove(request);
201 RequestQueue.this.persistentRequests.remove(request);
202 RequestQueue.this.allRequests.remove(request);
203 request.onCancel(!requestsAwaitingTransmit.contains(request));
204 }
205 };
197 } 206 }
198 207
199 /** 208 /**
diff --git a/src/org/gnunet/util/RunaboutUtil.java b/src/org/gnunet/util/RunaboutUtil.java
new file mode 100644
index 0000000..54c16e6
--- /dev/null
+++ b/src/org/gnunet/util/RunaboutUtil.java
@@ -0,0 +1,56 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23import org.gnunet.construct.MessageLoader;
24import org.grothoff.Runabout;
25
26import java.lang.reflect.Method;
27import java.util.ArrayList;
28
29
30/**
31 * Utility methods for the runabout.
32 */
33public class RunaboutUtil {
34 public static ArrayList<Class> getRunaboutVisitees(Runabout r) {
35 Class rc = r.getClass();
36 ArrayList<Class> ret = new ArrayList<Class>(5);
37 for (Method m : rc.getMethods()) {
38 if (!(m.getName().equals("visit") && m.getParameterTypes().length == 1)) {
39 continue;
40 }
41 ret.add(m.getParameterTypes()[0]);
42 }
43 return ret;
44 }
45
46 @SuppressWarnings("unchecked")
47 // todo: where to put this?
48 public static int[] getRunaboutMessageTypes(Runabout r) {
49 ArrayList<Class> visitees = getRunaboutVisitees(r);
50 int[] msgtypes = new int[visitees.size()];
51 for (int i = 0; i < visitees.size(); ++i) {
52 msgtypes[i] = MessageLoader.getUnionTag(GnunetMessage.Body.class, visitees.get(i));
53 }
54 return msgtypes;
55 }
56}
diff --git a/src/org/gnunet/util/Scheduler.java b/src/org/gnunet/util/Scheduler.java
index f2c81e8..632aa15 100644
--- a/src/org/gnunet/util/Scheduler.java
+++ b/src/org/gnunet/util/Scheduler.java
@@ -109,7 +109,7 @@ public class Scheduler {
109 } 109 }
110 110
111 /** 111 /**
112 * A TaskIdentifier represents a Task that will execute or has already been executed. 112 * A TaskConfiguration represents a Task that will execute or has already been executed.
113 */ 113 */
114 public static class TaskConfiguration implements Cancelable { 114 public static class TaskConfiguration implements Cancelable {
115 private final Task task; 115 private final Task task;
@@ -121,7 +121,8 @@ public class Scheduler {
121 private ArrayList<SelectableChannel> eventChannels = null; 121 private ArrayList<SelectableChannel> eventChannels = null;
122 private ArrayList<Integer> eventTypes = null; 122 private ArrayList<Integer> eventTypes = null;
123 123
124 private boolean finished = false; 124 private boolean hasRun = false;
125 private boolean isCanceled = false;
125 126
126 /** 127 /**
127 * Create a TaskIdentifier. 128 * Create a TaskIdentifier.
@@ -187,22 +188,25 @@ public class Scheduler {
187 } 188 }
188 189
189 private void run() { 190 private void run() {
190 if (finished) { 191 if (hasRun) {
191 throw new AssertionError("same task ran twice"); 192 throw new AssertionError("same task ran twice");
192 } 193 }
194 if (isCanceled) {
195 return;
196 }
193 TaskConfiguration old = activeTask; 197 TaskConfiguration old = activeTask;
194 activeTask = this; 198 activeTask = this;
195 task.run(ctx); 199 task.run(ctx);
196 finished = true; 200 hasRun = true;
197 activeTask = old; 201 activeTask = old;
198 } 202 }
199 203
200 public void cancel() { 204 public void cancel() {
201 if (!pending.contains(this)) { 205 if (isCanceled) {
202 throw new AssertionError("canceling task that is not scheduled"); 206 throw new AssertionError("task canceled twice");
203 } 207 }
208 isCanceled = true;
204 pending.remove(this); 209 pending.remove(this);
205 logger.debug(""+ pending.size() + "tasks remaining");
206 } 210 }
207 211
208 public Cancelable schedule() { 212 public Cancelable schedule() {
@@ -234,16 +238,16 @@ public class Scheduler {
234 } 238 }
235 } 239 }
236 240
237 public void selectRead(SocketChannel channel) { 241 public void selectRead(SelectableChannel channel) {
238 addChannelEvent(channel, EVENT_READ); 242 addChannelEvent(channel, EVENT_READ);
239 } 243 }
240 public void selectWrite(SocketChannel channel) { 244 public void selectWrite(SelectableChannel channel) {
241 addChannelEvent(channel, EVENT_WRITE); 245 addChannelEvent(channel, EVENT_WRITE);
242 } 246 }
243 public void selectConnect(SocketChannel channel) { 247 public void selectConnect(SelectableChannel channel) {
244 addChannelEvent(channel, EVENT_CONNECT); 248 addChannelEvent(channel, EVENT_CONNECT);
245 } 249 }
246 public void selectAccept(SocketChannel channel) { 250 public void selectAccept(SelectableChannel channel) {
247 addChannelEvent(channel, EVENT_ACCEPT); 251 addChannelEvent(channel, EVENT_ACCEPT);
248 } 252 }
249 } 253 }
@@ -438,7 +442,9 @@ public class Scheduler {
438 * @param initialTask the initial task to run immediately 442 * @param initialTask the initial task to run immediately
439 */ 443 */
440 public static void run(Task initialTask) { 444 public static void run(Task initialTask) {
441 addContinuation(initialTask, EnumSet.of(Reason.STARTUP)); 445 if (initialTask != null) {
446 addContinuation(initialTask, EnumSet.of(Reason.STARTUP));
447 }
442 448
443 // the gnunet main loop 449 // the gnunet main loop
444 while (checkLiveness()) { 450 while (checkLiveness()) {
diff --git a/src/org/gnunet/util/Server.java b/src/org/gnunet/util/Server.java
index d6a4290..8aa7c60 100644
--- a/src/org/gnunet/util/Server.java
+++ b/src/org/gnunet/util/Server.java
@@ -30,17 +30,17 @@ import java.nio.channels.ServerSocketChannel;
30import java.nio.channels.SocketChannel; 30import java.nio.channels.SocketChannel;
31import java.util.ArrayList; 31import java.util.ArrayList;
32import java.util.HashMap; 32import java.util.HashMap;
33import java.util.LinkedList;
33import java.util.List; 34import java.util.List;
34 35
35public class Server { 36public class Server {
36
37
38 private final RelativeTime idleTimeout; 37 private final RelativeTime idleTimeout;
39 private final boolean requireFound; 38 private final boolean requireFound;
40 private List<ServerSocketChannel> listenSockets; 39 private List<ServerSocketChannel> listenSockets;
41 private List<ClientHandle> clients; 40 private List<ClientHandle> clients;
42 41
43 private HashMap<Class, MessageRunabout> handlers; 42 private HashMap<Class, MessageRunabout> handlers;
43 private List<DisconnectHandler> disconnectHandlers = new LinkedList<DisconnectHandler>();
44 44
45 45
46 public class ClientHandle { 46 public class ClientHandle {
@@ -62,9 +62,9 @@ public class Server {
62 * Notify us when the server has enough space to transmit 62 * Notify us when the server has enough space to transmit
63 * a message of the given size to the given client. 63 * a message of the given size to the given client.
64 * 64 *
65 * @param size requested amount of buffer space 65 * @param size requested amount of buffer space
66 * @param timeout after how long should we give up (and call 66 * @param timeout after how long should we give up (and call
67 * notify with buf NULL and size 0)? 67 * notify with buf NULL and size 0)?
68 * @param transmitter callback 68 * @param transmitter callback
69 * @return a handle to cancel the notification 69 * @return a handle to cancel the notification
70 */ 70 */
@@ -76,7 +76,7 @@ public class Server {
76 * Resume receiving from this client, we are done processing the 76 * Resume receiving from this client, we are done processing the
77 * current request. This function must be called from within each 77 * current request. This function must be called from within each
78 * message handler (or its respective continuations). 78 * message handler (or its respective continuations).
79 * 79 * <p/>
80 * The server does not automatically continue to receive messages to 80 * The server does not automatically continue to receive messages to
81 * support flow control. 81 * support flow control.
82 * 82 *
@@ -144,9 +144,8 @@ public class Server {
144 * @param srv ... 144 * @param srv ...
145 */ 145 */
146 private void doAccept(final ServerSocketChannel srv) { 146 private void doAccept(final ServerSocketChannel srv) {
147 /* 147 Scheduler.TaskConfiguration b = new Scheduler.TaskConfiguration(RelativeTime.FOREVER,
148 Scheduler.TaskBuilder b = new Scheduler.TaskBuilder(); 148 new Scheduler.Task() {
149 b.withTask(new Scheduler.Task() {
150 @Override 149 @Override
151 public void run(Scheduler.RunContext ctx) { 150 public void run(Scheduler.RunContext ctx) {
152 try { 151 try {
@@ -159,9 +158,8 @@ public class Server {
159 doAccept(srv); 158 doAccept(srv);
160 } 159 }
161 }); 160 });
162 b.withSelectAccept(srv); 161 b.selectAccept(srv);
163 Scheduler.add(b); 162 b.schedule();
164 */
165 } 163 }
166 164
167 165
@@ -214,13 +212,16 @@ public class Server {
214 void onDisconnect(ClientHandle clientHandle); 212 void onDisconnect(ClientHandle clientHandle);
215 } 213 }
216 214
217 public Cancelable notifyDisconnect(DisconnectHandler disconnectHandler) { 215 public Cancelable notifyDisconnect(final DisconnectHandler disconnectHandler) {
218 return null; 216 this.disconnectHandlers.add(disconnectHandler);
217 return new Cancelable() {
218 @Override
219 public void cancel() {
220 Server.this.disconnectHandlers.remove(disconnectHandler);
221 }
222 };
219 } 223 }
220 224
221 /**
222 * Free resources held by this server.
223 */
224 public void destroy() { 225 public void destroy() {
225 226
226 } 227 }
diff --git a/src/org/gnunet/util/Service.java b/src/org/gnunet/util/Service.java
index ffbe779..a401655 100644
--- a/src/org/gnunet/util/Service.java
+++ b/src/org/gnunet/util/Service.java
@@ -37,7 +37,6 @@ public abstract class Service extends Program {
37 37
38 public final Server getServer() { 38 public final Server getServer() {
39 return s; 39 return s;
40
41 } 40 }
42 41
43 public final void stop() { 42 public final void stop() {
@@ -49,11 +48,4 @@ public abstract class Service extends Program {
49 */ 48 */
50 public abstract void run(); 49 public abstract void run();
51 50
52 /**
53 * Start the Program as the initial Task of the Scheduler.
54 */
55 public void start() {
56 System.out.println("bla");
57 super.start();
58 }
59} 51}
diff --git a/src/org/grothoff/Runabout.java b/src/org/grothoff/Runabout.java
index b187260..3e8261f 100644
--- a/src/org/grothoff/Runabout.java
+++ b/src/org/grothoff/Runabout.java
@@ -249,6 +249,9 @@ public class Runabout {
249 throw new RunaboutException("Could not create/load dynamic code!"); 249 throw new RunaboutException("Could not create/load dynamic code!");
250 } 250 }
251 } else { 251 } else {
252 if (!m.isAccessible()) {
253 m.setAccessible(true);
254 }
252 // invoke the visitor with an anonymous inner class, 255 // invoke the visitor with an anonymous inner class,
253 // allows for the runabout to be public as the method made accessible 256 // allows for the runabout to be public as the method made accessible
254 // by the Method instance. 257 // by the Method instance.
@@ -257,6 +260,7 @@ public class Runabout {
257 @Override 260 @Override
258 public void visit(Runabout r, Object o) { 261 public void visit(Runabout r, Object o) {
259 try { 262 try {
263
260 m.invoke(r, o); 264 m.invoke(r, o);
261 } catch (IllegalAccessException e) { 265 } catch (IllegalAccessException e) {
262 throw new RunaboutException(e.toString()); 266 throw new RunaboutException(e.toString());
diff --git a/test/org/gnunet/construct/ConstructTest.java b/test/org/gnunet/construct/ConstructTest.java
deleted file mode 100644
index 6cecd83..0000000
--- a/test/org/gnunet/construct/ConstructTest.java
+++ /dev/null
@@ -1,191 +0,0 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.construct;
22
23public class ConstructTest {
24 /*
25
26 @Test
27 public void test_ByteFillMessage() {
28
29 ByteFillMessage bfm = new ByteFillMessage();
30 bfm.header = new MessageHeader();
31 bfm.someValue = 42;
32 bfm.rest = new byte[] {1,2,3,4,5,6,7,100, 8};
33
34 Construct.patch(bfm);
35
36 bfm.header.messageSize = Construct.getSize(bfm);
37
38 bfm.header.messageType = 42;
39
40 System.out.println(bfm.header.messageSize);
41
42 byte[] data = Construct.toBinary(bfm);
43
44 Assert.assertEquals(Construct.getSize(bfm), data.length);
45
46 System.out.println("data size: " + data.length);
47
48 ByteFillMessage bfm2 = Construct.parseAs(ByteBuffer.wrap(data), ByteFillMessage.class);
49
50 Assert.assertArrayEquals(bfm.rest, bfm2.rest);
51 }
52
53
54 @Test
55 public void test_VarTestMessage() {
56 VarTestMessage vtm = new VarTestMessage();
57 vtm.length = 5;
58 vtm.msgs = new SimpleTestMessage2[5];
59 for (int i = 0; i < 5; ++i) {
60 vtm.msgs[i] = new SimpleTestMessage2();
61 vtm.msgs[i].value = i;
62 }
63
64 byte[] a = Construct.toBinary(vtm);
65
66 VarTestMessage vtm2 = Construct.parseAs(ByteBuffer.wrap(a), VarTestMessage.class);
67
68 Assert.assertEquals(vtm2.length, 5);
69 for (int i = 0; i < 5; ++i) {
70 Assert.assertEquals(vtm2.msgs[i].value, i);
71 }
72
73 }
74
75 @Test
76 public void test_SimpleTestMessage() {
77 SimpleTestMessage stm = new SimpleTestMessage();
78 stm.v1 = 20;
79 stm.v2 = 21;
80 stm.mn = new SimpleTestMessage2();
81 stm.mn.value = 42;
82 stm.mns = new SimpleTestMessage2[5];
83 for (int i = 0; i < stm.mns.length; i++) {
84 stm.mns[i] = new SimpleTestMessage2();
85 stm.mns[i].value = i;
86 }
87
88 byte[] a = Construct.toBinary(stm);
89 SimpleTestMessage stm2 = Construct.parseAs(ByteBuffer.wrap(a),
90 SimpleTestMessage.class);
91
92 Assert.assertEquals(stm.v1, stm2.v1);
93 Assert.assertEquals(stm.v2, stm2.v2);
94 Assert.assertEquals(stm.mn.value, stm2.mn.value);
95 Assert.assertEquals(stm.mns.length, stm2.mns.length);
96
97 for (int i = 0; i < stm.mns.length; i++) {
98 Assert.assertEquals(stm.mns[i].value, stm2.mns[i].value);
99 }
100
101 }
102
103 public static String toHex(byte[] bytes) {
104 BigInteger bi = new BigInteger(1, bytes);
105 return String.format("%0" + (bytes.length << 1) + "X", bi);
106 }
107
108 @Test
109 public void test_StringMessage() {
110 StringMessage strm = new StringMessage();
111 strm.num = 58;
112 strm.str = "ab";
113 strm.num2 = 80;
114
115 byte[] a = Construct.toBinary(strm);
116 StringMessage strm2 = Construct.parseAs(ByteBuffer.wrap(a), StringMessage.class);
117
118 for (byte b : a) {
119 System.out.print((char) b);
120 }
121
122 Assert.assertEquals(strm.num, strm2.num);
123 Assert.assertEquals(strm.num2, strm2.num2);
124 Assert.assertEquals(strm.str, strm2.str);
125
126 }
127
128 @Test
129 public void test_QueryMessage() {
130 QueryMessage qm = new QueryMessage();
131 qm.header = new MessageHeader();
132 qm.header.messageType = 0x42;
133 qm.query = 0x43;
134 qm.varsize = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
135 14, 15 };
136
137 Construct.patch(qm);
138
139 byte[] a = Construct.toBinary(qm);
140
141 Assert.assertEquals(a.length, qm.header.messageSize);
142
143 QueryMessage qm2 = Construct.parseAs(ByteBuffer.wrap(a), QueryMessage.class);
144
145 Assert.assertEquals(qm.header.messageSize, qm2.header.messageSize);
146 Assert.assertEquals(qm.header.messageType, qm2.header.messageType);
147 Assert.assertEquals(qm.query, qm2.query);
148
149 Assert.assertArrayEquals(qm.varsize, qm2.varsize);
150
151 }
152
153 @Test
154 public void test_SizeTestMessage() {
155 SizeTestMessage stm = new SizeTestMessage();
156 stm.someValue = 42;
157 stm.rest = new byte[] { 1, 2, 3, 4, 5 };
158
159 Construct.patch(stm);
160
161 byte[] a = Construct.toBinary(stm);
162
163 SizeTestMessage stm2 = Construct.parseAs(ByteBuffer.wrap(a), SizeTestMessage.class);
164
165 Assert.assertEquals(stm.someValue, stm2.someValue);
166 Assert.assertEquals(stm.totalSize, stm2.totalSize);
167
168 Assert.assertArrayEquals(stm.rest, stm2.rest);
169 }
170
171 @Test
172 public void test_MessageHeader() {
173 MessageHeader h1 = new MessageHeader();
174
175 h1.messageSize = 42;
176 h1.messageType = 52;
177
178 byte[] a = Construct.toBinary(h1);
179
180 MessageHeader h2 = Construct.parseAs(ByteBuffer.wrap(a), MessageHeader.class);
181
182 byte[] b = Construct.toBinary(h2);
183
184 Assert.assertArrayEquals(a, b);
185
186 Assert.assertEquals(h1.messageSize, h2.messageSize);
187 Assert.assertEquals(h1.messageType, h2.messageType);
188 }
189
190 */
191}
diff --git a/test/org/gnunet/construct/UnionTest.java b/test/org/gnunet/construct/UnionTest.java
deleted file mode 100644
index 02012f7..0000000
--- a/test/org/gnunet/construct/UnionTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.construct;
22
23
24import org.junit.Assert;
25import org.junit.Test;
26
27import java.nio.ByteBuffer;
28
29public class UnionTest {
30 public static interface TestUnion extends MessageUnion {}
31
32 @UnionCase(0)
33 public static class TestUnionCase0 implements TestUnion {
34 @Int8
35 public int val;
36 }
37
38 @UnionCase(1)
39 public static class TestUnionCase1 implements TestUnion{
40 @ZeroTerminatedString
41 public String str;
42 }
43
44 public static class UnionTestMessage implements Message {
45 @Int16
46 public int tag;
47 @Union(tag = "tag")
48 public TestUnion instance;
49 }
50
51
52
53 @Test
54 public void test_Union() {
55 UnionTestMessage utm = new UnionTestMessage();
56 utm.tag = 0;
57 utm.instance = new TestUnionCase0();
58 ((TestUnionCase0)utm.instance).val = 20;
59
60 byte[] a = Construct.toBinary(utm);
61
62 System.out.println(a.length);
63 System.out.println(Construct.getSize(utm));
64
65 UnionTestMessage utm2 = Construct.parseAs(ByteBuffer.wrap(a), UnionTestMessage.class);
66
67 Assert.assertEquals(((TestUnionCase0) utm.instance).val, ((TestUnionCase0) utm2.instance).val);
68
69 }
70}
diff --git a/test/org/gnunet/construct/parsers/IntegerParserTest.java b/test/org/gnunet/construct/parsers/IntegerParserTest.java
deleted file mode 100644
index e94b74e..0000000
--- a/test/org/gnunet/construct/parsers/IntegerParserTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.construct.parsers;
22
23import org.gnunet.construct.*;
24import org.junit.Assert;
25import org.junit.Test;
26
27public class IntegerParserTest {
28 public static class IntTestMessage implements Message {
29 @UInt8
30 public byte test1;
31 @UInt8
32 public int test2;
33 @UInt16
34 public int test3;
35 @Int8
36 byte test4;
37 @Int8
38 byte test5;
39 @Int16
40 byte test6;
41 @Int16
42 byte test7;
43 }
44
45 @Test
46 public void test_UInt8() {
47 byte b = Byte.MIN_VALUE;
48 do {
49 IntTestMessage itm1 = new IntTestMessage();
50 itm1.test1 = b;
51 itm1.test2 = 0;
52 byte[] bbuf = Construct.toBinary(itm1);
53 IntTestMessage itm2 = Construct.parseAs(bbuf, IntTestMessage.class);
54 Assert.assertEquals(itm1.test1, itm2.test1);
55 Assert.assertEquals(itm1.test2, itm2.test2);
56
57 b++;
58 } while (b != Byte.MAX_VALUE);
59 }
60
61 @Test
62 public void test_UInt16() {
63 int i = 0;
64 do {
65 IntTestMessage itm1 = new IntTestMessage();
66 itm1.test3 = i;
67 byte[] bbuf = Construct.toBinary(itm1);
68 IntTestMessage itm2 = Construct.parseAs(bbuf, IntTestMessage.class);
69 Assert.assertEquals(itm1.test3, itm2.test3);
70 i++;
71 } while (i != (1 << 15));
72
73
74 }
75
76 @Test
77 public void test_UInt16_short() {
78 short s = Short.MIN_VALUE;
79 do {
80 IntTestMessage itm1 = new IntTestMessage();
81 itm1.test3 = s;
82 byte[] bbuf = Construct.toBinary(itm1);
83 IntTestMessage itm2 = Construct.parseAs(bbuf, IntTestMessage.class);
84 Assert.assertEquals(itm1.test3, itm2.test3);
85 s++;
86 } while (s != Short.MAX_VALUE);
87 }
88}
diff --git a/test/org/gnunet/core/CoreTest.java b/test/org/gnunet/core/CoreTest.java
new file mode 100644
index 0000000..8b5ed63
--- /dev/null
+++ b/test/org/gnunet/core/CoreTest.java
@@ -0,0 +1,100 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.core;
22
23
24import org.gnunet.util.*;
25import org.grothoff.Runabout;
26import org.junit.Assert;
27import org.junit.Test;
28
29import static org.junit.Assert.assertTrue;
30
31public class CoreTest {
32 @Test
33 public void test_core_init() {
34
35 final Wrapper<Boolean> res = new Wrapper<Boolean>(false);
36
37 new Program(new String[]{}) {
38 @Override
39 public void run() {
40 final Core core = new Core(getConfiguration());
41 core.observeConnect(new ConnectHandler() {
42 @Override
43 public void onConnect(PeerIdentity peerIdentity) {
44 System.out.println("got connect!");
45 }
46 });
47 core.init(new InitCallback() {
48 @Override
49 public void onInit(PeerIdentity myIdentity) {
50 res.value = true;
51 assertTrue(myIdentity != null);
52 core.disconnect();
53 }
54 });
55 }
56 }.start();
57
58 assertTrue(res.value);
59 }
60
61
62 @Test(timeout = 5000)
63 public void test_core_echo() {
64 final Wrapper<Boolean> gotResponse = new Wrapper<Boolean>(false);
65 new Program(new String[]{}) {
66 @Override
67 public void run() {
68 final Core core = new Core(getConfiguration());
69 core.setMessageHandler(new Runabout() {
70 public void visit(TESTMessage t) {
71 System.out.println("got TEST message");
72 gotResponse.set(true);
73 core.disconnect();
74 }
75 });
76
77 core.init(new InitCallback() {
78 @Override
79 public void onInit(PeerIdentity myIdentity) {
80 System.out.println("hi, init callback");
81 core.notifyTransmitReady(0, RelativeTime.FOREVER, myIdentity, 4, new MessageTransmitter() {
82 @Override
83 public void transmit(Connection.MessageSink sink) {
84 System.out.println("in transmit!");
85 sink.send(new TESTMessage());
86 }
87
88 @Override
89 public void handleError() {
90 Assert.fail();
91 }
92 });
93 }
94 });
95 }
96 }.start();
97
98 assertTrue(gotResponse.get());
99 }
100}
diff --git a/test/org/gnunet/dht/DHTTest.java b/test/org/gnunet/dht/DHTTest.java
new file mode 100644
index 0000000..ec56834
--- /dev/null
+++ b/test/org/gnunet/dht/DHTTest.java
@@ -0,0 +1,49 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.dht;
22
23import junit.framework.Assert;
24import org.gnunet.util.*;
25import org.junit.Test;
26
27import java.util.EnumSet;
28
29public class DHTTest {
30 @Test
31 public void test_dht_put() {
32 final Wrapper<Boolean> putFinished = new Wrapper<Boolean>(true);
33 new Program(new String[0]) {
34 @Override
35 public void run() {
36 final DistributedHashTable dht = new DistributedHashTable(getConfiguration());
37 dht.put(new HashCode("gnj-test"), new byte[]{1,2,3}, 1, EnumSet.noneOf(RouteOption.class),
38 BlockType.TEST.val, RelativeTime.HOUR.toAbsolute(), RelativeTime.FOREVER, new Continuation() {
39 @Override
40 public void cont(boolean success) {
41 putFinished.set(true);
42 dht.destroy();
43 }
44 });
45 }
46 }.start();
47 Assert.assertTrue(putFinished.get());
48 }
49}
diff --git a/test/org/gnunet/statistics/StatisticsTest.java b/test/org/gnunet/statistics/StatisticsTest.java
new file mode 100644
index 0000000..33af3e2
--- /dev/null
+++ b/test/org/gnunet/statistics/StatisticsTest.java
@@ -0,0 +1,161 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.statistics;
22
23import com.google.common.io.ByteStreams;
24import com.google.common.io.Files;
25import com.google.common.io.InputSupplier;
26import org.gnunet.util.*;
27import org.junit.Test;
28
29import java.io.File;
30import java.io.IOException;
31import java.io.InputStream;
32
33public class StatisticsTest {
34 // todo: load configuration and start service in fixup / @Before
35
36 public interface Next {
37 void next();
38 }
39
40 public void assertStatisticsGet(AssertionList assertions, Statistics stat, final String subsystem,
41 final String name,
42 final long expectedValue, final Next next) {
43
44 final Assertion getAssertion = assertions.create("get %s:%s -> %s", subsystem, name, expectedValue);
45 final Assertion contAssertion = assertions.create("cont");
46 stat.get(RelativeTime.FOREVER, subsystem, name, new StatisticsReceiver() {
47 @Override
48 public void onReceive(String rsubsystem, String rname, long rvalue) {
49 if (rsubsystem.equals(subsystem) && rname.equals(name) && rvalue == expectedValue) {
50 getAssertion.assertTrue(true);
51 } else {
52 getAssertion.assertTrue(false);
53 }
54 }
55 }, new Continuation() {
56 @Override
57 public void cont(boolean success) {
58 System.out.println("cont called");
59 contAssertion.assertTrue(success);
60 if (next != null) {
61 next.next();
62 }
63 }
64 }
65 );
66 }
67
68 @Test
69 public void test_statistics_get_set() {
70 final AssertionList assertions = new AssertionList();
71
72 new Program(new String[]{}) {
73 @Override
74 public void run() {
75 final Statistics stat1 = new Statistics(cfg);
76
77 stat1.set("gnj-test", "test1", 5, false);
78 stat1.set("gnj-test", "test2", 7, true);
79
80 stat1.set("gnj-test", "test3", 0, true);
81 stat1.update("gnj-test", "test3", 5, true);
82 stat1.update("gnj-test", "test3", -1, true);
83
84 stat1.destroy();
85
86 System.out.println("starting get tests");
87
88 final Statistics stat2 = new Statistics(cfg);
89
90 assertStatisticsGet(assertions, stat2, "gnj-test", "test1", 5, new Next() {
91 @Override
92 public void next() {
93 assertStatisticsGet(assertions, stat2, "gnj-test", "test2", 7, new Next() {
94 @Override
95 public void next() {
96 assertStatisticsGet(assertions, stat2, "gnj-test", "test3", 4, new Next() {
97 @Override
98 public void next() {
99 stat2.destroy();
100 System.out.println("destroy called");
101 }
102 });
103 }
104 });
105
106 }
107 });
108 }
109 }.start();
110
111 assertions.assertAll();
112
113
114 }
115
116
117 @Test
118 public void test_watch() {
119 Program.configureLogging(null, null);
120 Configuration cfg = new Configuration();
121 File f;
122 try {
123 f = File.createTempFile("gnunet", "conf");
124 } catch (IOException e) {
125 throw new RuntimeException("could not create temp file", e);
126 }
127 final InputStream stream = StatisticsTest.class.getResourceAsStream("/org/gnunet/statistics/statistics-test.conf");
128 if (stream == null) {
129 throw new RuntimeException("could not find resource");
130 }
131
132 try {
133 Files.copy(new InputSupplier<InputStream>() {
134 @Override
135 public InputStream getInput() throws IOException {
136 return stream;
137 }
138 }, f);
139 } catch (IOException e) {
140 throw new RuntimeException("could not copy config file", e);
141 }
142
143 Process p;
144
145 try {
146 p = Runtime.getRuntime().exec(new String[]{"gnunet-service-statistics", "-LDEBUG", "-c", f.getAbsolutePath()});
147 } catch (IOException e) {
148 throw new RuntimeException("could not start process", e);
149 }
150
151 try {
152 ByteStreams.copy(p.getErrorStream(), System.out);
153 } catch (IOException e) {
154 e.printStackTrace();
155 }
156
157 p.destroy();
158
159
160 }
161}
diff --git a/test/org/gnunet/statistics/statistics-test.conf b/test/org/gnunet/statistics/statistics-test.conf
new file mode 100644
index 0000000..a01b650
--- /dev/null
+++ b/test/org/gnunet/statistics/statistics-test.conf
@@ -0,0 +1,18 @@
1[statistics]
2PORT = 3088
3HOSTNAME = localhost
4BINARY = gnunet-service-statistics
5ACCEPT_FROM = 127.0.0.1;
6ACCEPT_FROM6 = ::1;
7UNIX_MATCH_UID = NO
8UNIX_MATCH_GID = YES
9# DISABLE_SOCKET_FORWARDING = NO
10# USERNAME =
11# MAXBUF =
12# TIMEOUT =
13# DISABLEV6 =
14# BINDTO =
15# REJECT_FROM =
16# REJECT_FROM6 =
17# PREFIX =
18
diff --git a/test/org/gnunet/util/Assertion.java b/test/org/gnunet/util/Assertion.java
new file mode 100644
index 0000000..ec2b38a
--- /dev/null
+++ b/test/org/gnunet/util/Assertion.java
@@ -0,0 +1,42 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23
24public class Assertion {
25 public boolean success;
26 public int asserted;
27 public String message;
28 public String failMessage;
29
30 public Assertion(String message) {
31 this.message = message;
32 }
33
34 public void assertTrue(boolean b) {
35 success = b;
36 asserted += 1;
37 }
38 public void assertTrue(boolean b, String failMessage) {
39 assertTrue(b);
40 this.failMessage = failMessage;
41 }
42}
diff --git a/test/org/gnunet/util/AssertionList.java b/test/org/gnunet/util/AssertionList.java
new file mode 100644
index 0000000..d80ed0e
--- /dev/null
+++ b/test/org/gnunet/util/AssertionList.java
@@ -0,0 +1,30 @@
1package org.gnunet.util;
2
3import java.util.LinkedList;
4import java.util.List;
5
6public class AssertionList {
7
8 List<Assertion> asyncAssertions = new LinkedList<Assertion>();
9
10
11 public Assertion create(String message, Object... args) {
12 Assertion assertion = new Assertion(String.format(message, args));
13 asyncAssertions.add(assertion);
14 return assertion;
15 }
16
17 public void assertAll() {
18 for (Assertion assertion : asyncAssertions) {
19 if (assertion.asserted != 1) {
20 throw new AssertionError(
21 String.format("Assertion '%s' asserted %s times", assertion.message, assertion.asserted));
22 }
23 if (!assertion.success) {
24 throw new AssertionError(
25 String.format("Assertion '%s' failed", assertion.message));
26 }
27 }
28 }
29
30}
diff --git a/test/org/gnunet/util/ResolverTest.java b/test/org/gnunet/util/ResolverTest.java
new file mode 100644
index 0000000..586bc7d
--- /dev/null
+++ b/test/org/gnunet/util/ResolverTest.java
@@ -0,0 +1,84 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23import org.junit.Test;
24
25import java.net.InetAddress;
26
27import static org.junit.Assert.assertTrue;
28import static org.junit.Assert.fail;
29
30/**
31 *
32 * @author Florian Dold
33 */
34public class ResolverTest {
35 @Test
36 public void test_resolver() {
37 final Wrapper<Boolean> finished1 = new Wrapper<Boolean>(true);
38 final Wrapper<Boolean> finished2 = new Wrapper<Boolean>(true);
39
40 new Program(new String[0]) {
41 @Override
42 public void run() {
43 Resolver r = Resolver.getInstance();
44 r.resolveHostname("gnunet.org", RelativeTime.FOREVER, new Resolver.AddressCallback() {
45 @Override
46 public void onAddress(InetAddress addr) {
47 System.out.println(addr.getHostAddress());
48 }
49
50 @Override
51 public void onFinished() {
52 finished1.set(true);
53 }
54
55 @Override
56 public void onTimeout() {
57 fail();
58 }
59 });
60 r.resolveHostname("gnu.org", RelativeTime.FOREVER, new Resolver.AddressCallback() {
61 @Override
62 public void onAddress(InetAddress addr) {
63 System.out.println(addr.getHostAddress());
64 }
65
66 @Override
67 public void onFinished() {
68 finished2.set(true);
69 }
70
71 @Override
72 public void onTimeout() {
73 fail();
74 }
75 });
76 }
77 }.start();
78
79 assertTrue(finished1.get());
80 assertTrue(finished2.get());
81
82 }
83
84}
diff --git a/test/org/gnunet/util/ServerTest.java b/test/org/gnunet/util/ServerTest.java
new file mode 100644
index 0000000..28cc7e8
--- /dev/null
+++ b/test/org/gnunet/util/ServerTest.java
@@ -0,0 +1,27 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23/**
24 * @author Florian Dold
25 */
26public class ServerTest {
27}
diff --git a/test/org/gnunet/util/TestingSetup.java b/test/org/gnunet/util/TestingSetup.java
new file mode 100644
index 0000000..ac4f762
--- /dev/null
+++ b/test/org/gnunet/util/TestingSetup.java
@@ -0,0 +1,28 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23/**
24 * @author Florian Dold
25 */
26public class TestingSetup {
27
28}
diff --git a/test/org/gnunet/util/Wrapper.java b/test/org/gnunet/util/Wrapper.java
new file mode 100644
index 0000000..be84b54
--- /dev/null
+++ b/test/org/gnunet/util/Wrapper.java
@@ -0,0 +1,43 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.gnunet.util;
22
23
24/**
25 * Wrapper, used when it is necessary to store a value in a final-variable.
26 *
27 * @param <E> type of the stored value
28 */
29public class Wrapper<E> {
30 public E value;
31 public Wrapper(E initialValue) {
32 value = initialValue;
33 }
34 public Wrapper() {
35 // default constructor
36 }
37 public void set(E newValue) {
38 value = newValue;
39 }
40 public E get() {
41 return value;
42 }
43}
diff --git a/test/org/gnunet/util/GetoptTest.java b/test/org/gnunet/util/getopt/GetoptTest.java
index 845126a..9f8b223 100644
--- a/test/org/gnunet/util/GetoptTest.java
+++ b/test/org/gnunet/util/getopt/GetoptTest.java
@@ -18,12 +18,9 @@
18 Boston, MA 02111-1307, USA. 18 Boston, MA 02111-1307, USA.
19 */ 19 */
20 20
21package org.gnunet.util; 21package org.gnunet.util.getopt;
22 22
23 23
24import org.gnunet.util.getopt.Option;
25import org.gnunet.util.getopt.OptionAction;
26import org.gnunet.util.getopt.Parser;
27import org.junit.Assert; 24import org.junit.Assert;
28import org.junit.Test; 25import org.junit.Test;
29 26
diff --git a/test/org/grothoff/RunaboutBenchmark.java b/test/org/grothoff/RunaboutBenchmark.java
index fd12b36..18f456d 100644
--- a/test/org/grothoff/RunaboutBenchmark.java
+++ b/test/org/grothoff/RunaboutBenchmark.java
@@ -34,7 +34,7 @@ public class RunaboutBenchmark {
34 34
35 35
36 public static void main(String[] args) { 36 public static void main(String[] args) {
37 final int runs = 50000000; 37 final int runs = 5000000;
38 38
39 Runabout r = new MyRunabout(); 39 Runabout r = new MyRunabout();
40 40
@@ -51,7 +51,6 @@ public class RunaboutBenchmark {
51 long duration1 = end - start; 51 long duration1 = end - start;
52 52
53 53
54
55 Runabout r2 = new Runabout() { 54 Runabout r2 = new Runabout() {
56 public void visit(String s) { 55 public void visit(String s) {
57 56
@@ -76,7 +75,7 @@ public class RunaboutBenchmark {
76 75
77 System.out.println("Runs: " + runs); 76 System.out.println("Runs: " + runs);
78 System.out.println("public: " + duration1); 77 System.out.println("public: " + duration1);
79 System.out.println("AIC: " + duration2); 78 System.out.println("Anon Inner Class: " + duration2);
80 System.out.println("Overhead: " + duration2 / (double) duration1); 79 System.out.println("Overhead: " + duration2 / (double) duration1);
81 80
82 } 81 }
diff --git a/test/org/org/gnunet/nse/NSETest.java b/test/org/org/gnunet/nse/NSETest.java
new file mode 100644
index 0000000..0d83f75
--- /dev/null
+++ b/test/org/org/gnunet/nse/NSETest.java
@@ -0,0 +1,53 @@
1/*
2 This file is part of GNUnet.
3 (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 */
20
21package org.org.gnunet.nse;
22
23import org.gnunet.nse.NetworkSizeEstimation;
24import org.gnunet.util.AbsoluteTime;
25import org.gnunet.util.Program;
26import org.gnunet.util.Wrapper;
27import org.junit.Test;
28import static org.junit.Assert.*;
29
30/**
31 * @author Florian Dold
32 */
33public class NSETest {
34 @Test
35 public void test_nse() {
36 final Wrapper<Boolean> gotResult = new Wrapper<Boolean>(false);
37 new Program(new String[0]) {
38 @Override
39 public void run() {
40 final NetworkSizeEstimation nse = new NetworkSizeEstimation(getConfiguration());
41 nse.subscribe(new NetworkSizeEstimation.Subscriber() {
42 @Override
43 public void update(AbsoluteTime timestamp, double estimate, double deviation) {
44 assertNotNull(timestamp);
45 gotResult.set(true);
46 nse.disconnect();
47 }
48 });
49 }
50 }.start();
51 assertTrue(gotResult.get());
52 }
53}
diff --git a/tools/build b/tools/build
index 303ed0d..1895139 100755
--- a/tools/build
+++ b/tools/build
@@ -10,7 +10,7 @@ SOURCES=`find "$BASEDIR/src/" "$BASEDIR/test/" -name "*.java"`
10 10
11mkdir -p $BASEDIR/build 11mkdir -p $BASEDIR/build
12 12
13javac $JFLAGS -cp "$BASEDIR/build/:$BASEDIR/lib/*" -d $BASEDIR/build/ $SOURCES || exit 1 13javac -g $JFLAGS -cp "$BASEDIR/build/:$BASEDIR/lib/*" -d $BASEDIR/build/ $SOURCES || exit 1
14 14
15cd "$BASEDIR/src/" 15cd "$BASEDIR/src/"
16 16
diff --git a/tools/coverage b/tools/coverage
index 3c3c73b..2f88d6c 100755
--- a/tools/coverage
+++ b/tools/coverage
@@ -2,16 +2,16 @@
2 2
3BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/.. 3BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
4 4
5INSTRUMENT_CMD="sh $BASEDIR/cobertura/cobertura-instrument.sh --datafile $BASEDIR/coverage.data --destination $BASEDIR/bin-instrumented --ignore .*assert.* " 5INSTRUMENT_CMD="sh $BASEDIR/cobertura/cobertura-instrument.sh --datafile $BASEDIR/coverage.data --destination $BASEDIR/build-instrumented --ignore .*assert.* "
6 6
7 7
8case "$1" in 8case "$1" in
9instrument) 9instrument)
10 cp -r "$BASEDIR/bin/" "$BASEDIR/bin-instrumented/" 10 cp -r "$BASEDIR/build/" "$BASEDIR/build-instrumented/"
11 find $BASEDIR/bin/ -name *.class | xargs $INSTRUMENT_CMD 11 find $BASEDIR/build/ -name *.class | xargs $INSTRUMENT_CMD
12 ;; 12 ;;
13clean) 13clean)
14 rm -r $BASEDIR/bin-instrumented &>/dev/null 14 rm -r $BASEDIR/build-instrumented &>/dev/null
15 rm $BASEDIR/coverage.data &>/dev/null 15 rm $BASEDIR/coverage.data &>/dev/null
16 rm -r $BASEDIR/coverage-report &>/dev/null 16 rm -r $BASEDIR/coverage-report &>/dev/null
17 ;; 17 ;;
@@ -28,7 +28,7 @@ run)
28 28
29 COBERTURA="$BASEDIR/cobertura/cobertura.jar" 29 COBERTURA="$BASEDIR/cobertura/cobertura.jar"
30 30
31 java -ea -cp "$COBERTURA:$BASEDIR/bin-instrumented:$BASEDIR/lib/*" \ 31 java -ea -cp "$COBERTURA:$BASEDIR/build-instrumented:$BASEDIR/lib/*" \
32 -Dnet.sourceforge.cobertura.datafile="$BASEDIR/coverage.data" \ 32 -Dnet.sourceforge.cobertura.datafile="$BASEDIR/coverage.data" \
33 org.junit.runner.JUnitCore $TESTS 33 org.junit.runner.JUnitCore $TESTS
34 ;; 34 ;;
diff --git a/tools/run-tests b/tools/run-tests
index 722635d..9ff5178 100755
--- a/tools/run-tests
+++ b/tools/run-tests
@@ -4,16 +4,13 @@ BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
4 4
5cd "$BASEDIR/test" 5cd "$BASEDIR/test"
6 6
7# find all *Test.java files, remove extension, replace all '/' with .
7TESTS=$( find . -name "*Test.java" | sed -e 's/\.java//' -e 's/..//' -e 's/\//\./g' ) 8TESTS=$( find . -name "*Test.java" | sed -e 's/\.java//' -e 's/..//' -e 's/\//\./g' )
8 9
9echo Testing classes: $TESTS 10echo Testing classes: $TESTS
10 11
11# the version without coverage: 12java -cp "$BASEDIR/build:$BASEDIR/lib/*" org.junit.runner.JUnitCore $TESTS
12java -cp "$BASEDIR/bin:$BASEDIR/lib/*" org.junit.runner.JUnitCore $TESTS
13 13
14COBERTURA="$BASEDIR/cobertura/cobertura.jar" 14cd $OLDPWD
15
16
17#java -cp "$COBERTURA:$BASEDIR/bin-instrumented:$BASEDIR/lib/*" org.junit.runner.JUnitCore $TESTS
18 15
19 16