practical jxta ii

271
Practical JXTA II Cracking the P2P puzzle

Upload: jerome-verstrynge

Post on 03-Apr-2015

14.560 views

Category:

Documents


9 download

DESCRIPTION

This book is an introduction to the JXTA P2P protocol. It is written for software developers and architects willing to understand what P2P is all about, and those looking for code examples explaining how to use JXSE, step-by-step.

TRANSCRIPT

Practical JXTA IICracking the P2P puzzle

Practical JXTA IICopyright © 2010 by DawningStreams, Inc. The Netherlands

First edition: July, 2008.

Second edition: July, 2010.

All right reserved. No part of this book may be reproduced or transmitted in any form or by anymeans, electronic or mechanical, including photocopying, recording, or by any information stor-age and retrieval system, without written permission from the publisher, except for the inclusionof brief quotations in a review.

International Standard Book Number: 978-1-4461-3956-1

Limit of Liability/Disclaimer of Warranty: While the publisher and the author have used theirbest effort in preparing this book, they make no representation or warranties with respect to theaccuracy or completeness of the contents of this book.

The software code examples, advice, strategies herein are provided “as is” and any expressed orimplied warranties, including, but not limited to, the implied warranties or merchantability andfitness for a particular purpose are disclaimed. No warranty may be created or extended by salesrepresentatives or written sales materials. In no event, shall DawningStreams, Inc. be liable forany direct, indirect, incidental, special, exemplary, or consequential damages (including, but notlimited to, procurement of substitute goods or services; loss of use, data, or profit; or business in-terruption) however caused and on any theory of liability, whether in contract, strict liability, ortort (including negligence or otherwise) arising in any way out of the use of the software code ex-amples, advice, strategies, even if advised of the possibility of such damages. You should consultwith a professional where appropriate.

Trademarks: DawningStreams, Inc. is a registered trademarks of DawningStreams, Inc. in theUnited States and other countries and may not be be used without permission. All other trade-marks are the property of their respective owners. DawningStreams, Inc. is not associated withany products or vendors mentioned in this book.

Publisher: Lulu Enterprises, Inc. (www.lulu.com)

- 2

Table of Contents

Foreword 11

Why This Book?.............................................................................................................................................................................12

Why A Second Edition?................................................................................................................................................................13

Who Should Read This Book?.....................................................................................................................................................14

Prerequisites..................................................................................................................................................................................15

Introduction 16

Peer to Peer....................................................................................................................................................................................16

A Bad Reputation?.................................................................................................................................................................16A Quick Historical Review....................................................................................................................................................18

Architectures & Design Principles..............................................................................................................................................20

Client/Server..........................................................................................................................................................................20Three-tier & Multi-tier ..........................................................................................................................................................21Clustering & Load Balancing ...............................................................................................................................................21Service Oriented Architecture & Middleware....................................................................................................................22Grid Computing.....................................................................................................................................................................23Cloud Computing..................................................................................................................................................................23About Needs That Have Shaped IT Solutions....................................................................................................................23

What is P2P?..................................................................................................................................................................................24

ICQ...........................................................................................................................................................................................24Napster....................................................................................................................................................................................25Gnutella...................................................................................................................................................................................26Kazaa.......................................................................................................................................................................................27BitTorrent................................................................................................................................................................................28Freenet.....................................................................................................................................................................................28Pure P2P..................................................................................................................................................................................28Initial Objectives and Evolution...........................................................................................................................................29Benefits....................................................................................................................................................................................30Drawbacks..............................................................................................................................................................................30So, What Is The Use of P2P?..................................................................................................................................................32Towards Universality ...........................................................................................................................................................32

JXTA...............................................................................................................................................................................................34

Introduction............................................................................................................................................................................34The Three Layer Cake............................................................................................................................................................35The JXTA Project....................................................................................................................................................................36JXSE Community....................................................................................................................................................................36

C/C++..............................................................................................................................................................................37JXME.................................................................................................................................................................................37

Documentation, Forum & FAQ............................................................................................................................................37

Understanding JXTA 39

Introduction...................................................................................................................................................................................39

A Tribes-In-Islands Metaphor...............................................................................................................................................39

The Concepts.................................................................................................................................................................................40

Overview.................................................................................................................................................................................40Peer..........................................................................................................................................................................................41Peer Group..............................................................................................................................................................................43Service......................................................................................................................................................................................44Resources.................................................................................................................................................................................47Advertisement........................................................................................................................................................................47

Peer Advertisement.........................................................................................................................................................48Peer Group Advertisement............................................................................................................................................48Publication.......................................................................................................................................................................48

ID..............................................................................................................................................................................................49

- 3

Content....................................................................................................................................................................................50Codats......................................................................................................................................................................................50Pipes.........................................................................................................................................................................................50Module....................................................................................................................................................................................50

The Protocols.................................................................................................................................................................................52

Message...................................................................................................................................................................................53Endpoint Routing Protocol (ERP)........................................................................................................................................53

Endpoint Service.............................................................................................................................................................53Endpoint Address...........................................................................................................................................................54Endpoint Routing Protocol.............................................................................................................................................54ERP Messages & Advertisements..................................................................................................................................56Top-Down-Top................................................................................................................................................................57

Rendezvous Protocol (RVP)..................................................................................................................................................58Message Propagation Protocol.......................................................................................................................................58PeerView Protocol...........................................................................................................................................................59Rendezvous Advertisement...........................................................................................................................................60Rendezvous Lease Protocol............................................................................................................................................61Peer Connection to Rendezvous ...................................................................................................................................61Propagation Control........................................................................................................................................................61Top-Down-Top................................................................................................................................................................63

Pipe Binding Protocol (PBP).................................................................................................................................................63Pipe Advertisement.........................................................................................................................................................64Pipe Resolver Message...................................................................................................................................................64Propagate Pipe Message Header...................................................................................................................................65Top-Down-Top................................................................................................................................................................65

Peer Resolver Protocol (PRP)................................................................................................................................................65Resolver Query Message................................................................................................................................................66Resolver Response Message...........................................................................................................................................66Shared Resource Distributed Index (SRDI)..................................................................................................................66Resolver SRDI Message..................................................................................................................................................67Top-Down-Top................................................................................................................................................................68

Peer Information Protocol (PIP)............................................................................................................................................68PIP Query Message.........................................................................................................................................................69PIP Response Message....................................................................................................................................................69Top-Down-Top................................................................................................................................................................69

Peer Discovery Protocol (PDP).............................................................................................................................................70Discovery Query Message..............................................................................................................................................70Discovery Query Response............................................................................................................................................70Top-Down-Top................................................................................................................................................................71

Access Control...............................................................................................................................................................................71

Membership Service...............................................................................................................................................................72Access Service.........................................................................................................................................................................72

The Ignition Process......................................................................................................................................................................73

Module....................................................................................................................................................................................73Service......................................................................................................................................................................................74

Peer Group As A Service – Part I...................................................................................................................................74Well-known Module Class, Specification and Implementation IDs..........................................................................74Bootstrapping JXTA........................................................................................................................................................74Peer Group As A Service – Part II.................................................................................................................................77Loading Other Services...................................................................................................................................................77

Network Boundaries 79

Reminder........................................................................................................................................................................................79

IP..............................................................................................................................................................................................80Unicast, Broadcast & Multicast......................................................................................................................................81IPv4 Versus IPv6..............................................................................................................................................................81

TCP..........................................................................................................................................................................................81Handshake.......................................................................................................................................................................81

UDP..........................................................................................................................................................................................82Datagram..........................................................................................................................................................................82

- 4

Port...........................................................................................................................................................................................82Firewalls..................................................................................................................................................................................83NAT.........................................................................................................................................................................................84

Some Limitations.............................................................................................................................................................86PAT...................................................................................................................................................................................86

Proxy........................................................................................................................................................................................87Router......................................................................................................................................................................................87

Multicasting Versus Subnets..........................................................................................................................................87Natural Network Boundaries...............................................................................................................................................88Artificial Network Boundaries.............................................................................................................................................89

JXTA Transportation Layer..........................................................................................................................................................89

JXSE Transportation Layer...........................................................................................................................................................90

Overcoming Firewalls............................................................................................................................................................90Relay Service....................................................................................................................................................................91

Overcoming NATs.................................................................................................................................................................91Overcoming Proxies...............................................................................................................................................................92Seeds........................................................................................................................................................................................94

Peer Accessibility..........................................................................................................................................................................95

WAN........................................................................................................................................................................................95LAN.........................................................................................................................................................................................96

Same Subnet.....................................................................................................................................................................96Different Subnets.............................................................................................................................................................96

NAT Traversal...............................................................................................................................................................................97

IP Obstacles......................................................................................................................................................................97Port Prediction.................................................................................................................................................................98Punching Holes...............................................................................................................................................................98Hairpin Issue....................................................................................................................................................................98RFC 5128...........................................................................................................................................................................99

TURN.......................................................................................................................................................................................99STUN.......................................................................................................................................................................................99STUNT...................................................................................................................................................................................100

TTL-less Version of STUNT.........................................................................................................................................102New NAT Classification...............................................................................................................................................102

NUTSS...................................................................................................................................................................................103P2PNAT.................................................................................................................................................................................103NATBlaster...........................................................................................................................................................................104NatTrav.................................................................................................................................................................................104PWNAT.................................................................................................................................................................................105ALG........................................................................................................................................................................................106UPnP......................................................................................................................................................................................107ICE..........................................................................................................................................................................................107

ICE-TCP..........................................................................................................................................................................108“Behave” Compliant NAT..................................................................................................................................................108

RFC 5382.........................................................................................................................................................................108RFC 4787.........................................................................................................................................................................109

Where Does JXSE Stand?.....................................................................................................................................................110

Conclusion...................................................................................................................................................................................111

JXSE Cryptographic Layer 113

Cryptography Reminder............................................................................................................................................................113

Alice, Bob & Eve...................................................................................................................................................................113Introduction To Secure Communication...........................................................................................................................114...And Vicious Circles!..........................................................................................................................................................117Public Key Infrastructure (PKI)..........................................................................................................................................119

Who Certifies The Root Certificate Authority?..........................................................................................................120Duties Of A Certificate Authority...............................................................................................................................120

Web Of Trust.........................................................................................................................................................................121X.509.......................................................................................................................................................................................122X.500 & Principal..................................................................................................................................................................123Hash Function.......................................................................................................................................................................123

- 5

The Collision Issue........................................................................................................................................................124Key Sizes ..............................................................................................................................................................................125Assumptions ........................................................................................................................................................................125

The DRM Illusion..........................................................................................................................................................126Calling Experts.....................................................................................................................................................................126

Personal Security Environment (PSE).......................................................................................................................................127

Java Cryptography Architecture........................................................................................................................................127KeyStore................................................................................................................................................................................127

Creation..........................................................................................................................................................................128Automatic X.509 Certificate & Private Key Creation................................................................................................128Big Big Big Warning!.....................................................................................................................................................131Registering Your Own X.509........................................................................................................................................132

PSE Configuration................................................................................................................................................................132

Other Concepts............................................................................................................................................................................134

Secure Socket Layer (SSL)...................................................................................................................................................134Transport Security Layer (TLS)..........................................................................................................................................134Virtual Private Network (VPN)..........................................................................................................................................134

JXTA Security Layer....................................................................................................................................................................135

About Cipher Suites.............................................................................................................................................................135About Encryption of Private Keys......................................................................................................................................135

PSE Configuration Advertisement Encryption..........................................................................................................137Conclusion............................................................................................................................................................................137

Where Does JXSE 2.6 Stand?........................................................................................................................................138

Architectural Considerations 139

Identity Issues..............................................................................................................................................................................139

IP Addresses As Identities..................................................................................................................................................139Defining An Identity in JXTA.............................................................................................................................................140Creation Of Peer IDs & Importation Of IDs From Other Systems..................................................................................141Peer Group Creation & Identity.........................................................................................................................................141

Configuration Modes..................................................................................................................................................................143

JXTA Peer Types...................................................................................................................................................................143Minimal Edge Peer........................................................................................................................................................143Full-Featured Edge Peer...............................................................................................................................................143Rendezvous Peer...........................................................................................................................................................143Relay Peer.......................................................................................................................................................................143

JXSE Configuration Modes..................................................................................................................................................144ADHOC..........................................................................................................................................................................144EDGE..............................................................................................................................................................................144RENDEZVOUS..............................................................................................................................................................145RELAY............................................................................................................................................................................145PROXY............................................................................................................................................................................146

Peer Type versus Configuration Types..............................................................................................................................146About Implementation Of Services....................................................................................................................................146

Network Scope............................................................................................................................................................................147

To Be Or Not To Be?.............................................................................................................................................................147A Relay...........................................................................................................................................................................147A RendezVous...............................................................................................................................................................148Number of Seeds...........................................................................................................................................................149

Network Administration............................................................................................................................................................149

Default IP Ports....................................................................................................................................................................149Default HTTP Port...............................................................................................................................................................149Default Multicasting Port & IP Address............................................................................................................................150Implementing Seeds.............................................................................................................................................................150About Subnets......................................................................................................................................................................150

Cryptography..............................................................................................................................................................................151

Implementing Your Own Cryptography Layer................................................................................................................151Exportation Limitations................................................................................................................................................151

Access Control Implementation................................................................................................................................................152

- 6

Using JXSE 153

Getting Started.............................................................................................................................................................................153

Creating A Project................................................................................................................................................................153Maven....................................................................................................................................................................................154Javadoc..................................................................................................................................................................................154

First Connection & Local Configuration...................................................................................................................................154

Example 100 - Starting And Stopping JXTA.....................................................................................................................154Example 110 – Creating A Local Configuration...............................................................................................................156Example 120 – Retrieving, Modifying & Saving A Local Configuration.......................................................................157Miscellaneous.......................................................................................................................................................................159

Understanding ConfigParam.......................................................................................................................................159Modifying Other Configuration Parameters..............................................................................................................159Loading A Configuration From A URI.......................................................................................................................159Automatic Change Of IP Addresses...........................................................................................................................159Local Configuration Directory Structure....................................................................................................................160

New Configuration Objects & Connecting With OSGi...........................................................................................................160

Example 150 - Configuration Objects.................................................................................................................................160Example 160 – Connecting with OSGi...............................................................................................................................161

Exploring Connectivity Issues...................................................................................................................................................163

Creating & Using Seeds.......................................................................................................................................................163About The Default JXTA Seeds...........................................................................................................................................166Running Multiple Peers On A Single Device....................................................................................................................166

Multiple Peer In The Same JVM..................................................................................................................................166The Proper Angle To Strike A Match.................................................................................................................................167Jack, The Rendezvous..........................................................................................................................................................167Anna, The Edge....................................................................................................................................................................169Testing Angles Between Jack And Anna...........................................................................................................................171

Angle I - Start Jack, Then Anna, Delete Configuration & Approve Seed................................................................171Angle II - Start Anna, Then Jack, Delete Configuration & Approve Seed..............................................................172Angle III - Start Jack, Then Anna, Keep Configuration & Disapprove Seed..........................................................173Remarks & Warning......................................................................................................................................................173

Aminah, The Other RendezVous.......................................................................................................................................174Chihiro, The Other Edge.....................................................................................................................................................175Automatic Reconnection To Other RendezVous..............................................................................................................178Connectivity Manager.........................................................................................................................................................179Robert, The Relay.................................................................................................................................................................180Relay Connectivity...............................................................................................................................................................182Summary...............................................................................................................................................................................182

Creating Peers And Peer Groups..............................................................................................................................................183

Example 200 – Creating IDs................................................................................................................................................183Example 210 – Creating A New Peer.................................................................................................................................184Example 220 – Creating A Customized Peer Group........................................................................................................185

Discovery Operations.................................................................................................................................................................188

Finding Advertisements......................................................................................................................................................188Example 300 - Retrieving And Flushing Local Advertisements.....................................................................................188Example 310 – Remote Search For Advertisements.........................................................................................................190Local And Remote Publication...........................................................................................................................................194

Messages & Advertisements......................................................................................................................................................194

Example 400 – Creating An Empty Message....................................................................................................................194Example 410 – Add String, Long & Int Elements.............................................................................................................194Example 420 – Retrieving Message Elements...................................................................................................................195Example 430 – Add Byte Array Element And Retrieve InputStream.............................................................................196Example 440 – Adding An Advertisement In A Message...............................................................................................197Example 500 – Customized Advertisement......................................................................................................................198

Attributes........................................................................................................................................................................201Methods..........................................................................................................................................................................201Instantiator.....................................................................................................................................................................202

Example 510 – Registering A Customized Advertisement Instance..............................................................................202

Private Keys, Certificates & KeyStores.....................................................................................................................................203

- 7

Example 600 - Exporting & Importing Private Keys And X.509 Certificates.................................................................203Example 610 – Working With A KeyStore........................................................................................................................205Example 620 – Custom PSE Peer Group & Joining .........................................................................................................207

Simple Pipe Communication.....................................................................................................................................................210

Chandra, The Rendezvous Listening to Messages...........................................................................................................211Dimitri, The Edge Sending Messages................................................................................................................................213Running The Example.........................................................................................................................................................215Unicast Secure Pipes............................................................................................................................................................217

Bidirectional Pipe Communication...........................................................................................................................................217

Adelaide, The RendezVous At One End...........................................................................................................................217Quinisela, The Edge At The Other End.............................................................................................................................220Running The Example.........................................................................................................................................................222

JXTA Socket & Socket Server.....................................................................................................................................................223

Lidong, The Rendezvous And JXTA Socket Server..........................................................................................................223Ayrton, The Edge And JXTA Socket..................................................................................................................................226Running The Example.........................................................................................................................................................228

JXTA Multicast Socket................................................................................................................................................................229

Hans, The Rendezvous, A Multicast Participant..............................................................................................................229Teyacapan, The Edge, Another Multicast Participant......................................................................................................231Running The Example.........................................................................................................................................................233

Implementing A Customized Service.......................................................................................................................................233

Introduction..........................................................................................................................................................................233Example 700 – Creating Module IDs..................................................................................................................................233Example 710 – Astrology Service .......................................................................................................................................234

Static And Non-Static Attributes.................................................................................................................................238Static Methods...............................................................................................................................................................239Static Class......................................................................................................................................................................239Implementation Of Interfaces......................................................................................................................................239

RendezVous Joe, The Astrologer .......................................................................................................................................239Edge Jill, The Customer ......................................................................................................................................................241Running The Example.........................................................................................................................................................244Self-Service Weather Forecasting Method.........................................................................................................................244

Peer Information.........................................................................................................................................................................245

Activation Of The Peer Information Service.....................................................................................................................245

Ping...............................................................................................................................................................................................245

Example 800 – Ping..............................................................................................................................................................246Example 810 – Pong.............................................................................................................................................................247Running the Example..........................................................................................................................................................249

Miscellaneous..............................................................................................................................................................................249

Sending A Message With The Endpoint Service..............................................................................................................249Customized Queries.............................................................................................................................................................249About Registering Handlers In Services............................................................................................................................250

JXSE Shell.....................................................................................................................................................................................250

About The Future... 251

...Of P2P........................................................................................................................................................................................251

Perception vs. Facts..............................................................................................................................................................251About Needs That Have Shaped IT Solutions – Part II.............................................................................................251

Distributed Content.............................................................................................................................................................251CHURN.................................................................................................................................................................................252Economical............................................................................................................................................................................252

Costs And Return On Investment...............................................................................................................................252Potential For Profit........................................................................................................................................................254

...Of JXTA.....................................................................................................................................................................................255

Technological........................................................................................................................................................................255Simplification Of Complexity - Universality..............................................................................................................255New Applications..........................................................................................................................................................255Accountability & Vendor's Credibility.......................................................................................................................255

Educational...........................................................................................................................................................................256

- 8

Documentation, Books And Tutorials.........................................................................................................................256Code Examples..............................................................................................................................................................257

The Community...................................................................................................................................................................257The Protocols........................................................................................................................................................................258

JXTA vs. OSGi................................................................................................................................................................258

...Of JXSE......................................................................................................................................................................................258

Security..................................................................................................................................................................................258Cache Pollution..............................................................................................................................................................259

Conclusion...................................................................................................................................................................................259

Appendix 261

Protocol Messages Types............................................................................................................................................................261

Advertisement Attributes...........................................................................................................................................................262

Peer Advertisement..............................................................................................................................................................262Peer Group Advertisement.................................................................................................................................................262Module Class Advertisement.............................................................................................................................................262Module Specification Advertisement ................................................................................................................................262Module Implementation Advertisement ..........................................................................................................................263Pipe Advertisement.............................................................................................................................................................263Rendezvous Advertisement................................................................................................................................................264Route Advertisement...........................................................................................................................................................264Access Point Advertisement...............................................................................................................................................264

Index.............................................................................................................................................................................................265

- 9

- 10

Foreword

Acknowledgments

I thank my friend Jill Schmidig for her support. There are times in life when you need unconditionalsupport from your friends, just because of the challenges of life. I am talking about the kind of sup-port some people believe they will never need (or never have). I was one of these people. I amgrateful to have had her during those days when life hit hard on me, my friends and my family.She was always there to listen and to talk when I needed to.

I also thank all those who have helped me answering questions and to clarify issues about JXTAon the JXTA forum. I also thank all those who have participated to the development of JXTA andthe Open Source community in general.

About the Author

Jérôme Verstrynge is a graduate in computer science from the Université Libre de Bruxelles (Bel-gium). He also obtained a Master in Human Resource Management from that same institution anda Master of Business Administration in marketing from the Rotterdam School of Management (TheNetherlands). Since he finished his MBA, he has started his own company in Amsterdam (TheNetherlands) with a friend, in the New-York Metropolitan Area (New Jersey, USA). They are work-ing on their own P2P related project.

Jérôme Verstrynge has joined the community of JXTA software developers in 2008. He particip-ates to the JXTA forum using the AdamMan71 pseudonym. He can be reached by email at adam-

[email protected].

Foreword Foreword - 11

Why This Book?

The name of the book is inspired from another book called Practical Cryptography1 by Niels Fer-guson and Bruce Schneier. Practical Cryptography aimed at discussing cryptography implementa-tion at an engineer's level, rather than at a mathematical level, which is often abstract and concep-tual. It discussed “how to apply the cryptographic functions in a real-world setting” citing real soft-ware implementation issues.

Sun Microsystems introduced JXTA in 2001. JXTA is a set of protocol specifications for imple-menting peer-to-peer applications. Like cryptography, JXTA is very abstract and conceptual in itsdefinition. It does not get involved with implementation issues (or very little). Although severalbooks written about JXTA at the beginning of the Millennium included discussions on its imple-mentation in the Java programming language, its evolution and the evolution of its implementationhas made these books progressively obsolete.

The author started investigating JXTA in early 2006 and faced many issues trying to understandthis technology. The Java implementation was undergoing a major overhaul as it was migrated toversion 1.5 of the Java platform. The available documentation became obsolete as new code wasdelivered by the open source community. The available software guides were becoming obsolete.This made learning JXTA very tedious.

Then, the latest available version of JXTA was 2.5. Although the corresponding version of the pro-grammer's guide constituted an improvement over the previous versions, it did not explain howJXTA concepts operated in details. Moreover, it did not describe the technical issues those whohad implemented JXTA had to solve to enable smooth communication over computer networks.Understanding these issues is essential when designing, implementing and configuring softwareapplications based on JXTA.

The first version of this book was aiming at shedding more light as to how JXTA operates behindthe scenes, both from a conceptual and a practical point-of-view. In addition, it provided a remind-er covering network concepts and basic cryptographic issues. That book was about bringing thecore concepts of the JXTA puzzle together, in order to crack it and to make JXTA a practical tech-nology to use.

1 Practical Cryptography, by Niels Ferguson and Bruce Schneier, published at Wiley Publishing, Inc. in 2003.

Foreword Why This Book? - 12

Why A Second Edition?

In spring 2009, the author decided to take the lead to release version 2.6 of JXTA/JXSE. This wasan opportunity to clean-up an increasing technical debt in the code, to refactor it, and to solve sev-eral bugs left in the 2.5 release. Together with several developers from the community, new fea-tures have also been made available:

• In-memory implementation of SRDI

• Database implementation of the cache manager

• Improvement of threads and resource consumption with a task manager

• New TCP layer implementation

• Introduction of the OSGi framework

• Configuration objects

• Mavenization of the project

• New connectivity methods

Many people were happy to see a new and updated book about the JXTA technology come out in2008, but some remained frustrated that more information about what is happening under thehood was not available. This information has never been documented and released until recently.It is now available in the Programmer's Guide v2.6.

This second edition is about updating the first edition with novelties delivered in the JXTA/JXSE2.6 release. It also includes some of the 'under the hood2' information delivered in the Program-mer's Guide v2.6. Code examples have been improved and rewritten where necessary.

The purpose of Practical JXTA remains to be a complete introductory book to P2P in general andto the JXTA/JXSE technology. It gives pointers to those who want to explore it and its implementa-tion deeper.

2 See http://jxse.kenai.com/Developers/Developers.html

Foreword Why A Second Edition? - 13

Who Should Read This Book?

This book is intended for:

• JXTA early adoptersJXTA early adoptersJXTA early adoptersJXTA early adopters – If you are one of those who adopted JXTA since its inception, thisbook will help keep you up-to-date with the recent evolution of the JXTA implementation.Contrary to many books published earlier, this book contains code examples using themost recent features of JXSE, including those delivered as part of release 2.6.

• Functional analysts and software architectsFunctional analysts and software architectsFunctional analysts and software architectsFunctional analysts and software architects – This book covers all the JXTA concepts (in-cluding their usage), that a functional analyst or a software architect needs to understand,in order to design JXTA-based P2P applications. The official JXTA specification documentcontains several abstract terms referencing each other, together with a lot of technical lan-guage, making it hard to understand by everyone. This book is solving this entanglementby using many metaphors from the real world.

• Software developersSoftware developersSoftware developersSoftware developers – This book will explain altogether the basic concepts of JXTA andhow to use JXSE, the Java implementation of JXTA, to develop your own P2P applica-tions. It contains several basic code examples explaining how to use JXTA, step-by-step.These were designed to be as didactic as possible, that is, without optimization, to facilit-ate the learning. You will be able to take inspiration from these building blocks for yourown software implementations.

• System and network administratorsSystem and network administratorsSystem and network administratorsSystem and network administrators – The JXTA technology is abstract in its concepts, butit relies heavily on network transportation. Many transportation protocols can be imple-mented with JXTA, although TCP/IP and HTTP are the most common. Nearly all imple-mentations of JXTA require mechanisms to overcome firewalls, NATs and proxies bound-aries. This book explains how administrators can improve the overall performance of JX-TA-based applications using an adequate configuration of their systems, and without com-promising security policies.

• Managers and decision makersManagers and decision makersManagers and decision makersManagers and decision makers – If you are a manager or a decision maker, you mayhave heard about peer-to-peer technologies. You may even have used them for chatting,phoning over the Internet, or on your mobile phone and hand-held devices, and would liketo know more about them. This book explains the origin of P2P and demystifies the un-deserved negative publicity it received at the beginning of the decade. It describes the be-nefits of P2P, how to take advantage of it. Security and control access issues to copyright

Foreword Who Should Read This Book? - 14

protected documents are also discussed here.

This book does not explain how to implement JXTA. However, it can be used as a base to under-stand JXTA. Developers willing to implement the JXTA protocols will have to refer to the officialspecification documentation available online at https://jxta-spec.dev.java.net/ for technical details.

Prerequisites

This book assumes that software developers know about the Java programming language andconcepts such as URI (Uniform Resource Identifiers), URL (Uniform Resource Locater) and URN(Uniform Resource Name). They should master the event firing and even listening mechanism.Functional analysts and software architects need to know about XML, TCP/IP and HTTP, in gen-eral. System and network administrators should be aware of how TCP/IP, firewalls, NATs, proxies,routers and other types of network transportation systems operate in general. Managers and de-cision makers do not need to know more than general IT concepts.

The code examples provided in this book are relying on version 2.6 of JXSE, which requires JDK1.5 (or a higher version).

Foreword Prerequisites - 15

Introduction

This chapter introduces peer-to-peer and JXTA in general. We will describe the mo-tivations that led to the emergence of the peer-to-peer philosophy by revisiting partsof the IT history since the 1960's. We will compare it with other major IT design philo-sophies; describe its specificities, potential benefits and drawbacks. We will also ex-plain why a universal set of protocols became necessary to implement open peer-to-peer functionalities in software applications, thus leading to the creation of JXTA.

Peer to Peer

Peer-to-Peer (or P2P for short) is defined as a concept allowing direct communication between in-dividual computers by some, and as a set of networking design principles by others. The actualdefinition of what P2P is varies according to authors; but most agree that a peer-to-peer systemtraditionally rejects the client/server model and the underlying hierarchy it imposes between com-puters operating on a network.

Most of us heard about P2P for the first time when we used a file exchange application such asNapster, Kazaa or Gnutella, an instant messaging application such as ICQ or Yahoo! Messenger,or when we started “phoning” over the Internet with Skype. Others discovered P2P with Groove(now Microsoft Groove), a software application developed by Groove Networks in the 1990's.

A Bad Reputation?

In his July 15, 2007 cryptogram newsletter3, Bruce Schneier, a renowned cryptography and secur-ity specialist, discussed the role of the correspondent inference theory on the human perception ofterrorist group motivations. This theory, proposed by Edward E. Jones and Keith Davis, suggeststhat people are analyzing the consequences of other people's behavior and actions to guess theirmotivation, regardless of external or situational factors.

Bruce Schneider provided the example of someone violently hitting someone else. Most would as-sume that this person would be inherently violent, until one tells them that he or she is role playingfor a movie and that the camera can be seen in the distance. Information about the context is nottaken into account and a false conclusion is drawn. Several television shows use this technique totrap guests and celebrities by hiding contextual information.

3 http://www.schneier.com/crypto-gram-0707.html

Introduction Peer to Peer - 16

Since the year 2000, P2P technologies have boomed in a high number of file sharing and chattingapplications. Unfortunately, some P2P applications have often been associated with illegal filetransfers, copyright infringements on music and films, and all sorts of other illegal or unsafe activit-ies. Those using P2P technologies have been accused of participating in a movement damagingthe economy.

On the other side of the fence, others claimed that some companies, especially in the media in-dustry, were abusing their dominating position and inadvertently created the context for these newInternet technologies to appear. They claimed these P2P technologies were good, since they al-low us to buy songs and exchange movies online, to listen and view them at any time, improvingthe customer's overall experience. They claimed that all of this should be accepted as part of thenatural evolution of economies.

Can we really blame P2P technologies for bad behavior, illegal activities and exposure to securitybreaches? The first P2P application dates back to 1979 and many have been created since. Thepublic started using P2P in the late 1990's as the Internet became more and more available to awide audience. These applications were not initially designed by intention to perform any sort of il-legal activity.

Although we can observe a correlation between the increasing number of P2P application usersand some copyright infringement activities since the beginning of the Millennium, we cannot inferthat these applications are the cause. The absence of access control to resources is not intrinsicto P2P applications. One needs to make a clear difference between access control to resourcesand P2P software design principles. They are not incompatible and can be implemented togetherharmoniously.

Several P2P applications have been called unsafe. The main argument being that since all sortsof files, including applications, were being exchanged, the risk of virus propagation was increased.Interestingly enough, email applications have never been called unsafe, although emails contrib-ute to the propagation of viruses. Email content, not the application itself, has been blamed. Differ-ent perceptions have created different explanations for a unique cause requiring a unique solution:anti-virus software applications.

So, is the bad reputation attributed by some to P2P applications fair? Some developers have ex-ploited key features of P2P applications and added anonymity to facilitate anonymous transac-tions. Some were claiming a right for privacy alibi, while de facto, their applications were aboutsharing copyright protected content, such as audio files and movies. Consider similar controversy:

Introduction Peer to Peer - 17

should we blame knives and ban them because they have been used by some criminals? Orshould we focus on the criminals? Would the elimination of knives prevent criminals from commit-ting crimes? Aren't knives useful in other situations? P2P, itself, is not to blame for illegal activitiesand does not deserve the bad reputation.

P2P design principles have been instrumentalized by some to enable many activities, including il-legal activities, but these should not be rejected as a whole. We will see that it is possible to takeadvantage of all the benefits of P2P design principles without suffering from the abuse of carelessor malintentioned individuals, through the use of access control and cryptography, for example.

A Quick Historical Review

More than 40-years ago, the first mainframe computers appeared, allowingremote users to share their usage via a client/server model. These main-frames were expensive items. Users (clients) would access the mainframe(server) with terminal computers performing very basic operations: establish-ing a connection with the central server, collecting key strokes from users,sending them to the mainframe for processing and waiting for feedback, that is, characters to dis-play on the screen. That's it! The communication model between the client and the server wasvery primitive and the client terminal was completely useless when not connected to the main-frame server. These individual devices were very different from today's personal computers whichare capable of much more sophisticated operations.

As time went by, mainframes became more powerful and less expensive to acquire. Eventuallythe need for these computers to exchange information between themselves arose. The first con-nection was established in 1969 via the ancestor of the Internet, the ARPANET. This type of com-munication was very different from the passive client/server model described above. Both partieswhere acting individually, requesting, providing and processing information on their own. In the ab-sence of a connection, each party was still capable of operating on its own. This was not the casewith terminal computers. Technically speaking, we can consider this as the first P2P connectionbetween two computers. In 1983, ARPANET evolved into what is now called TCP/IP, a set of pro-tocols to exchange information between remote computers over the Internet.

Meanwhile, starting from the end of the 70's, computers became available to individual con-sumers: the personal computer was born. Some were equipped with the capacity to connect tomainframes or to other computers via telephones and modems. In technical terms, P2P connec-tions could be established between peers. But this is still far from today's definition and the gener-

Introduction Peer to Peer - 18

ADM-3A terminal

al understanding of P2P systems and applications.

The World Wide Web was introduced in the early 1990's and the usage of TCP/IP increased.More users connected to the Internet and for longer periods of time. Yet, users were still access-ing web pages or databases located on a central server and sending their email via mail servers.This way of interacting between computers closely resembles to the 1960's client/server model.To some extent, having to connect to central servers and waiting for responses was nothing differ-ent than behaving like terminal computers of the 60's. PC's are left with a lot of underutilizedpower and resources.

One thing leading to another, some developers imagined the possibility of designing P2P-like ap-plications operating directly from PC to PCs instead of going through central servers. This was fa-cilitated by the fact that every PC was capable of establishing connections to other PC's via the In-ternet. Were these new applications the first P2P applications?

Not really. In 1979, Usenet, an Internet application allowing users to post messages, was created.Its true novelty was that it did not rely on a single server, but on a changing set of loosely connec-ted servers. Users could post messages on a server and servers could exchange these messagesbetween themselves in order to make them available to other users. There was no central serveror central authority. Decentralization and distributed communication were born. The downside ofthis is these concepts were only available to servers, but not yet to end users.

So, what is P2P precisely? Is the 'absence of central authority or central servers' required to claimthat an application or a system is P2P? In that case, Napster, one the most popular early P2P ap-plications would be disqualified for using a central server for indexing shared files. Does 'twopeers exchanging files and communicating directly' say enough to claim that we are dealing with aP2P application? Some P2P applications are now used to process data on a large set of com-puters. This is more than just exchanging files and communicating; peers are providing services toeach other. Should this be taken into account in the definition of P2P? P2P covers many facets,as we will see.

First, we will explore different types of IT architectures and design principles to refine our definitionand understanding of what P2P is all about..

Introduction Peer to Peer - 19

Architectures & Design Principles

Client/Server

The client/server model was the first type of architec-ture created by the IT industry. It solved a very basicproblem related to the nature of early computers: theywere very expensive and valuable, since they couldperform many operations in a short period of time. Thismade them a scarce resource desired by many. Sinceit was not practical to have all potential users work inthe room containing the computer, nor to use the samekeyboard, terminal computers were created. Thesecentralized computer systems offered several advant-ages: easy access control, optimized consumption of a resource, and single localization of dataand software applications.

As computers became increasingly successful, more users required their services. Since a servercan only accommodate so many users before experiencing performance degradation, new serv-ers were acquired. Data required to provide services to all users was synchronized between sev-eral servers. This increased the maintenance and operational efforts required to mitigate potentialinconsistencies. The comfort of single computer systems was gone: software and data was notlocated on a unique system anymore. This increased the maintenance and operational effort. Theneed to exchange or to synchronize data between systems on a regular basis became omni-present. Network communications mechanisms were developed. Information was now able to flowbetween systems, in quantity.

Database applications were developed to gather, organize and centralize various types of systeminformation. They represented a great means to protect access to sensitive and confidential in-formation by avoiding dispersion. They reinforced the need for centralized systems. The first soft-ware applications using databases were developed; the code was separated from the datasource. Several software applications could access the same database in a queue model wherequeries were processed sequentially. Remote access mechanisms between software applicationsand databases were developed. Software applications could be run on one computer while thedatabase was accessed on another computer.

This data exchange between computers led to yet another issue: how to make sure it was not ac-

Introduction Architectures & Design Principles - 20

cessed by third parties when transmitted between two systems? That is when modern crypto-graphy emerged as a new science in the 1970's.

Three-tier & Multi-tier

A database system and the software containing the businesslogic accessing this database are two different software ap-plications. Software applications have a life of their own: theyevolve, new functionalities are being developed and bugs arebeing corrected. When a new version of an application or apatch is available, it has to be installed on all systems runningthat application. Keeping such applications in a central loca-tion to install upgrades and new versions is far easier thanperforming the same operation on distant systems.

The 2-tier architecture of client/server models be-came 3-tiers: the data-tier (centralized), the applic-ation-tier (most often centralized) and the present-ation-tier for end users (decentralized). In order toavoid having to install any software on a user'sPC, four-tier architectures, making usage ofweb/application servers have also been de-veloped. Users can use their application from any-where in the world via their browsers as long as an

Internet connection is available.

Software application systems running on several systems are called multi-tier applications, wheth-er they use two, three or more tiers. The division of software applications, in tiers, is a logical divi-sion. There is nothing preventing users from running several tiers on one physical machine, al-though most often, this may result in bad performance issues.

Clustering & Load Balancing

Companies and institutions have increasingly used more and more multi-tier software applica-tions. As expected, increased usage meant increased issues as web servers and application serv-ers received more and more requests from users. Network congestion rendered some systemsunavailable or resulted in unacceptable delays responding to user queries. This is comparable tohoards of holiday shoppers in one store or to cars lining a highway at rush hour.

Introduction Architectures & Design Principles - 21

The more complex a system becomes, the more proneit is to the single point of failure problem, that is, a situ-ation where one failing server or component of a soft-ware application compromises the whole system. Theobvious solution was to create redundant servers,either to make sure that one was ready to replace afailing one, or simply to share the workload betweenthem.

Two other concepts appeared, server clustering andload balancing. Server clustering is the idea that a setof servers, usually located very closely to each otheron the network, would work together and be perceivedas one unique computer from the outside. In someconfiguration, each server (master) has one morebackups (slaves) and which are kept synchronizedwith the master. If a master server fails, one of itsbackup takes over and automatically becomes the newmaster providing services.

Load balancing is about distributing user requestsamong several servers to make sure services are provided within a reasonable amount of time.This includes detecting a down server and redirecting the traffic away to an operational one.

Service Oriented Architecture & Middleware

Service Oriented Architecture (or SOA for short) aims at defining not only services (usually busi-ness processes), but also the IT infrastructure required to operate these processes. The primaryconcept is that services should not be implemented for a unique software application, but that theyshould be made available to a broad audience. Applications or other services can invoke them re-motely when needed. Databases are an example of shared services for data manipulation andstorage. A device providing temperature and humidity in a location is another example of service.

Making different software applications or systems work together, old and new, from same or differ-ent companies, whether or not they have been developed with SOA, is not automatic. This integ-ration is often performed with middleware: some glue to make the blocks stick together and to op-erate as smoothly as possible. Middleware helps software components or services, operating on

Introduction Architectures & Design Principles - 22

different systems, with different communication languages work together, regardless of the hard-ware. It can be implemented as an interface between a database and a web server, or between afinance application developed by one vendor and payroll application developed by anothervendor. The shape and structure of middleware is heavily dependent on the blocks it tries to con-nect.

SOA and Middleware are complementary concepts.

Grid Computing

The grid computing concept has risen from the world of distributed computing, that is, the idea ofsolving problems or storing data on several computers connected together via a network, ratherthan one computer or super computer containing multiple processors. The set of computers andclusters of computers performing distributed computing are each considered as a resource ornode on the grid. Grid computing can be less expensive to perform than centralized computing,since the acquisition of several commodity computers can be much cheaper than the acquisitionof a super computer.

Cloud Computing

Cloud computing is the latest emerging concept attempting to name architectural trends it the ITindustry. Just like the Web 2.0 acronym was englobing several technologies and concept in theearly 2000, cloud computing englobes SOA while hiding technical details of any underlying IT ar-chitecture. Anything consumable on the Internet (service, date, video, applications...) is madeavailable to anyone on the Internet, on demand. It claims to be a step further from the client servermodel.

About Needs That Have Shaped IT Solutions

By revisiting some IT history and concepts, we can identify some of the core needs that haveshaped the development of solutions in the IT industry. Of course, these were not the only forceswhich had an influence: wars, the economy, marketing, dominating positions – to name a few –also had a great influence:

➢ Remote access to a resource – Early on, engineers had to develop a way to give access acomputer resource from a distant location. The terminal-mainframe model is an example.This included controlling access to these resources. Later, it was not only users who hada need to access these resources, but computer resources themselves. This required amechanism to locate those resources.

Introduction Architectures & Design Principles - 23

➢ Concurrent access to a resource – Engineers had to provide a means for many users toaccess computer power and resources available in scarce quantity, thus time sharing wasimplemented. Each user would be given slices of time to run their application on theunique resource: the processor.

➢ Exchange of information between resources – Engineers had to develop a mechanism al-lowing the exchange of information between different computer resources located 'far'from each other. This included protecting it from third parties during transportation.

➢ Collection, centralization and organization of information from resources – Following thedispersion of information and its increasing collection, engineers had to develop systemscapable of organizing, storing and processing this data.

➢ Replication of resources – Since a single resource could not always supply for the re-quests from users, engineers had to find ways to replicate it to satisfy the demand.

Until recently, these needs have been satisfied with client/server-like methodologies and solutions.Today, the power of an average PC is significantly greater than the power of server computersavailable in the 1960's and 1970's. Everyone has enough equipment and computer power to oper-ate independently from central servers.

One can conceptually start from individual resources and have them organize themselves using acollective approach (from the bottom up), rather than organizing them around a central authority(top-down approach). This is precisely the starting point of peer-to-peer computing; a set of indi-viduals working together as opposed to authorities organizing and controlling a society of com-puters.

What is P2P?

The general idea behind P2P is that computer devices belonging to users should act both as clientand server on the network and that they should connect directly to each other, that is, without theneed of a central server, to exchange information or services. A P2P software application is oneenabling such operations between several computer devices connected to each other via a net-work.

ICQ

ICQ4 (pronounced “I seek you”) was one of the first P2P-like applications made available to a wide

4 http://www.icq.com/

Introduction What is P2P? - 24

audience. It allowed users to exchange instant messages and to be notified when they were on-line. It inspired Microsoft, AOL and Yahoo! to create their own version of instant messaging calledrespectively MSN, Internet AOL Messenger and Yahoo! Messenger. These were not compatiblesince they were not using a common communication protocol. This has changed since.

Purists do not consider ICQ as a pure P2P application,since it is using a central server to identify users appearingon the network and to notify other connected users of theirpresence. Once the notification is sent, users communic-ate directly. Therefore it is a combination of client/serverand P2P design principles.

As we will see further, the localization of a user on the In-ternet is not obvious. We are nomads in nature and manyof us take our computer to work, to an Internet café, on abusiness trip and back home. On our way, we connect tothe Internet from several locations. Even if we keep our PC home, our address on the Internetmay change each time we connect to it. ICQ solved the location issue by having users first con-nect to its well-known central server to give their Internet address (i.e., location), which was thenforwarded to other users already connected to ICQ.

Napster

Three years after ICQ, Napster5 appeared on the Internet in 1999 and provided users with thepossibility to exchange MP3 audio files. Users uploaded their file list on a central server. Then,they sent their queries for specific files to that server, which replied with a list of IP addresses (i.e.,Internet locations) of users having those files. At last, they established a connection with theseusers to download files. Of course, there was a risk of obtaining obsolete IP addresses sinceusers would connect from different locations or would be assigned new IP addresses each timethey connect to the Internet.

This application achieved something that the traditional client/server model never achieved. It wastapping on the local hard drive space of users to store its content instead of centralizing all files ina unique location, creating an unprecedented way of storing data on remote locations. Moreover,it was significantly reducing the traditional network congestion of the client/server model by limitingcommunications to file lists and requests. Napster would never have succeeded if it had tried to

5 Napster was shutdown in July 2002, but the brand is still used on http://free.napster.com/

Introduction What is P2P? - 25

store all exchange files on a central server. The server and the network would never have beenable to support all transactions.

Gnutella

Gnutella6 appeared in March 2000. Like Napster, itwas a file exchange application. However, itdiffered significantly from Napster in its way of es-tablishing contact with other peers and querying forfiles. Instead of contacting a central server, theGnutella application would try to connect to a pre-defined set of nodes to obtain a list of IP addressesof other nodes. It would then try to connect to thesenodes to obtain more IP addresses until a sufficientset of successful connection was reached. Unsuc-cessful addresses were automatically discarded.This type of bootstrapping method made the applic-ation decentralized and independent of the current node network topography. Nodes could joinand quit the network from anywhere without hampering the systems' capacity to establish connec-tions with other nodes as long as seed nodes were available.

Once the contact was established, eachnode could send file queries to the pool ofconnected nodes. They would forwardthese to the nodes they knew, whichwould forward these to nodes they knew,etc... etc... provoking a cascading effect.When a node possessed the researchedfile, it would notify the original node send-ing the query, so that a file transfer couldbe started between them.

Each query would contain a positive num-ber called time to live (TTL) which wasdecreased each time the query was for-warded to another node. When TTL6 http://www.gnutella.com/

Introduction What is P2P? - 26

reached 0, the query was not forwarded anymore. The list of visited nodes was kept in each copyof the propagated query to avoid loops. Unfortunately, it did not prevent nodes from receiving thesame query twice, through different paths. The increasing number of users resulted into an incred-ible amount of useless traffic between nodes. The consequence was that the network congestionaround servers was now propagated around all users.

The architecture of Gnutella presented a benefit over the architecture of Napster. The latter couldeasily be attacked or stopped since it was relying on a central server. With Gnutella, attacking orstopping a node was inefficient, since other nodes could take over and compensate for the miss-ing node.

Kazaa

Kazaa7 appeared in March 2000 and introduced a new concept: super nodes. Instead of havingeach node maintaining its own list of shared files to share locally, they were uploaded to supernodes at regular intervals.

User's queries were sent to super nodes.Then, these nodes would reply with the list ofnodes offering the searched file. Queries werenot propagated in all directions anymore. Theuser could then establish a connection withthe remote node containing the requested fileand start the transfer.

This method induces significantly less networktraffic than Gnutella-like applications. Supernodes are automatically chosen by the systemaccording to their capacity (storage, band-width, etc...). In this model, some individualsin the community are being given more responsibilities to organize the life of the community.

7 http://www.kazaa.com/

Introduction What is P2P? - 27

BitTorrent

BitTorrent8 appeared in July 2001. It introduced a new way of ex-changing files on a P2P network. Instead of focusing on a singlepeer for the transfer of large files, the query peer would obtain partsof it from different peers simultaneously, creating a torrent of data.

This method allows faster download time compared to traditionalP2P transfer methods. If you were unlucky and downloaded a filefrom a peer having a low bandwidth connection, you had no otheroption than to wait or to cancel the connection and try with anotherpeer, hoping for a better connection. With this new method, even aset of low bandwidth peers can generate rapid transfer times.

Freenet

Freenet9 appeared in 1999 (at least conceptually). The objective of this P2P application was to letits user publish and exchange decentralized information in pure anonymity using cryptographyand special routing functions between nodes, making it hard to trace peers querying for informa-tion.

Other applications such as Napster, Gnutella and Kazaa do not provide anonymity. Users knowwho they are downloading data from and they also know where users queries are coming from,making it relatively easy to trace them.

Pure P2P

A P2P network is often defined as pure when the following criteria are met:

• Flat hierarchy in roles and responsibilities between nodes

• No central authority managing the network

• No central authority indicating how two nodes should connect

In that respect, ICQ and Napster do not qualify as pure P2P networks. Gnutella is getting closer,although some of the bootstrapping nodes were initially hard-coded. Other techniques are nowavailable to fetch initial seed nodes, such as reading a file from a specific location on the network.Its content would indicate where to locate active seed nodes.

8 http://www.bittorrent.com/ 9 http://freenetproject.org/

Introduction What is P2P? - 28

Pure P2P networks are impractical since not organizing the traffic between peers using efficientmethods results in a poor performance of the system overall. Some peers need to have more re-sponsibilities than others to manage the network and to help new peers to find other peers.

Initial Objectives and Evolution

At the beginning of the millennium, the initial objectives of P2P were multiple. They started withchatting, then with file sharing and escaping central server computers in general. However, theseearly objectives obscured another goal of P2P application: distributed computing.

One of the most successful examples is the SETI@home project10. Internet users can download a

free program that would use the idle time of their computer to analyze radio telescope data. Whenfinished, the results are sent back to a central server and new data is downloaded for analysis. Al-though this application is not P2P in its design, it illustrates how many computers can solve alarge divisible problem. A real-life example of divisible problems is mowing the lawn. One personcan do it alone or several can simultaneously do it by taking care of a part of the yard.

There are some indivisible problems, such as checking one's account balance when withdrawingmoney. You need to centralize all account transactions in one location in order to compute the bal-ance and make sure there is money available when performing the withdrawal. However checkingmany balance accounts is a divisible problem: the account checking can be spread over a set ofcomputers. Each account can be verified simultaneously. In general, indivisible problems are bet-ter served in a client/server model and divisible problems in a P2P model.

One will notice that, excluding semantics, grid computing and a P2P network of computers per-forming distributed computing is virtually the same thing. Both systems have to satisfy the samecore needs to locate resources, request services, access, exchange and collect information re-motely.

A surprising evolution of P2P is Skype, the application allowing us to phone for free with our com-puter anywhere around the world. This ground breaking technology has had a tremendous impacton the telecoms industry. Today, some are trying to develop P2P television, but they are facing is-sues with network bandwidth availability.

To summarize it, P2P is the last extremity of a continuum starting from the mainframe-terminalconcept and going forward to the client-server, multi-tier, SOA and cloud computing concepts. Asmuch as a single mainframe is impractical to use by many, as set of pure P2P devices are imprac-tical to operate globally. So far, all successful operational systems and architectures have been10 http://setiathome.berkeley.edu/

Introduction What is P2P? - 29

implemented somewhere between those two extremities.

Benefits

The common benefits associated with P2P applications are:

• Tapping into resources at the edge of the Internet – Instead of relying on a central serverto perform many operations, P2P attempts to maximize the utilization of resources of cli-ent PCs (memory, processing power and storage capacities) instead.

• Reduced network traffic – If more work is performed at the edge of the Internet or if re-sources are distributed between nodes, then there will be less traffic and network conges-tion around servers. However, we have seen that if the search mechanism for resourcesacross peers is not well implemented, it can generate a lot of useless traffic.

• Cost savings – If work can be done by peers, then there is no need to buy a server to doit. Therefore, one can save money in material and maintenance.

• Faster information delivery – We have seen that high volumes of data can be generatedby downloading data parts from multiple peers simultaneously. This is more efficient thanacquiring a bigger bandwidth between two entities where only one end is transmittingdata.

• Scalability – If you need extra processing power for a P2P application, you just need toadd extra nodes which is easier than installing another server. This can be useful for divis-ible problems.

• Self-organization – Nodes arrive and depart at frequent intervals in P2P systems. Despitethis chaotic activity, P2P systems can re-organize themselves automatically.

• Network fault tolerance – If one peer goes down the network is still alive, another one cantake over. If a server is down that is not (always) true.

• Pervasiveness – This is the capacity to reconnect with peers and services that havechanged location on the Internet. It allows users to behave like nomads on the Internet.

Drawbacks

The common drawbacks associated with P2P applications are:

• Non-deterministic services – Since peers connect and disconnect to the network more of-ten than servers, there is a higher risk of resource or service unavailability. However, if the

Introduction What is P2P? - 30

resources and services are duplicated on another peer, this problem can be mitigated. Iftwo peers request the same service or resources on a P2P network, they may obtain itfrom different peers via different routes, with different bandwidths, resulting in differentservice quality.

• Content ownership infringement – Early P2P allowed fast distribution of any content, in-cluding copyright protected content. However, some control on who-exchanges-what-with-whom can be implemented now within P2P applications, limiting the massive illegalpropagation of resources. Sharing content or resource is a matter of trust. There is noth-ing that can prevent someone with bad intentions from distributing protected content withpermissive applications.

• Absence of central control –––– The fact that P2P applications allow the exchange of directinformation from one peer to another means that improper content can be transferred too,such as child pornography or terrorist documents. The flip side of this argument is that acomplete central server-like type of control would still not prevent users from exchangingthis kind of information. They would simply do it by other means.

There is a fundamental conceptual flaw with the idea that control needs to be central.Control is about trust. Whom do you trust? Why? And what privileges do you grant to thatperson or entity? When one receives a driving license, one does not need to show it to theadministration each time one drives its car. A policeman can verify it at anytime, any-where. Control is very often distributed in our societies. This is also true in client/servermodel where multiple web servers can verify cryptographic keys and messages generatedby servers they do not need to contact.

The very idea that one has to control a device to control its interactions, in combinationwith the fact that early P2P applications had no controlling features, led to the belief thatP2P was intrinsically unsafe. If many devices can perform controlling operations alone ina client/server model, why could not they in a P2P model?

Some have mentioned that profitability is a drawback of P2P systems, since transactions are notperformed via a central authority, and therefore cannot be registered and billed. However, there isnothing preventing one from selling licenses of limited duration to access content on a P2P net-work.

Introduction What is P2P? - 31

So, What Is The Use of P2P?

Traditionally, P2P is introduced in opposition to the client/server model. The qualities of P2P sys-tems are described by comparing them to those of the client/server model. But is this enough toestablish an identity? Is a hammer better than a wrench? Do we define hammers by comparingthem to wrenches? No, we tend to describe hammers by what you can do with them. A hammer ismore or less useful than a wrench depending on the situation and the task that has to beachieved.

If computers were bricks, P2P would be an excellent mortar! In addition to the benefits we de-scribed earlier, many readers will have identified P2P as a natural way to implement middlewaresolutions and service-offering architectures. Implementing clusters of computers is something nat-ural for P2P systems, since they inherently need to organize themselves to operate efficiently.Performing distributing computing with load balancing is possible with P2P. Redundancy can alsoeasily be implemented in P2P systems. The monitoring of other peers is something common.

P2P has the potential to support, enhance and transform many methodologies and techniques tra-ditionally used in the IT industry to develop systems and software. It can easily welcome the exist-ence of powerful servers on the network and let other peers behave like clients, utilizing the serverfor indivisible problems.

However, P2P will never be good at replacing multi-tier applications and will most probably neverreplace the World Wide Web technology, since the latter requires fixed servers to fetch webpages. Using P2P would not bring any added value to the current implementation of the WorldWide Web.

Towards Universality

In order to implement P2P universally, one needs to establish a common communication lan-guage between peers, regardless of the technology they are using. One also needs to organizetheir transactions. This can be achieved with protocols. In a broad sense, a protocol is a set ofrules explaining how an activity or a transaction should happen. Every society and culture has itsown rules and ways of organizing itself. Signs, gestures and comments do not always have thesame meaning from one culture to the other.

The birth of a diplomatic protocol is driven by the necessity to establish a communication channelbetween at least two different societies or cultures. The immediate effect is the creation of a newset of meanings between the two parties: 'if you do this in that context, it will mean that'. This newset of meaning may not be compatible with all the rules of one culture or its habits. However, if the

Introduction What is P2P? - 32

benefit of understanding each other is higher than the cost of adopting this new set of rules, theprotocol will be adopted and utilized.

What about IT? Just like diplomacy helps countries, cultures and nations to communicate and tounderstand each other, we have seen that the IT industry gradually required 'something' to help itsmultiple systems and computers communicate together. Many networking protocols and sets ofprotocols were created to solve this problem. A natural selection has happened resulting in the se-lection of TCP/IP (Transmission Control Protocol / Internet Protocol). In fact, it is not a unique pro-tocol, but a suite of communication protocols allowing computers and devices to communicateover what is now called the Internet.

One may wonder that since there is a protocol allowing computers to communicate directlybetween themselves over the Internet, why should we need a universal P2P protocol at all? In the-ory, we could rely only on TCP/IP to create a universal P2P application, or at least, a means ofP2P communication between systems using different technologies. That is what we already do, tosome extent. If I know the IP address of my correspondent, TCP/IP will establish a connectionwith that correspondent for me. If we know the link to a website, www.sun.com, our PC can findthe corresponding IP address via a technology called DNS (Domain Name System) and TCP/IPwill establish a connection to it. So, what's the big deal?

The big deal is that:

a) There is no such thing as one IP address per user on the Internet today. When you switchon your PC or connect to the Internet, you are very often assigned a dynamic IP addresswhich will remain valid for the duration of your connection. If you move to a wireless net-work, you will connect to the Internet via a different IP address. We can't rely on identify-ing a peer by its IP address, only. Some will say that version 6 of the Internet protocolshould provide a sufficient number of addresses. This is true, but that is not the only prob-lem to solve as we will explain later.

b) In order to locate a peer, we could use the DNS mechanism to resolve the IP address of acomputer from its name. Each peer could be assigned a unique name and we could useDNS to retrieve its IP address. Each time a peer would connect to the Internet, it wouldsend its IP address to a central server – à la ICQ – to the attention of other peers. But, us-ing DNS servers to locate peers on a P2P network implies using central servers, which isagainst the P2P philosophy. Moreover, who would maintain these servers?

c) Relying on TCP/IP means that one would be tied with a specific technology to implement

Introduction What is P2P? - 33

a universal P2P solution. Some protocols within TCP/IP are directly related to hardwaretechnologies. What if TCP/IP were completely replaced with a new technology or with newtypes of hardware from which new communication protocols would be derived in the fu-ture? Your P2P application would become instantaneously obsolete. You would have torewrite (at least) the transportation layer of your code.

d) TCP/IP enables communication between computers, but does not guarantee that what isbeing communicated will necessarily be understood by the other party. A common lan-guage to exchange information and organize transactions between peers is still necessary.

Therefore, defining a P2P protocol independent of any platform implementation is a necessity toachieve universal objectives. This is where JXTA comes into play.

JXTA

Introduction

JXTA, pronounced 'juxta', comes from the word juxtapose. JXTA reflects the operations by whichpeers establish temporary associations to form a P2P network; they juxtapose themselves to eachother. JXTA is not a software design philosophy and it is not a software application. It is a set ofprotocols that software developers can implement using their own technology to establish P2Pconnections with other peers using identical technologies or different implementations of JXTA.

For example, a group of developerscan implement JXTA in Visual Basicunder Windows XP. Another groupcould do the same in C++ underLinux and a third group could imple-ment the JXTA layer on a hand-helddevice in Java. They would all beable to find each other on the Internetand to start exchanging any kind ofinformation or services between them, despite the use of different underlying technologies.

The JXTA protocols are designed to be independent of transport protocols and make few assump-tions about network transportation mechanisms between computers and electronic devices. Inother words, JXTA does not take the responsibility of explaining how messages should physicallybe exchanged between peers or from a technical point-of-view.

Introduction JXTA - 34

JXTA imposes a common structured language to issue and exchange messages between peers:XML (Extensible Markup Language). Although this language is readable by human beings, whichis a benefit, its verbosity has often been pointed as a weakness regarding application perform-ance. XML documents are usually bigger than traditional binary data documents containing thesame amount of information. This issue can be me mitigated by the use of data compression with-in XML documents.

Contrary to binary data documents whose data can have any structure, the structure of XML docu-ments must comply with well-known standard rules. There is no need to code specific structurerules in your application, like for binary documents. The generic XML rules are good enough toread and manipulate any XML documents, even if they have been created by a software applica-tion developed in a different programming language than yours. This is a huge benefit, since lesscode is required to manipulate and exchange data openly between peers. The cascading effect isthat your software application is less complex, contains less code and requires less testing; there-fore, it is less prone to bugs.

The fact that JXTA defines its protocols independently from any other technologies and that it haschosen a neutral technology to communicate messages between peers implementing its protocolsguarantees its universality. Of course, its implementation on specific platforms and the choice of anetwork transportation layer between peers creates specific technical issues which have to besolved by each implementation of JXTA locally. This preserves its universality.

The Three Layer Cake

Conceptually, JXTA is made of three logical layers:

1. Platform – This layer is the base of JXTA and contains the imple-mentation of the minimal and essential functionalities required toperform P2P networking. Ideally, JXTA-enabled peers will implementall JXTA functionalities, although they are not required to. This layeris also known as the core layer.

2. Services – This layer contains additional services that are not absolutely necessary for aP2P system to operate, but which might be useful. For example: file sharing, PKI infra-structures, distributed files systems, etc... These services are not part of the set of ser-vices defined by JXTA.

3. Applications – P2P applications are built on top of the service layer. However, if I develop

Introduction JXTA - 35

Three Layer Cake

Applications

Services

Platform

a file sharing application and let other JXTA based applications make requests to my ap-plication, the other applications will perceive me as a service. Therefore, the borderbetween a service and an application depends on one's perspective.

As JXTA and the IT industry are evolving, the application layer concept is becoming somehowmeaningless. One should focus on the platform and the service layers. JXTA is not an operatingsystem and (most probably) will never become one.

The JXTA Project

The JXTA project was started by SunMicrosystems, Inc.11 in 2001 and is “re-sponsible for the formal specificationand documentation of the JXTA Proto-cols”. It is maintained by a group ofpeople which anyone can join.

The official website was accessiblefrom https://jxta-spec.dev.java.net/. It isnow officially moving tohttp://jxta.kenai.com.

There you can download the latest version of the official document describing the JXTA protocol inHTML or PDF format. Other information such about the board of directors, governance and themailing lists can be found.

JXSE Community

JXSE is the implementation of the JXTA protocols in the Java programming language. The JXSEacronym is more and more used to distinguish the protocols from their implementation in Java.Until recently, the source code and the downloads where available from: https://jxta-jxse.dev.-java.net/.

11 http://www.sun.com/

Introduction JXTA - 36

However, the site is officially moving tohttp://jxse.kenai.com/. The sourcecode, the javadoc, the .jar files, the

dependencies and the tutorial code ex-amples can be downloaded from there.

C/C++

Two web pages for the implementationof JXTA in C/C++ are available from:https://jxta-c.dev.java.net/ andhttp://wiki.java.net/bin/view/Jxta/JxtaC.The C/C++ implementation of JXTA can be downloaded from http://download.java.net/jxta/jxta-c/2.5.2/ and the API documentation is available from: http://rdv.jxtahosts.net/jxta/api-doc/jxta-c/.However, this project has not been active recently.

JXME

JXME, an implementation of JXTA for Java ME (Micro Edition) is available from: https://jx-ta-jxme.dev.java.net/. As a reminder, Java ME is a reduced version of the Java platform facilitatingthe development of software applications for small devices, such as cell phones and PDAs.

JXME is delivered in API (Application Programming Interface) bundles called: configuration, pro-files and optional packages. A configuration bundle provides the virtual machine features and aset of libraries that must be available as part of a specific implementation of the Java ME environ-ment. It is a building block. A profile bundle is another building block providing a set of API for aspecific category of devices. The combination of both enables the implementation of Java ME fora specific category of devices. This implementation can contain additional optional packages.

JXME should operate on devices using an implementation of Java ME based on the ConnectedLimited Device Configuration (CLDC) - Mobile Information Device Profile 2.0 (MIDP) combination.It should also operate on Connected Device Configuration (CDC), which is a fully compliant imple-mentation of the Java virtual machine optimized for small devices.

Unfortunately, this project has not received much attention recently.

Documentation, Forum & FAQ

The JXTA / JXSE Programmers Guide are available from the Tutorial link on the JXSE website.

Introduction JXTA - 37

Guides in preparation are available from the De-velopers link.

The forum is still available from http://forums.-java.net/jive/forum.jspa?forumID:50. Anyone isfree to register and to ask any questions relatedto the implementations of JXTA by starting con-versation threads. Technical issues can also besubmitted. The future of the forum is unclear as the projects are moving to Kenai. For more in-formation, one should register to the mailing lists still operating from the Java.net (as of the public-ation of this book)12.

One can also access the following web page for frequently asked questions over JXTA:http://wiki.java.net/bin/view/Jxta/JxtaFAQ. This will progressively be replaced by:http://kenai.com/projects/jxse/pages/FAQ.

12 See https://jxta.dev.java.net/servlets/ProjectMailingListList.

Introduction JXTA - 38

Understanding JXTA

This chapter presents the JXTA concepts and how they work together. Since most ofits content is conceptual, several metaphors are used to facilitate the understanding.We will first introduce each concept individually and progressively explain how theseoperate with each other. We will also focus on some JXTA implementation chal-lenges, but we will not explain how these have been overcome from a technicalpoint-of-view. This is mostly a functional chapter.

Introduction

A Tribes-In-Islands Metaphor

One good way to help create meaning in a world that is unknown to us is to use metaphors. Let'simagine several hundred tribes, each living on their own island (or set of islands), in the middle ofan unknown ocean. Each tribe has a king or a queen and a unique distinctive sign (a flag, an an-imal or a symbol) that helps to distinguish itself from other tribes. Some islands are in close prox-imity, others are distant. Each tribe grows its own type of crops. Some fish, others raise some typeof livestock. Some have developed special skills like working iron, drawing maps or curing dis-eases. Some tribes growing the same kind of crops want to organize themselves in groups to cre-ate markets. In the real world, the king or queen of a tribe is a human being and an island is anelectronic device capable of running an implementation of the JXTA protocols, that is, a JXTApeer.

All tribes are willing to travel from island to island to exchange products or services they do notproduce themselves to satisfy their needs. This is the concept of communication between JXTApeers. They all have boats to navigate over the ocean. Some tribes have mastered the ability to flyfrom island to island, but your tribe does not master this technique. Each tribe speaks its own lan-guage (or eventually shares one in common with others), but all have agreed on a minimal dialectthat helps them communicate with any other tribe, regardless of their language. This is XML, thelanguage selected by JXTA13. The king or queen of each tribe is able to write down notes on driedleaves, using the minimal dialect, in order to communicate with other kings and queens.

You are the ruler of a tribe and you have recently heard about two new services offered by other

13 Newcomers to JXTA are often scared by the fact that data transfer with XML documents is always more voluminous than with binarydocuments. The JXTA specification document defines two binary message formats to solve this issue.

Understanding JXTA Introduction - 39

tribes: astrology predictions and a self-service weather forecasting method. If you provide yourbirth date and your birth location to the tribe's astrologer, he or she will predict your future. Theweather forecast method has been written in your language (i.e., not the minimal dialect which istoo basic anyway) and you are interested in acquiring it to perform it as a service yourself for othertribes in the area.

In other words, you are (for example) interested in loading the weather forecast service written inJava on your device running JXSE.

The Concepts

Overview

The JXTA specifications define several abstract concepts referencing each other. We will coverthese one by one in the coming pages, but do not panic if you do not grasp the complete meaningof each concept right from the start. It will become more and more clear as you read further downthis chapter and explore the code examples provided later in this book.

Don't forget that JXTA specifications are abstract. They need to be implemented using a specificprogramming language and/or platform to become operational. This book focuses on JXSE, theJava programming language implementation of JXTA. In order to understand JXTA, we also needto explain how and why its concepts have been selected and implemented this or that way inJXSE. Otherwise, we take the risk of losing the reader in abstractions.

We will frequently switch from JXTA to JXSE and vice-versa to facilitate the description of JXTA.Of course, JXSE is not the only way to implement JXTA. Don't forget that there are many ways to

Understanding JXTA The Concepts - 40

comply with JXTA specifications. The methods and techniques chosen by those who have imple-mented JXSE are not necessarily the same methods and techniques others would use in differentimplementations of JXTA.

The figure provides a general overview of JXTA concepts and the relationship between them. Thebasic principle that one should keep in mind is that, conceptually, nearly everything is a resourcein JXTA. Peers are resources, resources are located on peers and peer groups, and resourcesare accessing or consuming local resources or resources located on other peers. The resourceconcept is the Ouroboros of JXTA. The two main exceptions are advertisements which representresources and IDs which identify resources.

Peer

For JXTA, a peer is “any networked device (sensor, phone, PDA, PC, server, supercomputer,etc.) that implements the core JXTA protocols”. In our metaphor, a peer is the king or queen of atribe, which we shall sometimes refer to as the ruler. For the time being, we will consider that a hu-man will use one and only one electronic device at once. Hence, we do not make a differencebetween a peer and a human being using a device running JXTA.

Technically speaking, the tribes are actually running the JXTA protocols. An island and its tribe isa networked device running a software application implementing the JXTA protocols. A tribe is nota peergroup in our metaphor. Some tribes are nomadic in nature and travel from island to islandwith their ruler. We can use several computers (one at home, one at work, etc...). Our PCs cansometimes be used by other members of our family or by our colleagues. Thus, the island is tem-porarily invaded by other tribes.

So, what is the difference between a peer and human being using its device? Fact is that withJXSE, you can save different configuration files on the same computer (one per user for example).It is even possible to run several instances of P2P applications simultaneously on the samedevice. This is comparable to having several tribes occupying a big island.

Technically speaking, a peer is a tribe and its leader with its configuration files. These could even-tually be located on a memory stick, meaning that a tribe can run JXTA-enabled software applica-tions from many devices (i.e., islands).

JXTA requires that:

• “A peer should not make any assumption about the runtime environment (island shape orsize) or programming language (tribe language) of other peers”.

Understanding JXTA The Concepts - 41

• “A peer should not make any assumption about the capabilities or complexity of the net-work of peers supporting the JXTA protocols”. There are small and big islands, close ordistant, easily reachable or not, with big and small tribes, providing little or many productsor services.

• “A peer wishing to interact with other peers through JXTA should implement the protocolsit decides to implement fully, not partially”. Kings and queens should play the game of ex-changes according to the rules.

• “A peer should cache advertisements and forward messages for other peers, althoughthis type of participation is optional”. Being good to the community helps.

A peer can take different responsibilities within a JXTA network. It can be a simple peer, connect-ing from time to time to the network and performing exchanges with other peers. It can also be arendezvous peer, that is, a tribe facilitating the research of other tribes and of services provided byother tribes.

Another type of responsibility is being a relay peer. Sometimes, tribes are located on remote is-lands or surrounded by unbridgeable coral reefs (firewalls, NAT, router, proxies...). Contrary torendezvous peers, the relay peer concept is not covered by the JXTA specification document. It isa necessary by-product of the implementation of JXTA in Java over TCP/IP. We will describe thislater.

JXTA peers are not obliged to implement all JXTA protocols to participate on a JXTA network, butthey are required to implement at least some of the core protocols described in the JXTA CoreSpecification together with corresponding concepts to make them operational. In other words,kings and queens must (at least) participate in the process of finding routes from one tribe islandto another.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: These minimal responsibilities consist in i) letting boats from other tribes moor onyour island to deliver messages, ii) helping tribes find a route to their destination if such informa-tion is available, and iii) preparing your own dried leaves and ink in order to write messages to theattention of other tribes.

Understanding JXTA The Concepts - 42

Consider that a ruler is not obliged to answer all requestsfrom other tribes. He is free to do what he wants with themessages he receives (deleting, answering or storing themfor the future), whenever he wants.

Let's imagine that Panama was a huge island covering allthe Americas from Alaska to the bottom of Argentina andthat its famous canal was not built yet. The shortest tradingroute from Cuba to Hawaii would be to navigate to the nar-rowest strip of land in “big” Panama, unload goods, crossthe land strip, reload the goods on another boat and navig-ate to Hawaii.

In JXTA, the ruler of 'big' Panama does not have the oblig-ation to facilitate the exchange of goods from Cuba toHawaii through the land strip, although it would be welcome. However, it should indicate theroutes it knows to reach Hawaii if Cubans ask them.

Currently, peers are characterized by an ID, called PeerID. There is currently no user concept in

JXTA and JXSE. This ID is part of the configuration parameters of the application running theJXTA protocols. This can be confusing because a human being can be running multiple instancesof the application on one or many devices, using one or many peer IDs, which can cause strangebehaviors. This issue was not anticipated in the initial design of JXTA.

Peer Group

A peer group is a set of tribes having some common interests who have decided to organizethemselves as a group. In JXTA, there are two fundamental peer groups called world peer groupand the net peer group. They both have unique IDs known by all applications implementing JXTA.Typically, a peer always connects to the JXTA network via at least one peer group by establishingconnections with other members of this peer group.

The key fact to remember is that a peer can belong to many peergroups at once while being con-nected to the JXTA network. That is, it can operate many different transactions with many differentpeers belonging to many different peergroups at once.

The world peer group must implement at least the minimum services required to establish connec-tions with other JXTA peers. By default in JXSE, the world peer group implements all the services

Understanding JXTA The Concepts - 43

defined as part of the JXTA specification document, although it is not required to do so. This is re-lated to the fact that a peer may (but does not have the obligation) to implement all JXTA proto-cols.

Peer groups are created according to ahierarchical structure where a child hasone and only one parent. For example, thebeef merchants peer group is a child of thecattle raisers peer group, which is a childof goods merchants peer group, which is achild of the net peer group.

By default, the parent of the net peer groupis the world peer group, although this is not an absolute requirement. Typically, a JXSE peer willnot connect to JXTA through the world peer group, but rather via the net peer group, which inher-its of the services made available from its parent, the world peer group. All additional peer groupscreated by peers should use the net peer group or any sub-peer group of the net peer group asthe parent, although it is also technically possible – but not recommended – to use the world peergroup as a parent in JXSE.

The last thing to remember is that peer groups are considered as a type of module in the JXTA paradigm.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: The world peer group could be (more or less) compared to Gaia, the Greek god-dess personifying earth, or any other religious deity that has created the world, and the net peergroup could be compared to humanity, that is, the world population. Humanity uses resources ofthe world to perform its activities.

Service

The JXTA protocols are implemented with the help of services and modules. These are the basicentities representing 'things' a JXTA peer must know how to 'do' to operate on the JXTA network.Services and modules are constituents of the glue that makes the JXTA network stick together.The other constituents are standard messages defined in JXTA.

At first, the distinction between modules and services in JXTA is not obvious. The relationshipbetween both concepts is not explicitly described in the protocol specifications. However, a mod-ule is defined as “an abstraction used to represent any piece of code used to implement a behavi-or in the JXTA world”.

Understanding JXTA The Concepts - 44

On the other side, there are many services described in the JXTA protocols specification docu-ment. These 'behavior' specifications can be considered as functionality specifications. Hence, theimplicit link between modules and services is that each service is ultimately implemented as amodule.

Services can be immediately loaded and available on the local peer, or can be accessed remotelyusing a pipe or another proxy module. Eventually, an authentication module can be used to checkcommunication with the service. The code can also be fetched from a remote location and loadedlater. The publication of a service advertisement should contain all necessary information explain-ing how to use it or to invoke it.

The JXTA specification 2.0 mention two types of services:

• Peer Services, where individual instances run on each peer. If a peer goes down, the indi-vidual service goes down too. Each instance of the service should publish its own advert-isement.

• Peer Group Services are published within peer group advertisements. Instances of theseservices run on each peer participating to the peer group. Typically, these services maycommunicate with each other.

Moreover, a JXTA-enabled service is defined as a service published using a Module SpecificationAdvertisement14.

Warning:Warning:Warning:Warning: All these types and sub-types of services, together with their publication processes, canbe confusing. For example, the difference between a peer service and a JXTA-enabled service isunclear. This will most probably be clarified in future versions of the JXTA protocols. For the timebeing, one should remember that, in practice, peers are modules creating peergroup modules andthat services (which are modules too) are attached to peergroups. A peer communicates and op-erates with other peers using the services attached to the peer groups it has created. Customizedor additional services can be loaded on peergroups created by the peer too.

JXTA defines core and standard services, these implement the protocols that we will describelater:

• Access Service – This is the service verifying the credentials and information of a rulermaking a request to access a resource from a tribe or a peer group, in order to find out ifhe or she has access to what is requested.

14 We will cover module specification advertisements later.

Understanding JXTA The Concepts - 45

• Discovery Service – This is the service allowing tribes to search for other tribes or peergroups within a peer group. Technically speaking, they will search for the advertisementsrepresenting them. The discovery service can also help searching for other types of re-sources, such as routes to islands or trading routes between tribes.

Warning:Warning:Warning:Warning: Newcomers to JXTA often believe that discovery means finding out whether apeer is connected online. Consequently, they implement complex strategies in JXSE in-volving expiration of advertisements to check whether peers (i.e. devices) are connectingor disconnecting to the Internet. They republish advertisements at regular interval as a'proof' that a peer is alive. Soon, they get frustrated because this technique does not workfor reasons that will become clear later.

In the JXTA paradigm, discovery means discovery of advertisements describing re-sources (such as peers, peergroups, services, etc...) within a given peergroup. It is NOTNOTNOTNOTthe instance of these resources themselves. It is like confusing a Class and an object in-

stance of this class in the Java programming language.

• Endpoint Service – This service is responsible for transmitting a message from one peerto another peer.

• Membership Service – This is the service used to allow or reject a new request for mem-bership in a peer group. It can be as simple as always approving a new member or morecomplex, like using a voting procedure. A tribe willing to join a group must first find one ofits members and request to join the group.

Warning:Warning:Warning:Warning: Many newcomers to JXTA, and more specifically to the JXSE technology, areoften disappointed by the currently available implementations of the membership service.Their expectations are high and not met. This situation will surely improve in the future re-leases of JXSE as there is a growing demand in the community.

• Peer Info Service – This service helps peers find about the status of other peers in a peergroup.

• Pipe Service – This service creates trading routes between one or many tribes (not is-lands) belonging to the same peer group.

• Rendezvous Service – This service is operated by peers acting as rendezvous to facilitatethe efficient forwarding of queries to peers belonging to the peer group.

• Resolver Service – This service is used to address queries made by a tribe leader to an-

Understanding JXTA The Concepts - 46

other tribe leader and to collect responses.

Some services implement core specifications that all JXTA implementations should deliver. Otherservices are considered standard and should preferably be implemented, but this is not mandat-ory. Remaining services are not mandatory.

Service/Functionalities Requirement

Endpoint Service Core

Resolver Service Core

Discovery Service Standard

Peer Information Service Standard

Pipe Service Standard

Rendezvous Service Standard

Resources

There are five basic types of resources in JXTA: peer groups, peers, pipes (i.e. trading routesbetween tribes), contents and services. A resource is something conceptual that is uniquely identi-fied with an ID in messages and advertisements exchanged between peers. It is the most abstractconcept in JXTA. Resources are represented by usually one, but sometimes up to three advertise-ments in JXTA.

Advertisement

In JXTA, an advertisement is what represents and describes a resource using the minimal com-mon dialect understood by all tribes (XML). It may also contain configuration information about aresource. In our metaphor, advertisements are written down on the dried leaves prepared by eachtribe and exchanged among them. Typically, your tribe, like any other tribe, will notify its existenceto other peers with an advertisement. This is also true for peer groups and all other JXTA re-sources.

There are several types of advertisements, for example: peer advertisements, peer group advert-isements, rendezvous advertisements, etc... Conceptually, it is not uncommon to confuse advert-isements representing a resource with the resource itself. We often talk about discovering re-sources, but as mentioned earlier, what we really mean is discovering advertisements represent-ing these resources. Accessing those resources is a completely different operation.

Understanding JXTA The Concepts - 47

Warning:Warning:Warning:Warning: It is key to remember that if an advertisement describing a resource is found, it does notnecessarily mean that an instance of that resource is 'up and running' on the JXTA network.

Peer Advertisement

A peer advertisement contains at least a peer ID and the ID of the peer group it belongs to. Even-tually it can contain a name, a description of the peer, an endpoint address (i.e., the location of theisland you are currently occupying) and attributes such as being a rendezvous for a peer group.

Warning:Warning:Warning:Warning: Earlier, we said that peers could participate to many groups simultaneously Since eachgroup has its own peergroup ID, this means that multiple peer advertisements exist for given peer.This is can be confusing if one assumes that a peer should be represented by one advertisementonly. Fact is, each peer advertisement should be published in its corresponding peergroup. A peeradvertisement is an advertisement in a group.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: Peer advertisements are similar to passports and driving licenses. They both con-tain a picture representing you, but are not physically you. You may have both a passport and adriving license which both represent you in different communities. A credit card is another ex-ample.

Peer Group Advertisement

A peer group advertisement contains at least the ID of the peer group and eventually a name anda description of the peer group. Typically, it designates a set made of peers who have agreed tooperate a common set of services for the community they constitute. The list of IDs of these ser-vices is also part of the advertisement.

Publication

Advertisement publication is a common operation in JXTA. It may consist of sending copies of anadvertisement to one or many members of your peer group. This is called remote publication.Publication can also be performed locally, meaning that other tribes will have to come to your is-land to find out about the advertisements describing what you have to offer.

Typically, a peer will locally cache its advertisements and those received or fetched from otherpeers for future use, improving general responsiveness of the JXTA network by avoiding unneces-sary queries. An advertisement is always published with a limited duration. When it has expired,the advertisement should be considered as obsolete.

Understanding JXTA The Concepts - 48

The publication of a peer group advertisement is always performed in the peer group itself and theparent peer group of that peer group. This enables parent-child relationships.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: A tribe leader may keep the dried leaves describing other tribes, group of tribesand resources they have to offer in a small box. After some time, some dried leaves will be too rot-ten or too damaged to be read and new ones should be fetched from remote tribes. A leader canalso decide to burn all his dried leaves if he or she wants.

Warnings:Warnings:Warnings:Warnings: A tribe leader should never forget that in the process of searching for other tribe advert-isements, for example, his people may get lost at sea, say, because of a storm. It does not meanthat the queried tribe (or resource) description does not exist. On the other side, it is not becauseone has a copy of a tribe advertisement (or resource advertisement), that the tribe (or service) stillexists (or is available). Volcanoes do erupt and tsunamis do happen. Some tribes truly disappearforever while copies of their advertisements still exist in other tribe's box of dried leaves. This isnot to be confused with tribes who are in hiding in a mountain cave for some period of time (i.e., adevice is disconnected from the network). Just because you can't reach them does not mean theyare gone forever.

Conversely, new tribes may appear. Yet, you will not know about them unless you specificallysearch for new tribes or they get in contact with you. Your box of dried leaves is a temporary rep-resentation of the reality, but not the reality itself. The validity of the information contained in yourbox degrades with time.

At last, a leader should not make any assumption about the time its people will need to fetch mes-sages and advertisement from other tribes. They may travel long distances before coming backwith results. This leads to another issue: what if a tribe has disappeared completely? You cannotascertain with a situation whether your peers are lost at sea or still searching. The solution is toset a time limit and assume that a tribe has probably disappeared if you cannot get an answerfrom them.

ID

In JXTA, an identifier (ID for short) is a unique reference to a resource. Different resources havedifferent IDs. Different types of resources have different type of IDs. For more details, the readershould read the JXTA specification document.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: IDs are the distinctive sign of each tribe or peer groups, for example.

Understanding JXTA The Concepts - 49

Content

A content is something 'material' (like a text file, a PDF file, an image or some binary code) as op-posed to services which do not have physical properties. However, the implementation of a ser-vice is something material.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: This could be the cargo carried by boats across the ocean between tribes (bana-nas, chickens, precious wood, etc...) or the weather forecasting method written down on a driedleaf.

Codats

Each content is published with a unique ID. The combination of a content and an ID is called aCodat. It belongs to a peer group. If the same content has to be published in two different peergroups, two codats are required. You can also create two codats for the same content in the samepeer group.

Pipes

Pipes are means for peers to exchange messages. Messages can be propagated from one peerto one or many peers. If there is only one destination, a pipe is called a point-to-point pipe. If thereare many destinations, they are called propagate pipes. JXTA also defines a secure unicast pipeto exchange information in a secured and confidential way between two peers.

To send data from one peer to another, a peer packages the data to be transmitted into a mes-sage and sends the message using the output end of a pipe. On the opposite end, a peer receivesa message from its input side and extracts the transmitted data.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: Pipes are trading routes between tribes and their ruler, notnotnotnot islands. Tribes can re-locate to new islands (i.e., change of IP address or devices). A message forwarded via an estab-lished trade route should reach the proper tribe, no matter its location. Don't forget about rulers us-ing memory sticks, their messages should be forwarded to the proper island (i.e., the devicewhere the memory stick is used).

Module

A module in JXTA is a set of functionalities that a peer can use, offer or obtain from another peer.It is an abstraction for services and applications in the three layer cake model15. A module can beinitialized, started and stopped. In JXTA, an application is a module that can be loaded and ex-

15 See page 35.

Understanding JXTA The Concepts - 50

ecuted on a device. It may eventually implement theJXTA protocols as services. However, remember thatthe application concept in the 3 layer cake is becom-ing obsolete.

There are 3 type of advertisements associated withmodules:

• Module Class Advertisement – This advertisement simply declares the existence of aclass of modules, but does not provide any information about their implementation or howto use them. It contains a Module Class ID, the name of the class of modules and its de-scription. A typical example is the peer group concept.

• Module Specification Advertisement – This advertisement provides some interfacing char-acteristics of a module16. This advertisement contains a unique Module Specification ID, aname, the name of the module creator, a URI to a specification documentation, a specific-ation version number, a specification description and parameters (usually IDs of othermodule specification) for the specification. Typical examples are: the world peer group,the net peer group, a customized peer group... Each can offer a different set of services.

It can contain also contain a pipe advertisement to communicate with other instances ofmodules of this specification, or the module specification ID of a proxy module which canbe used to communicate with other instances of modules of this specification. Lastly, itcan also contain the module specification ID of an authentication module which may berequired to communicate with other instances of modules of this specification.

Remark:Remark:Remark:Remark: This is not very easy to understand at first. In our metaphor, we mentioned anastrology service. Typically, its module specification advertisement would contain at leastthe following mandatory information: ID=34 and version=1.017.

We could include the Module Specification ID of an authentication module to make surethat those requesting astrology services have the right to do so. We should also include apipe advertisement that peers willing to use the astrology service should use to get in con-tact with an astrologer.

We could also use another method to communicate with the peer running the astrologyservice. We could specify the module specification ID of a proxy module and have the as-

16 Conceptually, this is more or less corresponding to the interface or abstract class API concept in the Java programming language.Functionalities are described but those objects still need to be implemented in order to be instantiated.

17 This would be the functional version of the module, not the implementation version.

Understanding JXTA The Concepts - 51

trology client peer search for an implementation of that proxy module, which he/she couldrun on his/her device. This peer would load that module on its device and use it to com-municate with the astrologer located on another island.

• Module Implementation Advertisement – This advertisement provides information about aconcrete implementation of a module specification. It contains a Module Specification ID(i.e., the one of the corresponding Module Specification Advertisement), some compatibil-ity information, the code of the module implementation or some information about themodule implementation code, a URI to the package containing the code of the module im-plementation, the name of the entity providing the module implementation and some para-meters for the module implementation.

If we consider the self-service weather forecasting method again, we know that if we wantto run it on our device, we need to find a version written in a language that our tribe willunderstand. If this is Java, we will be looking for a .jar file. Although the content of this

file could be included in the module implementation advertisement, we should preferablyload it using the URI specified in the advertisement. In Java, this is typically performedwith the loadClass() method.

Once loaded on the peer, the weather forecasting method can now be used by the peerand can be offered as a service for other peers of the group.

If you did not get it all at once, don't worry. Just remember that:

i. Modules are piece of code loaded one way or another on devices.

ii. There are different ways to establish communication with or between modules.

iii. Contrary to other types of JXTA resources, modules are described with three types of ad-vertisements instead of one. One type identifies the module class (i.e. category) in gener-al, one describes the functional version of the module and one describes how to retrievean implementation of the function version in a specific programming language.

The Protocols

JXTA defines 6 protocols. The core protocols are the Peer Resolver Protocol (PRP) and the End-point Routing Protocol (ERP). The standard protocols are the Peer Discovery Protocol (PDP), thePeer Information Protocol (PIP), the Pipe Binding Protocol (PBP) and the Rendezvous Protocol(RVP). Higher protocols use lower protocols to delegate work. Some lower protocols can some-

Understanding JXTA The Protocols - 52

times call higher protocols.

Every JXTA peer must im-plement at least the End-point Routing Protocol andthe Message PropagatingProtocol, which is a sub-protocol of the Peer Resolver Protocol, in order to participate to a JXTA network. We will describeeach JXTA protocol using a bottom-up approach and after describing the role of messages inJXTA.

Message

Messages are documents exchanged between JXTA peers. JXTA defines different type of mes-sages using a Matryoshka doll approach. The Matryoshka doll is a Russian is a set of dolls in de-creasing size and nested inside each other. They are opened recursively to find a smaller onewithin the first, an even smaller one inside the next, etc.

As messages are created by top protocols and go down to the bottom of the JXTA protocol stack,they can be wrapped within other messages, which can be wrapped up in other messages, etc...Some message elements can be added along the way. When the bottom protocols forward re-ceived messages to upper protocols, these messages are stripped from their layers to extract thecore.

We will briefly describe each type of JXTA message used by protocols. For more details, the read-er should read the JXTA specification document.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: A message is a dried leaf where kings and queens write the information they wantto communicate to other tribes using the common languages of tribes.

Endpoint Routing Protocol (ERP)

Endpoint Service

Before we describe the endpoint routing protocol, we need to describe the endpoint service. Thisservice is responsible for transmitting messages from one peer to another using the networktransportation protocols upon which a JXTA implementation is operating (i.e., TCP, multicasting orHTTP for JXSE). It is not responsible for finding a route between two peers. This is the responsib-ility of the endpoint routing protocol that we will describe later.

Understanding JXTA The Protocols - 53

Metaphorically:Metaphorically:Metaphorically:Metaphorically: an endpoint is the JXTA concept for identifying the location of the island a tribe oc-cupies. It is the source and destination of any message. Any messages managed by the endpointservice should have a source and a destination endpoint address.

Endpoint Address

An endpoint address indicates how and where a message should be sent to a peer by providinginformation specific to the transportation layer used by the JXTA implementation. It is made of fourparts (protocol, address, serviceName, serviceParam), but only the two first parts are

mandatory.

For example: tcp://10.42.218.15:9701/PipeService/urn:jxta:uuid-

E558B6E34E2B40958B3487E2342466013293A926FEA6485282A7D52DA855F58

604

In this example, the transportation protocol is TCP, but it could also be HTTP or any other protocolsupported by the JXTA implementation. The destination is an IP address with a port number. Themessage is for the pipe service and the value of the transmitted parameter is a pipe ID.

A peer can publish several endpoint addresses for different network interfaces (TCP/IP, HTTP). Apeer knows a direct route to another peer if it knows one of its endpoint addresses and if it canuse the corresponding network protocol successfully it to reach it without using intermediarypeers. Such intermediary peers are also called hops.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: an endpoint address is the location of an island on a map, with eventually thename and address of an individual to which a message is sent.

Endpoint Routing Protocol

The Endpoint Routing Protocol is the fundamental JXTA protocol on which all other JXTA proto-cols directly or indirectly rely to perform their operations. This protocol allows JXTA peers to sendmessages to other JXTA peers, even when no direct routes18 to those destination peers is knownby the sending peer. This protocol lies between the transportation layer used by JXTA implement-ations and the other JXTA protocols. It is primarily used to find out about the current status of thenetwork topology (i.e., location of islands and tribes in the ocean).

18 There are many technical reasons why direct routes cannot always be established between peers (NATs, Firewalls...). We will cover thislater.

Understanding JXTA The Protocols - 54

When a message has to be sent from peer A to peer B,peer A takes a look in its cache for a known route frompeer A to peer B. If such a route is known, the messageis sent across that route using the endpoint service. Else,peer A sends a route resolver query to members of itspeer group. Every peer receiving this query should (but isnot obliged to) send back the routes to peer B they know.Routes responses will contain one or several path routesto peer B, specified by a semi-ordered list of peer IDs(i.e., hops). Peer A can then use one of these routes tosend its message to peer B.

Let's imagine that peer A receives a route to peer B across many peers. If it knows a shorter routeto one of the intermediary peers to reach B, it can optimize it before sending its message. If anyintermediary peer can optimize the route further while the message is on its way, it may do so too.If peer A can directly access peer B from the information it received, it does so directly. No inter-mediary peer is called. This is the ultimate optimization. If a peer does not have a route to anotherpeer and does not get a response by sending a route resolver query, it gives up and notifies thecaller of the service.

An optimization consists in checking for direct connections to peers belonging to the route peer listwithin a route message query response, starting with the last hop. In our figure, the last peer is B,but we don't have a direct connection to it. The next-to-last peer is Z and we have a direct connec-tion to it, so we can erase any peers above it in the list, that is, peer X and Y. Our route is nowshorter. If we go over the list in the right order again, we get peer A > peer Z > peer B. Peer A willsend its message to peer Z, while indicating that the recipient is peer B. Typically, intermediarypeers are relay peers.

Remark:Remark:Remark:Remark: Unfortunately, JXSE 2.5 and 2.6 only checks the first hop of a route if it cannot reach thedestination directly and does not try the others19. This will most probably change in future re-leases, since long routes are sometimes necessary.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You want to notify your existence to the tribe providing the self-service weatherforecasting method. You know who they are (ID), but you don't know how to reach their island(peer). Therefore, you write a request for navigation routes to that island on a dried leaf and ask

19 The underlying assumption is that it potentially takes only one peer with a public address (i.e., hop) to connect any peers with privateaddresses. We will cover this topic deeper later.

Understanding JXTA The Protocols - 55

your people to navigate to other known tribes for answers. If these tribes have this information andare willing to give it, your people brings it back on dried leaves. These can be series of smallmaps. You may compare the information received with other information you already have and de-cide to create an optimized map to the forecaster tribe island.

Your people are now ready to notify your existence to this tribe. If they can reach the destinationisland directly, they will do so. Else, if the distances are too long or the destination island is part ofa group of islands surrounded by coral reefs, they will need to navigate through several islands toreach it. On their way, your people will show the map used to reach the destination island to tribesencountered on intermediary islands. These tribes may decide to optimize this map more to thebenefit of you and your people.

Some tribes are nomadic in nature. Although you may already have routes to reach them, youknow that these will become invalid in the future and you will need to find new ones to reach themagain from time to time.

ERP Messages & Advertisements

The endpoint routing protocol uses several messages and message elements:

• Route Query Message – This is the type of message peers send to obtain informationabout routes to other peers. It contains the ID of the destination peer and the route advert-isement of the peer requesting the route. The latter is required to send a reply to thequery.

• Route Response Message – This is the response sent by those receiving route querymessages. It contains the route advertisement to the destination peer mentioned in thequery, together with the route advertisement of the peer who has sent the query.

• Route Advertisement – It contains the ID of the target peer, its endpoint address and a listof access point advertisements to reach that peer.

• Access Point Advertisement – This advertisement provides a list of endpoint addressesfor a peer ID, sorted in the preferred order of usage. They explain how to reach peerswhen trying to establish a route to destination peers.

• NACK Message – This optional message is typically sent by peers receiving a message toroute to another peer for which they don't have a route. It tells sending peers that the se-lected route to destination is invalid.

Understanding JXTA The Protocols - 56

Top-Down-Top

In JXSE, the endpoint service implementation offers a method called addIncomingMessageL-

istener(...) to let anyone register a listener for specific messages reaching the current peer.

A service name and eventually a service parameter are provided when calling the method.

Each time a message reaches the peer, the endpoint service will search first for a listener havingthe proper service name and service parameter. If no such listener can be found, a listener withthe proper name and a null service parameter will be searched. If none can be found, the mes-

sage will be discarded.

Remark:Remark:Remark:Remark: the JXSE 2.6 implementation of the endpoint service offers additional methods (includingsome which were not available in 2.5)20:

• Messenger getMessengerImmediate(EnpointAddress...) - This method can be

used to retrieve a Messenger object to send a message to a remote peer. If no messen-

ger is available to the target peer, one is created and resolved asynchronously. The resol-ution may or may not fail. If successful, this peer will use the messenger to send the mes-sage.

Warning:Warning:Warning:Warning: It is not because a message is sent successfully from a peer that it necessarilyreaches the target peer. There is always small probability of getting lost when travelingacross multiple hops.

• Messenger getMessenger(EnpointAddress...) - This method is blocking and

only returns resolved messengers (or null if none if the endpoint address cannot be re-

solved). It can also be used to send messages to target peers.

• boolean isReachable(EnpointAddress..., tryToConnect) – This is the

ping() method of JXTA/JXSE.

◦ If the 'try to connect' boolean is not set, the method will indicate whether this peer hasalready managed to reach the target peer and still has an operational messenger to it.

◦ If the 'try to connect' boolean is set, and if no operational messenger to the target peeris available, the method will try create one. If it resolves successfully, the method willreturn true. Otherwise, it will return false.

• boolean isConnectedToRelayPeer() - This method indicates whether this peer has

20 We will not cover all methods offered by the EndpointService, but only those that software engineers might use in their own

applications.

Understanding JXTA The Protocols - 57

managed to connect to a relay peer21.

• Collection<PeerID> getConnectedRelayPeers() - This method return the set of

relay peer IDs to which this peer is connected to. Typically, in JXSE 2.6., a peer is onlyconnected to one relay at once.

• EndpointRoutingTransport getEndpointRouter() - The methods gives access

to the endpoint routing transport (which is responsible for the routing of messages) via amethod called getRouteController(). The route controller is the active manager of routes toremote peers. It uses the local cache of fetch routes from remotes peers. Some of itsmethods are:

◦ Collection<RouteAdvertisement> getAllRoutes() - The method gives ac-

cess to all actively used routes to reach remote peers.

◦ Collection<RouteAdvertisement> getRoutes(PeerID) – This method

provides all routes actively used to reach a specific peer.

◦ RouteAdvertisement getLocalPeerRoute() - This method return a route to

this peer.

Typically, route controller methods should only be used to trace connectivity issuesbetween peers.

Rendezvous Protocol (RVP)

The rendezvous protocol (RVP) builds on top of the endpoint routing protocol and is implementedas the rendezvous service. It contains of three sub-protocols: the message propagation protocol,the peerview protocol and the rendezvous lease protocol. Only the message propagation protocolis mandatory in JXTA, the others are optional. Typically, in JXSE, it allows propagation of mes-sages over network transportation layers that do not support multicasting or to peers located toofar to be reached by traditional TCP/IP broadcasting.

Message Propagation Protocol

This is the only mandatory protocol of RVP. It helps simple peers propagating individual mes-sages to other peers within a peer group. In our first example, Mary is connected to Arthur whobehaves as a rendezvous for the peer group. She asks him to help her send a message to Filip byproviding its peer ID. Arthur, with the help of Hillary, transmits the message to Filip.

21 We have not covered relay peers yet. For now, these are peers facilitating communication between hardly reachable peers.

Understanding JXTA The Protocols - 58

Technically speaking,Mary is lucky that Arthurknows about Hillary, whoknows about Filip. Maryand Arthur may haveknown about each othereither because they arelocated on the sameLAN, just like Hillary andFilip are on the sameLAN. Arthur may knowabout Hillary and vice-versa, because they both have a permanent public IP address which theyrely on to communicate with each other. We could rely on the endpoint routing protocol to find aroute between peers each time we are missing one or each time we need to send a message, butthis is not very efficient. This can be improved with the peerview protocol and the RendezvousLease protocol which we will describe further.

If these two protocols are implemented, then message propagation as described in JXTA definestwo other behaviors: the connection to a rendezvous peer and the propagation control which wewill describe later.

PeerView Protocol

This optional protocol helps rendezvous peers of a peer group organize themselves, by maintain-ing a distributed list of active peers within a peer group. This list is called a peerview. A peerviewoperates at the peer group level. Its content is distributed among the rendezvous peers of the peergroup. The set of active rendezvous of a peer group is called a rendezvous peerview. It is made ofthe peerview peers flagged as rendezvous in the peer group.

In our example, the members of the rendezvous peerview are Lilia, Mark, John, Arthur and Hillary.The members of the peerview are the member of the rendezvous peerview plus Mary, Julia, Eth-an, Mohamed, Filip, Sanchez and Yoko.

Each rendezvous peer of a group is responsible for maintaining its local portion of the peerviewand exchanges peerview messages with other members of the peerview to learn about the exist-ence of other rendezvous in the group. These messages can be probe or response messagescontaining rendezvous advertisements. Probe messages are used to find out about other peers in

Understanding JXTA The Protocols - 59

the peer view.

An edge probe is performed when a peer not belonging to a peerview wants to learn about mem-bers of a peer view. The response will contain rendezvous advertisement from which the rendez-vous service name identifying the peer group peerview can be retrieved. A participant probe is amessage sent from a peerview member to another peerview member.

There are four types of responses to probes:

i. Participant Response containing the rendezvous advertisement of the responding peer

ii. Participant Referral Response containing the rendezvous advertisement of another peerbelonging to the peerview

iii. Shutdown Notification indicating that a peer is shutting down and that it will not be avail-able anymore

iv. Failure Notification indicates that a peer has failed and is no longer available

Metaphorically:Metaphorically:Metaphorically:Metaphorically: This is the mechanism that tribes belonging to an astrology group would use tokeep a list of active members, for example.

Rendezvous Advertisement

Every peer acting as a rendezvous for a peer group publishes a rendezvous advertisement con-taining at least the peer group ID, the peer ID, the rendezvous service name identifying the peer

Understanding JXTA The Protocols - 60

view and eventually the name of the peer and a route advertisement to it.

Rendezvous Lease Protocol

The rendezvous lease protocol is an optional protocol allowing non-rendezvous peers of a peergroup to receive messages propagated within a peer group. The subscribing peer requests alease from a rendezvous via a Lease Request Message containing its peer advertisement. A ren-dezvous peer grants the lease via a Lease Granted Message containing the duration of the lease,the ID of the rendezvous peer granting the lease and eventually its peer advertisement. A lease iscanceled with a Lease Cancel Message containing the peer advertisement of the peer cancelingthe lease.

Peer Connection to Rendezvous

A peer can connect to a rendezvous via a lease and therefore obtain messages propagated withina peer group. The connection is established with the help of the Endpoint Routing Protocol. Theservice name and service parameter used in the endpoint address in the lease messages are re-spectively JxtaPropagate and the peer group ID, for example:

tcp://10.42.218.15:9701/JxtaPropagate/urn:jxta:uuid-

E2E76334369C484E8986AC6A6EE02F3E02

In order to receive propagated messages, a peer implementing the Rendezvous protocol will haveto register as listener of incoming messages in the endpoint protocol.

Propagation Control

A rendezvous peer should propagate the messages it receives from its leases to non-rendezvouspeers, unless:

• Loop – The message has already been processed by the rendezvous peer. This can bedetected because a list of visited peers is maintained in propagated message. Each timethe message reaches a new peer, the peer ID is being added to the list.

• TTL – The time to live of the message is decreased by one each time it reaches a peer. Ifit becomes 0, then message is not propagated anymore.

• Duplicate – A message can reach the same peer twice via different paths. If a peer hasalready received a message, it will discard it.

The Rendezvous Propagation Protocol is also responsible for providing:

Understanding JXTA The Protocols - 61

• The source of a propagated message – In our earlier example, Filip will know that themessage he receives came from Mary.

• The list of peers who already have received the propagated message while it is beingtransmitted – When Mary sends her message to rendezvous peers, it could22 eventuallyreach back Arthur by the Mary > Arthur > Hillary > Mark > Arthur path if the propagationmethod was inefficient. Arthur will be part of the list of peers who already have receivedthe message. It won't be propagated further, since Arthur already propagated it in an earli-er step.

• The listener name – That is, the service that will handle the propagation of messages.

• The remaining time to live of the propagated message – It is decreased each time itpasses through a peer and when it reaches zero, the message is not propagated any-more.

Remark:Remark:Remark:Remark: A developer should never have to deal with the rendezvous plumbing. It should never ac-cess the corresponding service to establish connections with rendezvous peers in JXSE. Newmechanisms to establish such contacts have been made available in new classes called the Net-

workManager and the Networkconfigurator via seeds.

It is key to remember that a peer may participate to multiple peer groups and act as a rendezvousin some of them and not in others.

The JXSE 2.6 implementation of the rendezvous service offers methods which can be useful forsoftware engineers:

• startRendezVous(), stopRendezVous() & isRendezVous() - These three

methods can be used to manually initiate a rendezvous behavior of a peer within the cor-responding peer group or to stop that behavior. One can also find out whether the rendez-vous behavior is enabled.

• setAutoStart(boolean auto, long period) - This method can be used to peri-

odically change the rendezvous behavior of this peer within a peergroup according to thenumber of available rendezvous and edge peers requesting leasing. If there are notenough rendezvous, the peer automatically becomes a rendezvous. If there are too manyrendezvous, it can demote itself to a simple edge peer.

• List<PeerID> getLocalRendezVousView() - If this peer acts as an edge in its22 This would happen if the forwarding method was to forward the message 'à la Gnutella' to all known peers without taking into account

the list of peers who already have received the message before proceeding.

Understanding JXTA The Protocols - 62

group, this method returns the rendezvous peer ID it is connected to (if any). If it acts as arendezvous, it returns the set of other rendezvous peers it knows about. This list is not ne-cessarily the whole peerview.

• List<PeerID> getLocalEdgeView() - If this peer acts as an edge in its group, this

method returns an empty list. If it acts as a rendezvous, it returns the set of edge peerswho have a lease with the rendezvous peer.

• boolean isConnectedToRendezVous() - If this peer acts as an edge in its group,

this method returns true if it has a lease with a rendezvous and false otherwise. If it

acts as a rendezvous, it returns true if it know about other rendezvous in the rendezvous

peerview, false otherwise.

Top-Down-Top

Typically, the rendezvous protocol will not send its messages itself, but invoke the endpoint rout-ing service. When a peer acts as a rendezvous in a peer group, the rendezvous service will re-gister proper listeners in the endpoint routing service to make sure rendezvous related messagesare collected properly.

Pipe Binding Protocol (PBP)

In JXTA, pipes connect a sending endpoint to one or several other receiving endpoints. The send-ing end of the pipe is called the output and the receiving end is called the input. JXTA defines uni-directional asynchronous unicast pipes. Unidirectional means that the data is moving only from theoutput end to the input end. Asynchronous means that the sending endpoint can send data at anytime and that receiving point can read it at any time. Unicast means that the communication is lim-ited only from point-to-point. Such pipes are called JxtaUnicast pipes.

JXTA also defines secured pipes using TLS 1.0 (Transport Layer Security). Such pipes are calledJxtaUnicastSecure pipes. There are also diffusion pipes for one-to-many peer communication

called JxtaPropagate pipes. The data sent by the sending endpoint is received by each receiv-

ing endpoints.

Understanding JXTA The Protocols - 63

The Pipe Binding Protocol is responsible for es-tablishing pipe connections between endpoints,but is not responsible for the data transferbetween these endpoints. It relies on the endpointprotocol for initial data exchanges to establish thepipe connection and for transporting databetween endpoints over the pipe connection. Theendpoint protocol take cares of crossing naturaland artificial network boundaries, which can implytransferring data through several peers before itreaches the destination endpoint.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have decided to establish a trade route between your tribe and one or severalother tribes to exchange goods (chicken, bananas, wood, etc...). You have asked your people tofind out whether other tribes are ready to do trade with you. They travel over the ocean and comeback with responses.

Pipe Advertisement

A pipe advertisement contains a unique ID for the pipe, its type (JxtaUnicast, JxtaUnicast-

Secure or JxtaPropagate) and eventually a name and a description.

Pipe Resolver Message

After publishing a pipe advertisement for a pipe, regardless of its type, we need to find out whichpeer is listening to the pipe (input end) before an output end can be created. The same type ofmessage (i.e., pipe resolver message) is used to query for those peers and to obtain responsesfrom them.

A pipe resolver message contains a message type (query or answer), the pipe ID, the type of

the pipe, a peer ID, a found boolean and a peer advertisement. If the message type is query and

a peer ID is specified, then the message is targeted for the specified peer only, other peers shouldnot answer it. Else, the message should be propagated to any peer of the peer group. The foundboolean indicates whether the specified pipe was found on the specified peer when replying. If themessage type is answer, the peer field will contain a list of peers known to have resolved the in-

put end of the pipe. The peer advertisement is one of the peers which resolved the input end ofthe pipe. This peer may appear in the peer field list, but not necessarily.

Understanding JXTA The Protocols - 64

Pipe resolver messages are used to establish a pipe connection between peers, not to send mes-sages over pipes themselves. This operation is performed by the endpoint routing protocol.

Propagate Pipe Message Header

Every message sent via a JxtaPropagate pipe (i.e., sent to many peers) includes an extra

message element called a propagate pipe message header. This element contains the ID of thepeer issuing the message, the Pipe ID, a message ID to avoid duplication when propagating it, aTTL that each peer should decrement before attempting to forward it and the list of already visitedpeers.

Top-Down-Top

Just like the rendezvous protocol, the pipe service will not send its messages itself, but invoke theendpoint routing service. It will register several listeners by setting the service name to 'PipeSer-

vice' and set the service parameter to the pipe ID. With this configuration, each piped message

will reach its destination properly, no matter if there is one or many destination peers. This pro-tocol also uses the resolver protocol to send and receive queries.

Remark:Remark:Remark:Remark: The JXSE 2.6 implementation of the pipe service offers methods which can be useful forsoftware engineers:

• InputPipe createInputPipe(PipeAdvertisement, PipeMsgListener) – This

method is the first step in establishing a pipe communication between peers. Messagesare received on the listeners.

• createOutputPipe(PipeAdvertisement, OutputPipeListener) – This method

starts the resolution process with a input pipe create on a remote peer. If such is found,the output pipe listener is notified.

Peer Resolver Protocol (PRP)

The Peer Resolver Protocol (PRP) is the protocol used to send a generic query to one or severalpeers via a resolver query message, and to receive one or many responses to that query via re-solver query responses. The query and the response are strings of characters whose interpreta-tion is not defined by JXTA. Queries and responses are sent to handlers which may or may not beregistered on peers via the resolver service. Each handler has a unique name and there may beone and only one handler registered on a peer for a given handler name. It is another way of say-ing that there should be one and only one mailbox on an island for a given destination address.

Understanding JXTA The Protocols - 65

Earlier, we mentioned that an endpoint addresses could contain the name of a service and a para-meter to that service. We provided an example containing a PipeService and a JXTA ID. Typ-

ically, the peer located at the spe-cified IP address should have re-gistered a handler called 'PipeSer-vice' in order to get the message sentto this address. In other words, thereshould be a mailbox having the prop-er name of the recipient, or the mes-sage will not be delivered.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You want to know ifother tribes are selling bananas. Yousend your people on a query to findout. Each tribe has its own set of del-egates to answer specific questions.Those having a supply query delegate provide an answer to your question. Others tribes ignore it.Your people bring back the answers they collected and transmit it to your delegate responsible formanaging answers to supply questions.

Resolver Query Message

A resolver query message (or query message for short) contains the credentials of the sender, aservice/handler's name, the peer ID of the query issuer, the query ID, the number of peers throughwhich the query has 'traveled' and the query itself expressed as a string.

Resolver Response Message

A resolver response message (or response message for short) contains the credentials of the re-spondent, the name of the handler to handle the response, the peer ID of the response issuer, thequery ID and the responses to the query. The number of responses can be 0 to many, and thesemight be copies of each other.

Shared Resource Distributed Index (SRDI)

JXTA defines an optional shared resource distribution index concept operating between rendez-vous peers in JXSE. SRDI aims at minimizing unnecessary traffic on the JXTA network. The inten-

Understanding JXTA The Protocols - 66

tion is to avoid forwarding peer queries in all directions and to focus on peers more likely to an-swer these.

In JXSE, each edge peer publishing advertisements in their local cache maintain an index contain-ing the keys of these advertisement and synchronize the content of this index from time to time toits rendezvous via the SRDI service. The rendezvous peers propagates copies to other rendez-vous peers of their peer group called replicas. Therefore, when rendezvous have some informa-tion about advertisements, they use it to avoid propagating queries in all directions. Else, theypropagate queries to other rendezvous.

It is key to remember that each advertisement has a setof indexable fields. This is the information contained inSRDI and exchanged between rendezvous peers, notthe whole advertisement itself.

Resolver SRDI Message

In order to keep the SRDI up-to-date between peers im-plementing it, JXTA uses resolver SRDI messages.These are made of a handler name, the credential of thesender and a payload (that is, a string to be interpretedby the handler).

Remark:Remark:Remark:Remark: If developers want to create a customized service to handle their own set of customizedqueries, they will typically register their own QueryHandler in the resolver service (not the end-

point service) and give it a specific name. In order to send a query or a response, they will invokethe sendQuery(...) and sendResponse(...) methods from that same service using Re-

solverQueryMsg and ResolverResponseMsg objects which contain the name of the target

query handler. Each time a resolver query or response or message reaches a peer, it is transmit-ted to the corresponding handler, if such exists.

The JXSE 2.6 implementation of the resolver service offers methods which can be useful forsoftware engineers:

• QueryHandler registerHandler(name, handler) – This method allows the regis-

tration of a unique query handler using the handler's name.

• QueryHandler unregisterHandler(name) – This method removes any registered

query handler using its name.

Understanding JXTA The Protocols - 67

• void sendQuery(destPeer, query) – This method sends a query to a destination

peer.

• void sendResponse(destPeer, response) – This method sends a query response

to a destination peer.

In order to create query messages, one can use the static ResolverQueryMsg

newResolverQueryMsg() and ResolverResponseMsg newResolverResponseMsg()

methods from each class. One can also use the ResolverResponseMsg makeResponse()

method on any received query message to prepare a response.

Top-Down-Top

Just like previous protocols, the peer resolver protocol will not send its messages itself, but invokethe endpoint routing service. It will also register its own handler for SRDI messages when it is ac-tivated (that is, if a peer acts as rendezvous in JXSE).

Peer Information Protocol (PIP)

The Peer Information Protocol is an optional JXTA protocol allowing peers to obtain informationabout other peers on the JXTA network. It operates with query and response messages and oper-ates on top of the peer resolver protocol. The JXTA specification document does not provide moredetails about how it should be implemented, but we will describe its implementation in JXSE23.

The peer info service can be used to retrieve status information about the current peer or remotepeers. This is performed with monitor reports containing service metrics. Such a service is 'any-thing metric' measured on a peer by a service monitor. One can implement cumulative servicemetrics, like the number of messages received by a peer for example. Each service monitor isidentified by a module class ID and can monitor anything. This 'service' terminology can be mis-leading because of the JXTA service concept. For example, a service metric could be the temper-ature of a room.

JXSE also implements monitor filters containing a list of service monitor filters. This can be usefulif you do not want to obtain all the metrics which can be obtained from a peer. If you are only inter -ested in the temperature of a room metric, you can create a monitor filter containing a servicemonitor filter for that specific metric.

The next step is to register a monitor listener in the peer info service. A reporting rate and a monit-

23 Unfortunately, this service has not been used and tested widely in JXSE. Existing documentation is limited. In release 2.5, the PIP (ormetric) code could be generated from the main Ant script. It is now fully integrated in 2.6 and activated via static booleans.

Understanding JXTA The Protocols - 68

or filter can be specified to only obtain relevant data at a regular interval. Later, the monitor listen-er can be invoked in three ways by the peer information service: i) to notify that the reporting hasbeen canceled (the reason can be retrieved from the corresponding event), or ii) the request formonitoring failed (and the reason can also be retrieved from the corresponding event), or iii) amonitoring report has been received and can be retrieved from the corresponding event.

One can obtain the monitoring capacities of a local or remote peer from the peer information ser-vice. This information is grouped in an object containing the list of module class ID correspondingto the service monitors available on the target peer. If the target peer is a remote peer, a specificpeer monitor info listener must be specified together with a timeout. This listener can be invoked intwo ways: either i) the information is returned in time by the target peer and can be retrieved fromthe event, or ii) the information is not returned in time.

PIP Query Message

A Pip Query Message contains ID of the peer making the request, the ID of the target peer beingqueried, and a request. The request is an optional field whose interpretation in not defined byJXTA. Typically, it contains a peer information query expressed as a string.

PIP Response Message

A Pip Query Message contains at least the ID of the peer who has made a request and the ID ofthe target peer being queried. Unless the information is unavailable or could open a securitybreach, this message should contain the up time of the peer expressed in milliseconds and thetime stamp at which this message was generated. This time stamp represents the number of milli-seconds since January 1st, 1970 at 00:00:00 GMT.

The message can also contain a response to the query. Again, the interpretation of this responseis left to the peer.

It can also contain information about the traffic, such as the time of the last incoming message, thetime of the last incoming message, information describing the incoming and/or outgoing trafficfrom various endpoint addresses, together with the number of bytes received/sent by the namedaddress endpoint.

Top-Down-Top

Typically, a peer information service will create its own queries and send them via the peer resolv-er service. It will also register its own query listeners in that same service.

Understanding JXTA The Protocols - 69

Peer Discovery Protocol (PDP)

The Peer Discovery Protocol is the highest level protocol in JXTA. It is used to find advertisementsof other peers, rendezvous and any kind of resource that has a published advertisement (a pipe, amodule, etc...). Ideally, it should be called resource description discovery protocol. This protocoloperates at a group level, meaning that discovery queries are performed within a group. This pro-tocol uses two messages: the Discovery Query Message and the Discovery Response messages.

Discovery Query Message

Contains at least the type of searched advertisements, a threshold indicating the maximum num-ber of messages a given peer should return and eventually the advertisement of the query senderand some search parameters.

This type of message may also contain a pair of attribute and value items. The value provided forthis pair of items will be used to search for advertisements having an attribute called attribute andfor which, the corresponding value is value.

Typically, a peer advertisement contains a field called Name. If you are searching for advertise-

ment of peers having a name starting with 'J', you will typically set the following in your discoveryquery message: attribute = 'Name' and value = 'J*'. Wild cards are allowed.

This feature can be very useful if you define your own advertisements having their own specific at-tributes. A list of attributes per advertisement types is provided in the Appendix.

Discovery Query Response

Contains the advertisement types, the number of responses in the message, the advertisement ofthe respondent, the expiration in milliseconds and the responses + expiration expressed in milli-seconds. If the attribute and value of a pair of items was present in the discovery query message,they will be present in the response too.

The JXSE 2.6 implementation of the discovery service offers methods which can be useful forsoftware engineers:

• getRemoteAdvertisements(...) – These methods enable the retrieval of advertise-

ments published on remote peers.

• getLocalAdvertisements(...) – This method allows the retrieval of advertisements

published on this peer.

Understanding JXTA The Protocols - 70

• publish(...) – This method publishes advertisements on this peer.

• remotePublish(...) – These methods publish advertisements on remote peers.

• flushAdvertisements(...) – These methods delete advertisements on this peer.

Top-Down-Top

The discovery service uses the peer resolver protocol to send its queries and receive answers.Typically, a user expecting answers from his discovery queries should register a discovery listenerfor each of his queries, but he or she could also register a general discovery listener.

Access Control

The above figure is the initial implementation design of access control in JXSE24. The general prin-ciples are the following:

1. The user retrieves the membership service of the peer group object instance.

2. It applies with authentication credentials, which provides an authenticator.

24 This image is extracted from the net.jxta.membership.doc-files package of the release 2.5 jxta.jar.

Understanding JXTA Access Control - 71

3. Authentication transactions are performed with this authenticator (via a screen, by provid-ing a password, etc...).

4. When the authenticator is ready to join, the user returns it to the membership service us-ing the join(...) method and if successful, a credential for the identity is returned. It

operates at a group level.

5. Later, this credential can be used with the access service to check access on privilegedoperations via the doAccessCheck(...) method.

Privilege operations are created from the access service using thenewPrivilegedOperation(...) method.

Membership Service

The membership service is a required JXTA service which must be implemented at the peer grouplevel. In its simplest form, it is used to request access to a peer group. Eventually, access can al-ways be granted. Each peergroup has a membership service. By default, the World Peer Groupand the Net Peer Group have a none membership service, that is, everyone is admitted. There isa corresponding always access service.

By default, new peer groups are created with the Personal Secure Environment (PSE) service andthe corresponding PSE access service. We will describe this specific membership service later, inthe cryptographic section of this book.

Access Service

The Access service is used to validate requests made by one peer to another. The peer receivingthe request provides the requesting peer credentials and information about the request beingmade to the Access Service to determine if the access is permitted. Not all actions within the peergroup need to be checked with the Access Service. Only those actions that are restricted to a sub-set of member peers must be checked.

Like other JXTA services, the access service is implemented as an interface in JXSE. One shouldretrieve the access service implemented by a peer group and then check whether a privileged op-eration can be performed with the doAccessCheck(...) method. This method takes in two

parameters: the privilege operation and the credentials of the peer requesting the operation. Fourvalues can be returned: DISALLOWED, PERMITTED, PERMITTED_EXPIRED and UNDETERMINED.

The PERMITTED_EXPIRED value indicates that the operation would be permitted if the creden-

Understanding JXTA Access Control - 72

tials were not expired.

The Ignition Process

How does a JXTA network get started? How does a peer get started? JXSE uses one of the mostinteresting features of the Java programming language: its capacity to load pieces of code at runtime, that is, while an application is running. Later, that same application can start running theseloaded pieces of code.

Remember that JXTA operates with modules and that these modules are to be 'loaded' on peers. Iguess one can safely bet that many readers are starting to get the whole picture. Understandingthe ignition process of JXTA in JXSE in details requires some knowledge of the Java program-ming language. However, the non-savvy reader will still understand most what is being said in thenext pages.

We will first review some features of modules and services in JXSE, before describing the ignitionprocess of JXTA.

Module

In JXSE a module can be initialized, started and stopped. It is implemented as a Java interface.When a module is initialized, a PeerGroup object, together with an ID and a module implementa-

tion advertisement are passed as parameters.

JXSE supports the co-depending start of modules. In other words, if module A needs to wait formodule B to be started and module B needs to wait until A is started before finishing it startingprocess, this can be achieved with JXSE. When a module is started, an array of string argumentscan be passed as a parameter. Calling the startApp() method returns a value which can be

one of the following:

• START_AGAIN_PROGRESS – This value indicates that the startApp() method of a mod-

ule needs to be called again later in order to finish its starting procedure. This module mayhave already performed parts of its starting procedure.

• START_AGAIN_STALLED – This value has the same meaning as START_AGAIN_PRO-

GRESS, but it gives the caller of the startApp() method an indication that the module

has stopped somewhere in its starting procedure. It should be called again later.

• START_DISABLED – This value indicates that the starting procedure of this module has

been disabled or that the module cannot start for some reason.

Understanding JXTA The Ignition Process - 73

• START_OK – This value indicates that the module has started successfully and that it can

be considered as operational. The start method should not be called again.

This is an important feature because if a high-level service using lower-level services is startedbefore these low-level services are started, it has a mean to notify the caller of its startApp()

method that it is waiting for other modules/services to be started before finishing its own start pro-cedure.

Service

In JXSE, a service is a type of module and is also implemented as an interface. In addition to themethods provided by the module interface, one can obtain the module implementation advertise-ment of this service by calling the getImplAdvertisement() method.

Peer Group As A Service – Part I

JXSE has developed a Java PeerGroup interface, which is a type of service, to attach other

JXTA services. If you think about it, it means that JXSE considers peer groups as services. JXTAservices are attached at a peer group level, and not at a peer level. Such services can be re-trieved with some of the following methods, for example: getDiscoveryService(), getEnd-

pointService() and getPeerInfoService().

Well-known Module Class, Specification and Implementation IDs

JXSE has defined several well-known module classes, module specification and module imple-mentation IDs. These are available as static fields in the Java PeerGroup interface. They all

share the same prefix: urn:jxta:uuid-DeadBeefDeafBabaFeedBabe. For example, the well-

known module class id for the standard implementation of the pipe service (i.e., the pipe-

ClassID) is: urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE0000000405. JXSE references

these when starting JXTA.

Bootstrapping JXTA

One way of starting the JXTA network in JXSE is to use the startNetwork() method of the

NetworkManager class. This method returns an instance of the Net Peer Group from which we

can access the default implementation of JXTA services.

This is what is happening when calling that method:

Understanding JXTA The Ignition Process - 74

1. If the net peer group has already been created, it is returned.

2. Else, a new instance of the NetPeerGroupFactory object is created. During this pro-

cess, a new instance of the WorldPeerGroupFactory is created. This call triggers the

creation of the world peer group PeerGroup Java object instance using its module imple-

mentation advertisement. This advertisements contains references to modules and ser-vices which should be running at the world peer group level.

3. The next step is to 'load' the services that the world peer group object will provide. Tech-nically speaking, this is equivalent to 'loading' the implementation of each of these mod-ules, which are, in fact, pieces of code delivered as part of the current implementation ofJXTA (i.e., the jxta.jar file since we are using JXSE). In another implementation, the

code or .jar file could be retrieved from a URI.

Some links need to be established between well-known module implementation IDs andthe Java byte code corresponding to the implementation of these modules. Some moduleimplementation advertisements have to be created to be passed as parameters when in-stantiating corresponding module objects in JXSE.

4. How is this resolved? As soon as the Java class called StdPeerGroup is referred to for

the first time (and this happens when the startNetwork() method is invoked for the

first time), its static initialization is performed. This operation includes the loading of in-formation located in the META-INF.services/net.jxta.platform.Module file de-

livered as part of the JXSE implementation. This file contains all the necessary informa-tion to resolve the set of module implementation IDs with the name of the Java classesimplementing that module in the jxta.jar file. Remember that a module/service is an

interface in Java and that we need a Java class implementing that interface to run thecode that will operate this module/service25.

25 Those savvy with OSGi will complain about the limitations of this method, for example, when there are multiple versions of a module,or when there are dependencies between modules. JXSE is ill-equipped to handle such complex situations. This has triggered theprogressive introduction of OSGi in release 2.6.

Understanding JXTA The Ignition Process - 75

5. The object implementing the World Peer Group is the Platform object. It extends the

StdPeerGroup object, which extends the PeerGroup interface. During initialization, the

Platform object loads every modules and services defined in its implementation advert-

isement with the help of a JxtaLoader, and starts them. This includes the creation of

physical transportation module objects (i.e., TCP, HTTP, multicasting...).

6. Once finished, the PeerGroup object instance of the world peer group is now ready to be

used and methods can be used to invoke the default implementation of JXTA services inJXSE. This instance is used as a parent for the creation of an instance of the net peergroup PeerGroup object (technically speaking, the type of this object is ShadowPeer-

Group). It will automatically inherit of the service implementations 'loaded' as part of the

creation of the world peer group (for example, the transportation module) or creates its

Understanding JXTA The Ignition Process - 76

own peergroup level service instances as necessary. This new net peer group instance isreturned by the startNetwork() method.

The code corresponding to module/service implementations is now 'loaded' and linked with theirmodule implementation IDs.

Peer Group As A Service – Part II

Typically, when the JXTA network is started in JXSE, the user specifies its peer ID (or a new oneis automatically created). This ID is taken into account when creating the initial world peer groupand net peer group PeerGroup objects. Since a peer group is a module in JXSE, its ID is trans-

mitted to the corresponding peer group module when it is initialized.

Now that the user has access to the JXTA network via the net peer group, it can start to search forother resources on the network with the discovery service for example. In a way, this peer has be-come a 'resource' of the net peer group during the bootstrapping process and it can now be ac-cessed by other peers. The system is bootstrapped.

If the user wants to connect to other peer groups (or create them), he or she will create additionalPeerGroup objects using one of the newGroup(...) methods from the net peer group object.

These groups will automatically benefit from the default implementation of JXTA services availablefrom the world peer group via the net peer group.

Remark:Remark:Remark:Remark: If you did not get it all, just remember the most important thing: in JXSE, a peer gets ini-tial access to the JXTA network via an instance of the world peer group and of the net peer group,who offer default services to operate on the JXTA network.

Loading Other Services

Once a peer is connected to the JXTA network via a peer group, it can load other peer level orpeer group level services with the one of the loadModule(...) methods from its peer group

Java object.

Understanding JXTA The Ignition Process - 77

- 78

Network Boundaries

This chapter covers the network communication technical issues one has to over-come when implementing JXTA. It contains a reminder about IT network conceptsand explains how artificial and natural network boundaries can be crossed using spe-cific techniques. These issues must be well understood by developers, architectsand network administrators to develop efficient P2P systems based on JXTA. Thischapter will provide the context to help them set-up JXSE properly and troubleshootcommon implementation issues.

Reminder

Historically, the Internet was not initially developed with the intention of supporting hundreds ofmillions of users. As the community grew, several problems arose and sophisticated solutionswere implemented to solve them. This has resulted in a complex plumbing that only experts un-derstand in details.

Today, many software developers don't know exactly what is happening inside this plumbing.They know how to connect to taps and sinks to send and receive data, but most often, they can'texplain precisely how the plumbing operates. This is normal, since the plumbers are offering acouple of services they can call to perform their operations. The developer delegates the duty oftransporting information over the network to these transportation services.

The world would be great if the Internet plumbing was simple and universal, but it is not. It was notinitially designed with universality in mind, but it became more and more universal as more andmore people used it. International organizations defined standards to normalize the utilization anddevelopment of solutions.

Every implementation of JXTA must be performed by selecting a network transportation layer.Otherwise, messages cannot be exchanged between peers. This causes a natural frictionbetween the high level concepts of JXTA and the down-to-earth issues of Internet plumbing.Some middle solutions must be implemented as part of every JXTA implementations to meet bothends. The consequence is that developers have to configure their application properly to makesure it will operate according to the universal objectives of JXTA.

We will start by providing a reminder about Internet concepts before explaining how the plumbingcan limit the universal ambition of JXTA. We will then explain how these issues are solved in

Network Boundaries Reminder - 79

JXSE.

IP

The Internet Protocol (or IP) is a protocol technology making the link between the hardware as-pect of networks (cables, network cards...) and software running on computers via a networktransport layer. Each time a computer connects to the Internet, it is using a fixed IP address or it isassigned one automatically.

Computers are usually connected together in rings (or segments) called LAN (local area networks)and then rings are connected to each other to form the Internet. To make things more complic-ated, those rings can be divided in subnets, that is, subsets of computers. This is a logical distinc-tion, not a physical one.

One of the main functions of IP is routing. When transmitting data, IP attempts to make the besteffort to deliver packets of data from a sending computer to a destination computer. However,some packets can be lost, arrive out of order or even duplicated because of technical or traffic is-sues. These can be solved with TCP, which we will discuss later.

When a data packet is sent to a destination host located on the same subnet as the sender, therouting is called direct. Else, if the host is located on another physical network or on another sub-net of the same physical network, it needs to transit through at least one, but usually many, IPgateways (also called routers) to reach its destination. This is called indirect routing.

This way of organizing networks provides network administrators with some flexibility to organizetheir networks both from a physical point-of-view and from a logical point-of-view. However, thereis an important limitation, they cannot create a subnet with computers belonging to different phys-ical networks.

Network Boundaries Reminder - 80

Unicast, Broadcast & Multicast

In IP, a data packet can be sent to one or many recipients. If the IP address of the destination isunique, the transfer is called unicast. If a data packet is send to many recipients, it is called broad-casting. Sending a packet to all members of a subnet is called multicasting. This is performed withreserved IP addresses (from 224.0.0.0 to 239.255.255.255).

IPv4 Versus IPv6

There are different versions of IP. The IP addresses of IPv4 are represented by 32 bits unsignedvalues. Therefore it allows a maximum of 4 294 967 296 IP addresses. The IP addresses of IPv6are represented by 128 bits unsigned values, allowing a maximum of ≈ 3.40 1038 IP addresses. The

number of IPv4 addresses is not enough for all computers and devices today. However, most ofour material still relies on IPv4 today. Subnetting physical networks was one way to solve this is-sue, but other techniques, which we will describe later, have been developed to work around thisissue.

TCP

IP does not operate only by itself. It is either combined with UDP (which we will discuss next) orthe Transmission Control Protocol (TCP). The latter provides a reliable way to exchange streamsof data expressed in bytes between computers. It operates by establishing a logical connectionbetween the two computers. The data packets transmitted between the sending computer and thedestination computer are delivered in order and only once. If necessary, packets lost at the IPlevel are requested by the source again to ensure proper service.

Handshake

In order to establish a TCP communication, devicesstart with a 3-way handshake:

1. Device A sends a synchronization packet(SYN) to device B.

2. Device B receives SYN and replies with a synchronization acknowledgment packet (SYN-ACK).

3. Device A receives SYN-ACK and replies with an acknowledgment packet (ACK).

4. Device B receive ACK.

Network Boundaries Reminder - 81

The TCP communication is established. Each communicated packet contains information aboutthe created connection.

UDP

The User Datagram Protocol (or UDP) is another transportation protocol operating on IP. Itprovides a faster, but insecure way to transfer messages between two computers by using data-grams.

Contrary to TCP, UDP is a connection-less mean to exchange data between devices. As long as adevice starts listening for UDP communication, it can potentially receive communication from anyother device on the Internet. There is no need for a handshake-like protocol.

Datagram

A datagram is the name of a message containing data sent over UDP. It is an independent unit ofinformation. It can reach its destination out of order. It can also be duplicated or may never reachits destination.

Port

A port is a number ranging between 0 to 65535 in the header of data packets sent over the TCPand UDP. It can be compared to specific terminal numbers assigned to planes to load or unloadpassengers in airports. It helps several software applications performing direct communicationsover a single IP communication line by addressing their data directly to another software applica-tion listening to the corresponding port. In JXTA, the corresponding mechanism is the servicename and service parameter in endpoint addresses.

For example, port 80 is used for HTTP, the World Wide Web protocol. This is the port your webbrowser uses to request and obtain the content of web pages from a web server.

The data packets exchanged over the Internet for HTTP are stamped with port number = 80 and

Network Boundaries Reminder - 82

are transferred automatically to your web browser and your web server application, who are bothlistening to port 80.

There is an important fact to keep in mind regarding ports: maximum one application can listen toa given port on a given PC. If a second application tries to listen to that port, it will receive an errormessage. The port must be freed before it can start listen to it. Eventually, an application can be-have as a proxy listening to one port for other applications. It will manage the distribution of incom-ing messages to proxy-ed applications.

The IANA (Internet Assigned Numbers Authority) maintains a list of port numbers26 which is organ-ized in 3 categories: well-known ports (0-1023), registered ports (1024-49151) anddynamic/private ports (49152-65535). Software applications are expected to comply with the IANAport list, that is, they will listen and communicate with the proper port corresponding to their activ-ity. However, this is not mandatory and cannot be enforced. Some malicious applications often tryto pass illicit data via free ports. Some don't hesitate to hijack well-known ports to allow externalparties to try to take control of your PC. In order to prevent this, a solution, called firewalls, hasbeen introduced.

Firewalls

A firewall is a device aimed at protecting a PC from external attacks. It can also be implementedto protect a LAN from attacks coming from the Internet. Firewalls filter the data packets moving inand out of the area or the PC they are protecting by enabling or disabling some ports. They arecomparable to guards at city gates in ancient times. If a data packet tries to pass through a dis-abled or blocked port, it is discarded.

Some readers may already have received some messages from their computer when an applica-tion was trying to communicate via a blocked port. They most probably did not know what to doand enabled it without fully understanding the consequences.

Of course, everyone knows the story of the Trojan horse which the Achaeans used to infiltrateTroy. The city guards though it to be a gift and let it in, not knowing that it contained Achaean war-riors inside. At night, these warriors killed the city guards and opened the city doors to let otherwarriors come in to take over the city. That is exactly what some malicious piece of software triesto do on your PC. Some are called viruses, others spyware. They are all looking for a way in. Thisis why we called them Trojan horse viruses.

Firewalls provide access control over ports and therefore, to improper communication via un-26 http://www.iana.org/assignments/port-numbers

Network Boundaries Reminder - 83

desired channels. Since only one application can listen to a given port at a given time, the first onewho gets it keeps it. If non-harmful applications get hold of their ports before others when you bootyour PC, this can prevent harmful applications from getting control of these ports. If you tell yourfirewall to disable all ports on your PC and ask to get a message each time an application tries toget hold of a port, you will know who is doing what on your PC. You may decide then to provideport access to the requesting application. Malicious applications will become visible when they tryto communicate on the Internet.

Unfortunately, if you have let a malicious application take control of a port, firewalls will be power-less against Trojan attacks, since they will comply with your order of letting that application usethe port. This is why anti-virus applications and spyware removers have been created. Users don'talways know whether they are dealing with a dangerous or even infected application. This is an-other issue. Some non-harmful applications can be infected by harmful application, but fortunately,that often leaves a trace in the code or in the behavior. Anti-virus and anti-spyware applicationshave lists of suspicious applications and known viruses. They scan your PC and its applicationfrom time to time, together with data being transmitted in and out of your PC for illegal or suspi-cious activities. They are complementary protections to firewalls.

In practice, one cannot block all ports of a computer to prevent attacks from the outside, since aPC alone is not very useful. Otherwise, we would not need firewalls at all, since no Internet con-nection would have to be established. The value of a PC increases when connecting to other com-puters.

Operating JXTA on TCP/IP (or UDP) requires listening to (at least) one port for incoming mes-sages and to send messages to specific ports on the destination peer listening to that port. Unfor-tunately, these ports can sometime be blocked by firewalls either on the sending peer or the des-tination peer of both. The firewall can also be located somewhere on the network between them.JXSE has a solution to this problem: relay peers. We will discuss this later.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: One can compare ports to the skin protecting our body from infections and to ournose filtering the air coming in. However, these protections do not prevent some viruses or bac-teria from getting into our lungs. Fortunately, our immune system takes care of these. We cannotlive without oxygen in the air, we need to let it in one way or the other. There no Internet connec-tion from PCs without ports.

NAT

Network Address Translation (or NAT) is a mechanism providing a solution to the shortage of IPv4

Network Boundaries Reminder - 84

addresses. Instead of assigning a unique IP address to every computer in the world, which is im-possible since there are not enough, we introduce a distinction between internal IP addresses andexternal IP addresses.

A set of internal addresses is used for a local network area (LAN). They are only valid for a givenLAN. However, two distinct LANs could use the same set of internal addresses. The computers ofone LAN cannot connect directly to the computers of the other LAN by referring to the same set ofaddresses. A set of external addresses is a set of unique IP addresses which could be assignedto any computers on the Internet (i.e., some of the 4 294 967 296 available, minus reserved ad-dresses).

Since the computers on the LAN do not need to connect to the Internet permanently (most often),they do not need to have a fixed IP address and can be assigned one of the internal addresses.When they need to connect to the Internet, they can borrow one of the external addresses tempor-arily. This is precisely what a NAT is accomplishing for them.

NATs are physical devices isolat-ing a physical network from theInternet. They keep a pool of ex-ternal IP addresses for the com-puters on the LAN which are us-ing internal addresses. Each timeone of these LAN computers accesses the Internet, the NAT will match its internal IP address witha free external IP address from its pool and make sure that answers received from the selectedexternal IP address are returned back to the right computer on the LAN. The local IP address ofthe LAN PC is substituted with one of the external addresses by the NAT in the data packets leav-ing the LAN to the Internet. These are copied back by the NAT in the data packets coming back tothe computer on the LAN.

Some NATs are capable of operating with one external IP address only. Since they are controllingall the incoming and outgoing data, they can play on the fact that they can reassign port numbersfrom the sender in outgoing messages to create unique IP addresses – port combinations (multi-plexing). When a response comes back, they will read the destination IP Address – port combina-tion from the data packet and search for the corresponding PC destination on the LAN in their listof combinations. They'll update the data packet with proper destination information (demultiplex-ing) and drop it on the LAN. The proper destination PC will get it.

Network Boundaries Reminder - 85

NATs also have their own internal IP address on the LAN, which is different than their externalpool address(es). They are accessed with different IP addresses on the LAN and on the WAN.

Some Limitations

NAT can only translate addresses from data packets holding their destination and source IP ad-dresses in a header. Some applications and protocols include IP addresses in the data part ofdata packets, which is hardly detectable by NATs. If such applications include their LAN IP ad-dress, it will not be useful to applications located outside of the NAT. These are not static ad-dresses and one cannot rely on these to identify a computer or to try to access it from outside theNAT.

NATs break the end-to-end principle that was valid until we started lacking IPv4 addresses. Theycompromise Internet protocols relying on the fact that IP addresses will not be translated in datapackets. Some other protocols work fine when, either the sending computer or the destinationcomputer, but not both, is located behind at NAT. Otherwise they fail. Additional mechanisms be-come necessary to solve these issues. There is a good side to NATs (in addition to solving thelack of IP addresses issues); direct attacks on specific computers located on a LAN become hardto achieve, since their IP address is unknown from the outside.

NAT can cause some trouble to JXTA applications operating on IT, but these can be relativelyeasily solved as we will see further.

PAT

PAT is an acronym for NAT port translation or port address translation. It is the process by whicha NAT may translate a private IP address port number into another public address port number.

Network Boundaries Reminder - 86

Proxy

A proxy server aims at forwarding Internet-like requests from its clients to other computers on theInternet. They can be used to manage HTTP requests for example.

Instead of sending their requests directly to the Internet, PCs located on a network isolated by aproxy server will need to send their requests to that proxy and will receive corresponding answersfrom it too. Proxy servers are most often used to perform controlling activities similar to those offirewalls.

In JXSE, if a peer needs to communicate on the Internet through a proxy, this has to be con-figured properly (we will cover this later).

Router

Routers are responsible for finding out whether data packets should be transferred from one sub-net to another or not, or whether they should be sent to the outside on Internet or not. They canfind this information from the IP addresses themselves; some ranges are reserved and have aspecial meaning regarding the destination of data packets.

By default, JXSE uses the 224.0.1.85 IP address for multicasting. Routers will not forward datapackets using this address to the Internet. These data packets will remain inside the part of theLAN isolated by the router.

Very often, routers also act as NATs and firewalls for the LAN they are isolating.

Multicasting Versus Subnets

Multicasting of data packets from computers located in different subnets of the same LAN may ormay not be enabled by the routers organizing these subnets.

Network Boundaries Reminder - 87

Natural Network Boundaries

Natural Network Boundaries (NNB) are those rising from physical devices and differencesbetween network transportation protocols. Your PC, together with its network card, its networkcable and its communication protocols can only communicate with to the set of PCs who can ex-change information with these same means. There is a natural boundary to the set of PCs it canreach considering its networking capacities.

Many PCs are now equipped with wireless communication facilities. It extends their capacity tocommunicate with other PC's without using network cables. Not all destination PCs can exchangeinformation that way. They need special material and software to do so. The natural networkboundary of wireless enabled PCs is larger than those who do not have wireless communicationfacilities, since they can potentially communicate with more computers than the latter.

However, a PC connected to the Internet with a network card and a network cable can communic-ate with a wireless PC connected to Internet through a wireless connection if there is a third PC onthe network equipped with adequate material and software to act as bridge between the cablednetwork and the wireless network. This is transparent for the user.

Now, imagine that in the future, a newtype of network communication layercalled FutureNet is created to replaceTCP/IP. Let's assume that it is not com-patible with TCP/IP. Some computerswill be able to operate on both networks,if they have the adequate material andsoftware, while others won't. Computersoperating only on FutureNet or only on TCP/IP will need to find a bridge computer to communicatebetween both transportation layers.

Why are we mentioning all this? Because every implementation of JXTA must select a networktransportation layer. In JXSE, peers can only reach peers accessible with TCP/IP or HTTP. If animplementation of JXTA does not support TCP/IP of HTTP, the peers of both implementations willnot be able to communicate with each other, even though they will have implemented the JXTAprotocols properly. They will not be able to cross the natural network boundary between them.

As a consequence, if JXTA were implemented in the future using only the FutureNet transporta-tion layer, computers using that implementation would not be able to communicate with peers us-

Network Boundaries Reminder - 88

ing JXSE, since it operates only over TCP/IP and HTTP. The problem would be solved once apeer becomes capable of operating over both networks with a JXTA implementation capable ofusing both network transportation layers. This is how the natural network boundary would becrossed.

Of course, there is a very high probability that if a new network communication layer called Fu-tureNet is created in the future, existing JXTA implementations will be adapted to operate on thatnetwork transportation layer too. Therefore bridge peers will not be necessary for peers using thatupdated implementation.

This is a very theoretical discussion, but it illustrates an important point: no matter how universalJXTA tries to be, the surface of its universality is constrained by the selected network transporta-tion layers for its implementations. In addition, it is not because a network technology is availableon one's PC that a JXTA implementation can automatically use it to connect to other JXTA peers,some adaptations may be required.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: Do you remember the tribes capable of navigating and the tribes capable offlying? If some tribes can only be reached by flying, those only capable of navigating will need thehelp of those capable of flying to send them messages or cargo. Regarding our argument, there isa very low probability that all tribes capable of flying would all be incapable of navigating too. Thisdemonstrates the need of having islands where boats can moor and flying devices can take offand land to connect with all tribes on all islands.

Artificial Network Boundaries

Artificial Network Boundaries (ANB) are devices controlling and organizing the natural flow of databetween networks, for example: routers, NATs, Firewalls and Proxies. Artificial network boundar-ies usually restrain the surface of natural network boundaries.

JXTA Transportation Layer

JXTA knows three concepts for transportation: endpoints, pipes and messages. Two peers areendpoints communicating messages, often over a pipe. JXTA specifications do not make any re-quests or put any constraints on the implementation of these concepts and the protocols that usethem.

Technically speaking, JXTA could be implemented on TCP, on UDP, on HTTP or any other trans-portation protocols. It does not matter as long as the specifications are met. The only limitation is

Network Boundaries JXTA Transportation Layer - 89

that applications implementing JXTA should not make any assumption about the time it takes tocommunicate data from one peer to another or assume that transmitted data will necessarilyreach its destination. That's it!

Metaphorically:Metaphorically:Metaphorically:Metaphorically: The transportation layer is the sea and the tribes capable of flying are using Fu-tureNet.

JXSE Transportation Layer

The network transportation layers selected by JXSE are TCP/IP and HTTP. Three types of poten-tial boundaries need to be crossed: proxies, firewalls and NATs. As we will see, both TCP/IP andHTTP are required to overcome the limitations imposed by these artificial network boundaries.

Overcoming Firewalls

By default, JXSE uses port range 9701 to 9799 for TCP/IP communication. If a peer wants tocommunicate with another peer beyond the LAN, it will use its IP address and port to send itsmessages sliced in data packets. Unfortunately, if the LAN on which the peer is located is isolatedby a firewall blocking ports 9701 to 9799, the message will never reach its destination.

In this case, JXSE will switch to another protocol: HTTP. It will first try to establish a connectionwith known relay peers using HTTP via port 9901. Relay peers are special peers capable of re-ceiving and answering HTTP requests from other peers inaccessible because of firewalls.

One should not forget that when users send HTTP requests from their browsers, these requestscan contain some data to the web server's attention. For example, when you type your login andyour password on a web page, they are transmitted as parameters to the web server in the corres-ponding HTTP request. The web server sends back an answer; most often an HTML page to bedisplayed by the web browser of the user. A HTTP request is always followed by an answer.

JXTA uses HTTP requests to pass its XML document as parameters in HTTP request. The relaypeer receiving these responds with another XML document in the HTML response to the initialpeer. This other document can come from third-party peers that the relay peer has contacted onbehalf of the firewalled peer. This mechanism implies that JXSE peer contain an HTTP enginewhich is activated when peers behaves as relays. Currently, JXSE uses the Jetty HTTP server. Itis in the process of being replaced by the Netty HTTP engine requiring much less resources to op-erate.

Unfortunately, the HTTP fetching mechanisms only works one way. Non-relay peers need to

Network Boundaries JXSE Transportation Layer - 90

probe relay peers from time to time to retrieve messages from other peers. A relay peer cannotinitiate HTTP requests to non-relay peers. The consequence is that relayed communications willalways be slower than non-relayed ones. It is tempting to increase the frequency of probes, butthis comes at the expense of relay peers' responsiveness.

At last, if all default JXSE ports (9701 to 9799, and 9901) are blocked by a firewall, a peer trying toconnect to other peers located beyond a firewalled LAN will not be able to communicate withthese no matter what. It will only be able to communicate with other peers located on the sameLAN. Some issues will also rise if applications start listening to all JXSE ports, before a JXSE peerhas a chance to listen to them as well.

Relay Service

The relay service is not defined as part of the JXTA specification, yet it has been created as partof JXSE to help overcoming artificial network boundaries. This service is responsible for managingHTTP communication between any peer and relay peers. It is activated when a peer behaves as arelay.

Remark:Remark:Remark:Remark: In the previous edition of this book, it was said that 'This service is responsible for man-aging HTTP communication between any peer and relay peers'. This is not exactly true, becausethe JXSE relay service can operate with TCP too (or any other transport).

This misconception – common in the JXTA community – comes from a comment in the 2.5 Pro-grammer's guide: 'If you are located behind a firewall or NAT, you must use HTTP and specify arelay node'.

Fact is, you only need to use HTTP communication with a relay peer when:

1. Corporate firewalls only allow HTTP communication.

2. Using small devices only offering an HTTP API not operated on TCP itself.

If private IP address translation is the only connectivity issue, TCP can be used with relay peers.

Overcoming NATs

In IPv4, NATs create an issue for JXSE, because the IP address of a peer located behind NATs isoften unknown to peers located outside of the NAT. IPv4 addresses on a LAN are frequently as-signed dynamically when a computer is booting. These are called dynamic IP addresses and areprivate to the LAN. Some peers behind a NAT also have fixed (or static) public IP addresses thatthey keep even after rebooting.

Network Boundaries JXSE Transportation Layer - 91

Assuming that a NAT is properly configured to forward all IP packets corresponding to a staticIPv4 address of a peer located on the LAN, that peer will always be visible on the net by all JXTApeers knowing a route containing an endpoint address created with that IPv4 static address. Thistype of peer will not be impacted by the NAT.

However, the situation is different for LAN peers having dynamic IP addresses. Those IP ad-dresses cannot be used directly on the Internet and need to be translated into external IP ad-dresses by the NAT. As a consequence, such peers remain inaccessible from remote peers loc-ated on the WAN (i.e., the Internet area not isolated by the NAT), until either a) a remote peermanages to obtain an virtual route to an inaccessible peer via a relay peer visible to the remotepeer and to which the inaccessible peer is connected, or b) the inaccessible peer establishes aconnection to the remote peer spontaneously.

Peers capable of using IPv6 addresses are not impacted by NATs, since there is no need to com-pensate for a lack of IP addresses in IPv6. They can easily establish direct IP connections withother peers capable of using IPv6 addresses. Such peers will publish route advertisements con-tain endpoint addresses created with IPv6 addresses. These advertisements may also containIPv4 addresses to (potentially) allow external peers to make IPv4 connections with them (if theyare not blocked by artificial network boundaries). Apparently, JXSE does not necessarily privilegeIPv6 over Ipv4.

Later, we will discuss NAT traversal issues and potential solutions to increase connectivitybetween peers.

Overcoming Proxies

Proxy servers are the easiest boundaries to overcome (when they can be). If your users have toaccess the Internet via a web proxy, you will need to pass the proxy parameters in the commandline when starting your JXSE-enabled application. Here is an example:

> java -Dhttp.proxyHost=theproxy.atmycompany.com Dhttp.proxyPort=8080 ...

For proxies requiring authentication, additional parameters should be added in the command line:

> java -Djxta.proxy.user=myusr -Djxta.proxy.password=mypwd ..

One can also explore the possibility to set those parameters at runtime with the following code be-fore starting the JXTA network for example:

Network Boundaries JXSE Transportation Layer - 92

...

System.getProperties().put(proxySet,true);

System.getProperties().put(proxyPort,8080);

System.getProperties().put(proxyHost,theproxy.atmycompany.com);

...

Remark: If a proxy is blocking the transmission of TCP/IP and HTTP data on the default ports se-lected by the JXSE implementation (9701 to 9799 for TCP/IP and port 9901 for HTTP), communic-ation between peers will be impossible. If the communication is blocked only on default TCP/IPports, a peer will be able to reach other peer if and only if it can establish contact with a relay peeron the WAN.

Network Boundaries JXSE Transportation Layer - 93

Seeds

If you develop your own JXTA-enabled application based on JXSE, your must take into accountthe fact that peers running your application may not always be able to connect to other peers us-ing that same application easily. Even if they are not hampered by artificial network boundaries,how can a peer located in Namibia and connected to JXTA via the net peer group know about an-other peer also connected to JXTA via the net peer group in Canada?

It is not because they are both connected to JXTA using the same peer group that they necessar-ily know how to contact each other by using one of the network protocols of the JXTA implementa-tion. How would they get to know about each other's route advertisement? By which means?

Network Boundaries JXSE Transportation Layer - 94

If we push this argument a little further, we can easily imagine that pockets of peers (all connectedto JXTA via the net peer group) could organize themselves in different countries, having their ownrendezvous peers to connect isolated pocket members, but those pockets of peers would still notbe connected together.

This lack of connectivity can be solved by the means of well-known rendezvous seeds, that is, aset of well-known peers not made inaccessible by artificial network boundaries. Some pocketpeers (for example, local rendezvous peers) would use these seeds to notify their presence andbe added to the peerview of the seed rendezvous.

Automatically, connections would be established with other rendezvous of other pockets, sinceJXTA automatically propagates peerview updates between connected rendezvous of a peergroup. This provokes a cascading effect allowing everyone to (potentially) know about everyoneelse.

The concept of seeds also applies to relay peers to help peers made inaccessible by NATs or fire-walls establishing connections with other peers. Of course these relay seeds should not be inac-cessible because of artificial network boundaries themselves.

Peer Accessibility

In JXTA, there is no such thing as a blind peer not capable of finding other peers on the JXTA net-work. There are only inaccessible peers and distant peers (that is, not accessible by LAN multic-asting only). Don't forget that peers can also be off-line, that is, not connected to the network for aperiod of time.

WAN

The following tables will help you understand what you should expect from JXSE according fromthe WAN. You should perform an analysis with both tables and combine the mentioned restric-tions to find out how accessible your peer is.

Behind afirewall

Yes TCP trafficenabledand portsopen

Yes Accessible from anywhere through TCP

No HTTP trafficenabled andports open

Yes Accessible if HTTP contact established with arelay accessible from the WAN

No Inaccessible from the WAN

No Accessible from anywhere through TCP

Network Boundaries Peer Accessibility - 95

Behind aNAT

Yes Peer usingIPv4address

Yes Using aprivateaddress

Yes Accessible from the WAN if contact establishedwith a relay accessible on the WAN

No Accessible from anywhere if NAT configuredproperly to let data packets stamped with staticIP address pass without translation

No Accessible from anywhere if IPv6 is operationalbetween communicating peers.

No Accessible from anywhere

LAN

Same Subnet

The natural way for peers located on the same subnet (and therefore in the same LAN) is to usemulticasting on a shared multicasting IP address and port. Typically, these peers do not need arendezvous peer to discover each other, unless the port used for multicasting is blocked on thepeers themselves, or multicasting is disabled on the LAN or the peers themselves.

If multicasting is disabled, one peer will need to act as a rendezvous for the other peers. Assum-ing that all peers are connecting to JXTA using the same peer group, the rendezvous should beset as a seed for the other peers. Discovery queries for peer advertisements should be sent byeach peer to get to know about other peers on the subnet/LAN.

If multicasting is enabled on a subnet, queries sent by a peer will be automatically sent to otherpeers on the subnet via the multicasting address. In this case, rendezvous peers are not neededto forward queries to peers on the subnet/LAN. However, rendezvous are necessary to forwardqueries to peers located outside the subnet/LAN.

Different Subnets

We have already mentioned that the capacity of peers located on different subnets to communic-ate depends on the setting of the router organizing these subnets. Typically, the rules regulatingthe visibility of peers between subnets of a same LAN are the same as those located on the WANin respect to firewalls when these are set between subnets. However, NATs do not affect trafficbetween subnets.

We have also mentioned earlier that multicasting between subnets of a same LAN may or may notbe enabled. Therefore, one may or may not need a rendezvous seed to establish connectionsbetween peers located between different subnets and to forward queries between them.

Network Boundaries Peer Accessibility - 96

NAT Traversal

Before we start discussing the various techniques available to establish communication betweenpeers located behind NAT with a private address, we need to introduce some vocabulary andsome key concepts. We will start by reminding all the obstacles an IP packet has to overcome toreach a destination peer.

IP Obstacles

When a IP packet (UDP or TCP) leaves a user's PC or device, it passes through severalobstacles:

1. It may be blocked by a firewall installed on the local PC or device.

2. It may be blocked a LAN firewall (usually implemented inside a router).

3. It may be blocked a LAN NAT (often part of a router) if the destination address is not rout-able.

4. It may be blocked by any additional corporate routers or proxy servers filtering traffic.

5. It may by blocked by an Internet Service Provider router (though this is rare).

6. It travel through many hops on the Internet and may be blocked (though this is rare too).

7. It may blocked by the destination's outmost router.

8. Etc... when navigating to the destination user PC or device.

Multiple IP address translations can happen at each encountered router/NAT. Further in thischapter, we will describe situations where only one NAT is involved, but one should keep in mindthat multiple layers of NATs are common when communicating on the Internet.

Network Boundaries NAT Traversal - 97

Port Prediction

Port prediction refers to guessing the portmapping operation performed by a NATwhen translating a private IP address to apublic IP address.

If one can predict NAT mappings when loc-al peers establish connections to the WAN,there is a possibility to connect two NAT-edpeers if they can predict each other's NAT translation mechanism by sending proper communica-tion to the predicted port.

Punching Holes

If port prediction can be performed successfully on a NAT, then a hidden peer knowing that anoth-er peer wants to communicate with it can punch a hole in its NAT (i.e., create a mapping) by initi-ating a dummy outbound communication. If the mapping is predictable, the other hidden peer canthen initiate a communication to that anticipated mapping. It will be forwarded to the initial peer bythe NAT, since it holds a mapping.

Punching holes is a fundamental mechanism by which NAT traversal can be performed on Ipv4.

Hairpin Issue

The hairpin situation is characterized by twopeers located behind the same NAT. Let's ima-gine that B has created an outbound communic-ation and that peer A knows about this transla-tion.

Under normal circumstances, peer A can alwayscommunicate with peer B using its local IP ad-dress, but what if is uses the translated addressof peer B? This is called a hairpin situation and it is not always handled properly by NATs. Typic-ally, NATs should forward the traffic to peer B, even though it does not come from the WAN.

Such situations are common when establishing communication with NAT-ed peers. It can alsohappen when multiple levels of NATs are involved.

Network Boundaries NAT Traversal - 98

RFC 5128

In March 2008, an informational memo called RFC 512827 was created to the attention of the Inter-net community. It summarizes the state of P2P communication across NATs and proposes a com-mon terminology regarding NAT mapping strategies and endpoint filtering. We will cover this later.

TURN

The current technique used by JXSE to establish connectionwith peers located behind NATs is equivalent to Traversal UsingRelay NAT (TURN). A relay with a public address accepts andforwards traffic from and to peers located behind NATs withprivate IP addresses. It can be used for both TCP and UDPtraffic.

The benefit of this technique is that it allows communication fromany peer to any peer on the Internet, regardless of the presenceof any (traversable) NATs.

The drawback is that is creates bottlenecks and many relays are required to sustain high commu-nication between peers.

STUN

STUN stands for Simple Traversal of User Datagram Protocol (UDP) through Network AddressTranslators. This protocol is about establishing direct UDP connection for peers located behindNATs.

The first version of the protocol defined in RFC 348928 went like this:

1. Each peer connects to two STUN servers (i.e. with a public address) to learn about thetranslation of their local address into a public address. This information is available to theSTUN server located on the WAN when receiving the UDP packets.

2. By analyzing the values returned by the STUN servers, one can classifying the NAT beha-viors as following:

27 See http://tools.ietf.org/html/rfc5128.28 See http://www.ietf.org/rfc.html for more details.

Network Boundaries NAT Traversal - 99

◦ Full Cone – Once a NAT mapping is estab-lished towards a remote WAN IP address, re-turn traffic from any IP address is accepted bythe NAT. In other words, it does not matterwhether returning/incoming traffic comes fromthe NAT mapped IP address and port or not, itis accepted and forwarded back to the hiddenpeer.

23.55.128.99:4445 ⇆XXX.XXX.XXX.XXX:YYYY

◦ Restricted Cone – Once a NAT mapping is established towards a remote WAN IP ad-dress, only traffic coming back from the translated address is accepted, regardless ofthe port:

23.55.128.99:4445 ⇆ 23.55.128.99:YYYY

◦ Restricted Cone – Once a NAT mapping is established towards a remote WAN IP,only traffic coming back from the translated address:port combination is accepted:

23.55.128.99:4445 ⇆ 23.55.128.99:4445

◦ Symmetric – Contrary to the above behaviors where a given LAN peer's local IP ad-dress is always translated to the same public dress, symmetric NATs always create anew public address:port communication for all outbound communication.

3. Each behavior can then be transmitted to the other peer which can establish direct UDPcommunication, except in the presence of symmetric NATs. In the presence of restrictedcone NATs, spoofing of sender's address would be necessary.

Unfortunately, this classification turned out to be too simple and is now abandoned It does notcover for all situations properly. RFC 3489 has been replaced by RFC 5389 in October 2008. Thescope has been reduced to detecting public mapping of a hidden peer/device and eventual con-nectivity between peers. The NAT classification has been dropped and the newly proposed stand-ard does not claim to be a NAT traversal solution anymore.

STUNT

STUNT stands for Simple Traversal of UDP through NATs and TCP too. This concept was intro-

Network Boundaries NAT Traversal - 100

duced in an article called: Characterization and Measurement of TCP Traversal through NATsand Firewalls, by Saikat Guha and professor Paul Francis29.

The first version (called STUNT #1) of this method includes spoofing in the 3-way handshake asfollowing:

1. Two peers A and B behind differ-ent NATs are connected to aSTUNT server.

2. They both initiate a dummy TCPconnection by setting a lowTTL30 in the first TCP packet(i.e., SYN). This punches a holein respective NATs, but a notific-ation of TTL failure is returned to each sending peer.

3. Yet, the mapping in each NAT remains valid and the returned TTL failure packet containslow level information about the dummy TCP connection. Both peers transmit this informa-tion to the STUNT server, which fabricates 'TCP connection accepted' packets for eachpeers and sends them back.

4. Both NATs believe that the responses come from the target peers and forward the packetreceived from the STUNT server to their local peers.

5. NAT traversal has been established.

There are two main issues with this method. Firstly, it is hard to find the proper low TTL values,since there may be multiple levels of NATs between a given NAT-ed peer and the STUNT server.Holes must be punched until the last NAT before reaching the STUNT server. Secondly, one musthave enough privilege to fiddle IP packets, which is not always possible under every operatingsystem or in every programming language.

The second version (called STUNT #2) of this method goes like this:

1. Only peer A initiates a dummy TCP connection by setting a low TTL. A hole is punched inNAT A.

29 See http://conferences.sigcomm.org/imc/2005/papers/imc05efiles/guha/guha.pdf.30 TTL stands for time to live. It sets a limit to the number of hops (i.e., intermediary devices) a packet can go through to reach its

destination. At each hop, the TTL is decreased by 1. When it reaches 0, the packet is discarded and a notification is sent back to thesender.

Network Boundaries NAT Traversal - 101

2. It collects the TTL failure response fromthe returned packet and sends to theSTUNT server who transmits the in-formation to peer B via a central peer.

3. Peer B sends a TCP connection re-quest to peer A using the informationprovided by the STUNT server. Itpunches a hole in its NAT.

4. NAT A accepts this incoming request (since a hole has already been punched) and sendsa positive response to peer B.

5. The TCP communication is established, NAT traversal has been performed.

The benefit of this method over STUNT #1 is that no packet spoofing is required.

TTL-less Version of STUNT

Using port prediction, TTL-less versions of STUNT #1 and #2 can be implemented too. The pack-ets are sent to the predicted ports after holes are punched.

New NAT Classification

The work of Saikat Guha and professor Paul Francis led to the creation of new grids describingNAT behaviors. The first one relates to NAT mapping when outbound communication is initiated:

NAT Mapping Description

IndependentThe mapping is independent from the target/outbound IP address and port. For agiven local address:port combination, the mapping will always be the same.

Address and Port1

For a given local address:port and target address:port combination, the mapping willremain the same if this combination is re-used. The mapping for new combinationsresults in an increase of the mapped port by 1.

Connection1Each new outbound communication creates a new mapping (no re-use of existingmapping) and the mapped port is increased by 1.

Port1

For a given local address:port, the mapping will remain the same if the target port isthe same. In other words, the mapping only depends on the local outboundaddress:port and target port.

Address1

For a given local address:port, the mapping will remain the same if the target port isthe same. In other words, the mapping only depends on the local outboundaddress:port and target port.

ConnectionREach new outbound communication creates a new mapping with an unpredictableport mapping.

Network Boundaries NAT Traversal - 102

Remark:Remark:Remark:Remark: the port increase is set to δ = 1 in the above table, but some NATs are known to have δ= 2.

The second grid relates to the treatment of incoming communication:

Endpoint Filtering Description

Address and Port Incoming communication must match the mapped address and port.

Address Incoming communication must match mapped address.

Port Incoming communication must match mapped port.

IndependentAll incoming communication from anywhere is accepted as long as a mapping isavailable.

These classifications have been summarized in RFC 5128.

Remark:Remark:Remark:Remark: By testing 16 lab NATs and 93 homes NATs, Saikat Guha and professor Paul Francisfound out that only 0.5% behaving like ConnectionR (or symmetric NATs). This is important, be-cause it is impossible to punch predictable holes with these NATs.

NUTSS

NUTSS31 is a network architecture also developed by Saikat Guha and professor Paul Francis atCornell University. It stands for: “NAT that effectively extends the IP address space, URIs that re-store end-to-end stable addressing, Tunnels that allow protocols like IPsec and mobile IP to runthrough NATs, SIP that routes messages with URIs, end-to-end, and lets hosts signal their inten-tions to each other and to middle boxes in real time, and lastly STUNT that tells how to establishdirect IP connectivity through NATs ”.

The project code has been made public in 2007 and is not maintained anymore.

P2PNAT

P2PNAT32 is a technique proposed in 2005 by Bryan Ford from the Massachusetts Institute ofTechnology, Pyda Srisuresh from Caymas Systems, Inc. and Dan Kegel. It aims at creating TCPcommunication between NAT-ed peers.

The idea is to have a central peer towhich two NAT-ed peers are connectedwith a TCP connection. When they wantto communicate with each other, they

31 See http://nutss.gforge.cis.cornell.edu/.32 See http://www.brynosaurus.com/pub/net/p2pnat/.

Network Boundaries NAT Traversal - 103

first fetch the other's translated address with the help of the server peer. Then, they both initiate aTCP connection to the other peer using the same port they were using to connect to the centralpeer and wait until the TCP connection is established successfully.

This method relies (amongst others) on the fact that NATs will accept an incoming TCP commu-nication request on the port used to sent an outbound TCP communication request to the targetpeer, before the outgoing request has been notifies as accepted by the target peer. This sequenceof TCP events is not necessarily accepted by all NATs.

NATBlaster

The NATBlaster technique wasproposed by Andrew Biggadike,Daniel Ferullo, Geoffrey Wilson,Adrian Perrig from the CarnegieMellon University in 2005. It is verysimilar to the STUNT #1 methodand goes like this:

1. Two peers A and B behind different NATs are connected to a central peer.

2. They both initiate a dummy TCP connection by setting a low TTL33 in the first TCP packet(i.e., SYN). This punches a hole in respective NATs, but a notification of TTL failure is re-turned to each sending peer.

3. The collected information is transmitted to each others' peer via the central peer.

4. Both peer send a 'TCP connection request accepted' response to the other peer.

5. NAT traversal is been established.

This method bears the same issues as STUNT #1, but does not require packet spoofing. How-ever, it uses TCP event sequences which are not always accepted by all NATs.

NatTrav

NatTrav is a STUN like method proposed in 2005 by Professor Jeffrey L. Eppinger from theCarnegie Mellon University to establish direct TCP connections between peers located behindNATs.

33 TTL stands for time to live. It sets a limit to the number of hops (i.e., intermediary devices) a packet can go through to reach itsdestination. At each hop, the TTL is decreased by 1. When it reaches 0, the packet is discarded and a notification is sent back to thesender if target has not been reached.

Network Boundaries NAT Traversal - 104

It involves a public broker peer helping hidden peers to establish a connection. Each peers main-tain some kind of UDP lease connection with the broker peer. When a peer wants to communicatewith the other, it notifies the broker, which notifies the target peer. The establishment of directcommunication process is started.

This method tacitly relies on the fact that for a given outgoing local address:port combination, theNAT will always use the same mapping, though this is not explicitly stated.

PWNAT

PWNAT34, pronounced poe-nat, is an ingenious technique developed by Samy Kamkar to punchholes in NATs for NAT traversal. Unfortunately, it relies on a NAT configuration that most compan-ies and network administrator disable for security reasons.

In general, all incoming and outgoing IP packets are filtered by NAT according to allowed and ex-isting mappings, but there is an exception. ICMP, the Internet Control Message Protocol, is part toof IP stack. It can be used to trace routes to remote device via echo requests messages (type 8).This is used by the ping instruction for example.

Contrary to other types of communication, Type 8 ICMP packet are not mapped. In fact, they can-not be mapped, because their purpose is to provoke an echo from all devices between this deviceand the targeted device. Since these are unknown, their IP address is also unknown. Hence, notmapping can be established. NAT work around this situation by analyzing the content of the re-turned ICMP packets (type 0, echo response).

Here is how pwnat works:

1. Let's imagine a source peer A onLAN A with local IP address192.168.0.34 hidden by a NAT Ahaving public address248.18.22.44.

2. Let's imagine a target peer B onLAN B with local IP address 192.168.0.45, knowing the public IP address of NAT A.

3. Both peer agree that communication between should happen on a pre-agreed port, for ex-ample: 2222.

4. When started, peer A starts sending ICMP echo packets to a dummy public address, for34 See http://samy.pl/pwnat/.

Network Boundaries NAT Traversal - 105

example 3.3.3.3, on port 7 (the echo port). This message has a pre-agreed (hard-coded)identifier, sequence number and content known by peer B too.

5. NAT A translates 192.168.0.34:7 to, let's say 248.18.22.44:7 and the echo is sent to3.3.3.3:7. Peer A never gets a response from 3.3.3.3 and does not expect any.

6. Let's imagine peer B want to communicate with Peer A, it creates dummy echo reply (type0 ICMP message) using the pre-agreed identifier, sequence number and content.

7. Peer B knows about the 248.18.22.44 public address. It sends its packet to248.18.22.44:7.

8. NAT B translates peer B's local address 192.168.0.45:7 to, let's say 87.88.89.90:7, andsends it to 248.18.22.44:7.

9. In the mean time, Peer B also starts sending UDP packet to peer A on the pre-agreedport: 248.18.22.44:2222. A hole is punched in the target peer for 2222.

10. NAT A receives the echo reply from peer B and does not check that the reply does notcome from 3.3.3.3. Peer B faked its identity as a step device (hop) between Peer A and3.3.3.3.

11. NAT A forwards this echo response to peer A after analyzing its content.

12. Peer A knows a) the translated address 87.88.89.90 of peer B, and that b) peer B wantsto communicate with it.

13. Peer A starts to fire UDP packets to 87.88.89.90:2222 and punches a hole for port 2222.

14. Peer A starts to receive communication from Peer B on 2222 and so does Peer B fromPeer A.

15. NAT traversal is accomplished.

This technique relies on port preservation between NATs, which is not always guaranteed.Moreover, corporations often close such ICMP echo communication.

ALG

ALG are application layer gateways. These can be installed on PCs, NATs or firewalls. Such ap-plications have been implemented to solve NAT traversal issues and installed on NATs to filterand analyze traffic.

Unfortunately, these solutions are not universal, because they would require installation on all

Network Boundaries NAT Traversal - 106

devices. Sometimes, IP address information is 'hidden' in the IP packet's content/payload or areencrypted. ALGs are not always able to handle such situations. Global updating and maintenanceof ALGs is not a simple operation.

One of the biggest problems with ALGs when it comes to NAT traversal is that they create anopen for man-in-the-middle attacks. Traffic can potentially be diverted inappropriately.

UPnP

Regarding NAT traversal, Universal Plug-and-Play is a technique by which devices can commu-nicate with router and tell them to forward external port traffic to a specific internal host on theLAN. The routers must support that technology to operate.

Unfortunately, this technique is not safe and can be used by hackers to perform many attacks. Forexample, a malicious application could let undesired traffic come in through the router.

ICE

ICE stands for Interactive Connection Establishment. It is an Internet standardization proposal forNetwork Address Translator (NAT) traversal for Offer/Answer Protocols. It relies on STUN andTURN. The first draft was submitted in 2003, and a very recent version of the proposal has beenreleased in April 201035 (RFC 5245).

The motivation for ICE comes from Session Initiation Protocol (SIP), a method used by voice of IP(VoIP) communications. As described by Jonathan Rosenberg in the IETF journal36 in 2007, NATtraversal was an issue then. Several solutions were implemented, but often came with their ownissues. A standard was needed.

We will briefly introduce the main steps of an ICE session creation:

1. Gathering – A peer starts to collect IP addresses and ports for possible communication.These are called candidates. The NAT translation of these addresses is obtained by con-tacting a STUN server. The result is called server-reflexive candidates.

2. Prioritizing – The candidates are assigned a priority according to a preference policy.

3. Offering – The candidates are sent to the remote peer.

4. Answer – The remote peers acknowledges the communication request and sends back itsown candidates.

35 See http://tools.ietf.org/html/rfc5245.36 See http://www.isoc.org/tools/blogs/ietfjournal/?p=117.

Network Boundaries NAT Traversal - 107

5. Checking – Each peer constructs candidate pairs with their candidates and remotes can-didates. Each pair is prioritized and tried successively.

6. Completing – Once a connection is established successfully, peers confirm the selectedcandidate pair and start communicating.

The ICE standard proposal has been through many evolutions. At the beginning, it was explicitlyreferring to SIP. Now, it does not anymore: “SIP can use ICE”. The latest standard proposal expli-citly refers to UDP, whereas in earlier versions, this was not the case.

ICE-TCP

ICE-TCP or TCP candidates with ICE37 is a standard draft created in October 2009. It aims at “ex-tending ICE to TCP-based media, including the ability to offer a mix of TCP and UDP-based can-didates for a single stream”. This document contains the key concepts of NUTSS.

“Behave” Compliant NAT

Solving the NAT traversal problem is not only a software related issue. Some best practices forNAT configuration and design have been defined in RFC 5382 and RFC 4787 for TCP and UDPcommunication respectively.

The consequence is that individuals & companies may need to invest in new compliant material tosmoothly operate P2P applications if old material cannot be configured properly or break possibil-ities of performing NAT traversal.

RFC 5382

For TCP, the best practice recommendations include the following. A NAT should:

• Have an 'Endpoint-Independent Mapping' behavior.

• Have an 'Endpoint-Independent Filtering' behavior, or an 'address dependent filtering' if amore rigorous behavior is required.

• Be capable of handling TCP simultaneous-open connections.

• Not answer an unsolicited inbound TCP request (SYN packet) for at least 6 seconds. If acorresponding outbound TCP request is received in the mean time, the original SYNpacket must silently be dropped, else a 'port unreachable' error may be sent.

37 See http://tools.ietf.org/html/draft-ietf-mmusic-ice-tcp-08.

Network Boundaries NAT Traversal - 108

• Not abandon an idle connection session before 2 hours and 4 minutes. For DDCP38 con-nections, the value of the "transitory connection idle-timeout" MUST NOT be less than 4minutes.

• Disable all ALGs impacting TCP.

• Not use port overloading (i.e., assigning a new port for each outbound connection).

• Support/manage hair-pinning situations properly.

• Translate ICMP Destination Unreachable (Type 3) messages if it translates TCP ad-dresses.

• Not terminate NAT mapping or TCP connections upon receipt of any sort of ICMP mes-sages (otherwise it would open many opportunities to disturb established communica-tions).

RFC 4787

For UDP, the best practice recommendations include the following. A NAT should:

• Have an 'Endpoint-Independent Mapping' behavior.

• Have an 'IP address pooling' behavior of 'Paired', that is, a device with a private IPaddress should always be translated with the same public IP address. This is relevant forNATs capable of exposing multiple public IP addresses (i.e., address pooling). If themapping is random, it is called 'Arbitrary'.

• Not implement 'Port overloading' for port assignments during translations.• Keep house source ports in the 0-1023 range into the same range for translation. • Keep house source ports in the 1024-65535 range into the same range for translation. • Implement 'port parity preservation', that is, an even port should be translated into an

even port, and an odd port should be translated into an odd port. This a recommendation,not an obligation.

• Not expire UDP mappings in less than two minutes, unless the port is in the 0-1023 range.A delay of 5 minutes is recommended.

• Have a 'NAT outbound refresh behavior' of true. That is, if an UPD datagram is sent froma NAT-ed device to the WAN, it should reset any idle timeout monitor to zero. A 'NATinbound refresh behavior' is optional.

• Make sure that configurable external IP interface do not conflict with internal IP addresses

38 Datagram Congestion Control Protocol: It is a protocol guaranteeing the delivery of datagrams, but not necessarily in order.

Network Boundaries NAT Traversal - 109

or make sure translation happens smoothly.• Have an 'Endpoint-Independent Filtering' behavior, or an 'address dependent filtering' if a

more rigorous behavior is required. This may be a configurable option on the NAT.

• Support/manage hair-pinning situations properly.

• Disable all ALGs impacting UDP. This may be a configurable option on the NAT.

• Have a deterministic behavior and not change translation or filtering behavior over time.

• Not terminate NAT mapping upon receipt of any sort of ICMP messages.

• Not filter ICMP messages based on their source IP address.

• Support ICMP destination unreachable messages (recommendation).

• If a packet received on an internal address with the 'don't fragment' flag set to 1, an ICMPmessage "Fragmentation needed and DF set" should be sent to the host. If the flag is setto 0, the NAT must fragment the packet and send the fragments in order.

• Should be able to receive in-order and out-of-order fragments (a 'Receive Fragments Outof Order' behavior).

Where Does JXSE Stand?

JXSE is currently relying on a TURN-like solution to overcome NAT issues. However, this is notvery efficient on a large scale. The community has shown some interests in implementing NATtraversal solutions to increase connectivity between peers.

Several factors should also be taken into account. As of release 2.6, JXSE uses TCP, multicastingand HTTP for communication. UDP is not used. Hence, if a pure TCP NAT traversal solution canbe implemented, it should have the priority. This eliminates the latest ICE standard proposal andshifts focus on ICE-TCP.

Any solution requiring specific privileges on peer devices should be discarded, as this parametercannot be controlled by the application. Short TTL based solutions are hazardous and not alwaysimplementable under every environment. The selected solution should work with as many NATsbehaviors as possible.

The research performed by Saikat Guha and professor Paul Francis indicates that STUNT #2without low-TTL would be the preferred solution, as it is the most robust to establish TCP connec-tion between NAT-ed peers. The community will decide.

Network Boundaries NAT Traversal - 110

Conclusion

Obviously, since the booming of P2P around year 2000, no definitive standard has emerged tosolve all NAT traversal issues. Existing research shows that it is a complex problem to solve. Mul-tiple solutions exist, but have not been integrated fully.

Evidently, the final standard for NAT traversal, if ever accepted by Internet community, will haveto:

a) Work both for TCP and UDP communication.

b) Make usage of port prediction from time to time to cover for all types of NAT behaviors.

c) Punch holes in NATs from time to time.

d) Work without requiring special user privileges on the device or to access to NATs directly.

e) Implement a fall-back solution for NATs filtering/refusing valid cases of TCP event se-quences.

f) Implement a fall-back solution if direct traversal communication cannot be established.

g) Have to offer the possibility of authenticating exchanged messages to avoid man-in-the-middle attacks while establishing NAT traversal.

If a global NAT traversal standard is made available and implemented in JXSE, one may wonder ifthe JXTA protocols will remain useful when it comes to connectivity. Solving NAT traversal issuesis tacitly assuming that a device has access to the WAN. But that it not always the case, either be-cause the device is not equipped for that, or because access is not granted on its part of the net-work. Communication may need to go through multiple peers before reaching destination.

One can imagine situations where communication might be necessary between such 'hard-to-reach' peers. If they implement the JXTA protocols, and cannot traverse their NATs or are too isol-ated, they could still forward their message to another 'local' JXTA peer who has access to theWAN. This peer would act as a JXTA proxy. Hence, the endpoint routing protocol of JXTA remaina valid fall back solution to unsolvable NAT traversal issues of a given peer.

Network Boundaries Conclusion - 111

- 112

JXSE Cryptographic Layer

Before we cover architectural considerations in JXTA, like how to develop and con-figure your P2P system, we will first cover the cryptographic layer of JXSE. Thischapter includes a reminder about the main concepts of cryptography. We will focuson public key infrastructures. If readers are not interested in cryptography at thisstage, they can skip this chapter and read it later.

Cryptography Reminder

Cryptography is a powerful tool that can help in mitigating (and sometimes eliminating) the inher-ent access control and confidentiality issues faced by all software applications when they commu-nicate and exchange data from remote locations. The following paragraphs remind us about com-mon cryptography concepts and issues every software developer and architect needs to keep inmind when designing a software application containing cryptography features.

Even the seasoned cryptographer's work is not exempt of weaknesses and flaws; this book can-not foresee every known attack on cryptographic systems. Therefore, we strongly recommendless-experienced programmers have their work reviewed by experts when implementing it withJXTA.

Alice, Bob & Eve

Alice, Bob and Eve39 are three famous characters in cryp-tography. They are the basic elements of a paradigm de-scribing the issues and objectives of cryptography.

The scenario is the following: Alice and Bob want to com-municate and exchange information confidentially, but Eve tries to interfere with the communica-tion. The objective of cryptography is to provide Alice and Bob with a system that allows them tocommunicate confidentially from remote locations while remaining protected from Eve's bad inten-tions.

More specifically, security is established between two users, computers or communicating entitiesover the Internet when:

39 Eve stands for eavesdropping. Cryptography uses many other names, such as Mallory for malicious attacker. For the sake of simplicitywe have kept only one name to identify an individual willing to disrupt the peaceful and private communication between Alice andBob using any possible means.

JXSE Cryptographic Layer Cryptography Reminder - 113

✔ Alice can establish a communication channel with Bob

✔ Alice can make sure the party at the other side of the channel is Bob (and not Eve fakinghis identity)

✔ Alice can exchange information over this channel without revealing its content to Eve

✔ Alice can make sure that a message transmitted over the channel to Bob has not beentampered or replayed by Eve

When the above is established perfectly, the anxiety of undesirable and uncontrollable disclosuresis perfectly eliminated and the level of trust between Alice and Bob is maximum, allowing lively ex-changes. Any pair of nodes on a P2P network can be considered as Alice and Bob.

Introduction To Secure Communication

Confidentiality between Alice and Bob can be achieved by the mean of a public key system. Cryp-tographic systems relying on these infrastructures often use two types of keys: asymmetric keysfor public exchanges and symmetric keys for private exchanges. This global system can be splitinto two subsystems.

The most common asymmetric key system (or public key system) used in cryptography is RSA. Ithas been designed to help distant parties initiate a secured connection, verify each other's identityand certify the origin of exchanged data. Unfortunately, the algorithms used by this system are notvery efficient at encrypting large quantities of data.

Another practical and faster solution was required, which led to the creation of symmetric key sys-tems (or private key systems). The most common one is Rijndael. It has been selected by the Na-tional Institute of Standards and Technology (NIST40) in 2001 as the advanced encryption stand-ard (AES) to be used by the U.S. Government.

To put it simply, after Alice and Bob have verified their identity with the public key system, theycreate a private key between themselves. Next, they use that private key to encrypt and to ex-change large quantities of data with the private key system which is more efficient.

Let's look at the procedure in more details (for the sake of simplicity, we will not include the usageof a private key system at this stage):

1. Alice and Bob both create their RSA asymmetric key, which is made of two parts, a publicpart and a private part. The public part of an RSA key is often called the public key. The

40 http://www.nist.gov/

JXSE Cryptographic Layer Cryptography Reminder - 114

private part of the RSA key is often called the private key, but it should not be confusedwith the symmetric key that will be created later with the private key system. This is acommon misunderstanding of novices in cryptography.

RSA keys pairs have an interesting property, if you encrypt a message with the public keypart, it can only be decrypted with the corresponding private key part. It is virtuallyimpossible to decrypt an encrypted message without knowing the private key part. This isthe main value of RSA keys.

2. Alice and Bob both publish the public part of their respective RSA key to a centralauthority they both trust. This authority is called a certificate authority. This authority isresponsible for certifying the public keys of its customers. They deliver certificatesestablishing a link between an identity (Alice, Bob...) and a public key. Third parties canlater verify the validity of these certificates to make sure these are not fakes.

3. Alice fetches Bob's public key from the certificate authority and Bob does the same withAlice's public key. They both verify the certificates against fakes. Now, Alice can useBob's public key part to encrypt a message and send it to him. Only Bob has thecorresponding private key part to decode it.

However, since Bob's public key is also available to Eve who can fetch it from thecertificate authority, she could also encrypt a message and send it to Bob. Therefore, Bobneeds a mechanism to make sure the author of the received message is Alice and notEve.

4. Authentication is achieved by having Alice encrypt a secret message that only Bob andher know (i.e., an authentication code) with Bob's public key and joins it to the encryptedmessage sent to Bob. This is something Eve cannot craft herself, since she does not haveaccess to Alice and Bob's secret. Moreover, she cannot get access to the secret when theauthentication code is being transmitted, since she does not have access to Bob's privatekey. When the message and authentication code arrives, Bob can verify that it is Alicewho has sent him the received message by decrypting the authentication code with hisprivate key and make sure it contains their secret.

JXSE Cryptographic Layer Cryptography Reminder - 115

But there is a major flaw in this way of communication: Eve can substitute the encryptedmessage sent by Alice to Bob with her own encrypted message using Alice's public keyand keep the authentication code created by Alice. She has the possibility to pollute thecommunication to Bob and he will not be able to detect this. The solution to this problem is to have an authentication code based, not only on a secretshared by Alice and Bob, but also on the message itself. This is what we call a messageauthentication code (or MAC for short). Computing a MAC is not a simple operation. Itcannot be performed by any algorithm. A good hash function41 is required, that is, afunction guaranteeing that finding the original message and secret used to compute theMAC is virtually impossible to achieve knowing the MAC only. It is a one-way function.Creating good hash functions is a fundamental and complex problem that has beenstudied in depth by cryptographers for a long time. It is imperative to use well-known andwell studied hash functions in cryptographic applications.

5. The new procedure to send a secret message is now i) to have Alice encrypt hermessage with Bob's public RSA key, and ii) to compute a MAC using the secret sheshares with Bob and the message itself. When Bob receives the communication fromAlice, he first decrypts the message with his private RSA key and then computes the MACof the message using the secret he shares with Alice. Then, if the computed MAC doesnot match the MAC received from Alice, the message is not authenticated and Bob shoulddiscard it. He has no guarantee that it comes from Alice.

Eve is not in a position to create a credible MAC, because she does not know the secretAlice and Bob share and she does not have access to the original message. Since thehash function used to create the MAC cannot be reversed easily, she will not be able tofigure out the secret and the message used to create the MAC.

If she substitutes the encrypted message with her own pollution message encrypted withBob's public key, she will still be missing their secret to create a credible MAC. Bob willnotice the discrepancy between the received MAC and the MAC he will compute himselfand know that someone has been fiddling with the communication.

There is still an issue we need to solve: how do we get Alice and Bob to share a common secret?

41 For example, the SHA functions: http://en.wikipedia.org/wiki/SHA_hash_functions

JXSE Cryptographic Layer Cryptography Reminder - 116

What type of secret should they share? The place of their first encounter or their favorite meal isprobably not very hard to guess by Eve! It should be something quite impossible to guess.

This issue can be solved by using the Diffie-Hellman protocol. Without entering into details, thisprotocol allows Alice and Bob to create a secret code from their remote locations using their RSAkeys. Even if Eve has access to the content of all transactions between Alice and Bob during theexecution of the Diffie-Hellman protocol, she will not be able to guess the secret code that is beingcreated. This protocol allows Alice and Bob to create secrets at will from remote locations.

There is another benefit to creating secrets with Diffie-Hellman. The secret can be used as a sym-metric key between Bob and Alice to encrypt bigger messages with faster algorithms (such AESfor example). In this situation, Eve will not be able to create polluted messages anymore, since a)they won't be using the public key of Bob to encrypt messages anymore and b) Eve will not haveaccess to the secret created by Alice and Bob.

The secret key created between Alice and Bob will be valid only between them. This is why wecall it symmetric as opposed to RSA keys which can be used to establish secured communica-tions between any given pair of peers (i.e., asymmetric communications).

...And Vicious Circles!

Many readers are probably wondering how we can prevent Eve from achieving her evil objectiveswhen i) Bob and Alice register their public RSA keys at the certificate authority or ii) when theyboth retrieve the other's key from that same authority? She could fake the identity of the certificateauthority and have Alice and Bob believe that they are talking to that certificate authority by deviat-ing the transactions with this authority.

One can be tempted to say: It's simple, establish a secure communicationwith the certificate authority and Eve won't be able to achieve her objectives!!! Another reader will answer: Yes, but you would need to obtain the publiccertificate of that authority first! What if Eve fiddles that communication too?This is an Ouroboros situation !!!

Moreover, Eve could create her own RSA key pair claiming she is Bob orAlice and register it at a certificate authority. Or better, Eve might be running the certificate author-ity service herself !!! There are several issues to be solved here.

There is a simple but impractical solution to tackle Eve's plans. Instead of using a certificate au-thority, Bob and Alice could meet face-to-face to exchange their public RSA key in the absence of

JXSE Cryptographic Layer Cryptography Reminder - 117

Eve. This is OK when Alice and Bob live in the same neighborhood, but what if they have hun-dreds of friends and colleagues all around the world? This method would be impractical.

In order to make sure that Eve is not creating a fake certificate pretending that she is Bob or Alice,the certificate authority has to verify her identity. This could be done with a driver's license or apassport, but we can't exclude the possibility that Eve is faking these too. Regardless of the factthat this solution would be impractical too, this is another case of Ouroboros. Can we trust the au-thority certifying Eve's-pretending-to-be-Alice's identity?

Let's imagine that Eve manages to obtain a fake certificate and pretends she is Alice with Bob.Bob will not be able to detect it, until after some time: a) he notices that the communication withAlice is bizarre... Why doesn't Alice remember the place of our first meeting in our conversations?or b) he gets to meet Alice face-to-face and talks about a discussion they apparently had on thenet the day before... A discussion Alice won't remember of course! Eve is busted !!!

Alice and Bob will need a mechanism to denounce and invalidate the false certificate used by Eve.This is a service that certificate authorities should offer. Now, Eve could also try to break the sys-tem by pretending to be Alice and claiming (falsely of course) that someone else called Eve has infact registered a fake Alice certificate. She would use her fake identity papers to pretend she is thereal Alice and ask the certificate authority to invalidate the current Alice certificate and replace itwith a new one. Alice who was Alice is now Eve playing Alice for other peers on the network. Infact, this technique may have been the technique she used in first place to fake her identity withBob. Do you think this is crazy? Cryptography is a complex matter !!!

This problem can be mitigated by notifying the 'former' Alice that her certificate has been revoked,unless Eve controls that communication channel, too. The 'former' Alice would then contact thecertificate authority and say that she never made a request to invalidate her certificate. The certi-ficate authority could perform more verifications and since they would most probably have kept acopy of Eve-pretending-to-be-Alice' identity papers, they would come to a conclusion that theseare invalid. They would notify other authorities that someone is trying to fake Alice's identity withthese false identity papers.

In these attacks, we are assuming that Eve is very powerful and that she can control things thatshe most probably would never be able to control in reality (at least, without being detected soon-er or later). However, we have to keep these scenarios in mind to minimize the capacity of poten-tial hackers to crack security systems.

In reality, certificate authorities cannot ask for identity papers each time someone wants to register

JXSE Cryptographic Layer Cryptography Reminder - 118

a certificate; it is impractical over the Internet. They often register an email address, a real mail ad-dress, a phone number and the IP address of the peer making the request for certification instead.They ask for a confirmation by sending an email to the registered address and request users toclick on a web page link contained in the email to confirm their registration. It is another opportun-ity to register IP addresses. In case of problem, the certificate authorities can always use that in-formation to track down the user who has registered that information. If they can't find that personor if the corresponding person does not match with the registered information, the certificate au-thority will know that there is something suspicious going on...

This discussion illustrates some of the problems cryptography has to solve. It also demonstratesthat if many people want to start communicating securely from distant locations, there is no otherpractical option than to put some initial trust in the cryptographic system and to accept that therewill always be a risk that people with bad intentions will try to exploit cracks and fake identities orcorrupt communications. This is like poker, if you want to play, you have to pay the ante !!!

The fundamental issue is that you have to trust 'things' that are representing people or entitieswithout always having a possibility to double-check with 100% certainty that those using these'things' are the real people or entities themselves. That is one type of loophole Eve is trying to findand to exploit. Such loopholes cannot be avoided since the whole world population is not living onthe same street. Moreover, it will never be interested in living in the same street for the benefit oftackling Eve by having only face-to-face conversations with other peers. It will always prefer totrade a bit of risk for the comfort of remote and quite secure communications.

There is no need to become paranoid about cryptography systems just by reading the above para-graphs. We trust the post office not to open or to fiddle with the letters we send to our belovedones (or others), even though these items are highly unprotected. We have been using ourphones and mobile phones for years without thinking that someone might listen to our conversa-tions. How many secrets did we reveal that way? Today, many of us are using chatting applica-tions which are sometimes not protected at all. We transmit sensitive documents by email eventhough we don't really know how much protection they have.

Before stressing on the cracks of cryptography systems, most of us should first stress on the waywe deal with confidential and sensitive information using traditional means of communications. Wewill now cover some of the concepts we have mentioned earlier in more details.

Public Key Infrastructure (PKI)

A public key infrastructure is a means by which public keys of users are bound with their identities

JXSE Cryptographic Layer Cryptography Reminder - 119

with the help of a certificate authority. As wementioned it earlier, a user willing to publishhis or her public key to other users starts byrequesting a certificate authority to certify itspublic key by providing its identity and re-ceives a certificate in return. This certificatecan then be distributed to other peers whocan verify and validate its content themselves(we will explain how later). A well-knownstandard for those certificates is X.509 whichis used as part of JXSE.

Who Certifies The Root Certificate Authority?

A PKI creates chains of certificates by certifying other authorities and users, but there is always (atleast) one root certificate authority to start with. The question is who will certify that authority? Theanswer is nobody. Root certificate authorities certify themselves and publish their own certificate.These are often big institutions relying on their established credibility to get the trust of their cus-tomers.

This type of credibility requires a level of trust which is similar to that we put in banks when theykeep our money or centrals banks when they print bank notes. Central banks are the root institu-tions delivering credits to other banks. Their objective is to facilitate economical transactionsbetween individuals or entities in an economy by providing certified bank notes.

Duties Of A Certificate Authority

Every certificate authority should provide a document explaining in detail how it issues and man-ages certificates. It should also describe all other associated services it may provide in relation-ship to certificate management. This document is called a Certificate Practice Statement (CPS).

Certificate authorities not only should implement a mechanism to verify the identity of users re-questing certifications, but also a means to get access to that user in reality.

They should also maintain a Certificate Revocation List (CRL), that is, a list of all certificates is-sued by the certificate authority which should not be considered as valid anymore.

Let's imagine that someone has managed to steal the private key of a user or that this private key

JXSE Cryptographic Layer Cryptography Reminder - 120

has been compromised by other means, the corresponding public key on the user's certificateshould not be used anymore. However, many copies of that certificate can still be owned by manyusers.

These users should check the CRL from time to time to make sure that the certificate of otherpeers they own has not been revoked.

Web Of Trust

The web of trust is an alternative to the central authoritymodel. Instead of calling a central authority to establishtrust relationships via certificate, one establishes trust re-lationships via the people they trust. If Alice trusts Bob,and Bob trusts Carol, can Alice trust Carol? Most probablyyes. How is this performed with certificates? Bob certifiesCarol's certificate. Since Alice can make sure that Bob – and no one else – has certified Carol'scertificate, Alice can trust Carol's certificate. Likewise, Carol will do the same with Alice's certific-ate via Bob.

This model will look very appealing to defenders of pure P2P systems. Every peer can create acommunity of peers they trust. Everyone generates their own certificates and have these certifiedby the people they trust. Unfortunately, it only works with small communities. Once several thou-sands or millions of users get involved, very long chains of certifications are created. Each will beas strong as the weakest link. If Eve manages to get in some of these chains (which is not veryhard with this type of trust model), she can compromise large parts of the system. In addition, apeer can be certified by different chains of peers, which is redundant. Moreover, this model doesnot explain how to perform efficient certificate revocation.

It turns out that authentication of peers and their public keys is best performed by central authorit-ies as opposed to a model where everyone certifies each other. Most of us can be trusted not tocheat, but there will always be a small percentage of people with bad intentions. They can do a lotof damage in the web of trust model. In order to have a practical and secure P2P system, you arebetter off using a couple of central authority peers. The trade-off is that you have to put your trustin these authorities, rather than in your close friends, but you will benefit from a higher overall levelof security.

JXSE Cryptographic Layer Cryptography Reminder - 121

X.509

X.509 is a standard for the definition of certificates which appeared in 1988. Since then, three ver-sions of this standard have been made available. The following table describes version 3 of theX.509 certificate structure. Some fields are mandatory and others are optional:

X.509 version 3structure

Description Hashedfield

version X.509 version 1, 2 or 3 Yes

serialNumber Unique identifier of the certificate Yes

signature Signature algorithm that should be used tocertify this certificate

Yes

issuer Identity of the certificate authority issuing thecertificate

Yes

validity Validity period of the certificate Yes

subject Identity of the user to certify Yes

subjectPublicKeyInfo Public key of the user Yes

issuerUniqueID Optional - Certificate authority unique ID Yes

subjectUniqueID Optional - User unique ID Yes

extensions Optional – Additional information Yes

signatureAlgorithm Signature algorithm used by the certificateauthority

No

signature Signature of the certificate itself No

Typically, a user will send its identity (subject field), eventually its ID (subjectUniqueID field)

and a request to use a specific signature algorithm to the certificate authority (signature field) to

the certificate authority. The certificate authority will fill the remaining fields to be hashed and willhash them with a proper hashing function. The result value will then be encrypted (i.e. signed) withthe private RSA key of the certificate authority to create the signature of the certificate. At last,

the certificate authority fills the signatureAlgorithm field to specify which algorithm has been

used and send the certificate back to the user42.

Later, the user can distribute his certificate (let's call it A) to other users. They can check that certi-ficate A is genuine by retrieving the certificate of the certificate authority (let's call it B) whosename is mentioned on A. This certificate should be retrieved from the certificate authority itself.Certificate B contains the public key of the central authority. Our verifying users compute the hashvalue of the to-be-hashed fields in certificate A using the method specified in the signatureAl-

42 We have not included identity verification in this procedure for the sake of clarity and simplicity, but it should be included in realimplementation of certificate authorities.

JXSE Cryptographic Layer Cryptography Reminder - 122

gorithm field. They also verify the content of the signature field with the public key of the certi-

ficate authority available from certificate B. This operation returns a value which can be comparedto the hash value of A. If these match, then certificate A can be considered as valid. A check onthe validity period of certificate A and a verification on the certificate authority CRL should be per-formed too to make sure the certificate has not become obsolete.

Now, I can also check the validity of certificate B with the certificate of the central authority men-tioned on that certificate. I can repeat that operation until I reach to the root certificate authority.This is how the links in the chain are connected to each other to form a chain of trust.

X.500 & Principal

A principal is something representing an entity which can be a peer, an individual, a corporation,etc... X.500 is a standard for directory services, that is, a system of software applications collect-ing, organizing, storing and providing information about network resources and users. This inform-ation is typically used by network system administrators.

JXSE uses the Java X500Principal object to describe certificate authority peers when imple-

menting cryptography. When a certificate authority peer signs a certificates, its name is expressedusing a format defined as part of the X.500 standard. The identity, or more specifically, the prin-cipal of the certified peer is also expressed using one of these standard formats.

Hash Function

Several hash functions have been developed by cryptographers. Crafting such function requires alot of mathematics and statistics. It is a complicated task and one should rely on well-known andstudied functions rather than trying to fiddle one's own algorithm (which will be cracked quickly byhackers...). Examples of hash function are: SHA1, MD5, RIPEMD and Tiger.

SHA1 is a hash function returning a result of 160 bits long, MD5 returns a result of 128 bits long.The size of the return value is very important when implementing a cryptographic system, be-cause of the collision issue which we will describe next. The number of possible input values ofgood hash functions is always incredibly greater than the set of possible output values, meaningthat many input values will generate the same output. One of the most interesting properties ofgood hash functions is that they tend to return values which are uniformly distributed in the set ofpossible returned values. In other words, it is very hard to guess the input value (or the set of inputvalues) of a hash function by knowing its output only.

JXSE Cryptographic Layer Cryptography Reminder - 123

The Collision Issue

The collision issue is often described with the birthday paradox. Let's imagine an empty roomwhere one would let random people come in one by one. Each time someone comes in, we checkwhether that person shares the same birthday as anyone else already in the room, regardless ofthe year of birth. The question is: after letting how many people will the probability to have at leasttwo people share the same birthday be over 50%? There are 365 days per year (except for leapyears). Surprisingly, this threshold is reached after only 23 people. Most people would think more.

The mathematics of the birthday paradox will tell you that if the number of possible output valuesfor a hash function is 2n for example, the 50% probability of encountering a collision (i.e., two inputvalues producing the same output value) will occur after more or less 2n/2 attempts. In the birthdayparadox, 365 = 28.51... and 28.51.../2 ≈ 19.104... This is close to the real number: 23. When n increasesthe relative error between the real value and the estimation of the threshold tends to 0.

But what is the problem with the collision issue? Well, it can be used to fake identities! Here ishow to proceed:

1. I request a certificate authority to sign my certificate A.

2. The authority checks my identity and signs my certificate, since I am who I claim I am.

3. I can compute the hash value of the to-be-hashed fields of my certificate. Let's call thisvalue hash(A).

4. Let's imagine that I want to fake the identity of a rich person (for example, Donald Trump),to send fake orders to his bank. I create a dummy certificate B with the same values as incertificate A, except for the fields identifying the user. I substitute these values with thosecorresponding to my victim.

5. Then, I select random values for the public key and compute the hash value of my craftedcertificate B, until the result hash(B) equals hash(A).

If MD5 is the hashing function, the birthday paradox theory says it should happen with aprobability above 50% after 264 ≈ 1019 attempts. This can reasonably be attempted with aset of powerful computers. Unfortunately, some weaknesses have been found with MD5(and many other hashing functions). Cryptographers have managed to create collisionswith a lower threshold, and therefore, to lower the number of attempts required to reachour objectives in reality. But let's ignore this for now.

6. I don't need to ask the certificate authority to sign certificate B, because I know that the re-

JXSE Cryptographic Layer Cryptography Reminder - 124

turned signature value will be identical to the one of certificate A, since hash(A) = hash(B).The certificate authority would sign the certificate with the same hash value, even thoughthe content of the fields are different. Different inputs are resulting in the same outputvalue. Therefore, I just need to copy the signature of certificate A on certificate B.

7. I can now use certificate B to send bank orders to Donald Trump's bank. The bank will getthe public key of the certificate authority to check the signature on certificate B (which thisauthority has never signed) and will find out that it matches with hash(B). Therefore, thebank will consider that I am Donald Trump and proceed with the order without ever detect-ing my true identity: Eve.

Do you like this trick? Why do you think hackers try to steal credit card information on theInternet? Would you have found this one by yourself? Do you think you can beat all the scientiststhat have dedicated hours of research and hard work, years after years, to identify those dirtytricks and produce robust solutions? If your answer is yes, then the NSA43 will have a job for you...Otherwise, trust the hard work that has been done by cryptographers and experts in the past. Askfor their advice.

What you need to remember about hash functions is that the size of their output, expressed as apower of 2, should preferably be equal to (or greater than) 160 (but preferably 256) to escape thecollision issue. There is not enough processing power to crack collisions in a space of 2256 valuesfor now or in the near future, since a collision would only probably happen after 1038 attemptswhen using a brute force attack (i.e., trying random combinations until a collision is obtained).

Key Sizes

The size of a symmetric key is a different concept than the size of asymmetric key pairs. The min-imum acceptable size of a symmetric key today is 128 bits, although 192 or 256 bits are recom-mended for more sensitive data. The size of an asymmetric key is in the 1024+ range. As of thepublication of this book, 2048 bits long asymmetric keys are believed to be valid until 2030, but4096 bits are more recommended.

Assumptions

One should keep in mind that the strength of the RSA public key system is relying on the fact thata number made up of the product of two very large prime numbers cannot be decomposed into itsoriginal factors easily. There is no known fast algorithm to achieve this operation, but it does not

43 National Security Agency

JXSE Cryptographic Layer Cryptography Reminder - 125

mean that none will be found in the future. It also does not mean that we won't be able to provethat such algorithms don't exist either. If such an algorithm is found, then the suggested size forcorresponding RSA keys will fall immediately and all cryptographic systems relying on RSA willcollapse instantaneously. If we can prove that no such algorithm exists, it will mean that we willhave a nearly perfect method to hide secrets for as long as we want. The same line of thought canalso be applied to other algorithms used in cryptography. We do not know of any easy way tocrack these, but we do not have proof that there is no way to crack them easily.

Banks, International Institutions and the military trust many of these algorithms to protect theirdata and their communications. Do you think you can trust them too?

The DRM Illusion

There is one venue that many believe to be a 'holy grail' when it comes to protect content on re-mote devices: Digital Rights Management (DRM). The intention is the following: Alice owns asecret recording of the Beatles and wants to share it with many people, but does not want them tocopy it. She implements an application checking whether Bobs are allowed to listen to the recordand preventing them from copying it. Both this application and the encrypted record are located onBobs' devices. The safe and the key are in the hands of the same individual.

No matter how much protection you put on your recording, at some stage, listeners are alwaysgranted some access to it. If Eve plays a Bob, she will always have the possibility of stripping allallallallprotection and access the content of the recording.

At best, DRM systems – and any system where individuals both have access to the safe and thekey – can only help keeping honest people honest, but not dishonest people honest. If you need toperform an operation involving a secret (i.e., key), perform it on a device that is under your fullcontrol and that no Bobs can physically access. Don't store your secrets on a device that is notfully under your control, they will sooner or later be compromised.

Calling Experts

We have briefly described some cryptography concepts which can be implemented in P2P sys-tems. However, there are many practical issues and ways of attacking cryptographic systems thathave not been covered in this book. We will repeat ourselves, but cryptography is a very complexscience. Arrogance, creativity and lack of experience are good indicators of people you shouldavoid in this domain. Humility, patience and experience are what you are looking for. Use code lib-raries developed by experts; do not try to do it yourself if you are not an expert. Your adversaries

JXSE Cryptographic Layer Cryptography Reminder - 126

know about the typical flaws novices make and can exploit weaknesses in unimaginable ways. Donot assume they won't find your cracks. They will.

If you include a cryptography system in your application, whether or not it is P2P, it is highly re-commended to call cryptography experts to review your design documents and to review the tech-nical implementation of your cryptographic system (i.e., the code and sometimes the hardware). Itis better to be safe than sorry. Keep a list of potential weaknesses of your system and monitorthese one way or the other.

At last, never believe that security systems will ever protect you perfectly. They won't. They willprovide degrees of security. These should match the value of what you have to protect. Don't ex-pect more, don't expect less.

Personal Security Environment (PSE)

The personal security environment is a specific implementation of the JXTA membership serviceusing a public key infrastructure. It is the default membership service implemented in JXSE, ex-cept for the NetPeerGroup and the WorldPeerGroup which have a 'grant-access-to-all' mem-

bership service. Every instance of the PSE Membership Service requires a keystore, that is, aplace where certificates and private keys can be stored safely.

Java Cryptography Architecture

Before we get into more details, the PSE relies on functionalities implemented as part of the JavaCryptography Architecture. This includes the creation of X.509 certificates and keystores for ex-ample. Developers will also find useful functionalities to create Certificate Revocation Lists.

Readers should get familiar with these API (Application Programming Interfaces) if they are notsavvy with Java cryptographic functionalities. Some documentation is available from:http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html.

KeyStore

JXSE implements three sorts of keystores via the KeyStoreManager interface: the CMKey-

StoreManager located in the local peer cache directory, the FileKeyStoreManager where the

user specifies File location when creating the keystore object and the URIKeyStoreManager

where the location is provided with a URI. When creating such objects, a keystore type can bespecified. It can be any type accepted by the standard KeyStore Java class. If no type is spe-

cified (null), the default JKS type implemented by Sun Microsystems will be used.

JXSE Cryptographic Layer Personal Security Environment (PSE) - 127

Creation

The following code44 describes how to create a simple File keystore:

...

// Preparing data

String MyKeyStoreFileName = "MyKeyStoreFile";

String MyKeyStoreLocation = "." + File.separator + "MyKeyStoreLocation";

String MyKeyStorePassword = "My Key Store Password";

String MyKeyStoreProvider = "Me Myself And I";

File MyKeyStoreDirectory = new File(MyKeyStoreLocation);

File MyKeyStoreFile = new File(MyKeyStoreLocation + File.separator

+ MyKeyStoreFileName);

// Deleting any existing key store and content

NetworkManager.RecursiveDelete(MyKeyStoreDirectory);

MyKeyStoreDirectory.mkdirs();

// Creating the key store

FileKeyStoreManager MyFileKeyStoreManager = new FileKeyStoreManager(

(String)null, MyKeyStoreProvider, MyKeyStoreFile);

MyFileKeyStoreManager.createKeyStore(MyKeyStorePassword.toCharArray());

// Checking initialization

if (MyFileKeyStoreManager.isInitialized()) {

System.out.println("Keystore initialized successfully");

} else {

System.out.println("Keystore NOT initialized successfully");

}

...

Before creating the keystore, the directory that will contain the resulting file is emptied from itscontent and the directory structure is (re)created if necessary. Then, we create a default keystoreand set its password. Next, we make sure it has been initialized properly. We should obtain thefollowing:

Keystore initialized successfully

This operation is a one time operation that all peers wishing to use the PSE membership environ-ment should perform. The keystore will be used next when setting the network configuration.

Automatic X.509 Certificate & Private Key Creation

Before starting the JXTA network, one should set some parameters in the NetworkConfigur-

ator object that will be used to configure the PSE membership service. After creating a keystore,

44 The complete code examples are available in the appendix.

JXSE Cryptographic Layer Personal Security Environment (PSE) - 128

one should set the keystore location with the setKeyStoreLocation(URI keyStoreLoca-tion) method.

If a peer does not have a X.509 certificate and private key pair and wishes to create one itself, itcan do so with the following code:

...

// Erasing any existing configuration

Tools.DeleteConfigurationInDefaultHome();

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.EDGE,

"My Network Manager instance name");

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting the key store location

MyNetworkConfigurator.setKeyStoreLocation(MyKeyStoreFile.toURI());

// Setting the name to be used for the X500 principal

String ThePrincipal = "Me, Myself & I";

MyNetworkConfigurator.setPrincipal(ThePrincipal);

// Setting a password for encrypting the private key that will be

// created as part of the X.509 automatic certificate creation

String SecretKeyPassword = "My Secret Key Password";

MyNetworkConfigurator.setPassword(SecretKeyPassword);

// Saving the configuration, which will trigger the X.509 certificate creation

MyNetworkConfigurator.save();

// Trying to retrieve the X.509 certificate from the configurator

X509Certificate MyX509Certificate = MyNetworkConfigurator.getCertificate();

if (MyX509Certificate==null) {

System.out.println("Cannot retrieve X509 certificate from NetworkConfigurator");

}

...

The above code begins by deleting any existing configuration. After creating the NetworkMan-

ager, we retrieve the NetworkConfigurator and set the principal for the X500 structure, to-

gether with the password that should be used to encrypt the private part of the public key that willbe created as part of the X.509 certificate creation. Saving the current configuration triggers thecreation of a X.509 certificate, since all existing configuration has been deleted.

If we try to retrieve the result from the NetworkConfigurator, it will be unsuccessful:

Cannot retrieve X509 certificate from NetworkConfigurator

Why? Because the NetworkConfigurator does not reload what it has just saved. However, we can

JXSE Cryptographic Layer Personal Security Environment (PSE) - 129

retrieve our automatically created X.509 certificate via the PSE configuration advertisement as fol-lowing:

...

// Retrieving the configuration parameters

ConfigParams MyConfigParams = MyNetworkConfigurator.getPlatformConfig();

// Retrieving the PSE configuration advertisement

PSEConfigAdv MyPSEConfigAdv = (PSEConfigAdv)

MyConfigParams.getSvcConfigAdvertisement(PeerGroup.membershipClassID);

// Retrieving the X.509 certificate

MyX509Certificate = MyPSEConfigAdv.getCertificate();

System.out.println(MyX509Certificate.toString());

...

We get something like this:

[

[

Version: V3

Subject: OU=3B9641C7512BE17295F3, CN="Me, Myself & I-CA", O=www.jxta.org

Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

Key: Sun RSA public key, 1024 bits

modulus: 1149142515334121103270713157246112976747...

public exponent: 65537

Validity: [From: Wed Apr 30 19:54:30 CEST 2008,

To: Mon Apr 30 19:54:30 CEST 2018]

Issuer: OU=3B9641C7512BE17295F3, CN="Me, Myself & I-CA", O=www.jxta.org

SerialNumber: [ 01]

]

Algorithm: [SHA1withRSA]

Signature:

0000: 6B E2 28 4C 9A C2 22 DD C6 E5 06 22 D2 5C 3F 04 k.(L.."....".\?.

0010: B5 B6 6F 70 01 BF 80 5B 23 06 4D 46 A8 90 0F 4A ..op...[#.MF...J

0020: F8 AB B4 2D 61 B7 84 AD CB 3F D6 1A 3D DD 90 45 ...-a....?..=..E

0030: 8A 6C 3C C2 46 7F F4 D8 AC C0 94 AD FF E0 F2 9B .l<.F...........

0040: C0 7A A5 6D 67 CE C2 05 A6 D5 86 93 E6 EA 14 76 .z.mg..........v

0050: FF 00 3B 7B 52 1E E4 A5 DB 57 3E 7C C7 45 A8 BF ..;.R....W>..E..

0060: 0D 11 EC 4D D5 1B AA DA 69 43 97 65 85 3E A3 B2 ...M....iC.e.>..

0070: 06 D8 84 DD DA 01 A6 F2 CD 50 66 44 CC AE 6F 1C .........PfD..o.

]

If we do not erase the newly created (and saved) configuration the next time we retrieve the Net-

workConfigurator, the X.509 certificate will be available directly from the MyNetworkCon-

figurator.getCertificate() method. One will not need to retrieve it from the PSE configur-

ation advertisement anymore. Regarding the private key, it can be retrieved from the Network-

Configurator assuming that the password used to encrypt it in the keystore has been set prop-

erly.

JXSE Cryptographic Layer Personal Security Environment (PSE) - 130

In the code examples we provide later, we will describe a third method to retrieve keys and certi-ficates from keystores using the PSE configuration object of the PSE membership service.

Big Big Big Warning!

The newly created certificate is based on a public RSA key pair of 1024 bits, which is not a lot. Asof the publication of this book, the largest RSA key pair which has been cracked is 768 bits long45.Cryptographers consider that data encrypted with keys of 1024 bits should be not be consideredsafe after 2015. Yet, the default duration of the certificate is set to 10 years. You do the math...!

Moreover, the hashing method is SHA1, which return results of 160 bits longs. Unfortunately,

some researchers have managed to create SHA1 collisions within 263 attempts46, instead of the

theoretical 280 limit. This is a little too close for comfort. You would still need a lot of computerpower to create collisions, but it is not unreasonable to think that such power can be made avail-able in the near future by coupling networks of computers47.

There is another issue you need to take into account: the password and method used to encryptthe secret key corresponding to the X.509 certificate. The number of different characters we usefor our passwords is roughly 45 (a-z, 0-9, special characters...). Since we often use passwords of6 to 8 characters long, the total number of combinations is more or less 458 ≈ 244. Again, this is nota lot. A network of powerful computers could try to generate all password combinations and findwhich one you used to encrypt your secret key.

And this is an optimistic view, since we assume that all characters will be used with equal probab-ilities. This is not the case in reality; our passwords usually contain more letters than numbers andmore numbers than special characters. In their Practical Cryptography book, Neil Ferguson andBruce Schneier indicate that the amount entropy per character in English text is in the neighbor-hood of 1.5-2 bits. Since most of us use passwords of 6 to 8 characters, we generate an entropyof 16 bits in average. This is much, much lower than the 244 limit.

Besides, our passwords often contain words from the dictionary, names, birth dates, etc... Someclaim that there is up 1 million words (220) available in English. This is a small amount of combina-tions to try in order to crack a password (even if you combine them with numbers and specialcharacters). This type of attack is called a dictionary attack.

There is technique called salting (or salt-and-stretching) to reduce password weaknesses. Instead

45 http://en.wikipedia.org/wiki/RSA_numbers#RSA-768 46 http://en.wikipedia.org/wiki/SHA1 47 Don't even think about JXTA to do this!!!

JXSE Cryptographic Layer Personal Security Environment (PSE) - 131

of using a password as is, we can use hash functions several times on it with a set of random bitsto produce a new hashed password. The idea is to have the number of hashing iterations com-pensates for the lack of password entropy.

We will come back later on security issues of JXTA and JXSE.

Registering Your Own X.509

If you create your own X.509 by other means or obtain it from third certificate authorities, you canregister these in the NetworkConfigurator with the setCertificate(X509Certificate

cert) method. You can also register your certificate chains with the

setCertificate(X509Certificate[] certificateChain) methods. Do not forget to

save your configuration.

PSE Configuration

When using the PSE membership service, some initial configuration may have to be performedvia the PSEConfig object after the keystore has been created. This object can be retrieved from

the PSEMembershipService itself:

...

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.EDGE,

"My Network Manager instance name");

// Starting JXTA and retrieving the net peer group

PeerGroup TheNetPeerGroup = MyNetworkManager.startNetwork();

// Retrieving the membership service

PSEMembershipService ThePSEMembershipService = (PSEMembershipService)

TheNetPeerGroup.getMembershipService();

// Retrieving the configuration object

PSEConfig ThePSEConfig = ThePSEMembershipService.getPSEConfig();

...

We can check whether the PSE configuration has been initialized and set an initial keystore pass-word if such has not been set. This password should not be confused with the password used toencrypt secret keys when automatically creating X.509 certificates.

...

if (ThePSEConfig.isInitialized()) {

System.out.println("PSE is initialized");

JXSE Cryptographic Layer Personal Security Environment (PSE) - 132

// Retrieving login password

String LoginPass = JOptionPane.showInputDialog(null, "Enter keystore password");

ThePSEConfig.setKeyStorePassword(LoginPass.toCharArray());

} else {

System.out.println("PSE is NOT initialized");

// Retrieving initial password

String InitPass = JoptionPane.showInputDialog(null,

"Enter initial keystore password:");

ThePSEConfig.setKeyStorePassword(InitPass.toCharArray());

// Initializing PSE configuration

ThePSEConfig.initialize();

}

...

Later, if that code is run again, one will detect that the PSE configuration has been initialized andthe corresponding password will be retrieved from the user. It is not mandatory to use a passwordwith a keystore. There is a possibility to set a protection for each entry with a specific passwordwith the following methods:

• void setKey(ID id, Certificate[] certchain, PrivateKey key, char[]

key_password) – This PSEConfig method creates (or replaces) an entry for the spe-

cified ID (usually a user or peer ID) to set a certificate chain and a private key. If thekey_password parameter is not null, it will be used to protect that entry.

• PrivateKey getKey(ID id, char[] key_password) – This other PSEConfig

method can be used to retrieve a PrivateKey corresponding to a specific ID. If a passwordhas been used to protect the entry, it will have to be specified again, else the key_pass-

word can be left null.

Typically, if you had your X.509 certificate created automatically, this is where you shoulduse the password you specified to encrypt the private key that has been created automat-ically too.

The same password protection principle applies to several other PSEConfig methods. This

second level of protection comes on top of the keystore password. One can check whether thepassword provided for an entry is valid with the validPasswr(ID id, char[] store_pass-

word, char[] key_password) method which returns a boolean. Several other practical

methods are available from the PSEConfig objects to manage keys and certificates. The reader

should check the javadoc for more information.

JXSE Cryptographic Layer Personal Security Environment (PSE) - 133

Other Concepts

Secure Socket Layer (SSL)

The Secure Socket Layer was invented to provide secured communications between two entitiesover the World Wide Web. It was originally implemented for HTTP connections. The idea was tohave only one party (the web server) authenticated. The user would check its certificate from thecorresponding certificate authority.

SSL operates at two levels: the SSL Handshake protocol and the SSL Record Protocol. Afterchecking the server's certificate, the first protocol is responsible for creating a symmetric keybetween the two parties. The second protocol is responsible for exchanging information in a se-cure way using the created symmetric key.

Several versions of SSL have been implemented; the latest being version 3. Earlier versions ofSSL have been disabled in many web browsers, because they contain several weaknesses.

Transport Security Layer (TLS)

Transport security layer is the follow-up of SSL. It is very similar to SSL, but is intended for abroader set of applications (not only web browsing). Typically, two applications or entities can useit to establish secure communications using one of many types of algorithms.

There is not real difference between SSL 3.0 and TLS 1.0. Today, TLS 1.1 and 1.2 are available.Both SSL and TLS are standardized in IETF48 documents.

Virtual Private Network (VPN)

Virtual Private Networks offer the idea of extending your local company network to the whole ofthe Internet via secured communications. In other words, instead of having your local network pro-tected only by routers, proxies and other artificial network boundaries, your users can connect toyour company from any remote location.

Since their identity can be established during the creation of the secured communication channeland since other parties cannot interfere with such connections, these users and their PCs can beconsidered as a safe part of the company's network, although they are not physically located with-in the company.

48 Internet Engineering Task Force: http://www.ietf.org/

JXSE Cryptographic Layer Other Concepts - 134

JXTA Security Layer

JXTA implements TLS version 1.0 for transportation of messages between peer endpoints on theJXTA network. This model is a clear-message-over-encrypted-communication-channels ratherthan an encrypted-message-over-clear-communication-channels model. JXSE guarantees that if amessage between two peers has to be transmitted via a relay peer or via other peers, these willnot have access to the content of the message.

About Cipher Suites

Experts in cryptography will tick at the fact that there are weaknesses in the methods used by TLS1.0 to establish secured communications. These methods are called cipher suites49. The officialspecification of TLS 1.0 authorizes the usage of specific cipher suits methods to establish securedconnections. Unfortunately, some of these suites use weak algorithms.

The current implementation of JXTA has peers automatically selecting/negotiating the cipher suitethemselves according to their capacity and order of cipher suite preference. This is coming fromthe Java implementation of TLS connections itself. This could be exploited by hackers to force theusage of a weak cipher algorithm. This attack venue is not very easy to exploit, but those havingmeans can certainly use it. The main issue is that there is no way to configure any JXTA TLScommunication parameters as of version 2.5 of JXSE. One cannot force the usage of safe ciphersuites only. Ideally, one should be able to use some of the TLS 1.1 or 1.2 cipher suites too andblock all the unsafe ones.

Those willing to modify the JXSE code to solve this issue themselves should take a look at classTlsConn in package net.jxta.impl.endpoint.tls in the TlsConn(TlsTransport tp,

EndpointAddress destAddr, boolean client) constructor. The setEnabledCipher-

Suite(String[] suites) method can be called on the ssls object after the call to ssls.-

setEnabledProtocols(new String[]{"TLSv1"}) to restrain the usage to specific cipher

suites. Other protocols can be selected too, but with the risk of not being 100% compatible withthose who do not use these.

About Encryption of Private Keys

Java offers two types of keystores: JKS and PKCS#12. JXSE offers the possibility to create key-stores via the PSEKeyStoreManagerFactory object, but their type is automatically set to JKS.

This how the PSEConfig object will create keystores when its initialize() method is called.

49 The list of authorized cipher suites for TLS can be found in Appendix A.5 of the TLS specification document available onhttp://www.ietf.org/rfc/rfc2246.txt.

JXSE Cryptographic Layer JXTA Security Layer - 135

PKCS#12 is a standard describing a syntax to define personal information exchange.

The Java keystore object contains two versions of the same method to store private keys:

• void setKeyEntry(String alias, byte[] key, Certificate[]

chain) – This method should called for private keys which have already been previ-

ously protected (i.e., encrypted) by other means.

• void setKeyEntry(String alias, Key key, char[] password, Cer-

tificate[] chain) – This method can be called for private keys which have not

been protected by external means.

But what do we know about the algorithm used by JKS keystores to encrypt private keys whichhave not been protected by other means? Apparently, not much information is available on the In-ternet.

If we take a look at the PSEConfig object, which can be used to configure the PSE membership

service delivered by JXSE, it contains a method to set private keys in the user's keystore:

...

public void setKey(ID id, Certificate[] certchain, PrivateKey key, char[] key_password)

throws KeyStoreException, IOException {

String alias = id.toString();

synchronized (keystore_manager) {

KeyStore store = keystore_manager.loadKeyStore(keystore_password);

// Remove any existing entry.

store.deleteEntry(alias);

store.setKeyEntry(alias, key, key_password, certchain);

keystore_manager.saveKeyStore(store, keystore_password);

}

}

...

The bad news is that this method calls the second version of the setKeyEntry() method of the

keystore, that is, for keys which have not been protected beforehand. The user may think that itsprivate keys will be protected safely in the keystore, but nothing is less sure.

The workaround is simple, one can retrieve the keystore from the PSEConfig object by calling oneof the getKeyStore() methods and call the proper version of the setKeyEntry() method

after having encrypted/protected its private key properly.

The reader may wonder why the encryption of private keys is an issue, since these are never ex-

JXSE Cryptographic Layer JXTA Security Layer - 136

changed during JXTA communications. There is a risk if someone gets access to the keystore fileof a user on its PC. This can happen if a PC is stolen for example.

PSE Configuration Advertisement Encryption

If one sets a private key and an encryption password in the NetworkConfigurator, and later

calls the save() method, a PSE configuration advertisement will be created and saved as part of

the local configuration. This advertisement will contain an encrypted version of the private key.The encryption method is salting the password 500 times with MD5 and then encrypting theprivate key with DES and the result of the hashing. Some cryptographers will complain about MD5and the number iterations, but this is still much better that the unknown algorithm in Java key-stores.

If someone steals a user's PC, his encrypted private key will be accessible to the thief. If the en-cryption password used to protect it is weak, then brute force attack will allow the thief to have ac-cess to it in a reasonable amount of time if he/she has access to sufficient computer power.

This issue can be mitigated by encrypting one's PC hard disk. It makes the access to the encryp-ted private key much harder, especially when a strong password has been used to encrypt thehard disk.

Conclusion

Discussing the weaknesses of an encryption system or of its usage always comes with a dilemma:who should be informed of this? Will hackers try to exploit those weaknesses? The fact is thathackers willing to attack JXTA/JXSE-enabled applications would easily spot the weaknesses men-tioned here. The information provided in this book may look very technical to those who have littleor no expertise in cryptography, but it is not to those with more experience, including hackers.

The author strongly believes that in this context, it is much more preferable to inform readers thannot, especially if some indication for solutions can be provided. The acute reader will notice thatsome of the issues raised here are not related to the implementation of cryptography in JXTA it-self, but to the usage of cryptography in general.

The development of JXTA and JXSE is an ongoing process. A project to better integrate JXSEwith JAAS (Java Authentication and Authorization Service) has been created. Contributions arewelcome.

JXSE Cryptographic Layer JXTA Security Layer - 137

Where Does JXSE 2.6 Stand?

Although JXSE code contains an embryo of secured communications, there are still some funda-mental issues to be solved. For example: published advertisements are not signed, and thereforecannot be authenticated. It is unfortunately an open venue to pollute local caches with remotepublication for example.

Some code has been implemented by a member of the community to solve these issues. How-ever, although patches exist, they have not been included as part of 2.6 because of a lack of re-sources and priority was given to other 'urgent' issues.

JXSE Cryptographic Layer JXTA Security Layer - 138

Architectural Considerations

This chapter discusses JXTA and implementation of software applications usingJXSE from an architectural point-of-view. We will cover the general issues and ques-tions software designers should be aware of. This includes the configuration ofpeers, the definition of a peer's identity and other factors.

Identity Issues

IP Addresses As Identities

Earlier, we mentioned that using IP addresses to identify peers or JXTA was not going to be agood solution, even when using IPv6. Although IPv6 is providing more IP addresses than the hu-manity will (most probably) ever need, we cannot rely safely on the fact that one could assign aunique IP address per peer and that this IP address could be used to identify any peer.

The problem is that if you assign a unique IP address to each physical device, for example, byhard coding it in the network card or within the processor of a computer, there is still a possibilitythat your computer needs some repair requiring you to change your network card or your pro-cessor. Either one would need to reset the IP address on its device or one would need to notifyeveryone that he or she has changed of IP address (i.e., identifier). If one can change its IP ad-dress on his/her device, he/she would therefore be able to fake its identity, since its IP address ishis/her identity on the network.

Another problem is that people change computers. Sometimes, they have many computers, too.Two different computers cannot have the same IP address (except when they belong to differentsubnets50), otherwise, the Internet would not be able determine which one should receive a datapacket. Therefore, if I had two computers, I would have two identities on the Internet. That is notreally what we are looking for.

Moreover, many people can connect to the Internet via the same computer. If a unique IP addressis used on that computer, then who is really connected to the Internet? We would need several IPaddresses for the same computer to establish different identities.

When using IPv4, there is also the problem of dynamically assigned IP addresses. If one's IP ad-dress changes each time one connects to the Internet, we cannot rely on its IPv4 address to es-

50 This is like two cities having a street with the same name. The postman does not get confused about the destination street, since thename of the city differentiates them.

Architectural Considerations Identity Issues - 139

tablish one's identity.

The fact is that we need to conceptually decouple the concept of location on the Internet and theconcept of user identity. Users can use one or many computer devices and devices can be usedby one or many users. We should also keep in mind that a computer or a device does not neces-sarily always have the same IP address according to its physical location when connecting to theInternet. Contrary to houses, computers are mobile, like laptops. There are 3 factors to take intoaccount: the user, the computer and the location of the connection on the Internet.

It is tempting to believe that since we need to identify peers in a unique way on the Internet andthat since IPv6 offers a sufficient number of IP address to accomplish this task, we should usethese to identify users. But, IP addresses are used to identify physical locations where to deliverdata, not users. Moreover IPv6 addresses can be changed for a given device.

Defining An Identity in JXTA

In JXTA, the concept of peer is a little bit blurring, since a peer is defined as 'any networkeddevice implementing the JXTA protocols'. However, we use peer IDs to identify peers on the net-work. To be correct, we should say that users are using a peer to connect on the JXTA network.

In JXSE, there is a clear decoupling between the identity of a peer (i.e., a physical device imple-menting the JXTA protocols) and its address on the network. This allows the peer to connect fromdifferent locations on the Internet. The peer ID is fixed, but the IP address can change. Oneshould not forget that a peer must provide its peer ID to connect to the JXTA network via a peergroup.

Now, there is a temptation to make a one-to-one relationship between a peer ID and a user, as if auser would always possess only one physical device running JXTA protocols. That is not a goodidea. If we connect two devices having the same peer ID on a JXTA network, the behavior of thesystem will be unpredictable. The identity of a peer in JXTA should not be confused with the iden-tity of a user.

A peer ID is defining a peer, not a user and not a computer device. In JXSE, a memory stick con-taining a JXTA-enabled application could be used by several users on several computer devices.Now, there is nothing preventing each of these users to connect to the JXTA network using theirown peer ID when they use the memory stick. If two memory sticks A and B were available, a userconnecting sometimes with A and sometimes with B would not be starting with the same JXTAstatus in terms of known advertisements, for example.

Architectural Considerations Identity Issues - 140

Metaphorically:Metaphorically:Metaphorically:Metaphorically: There is a risk of identity confusion in our metaphor, because:

1. Islands are physical locations on the ocean.

2. It is the tribe's people who are running the 'jxta protocols'.

Since we tend to identify ourselves with the tribes, rather than with their rulers, and since eachtribe has its distinctive sign (flag, tattoo, etc...), we tend to believe that it is our tribe's distinctivesign that defines us, but no: users are rulers and rulers are users. Our tribe's people is the soft-ware that is running the JXTA protocols; they can do that on many islands. We could be the rulerof a tribe having another distinctive sign.

Now, contrary to reality, islands are immobile. Our computer devices are not. This is a limitation ofthe metaphor. Yet, tribes' people still navigate between islands.

Creation Of Peer IDs & Importation Of IDs From Other Systems

A peer ID can be are created with two static methods of the IDFactory object:

• newPeerID(PeerGroupID groupID) – This method will create a new random Peer ID

using the ID of the peer group used to connect to the JXTA network.

• newPeerID(PeerGroupID groupID, byte[] seed) – This method can be used to

import IDs from other systems by converting them into byte arrays. If your IDs representusers, don't forget that you are tacitly assuming that there is a one-to-one relationshipbetween peers and IDs when providing them as seeds.

Every ID in JXTA has a format. A peer ID is made, amongst other things, of two hexadecimalstrings of 32 characters: one for the peer group and one for the peer itself. This gives us 3216 = 280

≈ 1024 combinations for the peer ID part only. Peer IDs are generated with a statistically uniformdistribution among possible combinations.

If you are too worried about possible collisions from our discussion about the birthday paradox,you can eventually split your population in peer groups.

Peer Group Creation & Identity

Just like peers, peer groups have their own JXTA IDs too. The identity of a peer group is easier todefine than for peers. We already know that there are two default peer groups having default IDs:the world peer group and the net peer group.

The question software architects and designers will have in mind is when to create a new group?

Architectural Considerations Identity Issues - 141

There are several factors influencing the answer to that question:

• InclusionInclusionInclusionInclusion – Sometimes, people need 'something' to get connected to each other. Peergroups can be used to create social semaphores that will help those sharing a commoninterest gathering together.

• SeclusionSeclusionSeclusionSeclusion – Sometimes, groups of individuals want to isolate themselves from the rest ofthe world to discuss specific issues. Instead of including everyone, they select the peoplethey want to let in. This can be implemented by the means of credentials and membershipservices.

• Access ControlAccess ControlAccess ControlAccess Control – Some peers may be offering services of value or possess valuable con-tent. Owners do not necessarily want to share and distribute this content. Access controlcan be implemented to solve this issue.

• Membership ControlMembership ControlMembership ControlMembership Control – From the protocol specifications, the net peer group and the worldpeer group should accept all requests for peergroup membership51. If membership controlis required, one should create a new group with the PSE membership service (for ex-ample).

• CapacityCapacityCapacityCapacity – Some peers may be capable of offering services that other peers can't, be-cause they have more capacity (software, memory, processors, etc...) than others. Onemay want to create a group to identify them and let people connect to that group to findout which peer is available to perform those resource consuming services.

• MonitoringMonitoringMonitoringMonitoring – Let's imagine that a meteorological institute installs a set of small devices op-erating on JXTA to measure the temperature or the humidity of a given area. One will beinterested in creating a peer group to monitor those devices and collect information fromthem.

Architects and designers will need to find the right balance to create peer groups. The more peergroups are created, the more rendezvous will be needed for those groups to operate properly. Donot forget that messages are only propagated within a peer group.

The consequence is that, ultimately, the more peer groups are created (i.e., very high specializa-tion), the less peers connected to these groups will be able to connect with other peers in othergroups. Since peer groups are organized according to a parent-child hierarchy, peers looking ran-domly for other peers would need to travel through that hierarchy and to connect to many groups

51 This requirement was not properly implemented in the 2.5 release. This has been solved in 2.6.

Architectural Considerations Identity Issues - 142

before finding someone 'interesting'. This is an extreme scenario, but it describes the limit to mul-tiple group creation.

Configuration Modes

JXTA defines four kind of peers52 and JXSE offers five basic configuration modes which can becombined together to create more sophisticated configurations.

JXTA Peer Types

Minimal Edge Peer

Typically, these peers send and receive messages, but they do not keep copies of advertisementsor route messages. The consequence is that other peers cannot count on them to provide supportwhen looking for resources or routes to reach other peers. This can be perceived as a selfish atti-tude, but is justified when dealing with devices having low capacities (sensors, mobile phones,etc...). Minimal edge peers can be considered as pure consumers of JXTA networks.

Full-Featured Edge Peer

Like minimal edge peers, full-featured edge peers can send and receive messages. Contrary tothese, they cache advertisements and participate to the discovery process initiated by other peersby answering to their queries when they can. However, full-featured edge peers do not forwardthese queries to other peers.

Full-featured edge peer make a greater contribution to the JXTA network then minimal edgepeers, since they help other peers finding or getting access to resources on the network.

Rendezvous Peer

Rendezvous peers are similar to full-featured edge peers, but they take more responsibility in or-ganizing the JXTA network. Among other things, they keep a map of all connected peers in a peergroup and they help forwarding messages and queries within a peer group. Such a peer is con-sidered as an infrastructure peer.

Relay Peer

Relay peers were formally known as route peers earlier in JXTA.. Their purpose is to help peers

52 These types are not defined in the JXTA specification document, but in the developer's guide version 2.5, which is a little ambiguous.

Architectural Considerations Configuration Modes - 143

hidden by some features of the network transportation layer connect with other peers and vice-versa. These are also considered as infrastructure peers.

JXSE Configuration Modes

JXSE defines configuration modes via the NetworkManager.ConfigMode.

ADHOC

Ad hoc is the most minimal JXSE configuration a peer can use.

• These peers do not connect to infrastructure peers (like RELAY or RENDEZVOUS) to be-nefit from their services.

• If they receive a query or any other kind of infrastructure-related request, they automatic-ally propagate it on their LAN if they cannot answer it, but do not get involved in moresophisticated operations. They perform strict minimum duties.

Such infrastructure communications are received by ADHOC when a RENDEZVOUS orEDGE peers are also located on the WAN and propagates information via multicasting.

• They only use multicasting on the LAN to communicate with other peers. Hence, theycannot directly be reached by peers on the WAN.

• They can automatically become EDGE or RENDEZVOUS if proper configur-ation is set and specific conditions are met. If this happens they never returnto an ADHOC status (unless the application is started again).

EDGE

Edge is the most frequent JXSE configuration used by devices to connect to theJXTA network:

• These peers automatically try to connect and to remain connected to one and only onerendezvous peer.

• If a connection with their rendezvous is lost, if their rendezvous goes down or if a rendez-vous does not accept a lease request, they will try to establish a connection with the nextrendezvous they know about until success. It is an infinite cycle.

• Edge peers can communicate using multicasting, TCP and HTTP when enabled throughconfiguration. Hence, they can directly communicate with adhoc on the LAN if multicasting

Architectural Considerations Configuration Modes - 144

is enabled.

• Edge peers with private IP addresses need to be connected to a relay peer to be reach-able from the WAN. Like with rendezvous peers, they attempt to connect to relay peersand do their best to remain connected, or shift to the next relay.

• When an edge wants to perform an operation involving infrastructure activity it does so viaits connected rendezvous. Some infrastructure related query and information can some-times be propagated on the LAN via multicasting if enabled.

• If properly configured, an Edge can become a rendezvous when there are not enoughrendezvous available for example. It can also switch back into an edge if there are fewedges connected to it.

RENDEZVOUS

Rendezvous peers are edge peers implementing and offering the services of JXTA rendezvouspeers for their peer group.

• Rendezvous can communicate using multicasting, TCP and HTTP. Typically, they shouldalways enable at least TCP, else they will barely be able to perform their duties.

• Typically, rendezvous peers should operate with a public address, which makes them (po-tentially) reachable from anywhere on the WAN.

• A rendezvous with a private address is redundant when multicasting is enabled by allpeers on the LAN. It only makes sense if only TCP is enabled and if the local rendezvousis connected to other rendezvous.

• Rendezvous can demote themselves into edge peers when configured so and when fewedge peers are connected to them. They can also become rendezvous again if there arenot enough rendezvous available.

• Rendezvous accept lease requests from edge peers and use these to propagate infra-structure related messages and messages propagated through the peergroup to edgepeers.

RELAY

In JXSE, relay peers are edge peers providing means for peers having a private address on aLAN to be reachable from the WAN.

Architectural Considerations Configuration Modes - 145

• Relay peers are typically enabled with a public IP address. Edge peers with a private ad-dress have to be able to connect to them. A relay with a private address is useless.

• Edge peers connect to relay peers. When a remote peers wants to connect to NAT-edpeers, the process of finding a route will indicate that they should go through the relaypeer.

PROXY

In early implementations of JXTA, there used to be proxy-needing peers who would connect toproxy peers to access the JXTA network. These proxy-needing peers were implemented for smalldevices with limited capacities.

Since, JXME peers have been developed and do not need to connect to JXTA via proxy peers.The proxy code has been deprecated in JXSE 2.6 and will be removed in a future version.

Peer Type versus Configuration Types

The following table establishes the relationship between the JXSE configuration mode of a peerand its type in JXTA.

Is a Minimal Edge Peer Fully-featured Edge Peer Rendezvous Peer Relay Peer

ADHOC Can be No No No

EDGE No Yes No No

RENDEZVOUS No Yes Yes Could be too

RELAY No Yes Could be too Yes

About Implementation Of Services...

Confusion can rise between the services available in JXSE peers and their role in the JXTA net-work. Some may believe that (for example) if a JXSE peer uses an edge configuration, rendez-vous or relay services will not be available from these peers. Yet, when one performs a test, onewill notice that these services can be retrieved from the PeerGroup object used to connect to the

JXTA network.

The fact is that JXSE developers decided to make the implementation of all JXTA services avail-able to all peers connecting to the JXTA network via the net peer group and the world peer group.However, those services are not necessarily activated. As a consequence, all connections to newpeer groups made by calling the newGroup(...) method of PeerGroup objects will automatic-

ally benefit from the implementation of these services as long as these are mentioned in the mod-

Architectural Considerations Configuration Modes - 146

ule implementation advertisement.

Developers who want to implement their own versions of JXTA services will have to implementcorresponding interfaces and either create a new object implementing the PeerGroup interface or

inherit from the existing class implementing the PeerGroup interface. In each case, the method

returning the service from the PeerGroup object should return the new one implemented by de-

velopers.

Network Scope

When implementing an application based on JXTA, one must decide the scope of the JXTA net-work one wants to reach. This question may seem silly at first, since JXTA is defining a universalset of protocols for P2P transactions, but it is not when considering implementation issues. In the-ory, JXTA offers the possibility to connect to all JXTA-enabled peers, but in practice, we havealready seen that technical issues prevent this from happening smoothly and automatically.

Each implementation of JXTA requires a network transportation layer, which determines the set ofJXTA-enabled peers which can be reached from a technical point-of-view. If you are using JXSE,you will be able to reach peers connected via TCP/IP (and HTTP). If you want to reach peers viaanother transportation layer, you will need another implementation of JXTA.

You also need take into account the technical capacities of each device that will run your JX-TA-enabled applications. Are they capable of running java byte code or not? Do you need to com-pile a C/C++ version on a specific platform? Do you need to implement JXTA in a new program-ming language?

To Be Or Not To Be?

In order to operate efficiently, JXTA also needs a set of super peers, that is, a set of peers havingmore responsibilities, capacities and duties than others in order to organize and to operate theJXTA network efficiently.

A Relay

The necessity for relay peers in JXSE comes from the need to overcome artificial network bound-aries. The factors to be considered are the following:

• Will you peers be assigned private Ipv4 addresses?

• Will your peers be connecting from/to the WAN to peers located behind a NAT?

Architectural Considerations Network Scope - 147

• Is only HTTP allowed outbound to the WAN on your network?

If the answer to any of these questions is yes, you will need to implement some relay peers withpublic IP addresses. These relays should be set as seeds for user peers running your JXTA-en-abled application. User peers should not be acting as relays themselves, but should rely on theset of relay peers you will implement when deploying your application.

You can control the maximum number of simultaneous connections to your relay peers via thesetRelayMaxClient(...) method of the network configurator.

A RendezVous

RendezVous are facilitating the propagation of messages and queries between peers in a peergroup whose members are not all reachable by multicasting. The necessity for rendezvous peer ismostly driven by the number of peer groups your JXTA-enabled application will use. There shouldbe enough rendezvous for each peer group.

But what is enough? There are three dimensions to this issue: a) Some seed peers should be set-up to enable general connectivity of peers within peer groups, and b) some edge peers may de-cide to become rendezvous themselves for the peer groups they are connected to and c) everyrendezvous can be accept a limited amount of connections from edge and rendezvous peers.

The RendezVousService of peer groups contains a couple of useful methods:

• setAutoStart(boolean auto, long period) – This method can be used to have

user peer switching between becoming rendezvous peers or not. They will reconsidertheir roles after an interval of period milliseconds have expired.

• IsConnectedToRendezvous(...) – Indicates whether a peer is connected to at

least one rendezvous.

• IsRendezvous(...) – Indicates whether a peer is acting as a rendezvous.

You can control the maximum number of simultaneous connections to your rendezvous peers viathe setRendezvousMaxClient(...) method of the network configurator.

One should remember that each rendezvous maintains its list of known rendezvous in a peergroup. These rendezvous peers regularly send random lists of their known rendezvous peers to aset of known rendezvous peers. Non-responding peers are removed from the lists. This helpskeeping the network connected.

Architectural Considerations Network Scope - 148

Moreover, a peer can be connected to several peer groups simultaneously. Therefore, it can actas a rendezvous for some or all of these peer groups.

Number of Seeds

Edge peers try to maintain one and only one connection with a rendezvous. However, a rendez-vous cannot support an infinite number of peers. Even if many rendezvous are set, the number ofpeers trying to connect to these can still be an issue.

Moreover, rendezvous peers also need to establish initial connections with other rendezvousseeds. If the same set of seed rendezvous is used for edge and rendezvous peers, the risk of run-ning out of lease connection will rise even more. A solution is to create a set of rendezvous seedsfor edges and a set of rendezvous seeds for rendezvous. If necessary multiple layers of seedscan be set. A seed belonging to a layer would only try to use seeds of an above layer.

Network Administration

There is a lot network administrators can do to guarantee the performance and connectivity of JX-SE-enabled applications.

Default IP Ports

The default IP ports used by JXSE are in the 9701 to 9799 range. If a user runs one JXSE-en-abled application, he/she will use one port. If several JXSE-enabled applications run on his/hercomputer (or device), several IP ports in the range above will be used. In this case, they are selec-ted randomly.

Network managers should do their best to configure their network firewalls in order to enable com-munication over these ports. However, if there is a conflict, JXSE-enabled applications can beconfigured to use other port ranges via the NetworkConfigurator object. This would have to

be discussed with the application developers.

Default HTTP Port

In order to establish communication with peers located behind NATs or with peers hidden behindfirewalls (because the default JXSE IP ports are not enabled), JXSE-enabled peers will try to es-tablish HTTP connections via port 9901 to relay peers. It is important to let peers communicate viathat port on firewalls too, because if they cannot connect via the standard IP port and IP ports,there will only be able to establish connections with other peers via multicasting on the LAN. This

Architectural Considerations Network Administration - 149

would be a very strong limitation.

Using the default HTTP port is also necessary to let peer from the WAN initiate connections withpeers located on the LAN via relay peers.

Again, if the default value for this port creates a conflict, JXSE-enabled peers can be configuredwith another value.

Default Multicasting Port & IP Address

JXSE-enabled peers naturally try to establish connections with other peers using the 224.0.1.85multicast address. They listen on port 1234 to do so. If firewalls are implemented on the userdevices themselves, this port should be enabled to establish multicasting connections. Those val-ues can be reconfigured in case of conflict.

Implementing Seeds

In order to operate a network of JXSE-enabled peers, rendezvous and relay seeds are required.These facilitate the connectivity of JXSE-enabled peers over the Internet. In order to operate prop-erly, such seeds must have a static IP address and should be visible from anywhere on the Inter-net. When implementing such seed devices, network managers need to make sure that NATs areconfigured to let data packets reach and leave these seeds directly (i.e., without translation).

Network Managers may be tempted to question the need of seeds since they control their net-works. They should keep in mind that users belonging to their own organization may need to es-tablish connect from outside their network, and that from these other locations, remote routers,firewalls and NAT may not be configured optimally for JXSE-enabled peers. These will often needto access known seeds of their organization to establish connections with other peers of their or-ganization.

About Subnets

If network managers have divided their networks into subnets, they need to make sure that alltheir routers are configured properly to allow peers located on one subnet to connect to peers loc-ated on another subnet using their local IP address. They should do also their best to enable mul-ticasting between these to facilitate connectivity. Otherwise, rendezvous peers will be necessaryto perform infrastructure activity between peers located on different subnets.

Architectural Considerations Network Administration - 150

Cryptography

Two main strategies are available regarding using cryptography over JXTA. One can rely on theTLS communication layer implemented within JXSE between peers, or one can implement its owncryptography layer over other JXTA items.

Implementing Your Own Cryptography Layer

Implementing a customized cryptographic layer using a PKI based on RSA key pairs requireschoosing a proper hash function and a proper a cipher algorithm for private messages exchangedbetween peers.

As of the publication of this book, only a few number of hash functions have not already beencracked with collisions. This includes the SHA-256/224 and SHA-512/384 functions. Others, likefamous MD5 and SHA-0 have been cracked with collisions and cannot be considered as safe any-more. The author recommends using the SHA series of hash functions since they have benefitedof a lot of attention from experts.

For the cipher algorithm, the author recommends using the AES (Advanced Encryption Standard)or one of the finalists of the competition that led to the selection of the AES: Serpent, Twofish,RC6 and MARS. We recommend using Counter (CTR) or Cipher-Block Chaining (CBC) for theblock cipher mode.

A good version of the Diffie-Hellman protocol will have to be implemented too to create privatekeys between peers.

Remark:Remark:Remark:Remark: Implementing your own cryptography layer is not an easy task. Your job should be re-viewed by experts.

Exportation Limitations

There is another issue you need to take care of: exportation limitations. Several countries havelimitations on exportation of products containing cryptographic features. The stronger the al-gorithm and the bigger the RSA key, the more you may need an exportation license for yourproduct.

Authorities are more permissive with mass-market software applications than, say 10 years ago,yet restrictions still exist. Check with lawyers for the latest export license requirements and obliga-tions.

Architectural Considerations Cryptography - 151

Access Control Implementation

We have seen earlier that the default implementations of the membership service and of the ac-cess service in JXSE are very permissive. Software architects will need to design their own ac-cess control system to protect the access to their JXTA resources, when necessary. This impliesdeveloping a Java class implementing the AccessService interface. Some may not be satisfied

with the default PSE Membership Service implementation and may want to re-implement it too.

In both case, one will need to modify the content of the net.jxta.platform.Module file in the

META-INF.services package of the JXSE reference implementation source code to make sure

these are loaded by the default peer group implementation.

# The list of Built-in Module Implementation Classes included with this distribution.

# Used by PeerGroup Implementation.

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000020106 net.jxta.impl.resolver.ResolverServiceImpl...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000030106 net.jxta.impl.discovery.DiscoveryServiceImpl...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000040106 net.jxta.impl.pipe.PipeServiceImpl Reference...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050106 net.jxta.impl.membership.none...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050206 net.jxta.impl.membership.passwd..

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050306 net.jxta.impl.membership.pse..

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000060106 net.jxta.impl.rendezvous..

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000070106 net.jxta.impl.peer.PeerInfoServiceImpl...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000080106 net.jxta.impl.endpoint.EndpointServiceImpl...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000090106 net.jxta.impl.endpoint.tcp.TcpTransport...

urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000A0106 net.jxta.impl.endpoint.servlethttp...

urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000B0106 net.jxta.impl.endpoint.router.EndpointRouter...

urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000D0106 net.jxta.impl.endpoint.tls.TlsTransport...

urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000E0106 net.jxta.impl.proxy.ProxyService...

urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000F0106 net.jxta.impl.endpoint.relay.RelayTransport...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000100106 net.jxta.impl.access.always...

urn:jxta:uuid-deadbeefdeafbabafeedbabe000000100206 net.jxta.impl.access.simpleACL...

The software developers will need to specify the name of the class containing their own accesscontrol implementation classes at the proper lines in the above file.

Remark:Remark:Remark:Remark: Access control can be implemented for other purpose than peer group membership. Itcould be used to control access to resources or services.

Architectural Considerations Access Control Implementation - 152

Using JXSE

This chapter explains how to use JXSE in your applications. It works step-by-step,starting with the basic concepts to facilitate the learning process and then builds ontop of these to reach the most complex concepts. A concept that is being explainedat one level, will not be re-explained at a subsequent level. Developers will be able touse these building blocks to integrate them in their own applications, according totheir needs.

Getting Started

All the code examples included in this book have been implemented using JXSE version 2.6.These are available from www.practicaljxta.com.

Creating A Project

We use NetBeans 6.8 to describe our code examples53. The following procedure explains how tocreate an initial project using the JXTA libraries:

i) Create a Java application project from the File> New Project menu. Check the Use Dedic-ated Folder for Storing Libraries flag and setthe Library folder to '.\lib'.

ii) Download the jxse-2.6.jar and lib-dependen-cies-2.6.zip libraries from http://jxse.kenai.-com/Downloads/Downloads.html. Put thejxse-2.6.jar and unzip the dependencies in the/lib directory of your project.

iii) Add the followings .jar in the libraries section:jxse-2.6.jar, bcprov-jdk15-145.jar,

derby-10.5.1.1.jar, felix.jar, h2-

1.2.127.jar, javax.servlet.jar, or-

g.mortbay.jar.jetty.jar, netty-

3.1.5.GA.jar.

53 See http://netbeans.org/downloads/index.html for download.

Using JXSE Getting Started - 153

You are now ready to implement the code examples.

Maven

JXSE 2.6 will soon be available from Maven via Sonatype54. Check for the latest information onhttp://jxse.kenai.com.

Javadoc

You can download the javadoc (jxse-2.6.-javadoc.zip) and add it to NetBeans by:

1. Selecting Tools > Java Platform.

2. Selecting the Javadoc tab.

3. Click Add Zip/Folder and select the downloaded zip file.

First Connection & Local Configuration

Example 100 - Starting And Stopping JXTA

The following code example describes the simplest way to start the JXTA network:

...

public class _100_Starting_And_Stopping_JXTA_Example {

public static final String Name = "Example 100";

public static void main(String[] args) {

try {

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.EDGE,

Name);

// Starting JXTA

Tools.PopInformationMessage(Name, "Starting JXTA network");

PeerGroup ConnectedVia = MyNetworkManager.startNetwork();

// Diplaying peer group information

Tools.PopInformationMessage(Name, "Connected via Peer Group: "

+ ConnectedVia.getPeerGroupName());

// Stopping JXTA

Tools.PopInformationMessage(Name, "Stopping JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

54 http://nexus.sonatype.org/oss-repository-hosting.html

Using JXSE First Connection & Local Configuration - 154

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

...

Example 100 – Starting and stopping JXTA

1. The first step is to create the network manager by specifying a configuration mode and aninstance name. We have selected the EDGE mode.

This version of the constructor will, by default, create a /.jxta directory in the current

working directory ($CWD) to store a local configuration. This may trigger an IOExcep-

tion if the local directory cannot be accessed.

If you do not want the network manager to create a local configuration by default, you canuse its setConfigPersistent(false) method to prevent this.

2. Secondly, we start the JXTA network by invoking the startNetwork() method from the

network manager we have just created. We will exist as a new peer on the network with anew peer ID, but we will not necessarily be able to connect to other peers, unless otherpeers can be reached on the LAN with IP multicasting.

By default, the network manager uses the net peer group as the reference group to startJXTA. It may throw a PeerGroupException if this group fails to initialize.

3. At last, we stop the JXTA network by invoking the stopNetwork() method from the net-

work manager.

The example calls the static PopInformationMessage(...) method from the Tools object.

This object has been created as part of the code examples contained in this chapter to offer basicfunctionalities necessary to run these code examples.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You are a random tribe which appeared on an island. You have elected a newruler who created his box of dried leaves. There is a very high probability that no one has noticedyour arrival, since you have not made contact with other tribes. Right after you appeared, youhave almost immediately decided to hide in a big cave in the mountains after storing your box ofdried leaves in its default location for later usage.

If you used the setConfigPersistent(false) method, you are an ephemeral new tribe who

has elected a new ruler. You have created a temporary box of dried leaves. However, you have

Using JXSE First Connection & Local Configuration - 155

decided to disappear soon after you arrived on the island. The tribe has been dismantled togetherwith the box of dried leaves. There is a high probability that no one has noticed your tribe's exist-ence at all.

Example 110 – Creating A Local Configuration

The following code example describes a simple way to create a local configuration for JXTA andto save it:

...

public class _110_Creating_A_Local_Configuration_Example {

public static final String Name = "Example 110";

public static void main(String[] args) {

try {

// Preparing the configuration storage location

String LocalPath = "." + System.getProperty("file.separator") + "MyPath";

File ConfigurationFile = new File(LocalPath);

// Removing any existing configuration

Tools.PopInformationMessage(Name, "Removing any existing local configuration");

NetworkManager.RecursiveDelete(ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name,

ConfigurationFile.toURI());

// Setting the peer name

Tools.PopInformationMessage(Name, "Setting the peer name");

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

MyNetworkConfigurator.setName(Name, "My peer name");

// Saving configuration

Tools.PopInformationMessage(Name, "Saving the local configuration in:\n\n"

+ ConfigurationFile.getCanonicalPath());

MyNetworkConfigurator.save();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

...

Example 110 - Creating a local configuration

1. We prepare a directory location for our local configuration. The above example points at adirectory called “MyPath” created in the current working directory.

2. Next, we use another constructor for the network manager and specify the location of the

Using JXSE First Connection & Local Configuration - 156

local configuration. If no configuration file can be found at that location, the network man-ager will create a new file called PlatformConfig.

3. We then retrieve the network configurator from the network manager.

4. We set the peer instance name in the network configurator.

5. We save our configuration.

The directory where the local configuration has been saved will contain a file called Platform-

Config. If we check its content, it will contain the name of our peer and the peer ID created auto-

matically:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE jxta:CP>

<jxta:CP type="jxta:PlatformConfig" xmlns:jxta="http://jxta.org">

<PID>

urn:jxta:uuid-

59616261646162614E504720503250337644372E0A464012AFE3EF0726DD904003

</PID>

<Name>

My peer name

</Name>

<Desc>

Created by NetworkManager

</Desc>

...

</jxta:CP>

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have decided to create a special box of dried leaves with special decorationand put your name on it. You have also created a specific storage location for that box on your is-land.

Example 120 – Retrieving, Modifying & Saving A Local Configuration

The following code example describes a simple way to retrieve a local configuration, to modify itand to save it.

...

public class _120_Retrieving_Modifying_And_Saving_An_Existing_Configuration_Example {

public static final String Name = "Example 120";

public static void main(String[] args) {

try {

// Preparing the configuration storage location

String LocalPath = "." + System.getProperty("file.separator") + "MyPath";

File ConfigurationFile = new File(LocalPath);

// Creation of the network manager

Using JXSE First Connection & Local Configuration - 157

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.EDGE,

Name,

ConfigurationFile.toURI());

// Checking for configuration existence

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

if (MyNetworkConfigurator.exists()) {

// Found existing configuration

Tools.PopInformationMessage(Name, "Found existing configuration");

} else {

// No configuration found

Tools.PopInformationMessage(Name, "No configuration found at:\n\n"

+ ConfigurationFile.getCanonicalPath());

}

// Modifying new name

String NewName = "My new name @ " + System.currentTimeMillis();

Tools.PopInformationMessage(Name, "Setting new name to: " + NewName);

MyNetworkConfigurator.setName(NewName);

// Saving modifications

Tools.PopInformationMessage(Name, "Saving configuration at:\n\n"

+ ConfigurationFile.getCanonicalPath());

MyNetworkConfigurator.save();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

...

Example 120 – Retrieving, modifying and saving a local configuration

1. First, we prepare the network manager by specifying the location of our local configura-tion. Then, we retrieve the network configurator.

2. Next, we check whether a local configuration exists at the specified location and display amessage.

3. We modify the name of the peer, and save the local configuration.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You and your tribe were hiding in a big cave in the mountain and you decided tocome out and to retrieve your box of dried leaves. If you can find it again, you will redo some of itsdecoration and change the name of it, else you automatically create a new one and set your newname. At last, you store back the box of dried leaves to its location.

Using JXSE First Connection & Local Configuration - 158

Miscellaneous

Understanding ConfigParam

ConfigParam is an advertisement containing a set of configuration parameters for a peer. It is

saved within the PlatformConfig file in the local configuration directory. If you open one with a

text editor, you will notice that it contains several advertisements describing all aspects of the de-sired behavior of a peer.

Technically speaking, the ConfigParam object, which contains the configuration of a peer, is

passed to the net peer group, which is then passed to the world peer group when the startNet-

work() method is called for the first time in the NetworkManager.

Some readers will complain that they would like to be able to provide a ConfigParam object for

each instance of PeerGroup objects they may create by invoking the newGroup() method from

those same PeerGroup objects. This is not possible for now, although a solution is being studied

for a future version of JXSE.

Modifying Other Configuration Parameters

The NetworkConfigurator object contains many methods to modify the default configuration

of JXSE peers (IP addresses, port ranges, multicast port, peer ID, etc...). Developers should usethese methods before starting the JXTA network. If a peer has already started the JXTA networkand needs to modify its configuration, it should first stop the JXTA network, perform configurationmodifications and restart the network.

Loading A Configuration From A URI

Some developers will want to load the configuration of a peer from a remote location. This can bedone with the load(URI uri) method of the NetworkConfigurator object. This can be very

useful for devices with low capacities.

Automatic Change Of IP Addresses

Some platforms support the automatic modification of IP addresses of devices on-the-fly. Unfortu-nately, there is no way to detect such events automatically in Java for now. If this should happenwhile the JXTA network has been started, this can cause unpredictable behavior. The JXTA net-work should be restarted.

Using JXSE First Connection & Local Configuration - 159

A workaround to this situation is to check the local host address from time to time with the staticmethod InetAddress.getLocalHost() and restart the JXTA network when necessary. The

NetworkManager offer a methods to check whether the JXTA network has been started.

Local Configuration Directory Structure

Typically, the local configuration directory structure of a peer contains a /cm directory. This direct-

ory will contain other directories whose names correspond to peer group IDs. These directorieswill contain two types of files: *.idx (index files) and *.tbl (table files). The later contain miscel-

laneous types of entries, such as advertisement published by the peer or obtained from otherpeers. The index files contain information about the content of table files.

New Configuration Objects & Connecting With OSGi

Release 2.6 comes with a new way of connecting to the JXTA network and of creating, using andsaving configurations.

Example 150 - Configuration Objects

The following code example describes how to create, save and load configuration objects:

...

public static final String Name = "Example 150";

public static void main(String[] args) {

try {

// Creating a default configuration object

JxsePeerConfiguration MyConfig = new JxsePeerConfiguration();

JxseHttpTransportConfiguration MyHttpConfig = MyConfig.getHttpTransportConfiguration();

JxseTcpTransportConfiguration MyTcpConfig = MyConfig.getTcpTransportConfiguration();

// Setting some configuration information

MyConfig.setPeerInstanceName("Config Object Test");

MyHttpConfig.setHttpIncoming(true);

MyTcpConfig.setTcpIncoming(true);

// DON'T FORGET TO SET BACK THE TRANSPORT CONFIGURATION

MyConfig.setHttpTransportConfiguration(MyHttpConfig);

MyConfig.setTcpTransportConfiguration(MyTcpConfig);

// Saving the configuration

ByteArrayOutputStream BAOS = new ByteArrayOutputStream();

MyConfig.storeToXML(BAOS, "My saving");

System.out.println(BAOS.toString());

// Reading the configuration

ByteArrayInputStream BAIS = new ByteArrayInputStream(BAOS.toByteArray());

JxsePeerConfiguration MyReadConfig = new JxsePeerConfiguration();

MyReadConfig.loadFromXML(BAIS);

// Checking

Tools.PopInformationMessage(Name, "The configuration name is: "

+ MyReadConfig.getPeerInstanceName());

Using JXSE New Configuration Objects & Connecting With OSGi - 160

JxseHttpTransportConfiguration MyReadHttpConfig =

MyReadConfig.getHttpTransportConfiguration();

JxseTcpTransportConfiguration MyReadTcpConfig =

MyReadConfig.getTcpTransportConfiguration();

Tools.PopInformationMessage(Name, "HTTP Incoming is: "

+ Boolean.valueOf(MyReadHttpConfig.getHttpIncoming()));

Tools.PopInformationMessage(Name, "TCP Incoming is: "

+ Boolean.valueOf(MyReadTcpConfig.getTcpIncoming()));

} catch (IOException ex) {

// Unexpected error

Tools.PopErrorMessage(Name, ex.toString());

}

}

...

Example 150 – Creating, saving & loading JXSE configuration

1. We start by creating a JXSE configuration object. These contain sub-objects to configuretransport layers.

2. In this example, we retrieve a copy the TCP and HTTP configuration objects and setsome values. We then set them back in the JXSE configuration object.

3. Next, we save the configuration into a byte array, but one would use a real file in a realapplication.

4. Then, we load that configuration again in a new JXSE configuration object.

5. We display the configured values.

Example 160 – Connecting with OSGi

The following code example describes how to start the JXTA network using the OSGi framework:

...

public static final String Name = "Example 160";

// The NetworkManager service instance

private static JxseOSGiNetworkManagerService TheNMS;

// The OSGi service tracker for the NetworkManager Service

private static ServiceTracker ST;

public static void main(String[] args) {

try {

// Starting the OSGi framework (Felix)

JxseOSGiFramework.INSTANCE.start();

// Retrieving the NetworkManager service

ST = JxseOSGiFramework.getServiceTracker(JxseOSGiNetworkManagerService.class);

// Starting to track the service

Using JXSE New Configuration Objects & Connecting With OSGi - 161

ST.open();

// Retrieving the NetworkManager service for at most 5 seconds

TheNMS = (JxseOSGiNetworkManagerService) ST.waitForService(5000);

if (TheNMS==null) {

Tools.PopErrorMessage(Name, "Could not retrieve the NetworkManager "

+ "service within 5 seconds");

System.exit(-1);

}

// Creating a peer configuration

JxsePeerConfiguration MyConfig = new JxsePeerConfiguration();

MyConfig.setConnectionMode(ConnectionMode.ADHOC);

MyConfig.setPeerID(IDFactory.newPeerID(PeerGroupID.worldPeerGroupID));

MyConfig.setPeerInstanceName("Poupoudipou");

// Setting the configuration in the NetworkManager OSGi service

TheNMS.setPeerConfiguration(MyConfig);

// Retrieving a configured network manager

NetworkManager MyNM = TheNMS.getConfiguredNetworkManager();

// Starting and stopping the network

MyNM.startNetwork();

MyNM.stopNetwork();

// Stopping the service tracking

ST.close();

TheNMS = null;

// Stopping the OSGI framework

JxseOSGiFramework.INSTANCE.stop();

// Waiting for stop for maximum 20 seconds

FrameworkEvent FE = JxseOSGiFramework.INSTANCE.waitForStop(20000);

// Checking whether we stopped properly

if ( FE.getType() != FrameworkEvent.STOPPED ) {

Tools.PopErrorMessage(Name,

"OSGi framework failed to stop after 20 seconds, event type: " + FE.getType() );

}

} catch (PeerGroupException ex) {

Tools.PopErrorMessage(Name, ex.toString());

} catch (JxtaConfigurationException ex) {

Tools.PopErrorMessage(Name, ex.toString());

} catch (InterruptedException ex) {

Tools.PopErrorMessage(Name, ex.toString());

} catch (BundleException ex) {

Tools.PopErrorMessage(Name, ex.toString());

} catch (IOException ex) {

Tools.PopErrorMessage(Name, ex.toString());

} catch (Exception ex) {

Tools.PopErrorMessage(Name, ex.toString());

}

}

...

Example 160 – Starting the JXTA Network with OSGi

Using JXSE New Configuration Objects & Connecting With OSGi - 162

1. We begin by starting the OSGi framework55.

2. Next, we retrieve the OSGi NetworkManager service via an OSGI service tracker, waitingfor at most 5 seconds.

3. Then, we create a JXSE peer configuration and set it in the NetworkManager service.

4. Next, we retrieve a configured NetworkManager object instance.

5. We start and stop the JXTA network.

6. At last, we stop the service tracker and the OSGi framework.

Exploring Connectivity Issues

Creating & Using Seeds

As mentioned previously, seeds are means by which pockets of peers get to communicate witheach other outside the LAN or when TCP communication is not enabled. The NetworkConfig-

urator offers several methods to set-up RDV seeds:

• addRdvSeedingURI(URI seedURI) – With this method, one can set a URI location

from which a list of rendezvous seeds is read every 30 minutes.

• addRdvSeedingURI(String seedURIStr) – This method is identical to the previous

one, but the URI is provided as a string.

• addSeedRendezvous(URI seedURI) – With this method, one can provide a physical

endpoint location of a rendezvous peer. Contrary to the above methods, no list of rendez-vous seed is read from it. Edge peers try to connect to a rendezvous via this endpoint.

• setRendezvousSeedingURIs(List<String> seedingURIs) – This method can be

used to set a group of URI locations (as strings) from which seeds will be read, with a 30minutes refresh.

• setRendezvousSeeds(Set<String> seeds) – This method can be used to set a

group of physical endpoint locations to which edge peers will try to connect to.

• clearRendezvousSeedingURIs() – This method removes all registered seeding URIs

from which sets of seeds are read.

• clearRendezvousSeeds() – This method removes all registered physical endpoint55 By default, JXSE release 2.6 uses the Apache Felix OSGI framework (see http://felix.apache.org/site/index.html). However, the

delivered JXSE .jar contains proper bundle configuration properties to be started from another OSGi framework implementation.

Using JXSE Exploring Connectivity Issues - 163

seeds.

The NetworkConfigurator offers corresponding methods for relay seeds.

The following code describes how to create seeds and to set them in the NetworkConfigurat-

or:

...

public static final String Name = "Creating and setting seeds";

public static final File ConfigurationFile = new File("."

+ System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Jack should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

// Creating an endpoint seed and setting it

URI TheSeed = URI.create("tcp://33.44.55.66:9202");

MyNetworkConfigurator.addSeedRendezvous(TheSeed);

// Creating a document read by seeding URIs

XMLDocument MyDoc = (XMLDocument)StructuredDocumentFactory.newStructuredDocument(

MimeMediaType.XML_DEFAULTENCODING, "jxta:seeds");

MyDoc.addAttribute("ordered", "false");

MyDoc.addAttribute("xmlns:jxta", "http://www.jxta.org");

// First seed

RouteAdvertisement MyRouteAdv = (RouteAdvertisement)

AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

PeerID MyRDV = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

"My first RDV".getBytes());

AccessPointAdvertisement MyAPA = (AccessPointAdvertisement)

AdvertisementFactory.newAdvertisement(

AccessPointAdvertisement.getAdvertisementType());

MyAPA.addEndpointAddress(new EndpointAddress("tcp://18.22.1.69:3333"));

MyRouteAdv.setDestPeerID(MyRDV);

MyRouteAdv.setDest(MyAPA);

XMLDocument MyRouteAdvDoc = (XMLDocument) MyRouteAdv.getDocument(MimeMediaType.XMLUTF8);

Tools.copyElements(MyDoc, MyDoc.getRoot(), MyRouteAdvDoc.getRoot(), true, false);

// Second seed

RouteAdvertisement MyRouteAdv2 = (RouteAdvertisement)

AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

PeerID MyRDV2 = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

"My second RDV".getBytes());

AccessPointAdvertisement MyAPA2 = (AccessPointAdvertisement)

AdvertisementFactory.newAdvertisement(

AccessPointAdvertisement.getAdvertisementType());

MyAPA2.addEndpointAddress(new EndpointAddress("tcp://171.17.22.4:2876"));

MyRouteAdv2.setDestPeerID(MyRDV2);

MyRouteAdv2.setDest(MyAPA2);

XMLDocument MyRouteAdvDoc2 = (XMLDocument) MyRouteAdv2.getDocument(

MimeMediaType.APPLICATION_XML_DEFAULTENCODING);

Using JXSE Exploring Connectivity Issues - 164

Tools.copyElements(MyDoc, MyDoc.getRoot(), MyRouteAdvDoc2.getRoot(), true, false);

// Third seed

RouteAdvertisement MyRouteAdv3 = (RouteAdvertisement)

AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

PeerID MyRDV3 = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

"My third RDV".getBytes());

AccessPointAdvertisement MyAPA3 = (AccessPointAdvertisement)

AdvertisementFactory.newAdvertisement(

AccessPointAdvertisement.getAdvertisementType());

MyAPA3.addEndpointAddress(new EndpointAddress("tcp://240.28.16.57:4210"));

MyRouteAdv3.setDestPeerID(MyRDV3);

MyRouteAdv3.setDest(MyAPA3);

XMLDocument MyRouteAdvDoc3 = (XMLDocument)

MyRouteAdv3.getDocument(MimeMediaType.XMLUTF8);

Tools.copyElements(MyDoc, MyDoc.getRoot(), MyRouteAdvDoc3.getRoot(), true, false);

// Printing the result

MyDoc.sendToStream(System.out);

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

}

...

Example – Creating & Setting Seeds

1. We start be retrieving a NetworkConfigurator from a NetworkManager and remove

any existing rendezvous seeds.

2. Then, we craft an endpoint seed and add it in the NetworkConfigurator.

3. Next, we create a document containing seed route advertisements. This is the type ofseed documents (located by an URI) which is read periodically by peers.

Remark:Remark:Remark:Remark: We do not add it directly to the NetworkConfigurator. In a real application,

this document would typically be posted on the web and accessed by peers.

The created seed document looks like this:

<?xml version="1.0"?>

<!DOCTYPE jxta:seeds>

<jxta:seeds xmlns:jxta="http://www.jxta.org" ordered="false">

<jxta:RA>

<DstPID>

urn:jxta:uuid-59616261646162614E504720503250334D79206669724374A052C45603

</DstPID>

<Dst>

<jxta:APA>

<EA>

tcp://18.22.1.69:3333

</EA>

</jxta:APA>

</Dst>

</jxta:RA>

<jxta:RA>

<DstPID>

urn:jxta:uuid-59616261646162614E504720503250334D79207365634F6EA420D2445603

Using JXSE Exploring Connectivity Issues - 165

</DstPID>

<Dst>

<jxta:APA>

<EA>

tcp://171.17.22.4:2876

</EA>

</jxta:APA>

</Dst>

</jxta:RA>

<jxta:RA>

<DstPID>

urn:jxta:uuid-59616261646162614E504720503250334D79207468694264A052C45603

</DstPID>

<Dst>

<jxta:APA>

<EA>

tcp://240.28.16.57:4210

</EA>

</jxta:APA>

</Dst>

</jxta:RA>

</jxta:seeds>

A similar document can be created for relay seeds.

About The Default JXTA Seeds

In the previous edition of this book, we described the way to set 'default seed' in order to connectto a rendezvous. Unfortunately, the default seed peers have not been maintained by the com-munity and are not reachable anymore. Thus, this example does not work anymore and has notbeen included here.

Consequently the http://rdv.jxtahosts.net/cgi-bin/rendezvous.cgi?3 andhttp://rdv.jxtahosts.net/cgi-bin/rendezvous.cgi?2 URLs are not valid anymore.

Running Multiple Peers On A Single Device

It is possible to simultaneously run several applications using JXSE (i.e., peers) on the samedevice and to have them connect to each other when configured properly. Since most readers donot necessarily have several PCs connected together to explore JXTA and JXSE features, we aregoing to use this technique to let them run the examples describing the features of JXTA on asingle PC (or device).

Multiple Peer In The Same JVM

It is not possible to run multiple peers in the same JVM, unless one starts peers with separateClassLoaders. This will probably change in future releases as the OSGi integration progresses.

Using JXSE Exploring Connectivity Issues - 166

The Proper Angle To Strike A Match

One of the key issues new comers to JXTA face is getting their peers to connect to each otherproperly. This can be a frustrating experience. Quite often, many try several combinations until itworks, but they do not really get to understand why it works. Later, what they have tried may notwork anymore and they don't understand why. They may also experience that what works on theirLAN does not seem to work that well beyond their LAN.

We are going to explore these issues with two peers called Jack the Rendezvous and Anna theEdge on the same PC. Each time the reader starts any of these peers, he or she will have the op-portunity to erase any existing configuration on those peers. The reader is free to run those ex-amples from NetBeans for example, or to compile the code for each peer and run these in separ-ately.

Jack, The Rendezvous

The following is the code used for Jack the rendezvous peer:

...

public class RendezVous_Jack {

public static final String Name = "RendezVous Jack";

public static final int TcpPort = 9710;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Check for removal of any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

MyNetworkConfigurator.setUseMulticast(false);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Waiting for rendezvous connection

Using JXSE Exploring Connectivity Issues - 167

Tools.PopInformationMessage(Name, "Waiting for other peers to connect");

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Jack The Rendezvous

Here is what Jack is doing:

1. We create a context by:

a) Defining the name of the peer: “RendezVous Jack”

b) Setting a unique port: 9710 (Anna will use another one to avoid conflicts)

c) Defining a unique peer ID

d) Defining a unique location for saving the configuration of Jack.

2. When Jack is started, we ask the user whether any existing configuration should be de-leted. This is an opportunity to start from scratch.

3. We create the NetworkManager and set the configuration mode to RENDEZVOUS, to-

gether with the location for saving the local configuration.

4. We retrieve the NetworkConfigurator and make sure TCP communication is enabled

properly. We also set the port to be used and the peer ID of Jack.

5. We wait for the user to start the JXTA network.

6. We wait for Anna to connect to Jack the RendezVous. This gives the user time to startAnna.

7. We check for peers connected to Jack and display the list of them. If none are connected,we display a corresponding message.

Using JXSE Exploring Connectivity Issues - 168

8. We wait for the user to stop the JXTA network.

Anna, The Edge

The following is the code used for Anna the edge peer:

...

public class Edge_Anna {

public static final String Name = "Edge Anna";

public static final int TcpPort = 9712;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Jack should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":" +

RendezVous_Jack.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

MyNetworkConfigurator.setUseMulticast(false);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network and to wait for a rendezvous”

+ “\nconnection with " + RendezVous_Jack.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connected to a rendezvous");

}

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Using JXSE Exploring Connectivity Issues - 169

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Anna The Edge

Here is what Anna is doing:

1. We create a context by:

a) Defining the name of the peer: “Edge Anna”

b) Setting a unique port: 9712 (different than the port of Jack 9710)

c) Defining a unique peer ID

d) Defining a unique location for saving the configuration of Anna.

2. When Anna is started, we ask the user whether any existing configuration should be de-leted. This is an opportunity to start from scratch.

3. We create the NetworkManager and set the configuration mode to EDGE, together with

the location for saving the local configuration.

4. We retrieve the NetworkConfigurator and set Jack as a rendezvous seed.

5. We also make sure TCP communication is enabled properly. We set the port to be usedby Anna and ask the peer ID of Anna.

6. We wait for the user to start the JXTA network and to wait for a connection with Jack formaximum 2 minutes.

7. Right after the JXTA network is started, we make sure that Anna never becomes a ren-dezvous spontaneously.

8. If a connection is established, we display the peer ID of the peer Anna is connected to,else we display a message indicating that no connection could be established.

9. We wait for the user to stop the JXTA network.

Using JXSE Exploring Connectivity Issues - 170

Testing Angles Between Jack And Anna

In the previous edition of this book, the examples contained a bug when it came to setting seedswhen running multiple peers on the same device. The addRdvSeedingURI(URI seedURI)

method was used instead of addSeedRendezvous(URI seedURI).

A conclusion was made that running multiple peers on the same device required multicasting. Thisis false.

Angle I - Start Jack, Then Anna, Delete Configuration & Approve Seed

The first angle we are going to explore to establish a connection between Jack and Anna is thefollowing:

1. Start Jack.

2. Approve deletion of any existing configuration.

3. Start the JXTA network for Jack.

4. When the screen indicating that RendezVous Jackis waiting for peers to connect is displayed, do notclick on OK.

5. Start Anna.

6. Approve deletion of any existing configuration.

7. Approve the addition of Jack as a seed.

8. Start the JXTA network for Anna and wait for a connection to a rendezvous.

9. After about a coupleof seconds, youshould get a messageindicating that Annahas managed to con-nect to a rendezvous. The displayed peer ID should be the one of Jack. Click on OK.

10. Go back to Jack and click on the OK button to finish waiting for Anna to connect.

11. Jack is displaying the peer ID of connected peers, that is, Anna (only). Click on OK

Using JXSE Exploring Connectivity Issues - 171

12. Stop the JXTA network forJack.

13. Stop the JXTA network forAnna.

We have managed to establish a connection between two peers, one being a rendezvous and theother being an edge. If the reader observes the content of the directories containing the configura-tion and the set of JXTA operational data registered by both peers, he or she will notice that it ismore developed for Jack.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have established two tribes on a single island. None has created its box ofdried leaves yet. They cannot get access to each other by land, since they are separated by insur-mountable mountains. The only possibility to make a connection is to navigate from one side ofthe island to the other. The tribe ruled by Anna has heard about the other tribe ruled by Jack, butJack does not know about Anna.

The Anna tribe decides to go on a quest for the Jack tribe and manages to find them. The Jacktribe now knows about the Anna tribe. They have both created their own box of dried leave and re-gistered the route to navigate to each other. They have also kept a description of each other onsome other dried leaves. In these descriptions, the Anna tribe remembers that the Jack tribe iscapable of propagating messages to other tribes on her behalf in the future.

The end of the day has come and both the Jack and the Anna tribe have decided to go hide intheir respective caves in the mountains. They will not be accessible by other tribes until they de-cide to come out again.

Angle II - Start Anna, Then Jack, Delete Configuration & Approve Seed

This angle is exactly the same as angle I, except that the JXTA network of Anna is started beforethe JXTA network of Jack. In this case, Anna will not be able to make a connection to Jack, untilJack is started:

1. When the screen indicating that RendezVous Jack is waiting for peers to connect is dis-played, do not click OK.

2. Start Anna.

3. Approve the deletion of any existing configuration.

4. Approve the addition of Jack as a seed.

Using JXSE Exploring Connectivity Issues - 172

5. Start the JXTA network for Jack and the wait for a connection to a rendezvous.

6. After about less than 10 seconds, you should get a message indicating that Anna hasmanaged to connect to rendezvous Jack. Click on OK.

14. Go back to Jack and click on the OK button to finish the wait for Anna to connect.

15. Jack is displaying the peer ID of connected peers, that is, Anna (only). Click on OK

16. Stop the JXTA network for Jack.

17. Stop the JXTA network for Anna.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: After the Anna tribe has managed to meet the Jack tribe, both tribes went intotheir respective caves. After some time, both tribes decide to come out of their caves again. TheAnna tribe tries to establish contact with the Jack tribe again, but this time, she has to wait untilJack comes out of his cave.

Angle III - Start Jack, Then Anna, Keep Configuration & Disapprove Seed

In this angle Jack is not set as a seed for Anna. In this case, Anna will not be able to connect withJack regardless of the information she has managed to collect from the first encounter.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: After the Anna tribe has managed to meet the Jack tribe, both tribes went intotheir respective caves. After some time, both tribes decide to come out of their caves again. TheAnna tribe tries to establish contact with the Jack tribe again, but she forgot to tell her people torecontact the Jack tribe. They get lost at sea not knowing their destination. After some time, bothtribes go back into their respective caves.

Remarks & Warning

• If one enables multicasting only on Anna & Jack, and set Jack as a seed of for Anna,Anne will be able to establish an EDGE – RENDEZVOUS connection, but this does notmake sense, since peers can already communicate using multicasting.

• The rendezvous service of every peer has a method called setAutoStart(boolean

auto, long period) which can be used to have a peer reconsider its role on the net-

work at periodic times. It means that an edge peer can dynamically become a rendezvousfor its peer group and vice-versa.

This is a very interesting feature that can help peers maintain connections together even ifall rendezvous seeds are down or if, for example, a set of peers on a LAN have lost ac-

Using JXSE Exploring Connectivity Issues - 173

cess to the Internet because of server failure, or if a major cable between countries orcontinents has been broken.

Although the capacity of the JXTA network to establish connections is reduced because ofphysical constraints beyond its control, pockets of peers will still be able to operate untilthe connectivity issues have been solved.

Typically, a peer should be able to establish connections with other peers in less than aminute if it has already established connections with other peers in the past. If this peer isfacing challenging artificial network boundaries conditions, this can take up to a couple ofminutes. Beyond, this limit (and assuming that the peer has been configured properly),one can reasonably consider that there is a bigger connectivity issue. A reasonable valuefor the period parameter is 4 or 5 minutes, although other values can be tested. Values

less than 2 minutes are not recommended.

• The NetworkConfigurator object has a method called setUseOnlyRendezvous-

Seeds(...) which can be used to force peers to use only provided rendezvous seeds.

Unless there is a really good reason for using this, one should avoid imposing this restric-tion and let peers also connect to rendezvous of their peer groups which are not part ofthe list of known rendezvous seeds. This will increase their capacity to establish connec-tions with other peers of their peer group.

• When several peers are operating on a LAN, but multicasting is not enabled betweenthem, one of them must act as a rendezvous to enable connectivity between them.

Aminah, The Other RendezVous

We are now introducing new peers to explore rendezvous connectivity a little more. The followingis the code used for Aminah, another rendezvous peer:

...

public class RendezVous_Aminah {

public static final String Name = "RendezVous Aminah";

public static final int TcpPort = 9713;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Check for removal of any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

Using JXSE Exploring Connectivity Issues - 174

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

MyNetworkConfigurator.setUseMulticast(false);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Waiting for rendezvous connection

Tools.PopInformationMessage(Name, "Waiting for " + Edge_Anna.Name

+ " to connect to " + RendezVous_Jack.Name);

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Aminah the Other Rendezvous

Aminah is doing exactly the same thing as Jack, except that she is using another unique port(9713).

Chihiro, The Other Edge

The following is the code used for Chihiro, another edge peer:

...

public class Edge_Chihiro {

public static final String Name = "Edge Chihiro";

public static final int TcpPort = 9715;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

Using JXSE Exploring Connectivity Issues - 175

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Adding Jack and Aminah as RendezVous seeds

MyNetworkConfigurator.clearRendezvousSeeds();

String TheJackSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress()

+ ":" + RendezVous_Jack.TcpPort;

URI LocalSeedingRendezVousURI = URI.create(TheJackSeed);

MyNetworkConfigurator.addSeedRendezvous(LocalSeedingRendezVousURI);

String TheAminahSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress()

+ ":" + RendezVous_Aminah.TcpPort;

URI LocalSeedingRendezVousURI2 = URI.create(TheAminahSeed);

MyNetworkConfigurator.addSeedRendezvous(LocalSeedingRendezVousURI2);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

MyNetworkConfigurator.setUseMulticast(false);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network and wait for a\n"

+ "rendezvous connection for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connected to a rendezvous");

}

// Waiting for Jack to shutdown

Tools.PopInformationMessage(Name, "Waiting for rendezvous to shut down");

// Challenging existence of rendezvous

Tools.PopInformationMessage(Name, "Waiting for cache to refresh for 30 seconds");

// Going to sleep for some time

Tools.GoToSleep(30000);

// Waiting for rendezvous connection again

Tools.PopInformationMessage(Name, "Waiting for rendezvous connection again");

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Using JXSE Exploring Connectivity Issues - 176

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Chihiro the Other Edge

Chihiro is an edge peer like Anna, but she is doing something a little different than Anna:

1. We create a context by:

a) Defining the name of the peer: “Edge Chihiro”

b) Setting a unique port: 9715

c) Defining a unique peer ID

d) Defining a unique location for saving the configuration of Chihiro.

2. When Chihiro is started, we ask the user whether any existing configuration should be de-leted. This is an opportunity to start from scratch.

3. We create the NetworkManager and set the configuration mode to EDGE, together with

the location for saving the local configuration.

4. We retrieve the NetworkConfigurator and set Jack and Aminah as a rendezvous

seeds.

5. We also make sure TCP communication is enabled properly. We set the port to be usedby Chihiro and her peer ID.

6. We wait for the user to start the JXTA network and to wait for a connection with a rendez-vous for maximum 2 minutes.

7. Right after the JXTA network is started, we make sure that Chihiro never becomes a ren-dezvous spontaneously.

Using JXSE Exploring Connectivity Issues - 177

8. If a connection is established, we display the peer ID of the peer Chihiro is connected to,else we display a message indicating that no connection could be established.

9. Next, we offer an opportunity to wait until one of the rendezvous peer is shutdown.

10. We wait for 60 seconds to let the cache list of rendezvous peers Chihiro is connected torefresh.

11. We wait a second time for a connection to a rendezvous peer.

12. We display the connected rendezvous peers if any.

13. We shut down the network for Chihiro.

Automatic Reconnection To Other RendezVous

The following procedure describes how an edge peer can automatically connect and reconnect torendezvous when these go down. We will use Jack the rendezvous, Aminah the other rendezvousand Chihiro the other edge.

1. Start Jack.

2. Approve deletion of any existing configuration.

3. Start the JXTA network for Jack.

4. When the screen indicating that RendezVous Jack is waiting for peers to connect is dis-played, do not click on OK.

5. Start Aminah.

6. Approve deletion of any existing configuration.

7. Start the JXTA network for Aminah.

8. When the screen indicating that RendezVous Aminah is waiting for peers to connect isdisplayed, do not click on OK.

9. Start Chihiro.

10. Approve deletion of any existing configuration.

11. Start the JXTA network and then wait for a rendezvous connection for Chihiro.

12. When Chihiro manages to connect to a rendezvous, write down the peer ID (...36B03 =

Jack, ...E6103 = Aminah).

Using JXSE Exploring Connectivity Issues - 178

13. Press the OK button of the 'waiting for peers to connect' of the rendezvous to which Chi-hiro is connected.

14. The corresponding rendezvous displays the peer connected to it (i.e., Chihiro). Click OK.

15. Stop the JXTA network for that rendezvous peer.

16. Go back to back to Chihiro and click OK of the windows indicating that she is waiting forthe shutdown of the rendezvous peer.

17. A window indicating that Chihiro is going to wait for 60 seconds to let the cache list of con-nected peers refresh is displayed. Click OK.

18. After 60 seconds, Chihiro displays another window indicating that she is ready to wait foranother rendezvous connection again. Click OK.

19. Relatively quickly, Chihiro indicates that she is now connected to the other rendezvousstill running. Click OK and shut down the JXTA network for her.

20. Back to the remaining rendezvous peer, click on OK on the screen indicating that the ren-dezvous is waiting for peers to connect.

21. The remaining rendezvous indicates that Chihiro is now connected to it.

22. Click OK and shut down the JXTA network for the remaining peer.

We can notice that with a bit of patience Chihiro, who was connected to one of its seed rendez-vous, has managed to reconnect to another rendezvous seed when her initial rendezvous wentdown. This is performed automatically by JXSE. Edge peers try to maintain contact with at leastand at most one rendezvous peer over time. They check their rendezvous connections every 15seconds56.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: The Jack tribe, the Aminah tribe and the Chihiro tribe are all living on the same bigisland, but they cannot establish contact with each other by land because of insurmountablemountains. Chihiro has heard about the Jack and the Aminah tribes. She establishes contact withone of them, but after some time, that tribe decides to go hide in its cave. Since Chihiro does notwant to be alone, she automatically establishes contact with the third tribe.

Connectivity Manager

This book revision contains a new example explaining how to implement a connectivity manager.

56 Unfortunately, unexpected loss of connections are not always detected and handled 'quickly' by JXSE. This a know issue. Solving itrequires much refactoring in core code. This could not be accomplished for release 2.6 and has been postponed to a further release.

Using JXSE Exploring Connectivity Issues - 179

It is made of 5 java classes, but we will not include all code here:

• ConnectivityMonitor – This is a frame displaying the connectivity status of peers.

• DelayedJxtaNetworkStopper – Allows an asynchronous stop of the JXTA network.

• Edge_Gina – A simple EDGE peer. A possibility to enable TCP and HTTP communica-

tion or not is provided.

• Relay_Robert – A simple RELAY peer.

• RendezVous_Mya – A simple RENDEZVOUS peer.

Robert, The Relay

The following is the code used for Robert, a relay peer:

...

public class Relay_Robert {

// Static

public static final String Name_RELAY = "RELAY";

public static final PeerID PID_RELAY = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name_RELAY.getBytes());

public static final int HttpPort_RELAY = 9900;

public static final int TcpPort_RELAY = 9715;

public static final File ConfigurationFile_RELAY = new File("."

+ System.getProperty("file.separator") + Name_RELAY);

public static void main(String[] args) {

try {

Using JXSE Exploring Connectivity Issues - 180

// Removing any existing configuration?

NetworkManager.RecursiveDelete(ConfigurationFile_RELAY);

// Creation of the network manager

final NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RELAY,

Name_RELAY, ConfigurationFile_RELAY.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting Configuration

MyNetworkConfigurator.setUseMulticast(false);

MyNetworkConfigurator.setTcpPort(TcpPort_RELAY);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

MyNetworkConfigurator.setHttpPort(HttpPort_RELAY);

MyNetworkConfigurator.setHttpEnabled(true);

MyNetworkConfigurator.setHttpIncoming(true);

MyNetworkConfigurator.setHttpOutgoing(true);

// Setting the Peer ID

MyNetworkConfigurator.setPeerID(PID_RELAY);

// Starting the JXTA network

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Starting the connectivity monitor

new ConnectivityMonitor(NetPeerGroup);

// Stopping the network asynchronously

ConnectivityMonitor.TheExecutor.schedule(

new DelayedJxtaNetworkStopper(

MyNetworkManager,

"Click to stop " + Name_RELAY,

"Stop"),

0,

TimeUnit.SECONDS);

} catch (IOException Ex) {

System.err.println(Ex.toString());

} catch (PeerGroupException Ex) {

System.err.println(Ex.toString());

}

}

}

Robert the Relay

1. Any existing configuration is deleted.

2. The network manager instance and corresponding network configurator are created.

3. Multicasting is disabled, while TCP and HTTP communication are enabled (we will explainwhy later).

4. A peer ID is set.

Using JXSE Exploring Connectivity Issues - 181

5. The connectivity monitor frame is set and started. It will start the JXTA network.

6. An asynchronous task is created to asynchronously stop the JXTA network.

By using Robert, Mya and Gina, one can test various connectivity scenarios with the connectivitymanager.

Relay Connectivity

A connection to a relay peer can be established either via TCP or HTTP57. This can be checkedwith edge Gina by enabling/disabling TCP and HTTP communication and by using Robert andMya. Edge peers loop through their seeds of relay to try to maintain a permanent connection totheir a relay peer.

One may wonder when HTTP communication would be needed if TCP can be used by peers hav-ing a private address, to connect to relay peers. Many corporations only allow outbound HTTPtraffic and block other ports and TCP traffic. In this case, HTTP becomes necessary.

Summary

The following table indicates which type of communication should be enabled according to theconnection mode:

Configuration ADHOC EDGE RENDEZVOUS RELAY

TCP outgoing Not required Preferably Yes If possible

TCP incoming Not required Not essential Yes Required

HTTP outgoing Not required Preferably No required Not required

HTTP incoming Not required Not essential Not required Required

Multicasting Required Preferably Preferably If possible

• It does not make sense to configure an edge with no outgoing communication enabled.

• If an edge is configured only with multicasting, make it an adhoc to operate better58.

• A relay peer should have either TCP incoming or HTTP incoming allowed. Otherwise,edge peers will not be able to connect to it.

• Peers on the same LAN do not need rendezvous to connect if they all have multicastingenabled.

57 In version 2.5 of the Programmer's Guide, it is mentioned that “If you are located behind a firewall or NAT, you must use HTTP andspecify a relay node“. This is not correct.

58 An edge expects availability of TCP to connect to a rendezvous.

Using JXSE Exploring Connectivity Issues - 182

Creating Peers And Peer Groups

We are now going to explore how to create peers and peer groups. Before that, we need to ex-plain how to create basic JXTA objects.

Example 200 – Creating IDs

The following code provides examples of ID creations.

...

public class _200_Creating_IDs_Example {

public static void main(String[] args) {

// Creating a peer group ID and a sub-peer group ID

PeerGroupID MyPeerGroupID_A = IDFactory.newPeerGroupID();

PeerGroupID MyPeerGroupID_B = IDFactory.newPeerGroupID(MyPeerGroupID_A);

PeerGroupID MyPeerGroupID_C = IDFactory.newPeerGroupID(MyPeerGroupID_B);

// Creating peer IDs

PeerID MyPeer_A = IDFactory.newPeerID(MyPeerGroupID_A);

PeerID MyPeer_B = IDFactory.newPeerID(MyPeerGroupID_B);

PeerID MyPeer_C = IDFactory.newPeerID(MyPeerGroupID_C);

byte[] MySeed = { 0, 1, 2, 3, 4, 5, 6 };

PeerID MyPeer_Seed = IDFactory.newPeerID(MyPeerGroupID_A, MySeed);

// Creating a Pipe ID

PipeID MyPipe_A = IDFactory.newPipeID(MyPeerGroupID_A);

// Displaying the IDs

System.out.println("Peer Group A : " + MyPeerGroupID_A.toString());

System.out.println("Peer of A : " + MyPeer_A.toString());

System.out.println("Pipe of A : " + MyPipe_A.toString());

System.out.println("Peer of A with seed : " + MyPeer_Seed.toString());

System.out.println("Peer Group B of A : " + MyPeerGroupID_B.toString());

System.out.println("Peer of B : " + MyPeer_B.toString());

System.out.println("Peer Group C of B : " + MyPeerGroupID_C.toString());

System.out.println("Peer of C : " + MyPeer_C.toString());

}

}

Example 200 – Creation of IDs

1. We create a hierarchy of peer group IDs.

2. We create peer IDs, by providing peer group IDs.

3. We also create a peer by providing our own seed.

4. We create a pipe ID, by providing a peer group ID.

5. Then, we print them all.

We get a result similar to:

Using JXSE Creating Peers And Peer Groups - 183

Peer Group A : urn:jxta:uuid-E2E76334369C484E8986AC6A6EE02F3E 02

Peer of A : urn:jxta:uuid-E2E76334369C484E8986AC6A6EE02F3E

5BCCE1738E284BDBA60AD939D7EAB25F 03

Pipe of A : urn:jxta:uuid-E2E76334369C484E8986AC6A6EE02F3E

FBB2B65AECF349288561BE8F5D3C7FFB 04

Peer of A with seed : urn:jxta:uuid-E2E76334369C484E8986AC6A6EE02F3E 0001020304054600800080 03

Peer Group B of A : urn:jxta:uuid-B44AA561277449CC8843E1872D59AB47

E2E76334369C484E8986AC6A6EE02F3E 02

Peer of B : urn:jxta:uuid-B44AA561277449CC8843E1872D59AB47

C0997BE0299F4140AE50DE6A85297D3C 03

Peer Group C of B : urn:jxta:uuid-48F764A983BE47C3938FD3B3B22EC2E3

B44AA561277449CC8843E1872D59AB47 02

Peer of C : urn:jxta:uuid-48F764A983BE47C3938FD3B3B22EC2E3

2AE55ACDEC7B452CB6B58EE94642833C 03

The ID of peer group A is used to create the ID of the peer and the pipe belonging to group A, butalso the ID of peer group B. The ID of peer group B is used to create the ID of the peer belongingto group B, but also the ID of peer group C. The ID of peer group C is used to create the ID of thepeer belonging to group C.

The ID of peer group A has also been used to create the ID of the peer belonging to A for which aseed has been provided.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: With your finger in the sand you have drawn the distinctive sign of 3 new groups oftribes. For each group, you have drawn the distinctive sign of a new tribe belonging to it. For oneof the groups, you have also drawn the distinctive sign of a trading route. The sea will wash yourhand writing in the sand at the next tide.

Example 210 – Creating A New Peer

The following code describes the creation of a peer:

...

public class _210_Creating_A_Peer_Example {

public static void main(String[] args) {

try {

// Removing existing configuration

Tools.DeleteConfigurationInDefaultHome();

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.EDGE,

Name);

// Creating a new peer

PeerGroup TheNetPeerGroup = MyNetworkManager.getNetPeerGroup();

PeerID MyPeerID = IDFactory.newPeerID(TheNetPeerGroup.getPeerGroupID());

MyNetworkManager.setPeerID(MyPeerID);

Using JXSE Creating Peers And Peer Groups - 184

// Alternative method

NetworkConfigurator TheNetworkConfigurator = MyNetworkManager.getConfigurator();

TheNetworkConfigurator.setPeerID(MyPeerID);

// Starting and stopping the network

MyNetworkManager.startNetwork();

MyNetworkManager.stopNetwork();

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Example 210 – Creating a New Peer

1. We create the network manager.

2. We retrieve the net peer group.

3. We create a new peer ID using the net peer group ID.

4. We set the peer ID using the setPeerID() method in the network manager. Alternat-

ively, we can also set the peer ID at the network configurator level.

5. We start and stop the JXTA network with our new Peer.

Remember that a peer is any device running (at least the minimum set of) JXTA protocols. In ourcase, our peer is connected to JXTA via the net peer group and will be identified by its peer ID.Each time a peer connects to JXTA by using the startNetwork method of the NetworkCon-

figurator, its peer ID is passed to the net peer group PeerGroup object, which in turn is

passed to the world peer group PeerGroup object.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have decided to create a new tribe belonging to the humanity on your islandand elected yourself as its king or queen. You have selected a new distinctive sign, Santa Clausde la JXTA, tattooed it on your chest. You have also set a flag on the beach with your sign to theattention of other tribes. You have quickly decided to go and hide in your cave.

Example 220 – Creating A Customized Peer Group

The following code explains how to create a peer group:

...

public class _220_Creating_A_Custom_PeerGroup_Example {

public static final String Name = "Example 220";

Using JXSE Creating Peers And Peer Groups - 185

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File(

"." + System.getProperty("file.separator") + Name);

public static final String PeerGroupName = "Custom peer group name";

public static final PeerGroupID CustPeerGroupID = IDFactory.newPeerGroupID(

PeerGroupID.defaultNetPeerGroupID, PeerGroupName.getBytes());

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Starting the network

PeerGroup MyNetPeerGroup = MyNetworkManager.startNetwork();

// Creating a child group with PSE

PeerGroup ChildPeerGroup = MyNetPeerGroup.newGroup(

CustPeerGroupID,

createAllPurposePeerGroupImplAdv(),

PeerGroupName,

"Custom peergroup..."

);

if (Module.START_OK != ChildPeerGroup.startApp(new String[0]))

System.err.println("Cannot start custom peergroup");

// Checking membership implementation

MembershipService ChildGroupMembership = ChildPeerGroup.getMembershipService();

Tools.PopInformationMessage(Name, "Custom group membership implementation:\n"

+ ChildGroupMembership.getClass().getSimpleName());

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

public static ModuleImplAdvertisement createAllPurposePeerGroupImplAdv() {

ModuleImplAdvertisement implAdv = CompatibilityUtils.createModuleImplAdvertisement(

PeerGroup.allPurposePeerGroupSpecID, StdPeerGroup.class.getName(),

"General Purpose Peer Group");

// Create the service list for the group.

StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv();

// set the services

paramAdv.addService(PeerGroup.endpointClassID, PeerGroup.refEndpointSpecID);

paramAdv.addService(PeerGroup.resolverClassID, PeerGroup.refResolverSpecID);

paramAdv.addService(PeerGroup.membershipClassID, PeerGroup.refMembershipSpecID);

paramAdv.addService(PeerGroup.accessClassID, PeerGroup.refAccessSpecID);

// standard services

paramAdv.addService(PeerGroup.discoveryClassID, PeerGroup.refDiscoverySpecID);

paramAdv.addService(PeerGroup.rendezvousClassID, PeerGroup.refRendezvousSpecID);

paramAdv.addService(PeerGroup.pipeClassID, PeerGroup.refPipeSpecID);

Using JXSE Creating Peers And Peer Groups - 186

paramAdv.addService(PeerGroup.peerinfoClassID, PeerGroup.refPeerinfoSpecID);

paramAdv.addService(PeerGroup.contentClassID, ContentServiceImpl.MODULE_SPEC_ID);

// Insert the newParamAdv in implAdv

XMLElement paramElement = (XMLElement) paramAdv.getDocument(MimeMediaType.XMLUTF8);

implAdv.setParam(paramElement);

return implAdv;

}

}

Example 210 – Creating a New Custom Peer Group

Here is how we proceed:

1. We create some context information to define the name and the peer ID that we are goingto use to connect to the JXTA network.

2. We also define a name and a peer group ID for the new peer group.

3. We erase the content of any existing configuration.

4. We create the network manager and set our peer ID.

5. We start the JXTA network and retrieve the net peer group.

6. We create a module implementation advertisement using reference module IDs .

7. We create the new peer group by calling the newGroup(...) method from the net peer

group retrieved earlier.

8. We start the new peer group and notify the user.

9. We display its membership implementation.

10. We stop the new peer group and notify the user.

11. We stop the network manager.

This method creates a new peer group on JXTA from scratch. This includes the local publicationof the corresponding new peer group advertisement in the parent group. This advertisement canbe later discovered by other peers who can decide to join the group (we will describe this later).This peer could also publish this advertisement remotely to notify other members of the net peergroup (we will also describe this later).

The newly created peer group automatically inherits from the implementation of transportation lay-ers (TCP, HTTP, multicasting...) from its parent group, the net peer group and the world peergroup when initialized and started.

Using JXSE Creating Peers And Peer Groups - 187

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have taken a piece of dried leaf and have drawn the distinctive sign of a newtribe corporation called the 'Custom peer group name'. You have assigned resources from yourtribe and your island to run that corporation for some time, before stopping it. If other tribes hadcontacted you to learn about peer groups, you would have mentioned the new custom group bygiving them a copy on the corresponding dried leaf describing it.

Discovery Operations

Finding Advertisements

All JXTA resources are represented by advertisements. Instead of having to hard code resourcedescriptions in software applications and configuration files, which is cumbersome and not flexible,peers can launch discovery operations to retrieve these advertisements and find out how to ac-cess these resources. The following code example describes how to perform advertisement dis-covery operations.

Example 300 - Retrieving And Flushing Local Advertisements

The following code in this example describes how to retrieve local advertisements and to flushthem.

...

public class _300_Retrieving_And_Flushing_Local_Advertisements_Example {

public static final String Name = "Example 300";

public static final int TcpPort = 9720;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Preparing context

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name);

// Retrieving network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Jack should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":" +

RendezVous_Jack.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

Using JXSE Discovery Operations - 188

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the network and waiting for a rendezvous connection

PeerGroup DefaultPeerGroup = MyNetworkManager.startNetwork();

Tools.PopInformationMessage(Name,

"Waiting for rendezvous connection for maximum 60 seconds");

if (MyNetworkManager.waitForRendezvousConnection(60000)) {

Tools.PopInformationMessage(Name, "Rendezvous connection successful!");

} else {

Tools.PopWarningMessage(Name, "Rendezvous connection NOT successful!");

}

// Retrieving local advertisements

Tools.PopInformationMessage(Name, "Retrieving local advertisements");

DiscoveryService TheDiscoveryService = DefaultPeerGroup.getDiscoveryService();

Enumeration<Advertisement> TheAdvEnum = TheDiscoveryService.getLocalAdvertisements(

DiscoveryService.ADV, null, null);

while (TheAdvEnum.hasMoreElements()) {

Advertisement TheAdv = TheAdvEnum.nextElement();

String ToDisplay = "Found " + TheAdv.getClass().getSimpleName();

if (TheAdv.getClass().getName().compareTo(RouteAdv.class.getName())==0) {

// We found a route advertisement

RouteAdv Temp = (RouteAdv) TheAdv;

ToDisplay = ToDisplay + "\n\nto " + Temp.getDestPeerID().toString();

} else if (TheAdv.getClass().getName().compareTo(RdvAdv.class.getName())==0) {

// We found a rendezvous advertisement

RdvAdv Temp = (RdvAdv) TheAdv;

ToDisplay = ToDisplay + "\n\nof " + Temp.getPeerID().toString();

}

// Displaying the advertisement

Tools.PopInformationMessage(Name, ToDisplay);

// Flushing advertisement

TheDiscoveryService.flushAdvertisement(TheAdv);

}

// Stopping JXTA

Tools.PopInformationMessage(Name, "Stopping the network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Using JXSE Discovery Operations - 189

Example 300 – Retrieving and Flushing Local Advertisements

This example performs the following:

1. We create some context information to define the name, the peer ID and the unique portthat we are going to use to connect to the JXTA network.

2. We provide the user with an opportunity to delete any existing configuration.

3. We create the network manager, retrieve the network configurator and provide the userwith an opportunity to set Jack the seed as a rendezvous seeds.

4. We start the JXTA network, and wait for a rendezvous connection for maximum oneminute. We display a message indicating whether a rendezvous connection could be es-tablished.

5. We retrieve the list of all local advertisements from the discovery service.

6. We display a message for each advertisement and then delete it.

7. We stop the JXTA network.

In order to make this example work, start Jack the Rendezvous until his JXTA network connectionis started. Erase existing configuration. Then start example 300 by erasing existing configurationand allowing Jack as a rendezvous seed. When all advertisements have been displayed, stop theJXTA network for both.

In this example we are showing how to get rid of a local advertisement. It is not recommended toerase all advertisements like we do. This is just for the sake of explaining how to proceed.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: You have heard that another tribe called the Jack tribe exists on the other side ofthe island, but you can't reach them by land. You decide to send your people to try to establishcontact. They may come back with dried leaves describing the rendezvous role of this tribe andthe route to reach them. Then, you decide to take all the dried leaves you own from your box, takea look at these, and decide to burn them all.

Example 310 – Remote Search For Advertisements

The following code introduces Maxime the Socializer, who will try to search for other peer advert-isements:

...

public class Edge_Maxime_The_Socializer implements DiscoveryListener {

Using JXSE Discovery Operations - 190

public static final String Name = "Edge Maxime, The Socializer";

public static final int TcpPort = 9721;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public void discoveryEvent(DiscoveryEvent TheDiscoveryEvent) {

// Who triggered the event?

DiscoveryResponseMsg TheDiscoveryResponseMsg = TheDiscoveryEvent.getResponse();

if (TheDiscoveryResponseMsg!=null) {

Enumeration<Advertisement> TheEnumeration =

TheDiscoveryResponseMsg.getAdvertisements();

while (TheEnumeration.hasMoreElements()) {

try {

PeerAdvertisement ThePeer = (PeerAdvertisement) TheEnumeration.nextElement();

Tools.PopInformationMessage(Name, "Received advertisement of: " +

ThePeer.getName());

} catch (ClassCastException Ex) {

// We are not dealing with a Peer Advertisement

}

}

}

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Jack should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":" +

RendezVous_Jack.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous\nconnection with "

+ RendezVous_Jack.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

Using JXSE Discovery Operations - 191

// Disabling any rendezvous autostart

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Launching query to retrieve peer advertisements

Tools.PopInformationMessage(Name,

"Start peer discovery and going to sleep for 60 seconds");

DiscoveryService TheDiscoveryService = NetPeerGroup.getDiscoveryService();

TheDiscoveryService.getRemoteAdvertisements(null, DiscoveryService.PEER,

null, null, 0, new Edge_Maxime_The_Socializer());

// Sleeping for 60 seconds

Tools.GoToSleep(60000);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Example 310 – Remote Search for Advertisements

Maxime the socializer is different than other peers since he implements the DiscoveryListen-

er to receive answers to his queries to other peers. Each time an answer is received, his dis-

coveryEvent() method is called and information can be extracted from the received data.

Otherwise, Maxime is performing the same initial operations as Anna until he manages to connectto Jack. Then, he retrieves the discovery service from the net peer group he is connected to. Helaunches a query to get remote peer advertisements by calling the getRemoteAdvertise-

ment() method. This method contains several parameters:

1. String peerid – If this parameter is left null, the query is propagated to every peer of

the subgroup via the connected rendezvous and by multicasting on the LAN. If a peer IDis specified, the query will be propagated to the specified peer only.

2. int type – This parameter indicates the type of the discovery: peer, peer groups or (oth-

er types of) advertisements.

Using JXSE Discovery Operations - 192

3. String attribute – This parameter, in combination with the value parameter, can be

used to filter the advertisements to be returned by peers receiving the query. Every ad-vertisement contains several attributes (see Appendix for lists) having values themselves.

4. String value – This parameter must be used in combination with the attribute para-

meter to filter returned advertisement values. Wildcards '*' can be used and the search isnot case sensitive.

5. int threshold – This limit indicates the maximum number of advertisements each

peer should return. If the type parameter is set to PEER and the threshold is set to 0, each

peer receiving the query should return its peer advertisement to the peer initiating thequery.

6. DiscoveryListener listener – This parameter can be used to specify the object

implementing a proper DiscoveryListener that will be called each time an answer to

the query is received.

In order to make this example work, one should first start Jack the Rendezvous and then startAnna the Edge and wait until Anna establishes a connection with Jack. Then, Maxime should bestarted. After the peer discovery is started, Maxime will receive several answers containing peeradvertisements of peers who have received and answered the query. Do not forget that you canget several answers for the same peer advertisement from different peers.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: The Jack, Anna and Maxime tribes are living on the same island, but are separ-ated by insurmountable mountains. The Anna tribe and the Maxime tribe both have heard aboutthe Jack tribe and make contact with it. Maxime, who is a socializer, wants to know about otherunknown tribes. He asks his people to navigate the sea and around the island to check for thosetribes.

The Jack tribe gets to know about Maxime's request and Jack answers it himself by asking hispeople to give a copy of dried leaves describing known tribes to Maxime's people. The Jack tribealso notifies the Anna tribe about Maxime's request and she decides to provide a copy of knownadvertisements to Maxime's people too. This is how Maxime gets to know about Anna.

Remark:Remark:Remark:Remark: In order to connect to another peer group, a user can search for its advertisement (forexample: The Dave Brubeck Fan Club) and start an instance of it with the newGroup(Advert-

isement pgAdv) method from the peer group it is connected to. The reader can try to create

such a peer, have it connect to Jack the Rendezvous, start Example 220 and perform the neces-sary actions to retrieve the corresponding peer group advertisement and to connect to it. The au-

Using JXSE Discovery Operations - 193

thor suggests to call him Tebogo, the Jazz fan.

Local And Remote Publication

The discovery service of peer groups offers several methods to publish advertisements locally andremotely. When published locally, a lifetime can be set. When published remotely, an expirationcan be set. In both cases, these indicate how long the advertisement will be cached on peers. Re-mote publication can be performed for every peer belonging to the peer group or to a specific peeronly. The reader will find more details about the description of the publish() and remotePub-

lish() methods in the javadoc.

Messages & Advertisements

Example 400 – Creating An Empty Message

The following code describes how to create an empty message in JXSE:

...

public class _400_Creating_An_Empty_Message_Example {

public static final String Name = "Example 400";

public static void main(String[] args) {

Message MyMessage = new Message();

Tools.DisplayMessageContent(Name, MyMessage);

}

}

Example 400 – Creating an Empty Message

Running the above code displays a simple message box with an empty message.

Example 410 – Add String, Long & Int Elements

The following code describes how to add Java String, long and int elements in your mes-

sage:

...

public class _410_Add_String_Long_Int_Elements_Example {

public static final String Name = "Example 410";

public static void main(String[] args) {

// Creating an empty message

Message MyMessage = new Message();

// Creating string element

Using JXSE Messages & Advertisements - 194

StringMessageElement MyStringMessageElement = new StringMessageElement(

"MyStringElement", "My string message content", null);

// Creating int element

StringMessageElement MyIntMessageElement = new StringMessageElement(

"MyIntElement", Integer.toString(33), null);

// Creating long element

StringMessageElement MyLongMessageElement = new StringMessageElement(

"MyLongElement", Long.toString(29345677), null);

// Adding string message elements

MyMessage.addMessageElement("MyNameSpace", MyStringMessageElement);

MyMessage.addMessageElement("MyNameSpace", MyIntMessageElement);

MyMessage.addMessageElement("MyNameSpace", MyLongMessageElement);

// Displaying message

Tools.DisplayMessageContent(Name, MyMessage);

}

}

Example 410 – Add String, Long & Int Elements

Adding simple Java objects in messages ispretty straight forward. By running the abovecode, the reader should get the following mes-sage box.

JXSE offers the possibility to define you ownname space and element names when inserting them in messages. This can be very useful fordata organization purposes.

Example 420 – Retrieving Message Elements

The following code describes how to retrieve message elements:

...

public class _420_Retrieving_Message_Elements_Example {

public static final String Name = "Example 420";

public static void main(String[] args) {

// Creating an empty message

Message MyMessage = new Message();

// Creating string element

StringMessageElement MyNameMessageElement = new StringMessageElement(

"NameElement", "John Arthur", null);

// Creating int element

StringMessageElement MyAddressMessageElement = new StringMessageElement(

“AddressElement", "42nd Street", null);

// Creating long element

StringMessageElement MyOtherMessageElement = new StringMessageElement(

"OtherElement", "Enjoys pizzas", null);

// Adding string message elements

Using JXSE Messages & Advertisements - 195

MyMessage.addMessageElement("MyNameSpace", MyNameMessageElement);

MyMessage.addMessageElement("MyNameSpace", MyAddressMessageElement);

MyMessage.addMessageElement("MyNameSpace", MyOtherMessageElement);

// Displaying message

Tools.DisplayMessageContent(Name, MyMessage);

// Retrieving message element

Tools.PopInformationMessage(Name, "Retrieving message element:\n\n"

+ MyMessage.getMessageElement("MyNameSpace", "AddressElement").toString());

}

}

Example 420 – Retrieve Message Elements

The above code creates a simple message and displays it. Then, we extract the address messageelement content and display it. A message box displaying “ 42nd Street” will pop up.

Example 430 – Add Byte Array Element And Retrieve InputStream

The following code describes how to insert a Java byte array in a message and how to get an

InputStream to retrieve its content:

...

public class _430_Add_ByteArray_Element_And_Retrieve_InputStream_Example {

public static final String Name = "Example 430";

public static void main(String[] args) {

try {

// Creating byte array and filling it

byte[] MyByteArray = new byte[10];

for (int i = 0; i < MyByteArray.length; i++) {

MyByteArray[i] = (byte) i;

}

Message MyMessage = new Message();

ByteArrayMessageElement MyByteArrayMessageElement = new ByteArrayMessageElement(

"MyByteArrayElement", MimeMediaType.AOS, MyByteArray, null);

MyMessage.addMessageElement("MyNameSpace", MyByteArrayMessageElement);

MessageElement MyElement = MyMessage.getMessageElement("MyNameSpace",

"MyByteArrayElement");

InputStream MyInputStream = MyElement.getStream();

int Read = MyInputStream.read();

String Result = "";

while (Read != -1) {

Result = Result + Read + " ";

Read = MyInputStream.read();

}

Tools.PopInformationMessage(Name, "Extracted byte array content:\n\n" + Result);

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

Using JXSE Messages & Advertisements - 196

}

}

}

Example 430 – Add Byte Array Element and Retrieve InputStream

The above code creates a simple message and adds a byte array. Then, we extract the content ofthe byte array and display its content.

Example 440 – Adding An Advertisement In A Message

The following code describes how to insert an advertisement in a message:

...

public class _440_Adding_An_Advertisement_In_Message_Example {

public static final String Name = "Example 440";

public static void main(String[] args) {

// Creating a customized advertisement

_500_Customized_Advertisement_Example MyAdvertisement =

new _500_Customized_Advertisement_Example();

MyAdvertisement.SetName("John");

MyAdvertisement.SetAge(33);

// Creating the message

Message MyMessage = new Message();

// Creating the message element and adding it

TextDocumentMessageElement MyTextDocumentMessageElement = new TextDocumentMessageElement(

"CUSTOMIZED_ADVERTISEMENT",

(XMLDocument) MyAdvertisement.getDocument(MimeMediaType.XMLUTF8),

null);

MyMessage.addMessageElement("CUSTOMIZED_ADVERTISEMENT",MyTextDocumentMessageElement);

// Retrieving the advertisement from the message

MessageElement MyMessageElement = MyMessage.getMessageElement(

"CUSTOMIZED_ADVERTISEMENT","CUSTOMIZED_ADVERTISEMENT");

try {

XMLDocument TheDocument = (XMLDocument)

StructuredDocumentFactory.newStructuredDocument(

MyMessageElement.getMimeType(),

MyMessageElement.getStream());

_500_Customized_Advertisement_Example MyCustomizedAdvertisement =

new _500_Customized_Advertisement_Example(TheDocument.getRoot());

// Displaying advertisement

Tools.PopInformationMessage(Name, MyCustomizedAdvertisement.toString());

} catch (IOException Ex) {

// Thrown when message element cannot be read.

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IllegalArgumentException Ex) {

// Thrown when the document or advertisement has an invalid structure

// (illegal values or missing tags...)

Tools.PopErrorMessage(Name, Ex.toString());

Using JXSE Messages & Advertisements - 197

}

}

}

Example 440 – Adding an Advertisement in a Message

Again, the above code is straight forward:

1. We create an advertisement (in this case, it is a customized advertisement which we willcover next).

2. We add a text document element using theXML format and UTF8 encoding. We setname of the namespace to "CUSTOM-IZED_ADVERTISEMENT".

3. Next, we attempt to retrieve our advertise-ment by first extracting it from the message(it has an XML document format). Then weprovide it to our customized advertise-ment's constructor.

4. At last, we display the retrieved advertisement, which should look as the message boxabove.

The method we have described here can easily be adapted to include XML documents in mes-sages too.

Example 500 – Customized Advertisement

The following code describes how to create a customized advertisement:

...

public class _500_Customized_Advertisement_Example extends Advertisement {

public static final String Name = "Example 500";

// Advertisement elements, tags and indexables

public final static String AdvertisementType = "jxta:CustomizedAdvertisement";

private ID AdvertisementID = ID.nullID;

private String TheName = "";

private int TheAge = -1;

private final static String IDTag = "MyIDTag";

private final static String NameTag = "MyNameTag";

private final static String AgeTag = "MyAgeTag";

private final static String[] IndexableFields = { IDTag, NameTag };

Using JXSE Messages & Advertisements - 198

public _500_Customized_Advertisement_Example() {

// Accepting default values

}

public _500_Customized_Advertisement_Example(Element Root) {

// Retrieving the elements

TextElement MyTextElement = (TextElement) Root;

Enumeration TheElements = MyTextElement.getChildren();

while (TheElements.hasMoreElements()) {

TextElement TheElement = (TextElement) TheElements.nextElement();

ProcessElement(TheElement);

}

}

public void ProcessElement(TextElement TheElement) {

String TheElementName = TheElement.getName();

String TheTextValue = TheElement.getTextValue();

if (TheElementName.compareTo(IDTag)==0) {

try {

URI ReadID = new URI(TheTextValue);

AdvertisementID = IDFactory.fromURI(ReadID);

return;

} catch (URISyntaxException Ex) {

// Issue with ID format

Ex.printStackTrace();

} catch (ClassCastException Ex) {

// Issue with ID type

Ex.printStackTrace();

}

}

if (TheElementName.compareTo(NameTag)==0) {

TheName = TheTextValue;

return;

}

if (TheElementName.compareTo(AgeTag)==0) {

TheAge = Integer.parseInt(TheTextValue);

return;

}

}

@Override

public Document getDocument(MimeMediaType TheMimeMediaType) {

// Creating document

StructuredDocument TheResult = StructuredDocumentFactory.newStructuredDocument(

TheMimeMediaType, AdvertisementType);

// Adding elements

Using JXSE Messages & Advertisements - 199

Element MyTempElement;

MyTempElement = TheResult.createElement(NameTag, TheName);

TheResult.appendChild(MyTempElement);

MyTempElement = TheResult.createElement(AgeTag, Integer.toString(TheAge));

TheResult.appendChild(MyTempElement);

return TheResult;

}

public void SetID(ID TheID) {

AdvertisementID = TheID;

}

@Override

public ID getID() {

return AdvertisementID;

}

@Override

public String[] getIndexFields() {

return IndexableFields;

}

public void SetName(String InName) {

TheName = InName;

}

public void SetAge(int InAge) {

TheAge = InAge;

}

public String GetName() {

return TheName;

}

public int GetAge() {

return TheAge;

}

@Override

public _500_Customized_Advertisement_Example clone() throws CloneNotSupportedException {

_500_Customized_Advertisement_Example Result =

(_500_Customized_Advertisement_Example) super.clone();

Result.AdvertisementID = this.AdvertisementID;

Result.TheName = this.TheName;

Result.TheAge = this.TheAge;

return Result;

}

@Override

public String getAdvType() {

return _500_Customized_Advertisement_Example.class.getName();

}

public static String getAdvertisementType() {

return AdvertisementType;

}

public static class Instantiator implements AdvertisementFactory.Instantiator {

public String getAdvertisementType() {

return _500_Customized_Advertisement_Example.getAdvertisementType();

}

Using JXSE Messages & Advertisements - 200

public Advertisement newInstance() {

return new _500_Customized_Advertisement_Example();

}

public Advertisement newInstance(net.jxta.document.Element root) {

return new _500_Customized_Advertisement_Example(root);

}

}

}

Example 500 – Customized Advertisement

The above code describes how to create a customized advertisement containing three attributes:advertisement ID, name and age. Our customized advertisement has to implement the Advert-

isement abstract class which requires defining some specific attributes, overriding some meth-

ods and defining an Instantiator class.

Attributes

Our attribute section contains static and non-static fields. The first static field is the advertisementtype which is necessary to implement the getAdvertisementType() method of the Advert-

isement abstract class. Then, we have a set of static fields describing the XML tags which will be

used when transforming the data contained in our advertisement into an XML document and vice-versa. The last, but very important, static field is the list of tag elements which can be used to in-dex the document (i.e. advertisement) when it will be transmitted between peers.

The non static attributes are an ID, the name (of a user for example) and an age. The reader willnotice that in our case, the age is not part of the indexable fields.

Methods

Our customized advertisement contains two sets of methods, those inherited and overridden fromthe Advertisement abstract class. We will start by describing the inherited methods:

• Advertisement clone() – This typical method ought to be overridden to make sure

that attributes added at our level will be properly copied and initialized in the duplicatedobject.

• static String getAdvertisementType() – This method returns information to

identify the JXTA type (i.e., not the Java class runtime type) of the advertisement.

• static String getAdvType() – This method returns information to identify the Java

class runtime type of the advertisement. In our case, we need to indicate that our advert-

Using JXSE Messages & Advertisements - 201

isement is a _500_Customized_Advertisement_Example Java class.

• Document getDocument(MimeMediaType asMimeType) – This methods is neces-

sary to convert our customized advertisement into an XML document.

• ID getID() – Returns the advertisement ID.

• String[] getIndexFields() – Returns the list of indexable fields.

• String toString() – Returns a string representation of the advertisement.

Regarding the other methods, we provide two constructors; one to create a empty customized ad-vertisement and one based on the root element of an XML document describing the advertise-ment. The latter is necessary to convert XML documents back into advertisements. We alsoprovide setter and getter methods for the advertisement attributes.

Instantiator

The implementation of an instantiator is an absolute necessity to make sure our new customizedadvertisement will be usable by peers on the network. It will be used by the standard implementa-tion of JXTA protocols in JXSE (via the AdvertisementFactory) to create Java object in-

stances of our customized advertisement when they reach peers for example.

Example 510 – Registering A Customized Advertisement Instance

The following code describes how to register customized advertisements in the Advertise-

mentFactory object:

import Examples.Z_Tools.Tools;

import net.jxta.document.AdvertisementFactory;

public class _510_Registering_Customized_Advertisement_Instance_Example {

public static final String Name = "Example 510";

public static void main(String[] args) {

// Registering our customized advertisement instance

AdvertisementFactory.registerAdvertisementInstance(

_500_Customized_Advertisement_Example.getAdvertisementType(),

new _500_Customized_Advertisement_Example.Instantiator());

// Notifying the user

Tools.PopInformationMessage(Name, "Registered in Advertisement Factory:\n\n"

+ _500_Customized_Advertisement_Example.getAdvertisementType());

}

}

Example 510 – Registering a Customized Advertisement Instance

Using JXSE Messages & Advertisements - 202

This operation must be performed on every peer that will use our customized advertisement, butnot necessarily those who will transport or index a message containing our advertisement. Else,the advertisement will not be processed correctly by peers receiving it.

This mechanism, in combination with the Initiator static class created as part of our custom-

ized advertisement, will ensure that peers receiving our customized advertisement will receive itas a Java object of type _500_Customized_Advertisement_Example. This eliminates tricky

code manipulations for developers; the received advertisement can safely be cast automaticallyinto the proper Java object type.

Technically speaking, the JXTA protocols in JXSE will invoke an Instantiator for the advertisementtype mentioned in the XML document they receive. Since the AdvertisementFactory will have

been initialized properly, it will be able to return such an Instantiator. The protocols can then

create an empty instance of our customized advertisement by invoking the newInstance()

method. Then, they will be able to fill this new instance with the remaining data contained in theXML document by invoking the ProcessElement(TextElement TheElement) method in our

customized advertisement.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: We have now learned how to write down messages on dried leaves. We have alsolearned how to create special dried leaves to describe/advertise our non-standard JXTA re-sources.

Private Keys, Certificates & KeyStores

Before we start describing how to use pipes to exchange messages, we need to describe how towork with private keys, certificates and keystores.

Example 600 - Exporting & Importing Private Keys And X.509 Certificates

The following code describes how to quickly generate a X509 certificate and its correspondingprivate key, plus how to export them into a String and re-import them from that same String:

...

public class _600_Exporting_And_Importing_Private_Keys_And_X509_Certificates {

public static final String Name = "Importing and Exporting Private Keys and Certificates";

public static void main(String[] args) {

try {

// Certificate and Private Key

X509Certificate TheX509Certificate;

PrivateKey ThePrivateKey;

Using JXSE Private Keys, Certificates & KeyStores - 203

// Initialization

PSEUtils.IssuerInfo ForPSE = PSEUtils.genCert(Name, null);

TheX509Certificate = ForPSE.cert;

ThePrivateKey = ForPSE.issuerPkey;

// String encoded certificate & private key

String Base64_X509Certificate = PSEUtils.base64Encode(TheX509Certificate.getEncoded());

String Base64_ThePrivateKey = PSEUtils.base64Encode(ThePrivateKey.getEncoded());

// Printing Results

System.out.println("------------------------------");

System.out.println(Base64_X509Certificate);

System.out.println("------------------------------");

System.out.println(Base64_ThePrivateKey);

System.out.println(ThePrivateKey.getFormat());

System.out.println("------------------------------");

// Recreating certificate & private key

X509Certificate RecreateX509Certificate;

PrivateKey RecreatePrivateKey;

// Recreating the X509 certificate

byte[] Temp = PSEUtils.base64Decode(new StringReader(Base64_X509Certificate));

CertificateFactory TheCF = CertificateFactory.getInstance("X509");

RecreateX509Certificate = (X509Certificate) TheCF.generateCertificate(

new ByteArrayInputStream(Temp));

System.out.println("-X509-Original-------------");

System.out.println(TheX509Certificate.toString());

System.out.println("-X509-Recreated------------");

System.out.println(RecreateX509Certificate.toString());

System.out.println("---------------------------");

// Restoring the private key

Temp = PSEUtils.base64Decode(new StringReader(Base64_ThePrivateKey));

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

PKCS8EncodedKeySpec MyPKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(Temp);

RecreatePrivateKey = keyFactory.generatePrivate(MyPKCS8EncodedKeySpec);

System.out.println("-Private-Key-Original-------------");

System.out.println(ThePrivateKey.toString());

System.out.println("-Private-Key-Recreated------------");

System.out.println(RecreatePrivateKey.toString());

System.out.println("----------------------------------");

} catch (Exception Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Example 600 - Exporting & Importing Private Keys And Certificates

This example is performing the following:

1. We generate a pair of corresponding X509 certificate and private key using the PSEUtils

tools provided as part of JXTA. The RSA key size is set to 1024 by default.

REM:REM:REM:REM: If the reader is not satisfied with those settings, he or she can take a look at thecode of PSEUtils to find out how to modify it or to write a new method inspired from it.

Using JXSE Private Keys, Certificates & KeyStores - 204

2. We export both the X509 certificate and the private key into base 64 strings and displaythe result. These strings can be easily exchanged, transported or stored by applications.Do not forget that the private key is not encrypted and has no protection.

3. We re-import the X509 certificate and the private key from the base 64 strings. Then, wedisplay the original and the re-imported result for comparison.

Some readers will notice some difference between the display of the original X509 certificate andthe recreated X509 certificate. In fact, the modulus and the exponent are expressed in decimals inone case and in hexadecimals in the other case, but the values are the same.

Example 610 – Working With A KeyStore

The following code example describes how to create a keystore and to interact with it:

...

public class _610_Working_With_A_Keystore {

public static final String Name = "Example 610";

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static final String MyPrincipalName = "Principal - " + Name;

public static final String MyPrivateKeyPassword = "PrivateKey Password - " + Name;

public static final String MyKeyStoreFileName = "MyKeyStoreFile";

public static final String MyKeyStoreLocation = "." + System.getProperty("file.separator")

+ Name + File.separator + "MyKeyStoreLocation";

public static final String MyKeyStorePassword = "KeyStore Password - " + Name;

public static final String MyKeyStoreProvider = "KeyStore Provider - " + Name;

public static final File MyKeyStoreDirectory = new File(MyKeyStoreLocation);

public static final File MyKeyStoreFile = new File(MyKeyStoreLocation + File.separator +

MyKeyStoreFileName);

public static final X509Certificate TheX509Certificate;

public static final PrivateKey ThePrivateKey;

static {

// Static initialization

PSEUtils.IssuerInfo ForPSE = PSEUtils.genCert(Name, null);

TheX509Certificate = ForPSE.cert;

ThePrivateKey = ForPSE.issuerPkey;

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Preparing data

MyKeyStoreDirectory.mkdirs();

// Creating the key store

FileKeyStoreManager MyFileKeyStoreManager = new FileKeyStoreManager(

Using JXSE Private Keys, Certificates & KeyStores - 205

(String)null, MyKeyStoreProvider, MyKeyStoreFile);

MyFileKeyStoreManager.createKeyStore(MyKeyStorePassword.toCharArray());

if (!MyFileKeyStoreManager.isInitialized()) {

Tools.PopInformationMessage(Name, "Keystore is NOT initialized");

} else {

Tools.PopInformationMessage(Name, "Keystore is initialized");

}

// Loading the (empty) keystore

KeyStore MyKeyStore =

MyFileKeyStoreManager.loadKeyStore(MyKeyStorePassword.toCharArray());

// Setting data

X509Certificate[] Temp = { TheX509Certificate };

MyKeyStore.setKeyEntry(PID.toString(), ThePrivateKey,

MyPrivateKeyPassword.toCharArray(), Temp);

// Saving the data

MyFileKeyStoreManager.saveKeyStore(MyKeyStore, MyKeyStorePassword.toCharArray());

// Reloading the KeyStore

MyKeyStore = MyFileKeyStoreManager.loadKeyStore(MyKeyStorePassword.toCharArray());

// Retrieving Certificate

X509Certificate MyCertificate = (X509Certificate)

MyKeyStore.getCertificate(PID.toString());

if (MyCertificate==null) {

Tools.PopInformationMessage(Name, "X509 Certificate CANNOT be retrieved");

} else {

Tools.PopInformationMessage(Name, "X509 Certificate can be retrieved");

System.out.println(MyCertificate.toString());

}

// Retrieving private key

PrivateKey MyPrivateKey = (PrivateKey) MyKeyStore.getKey(PID.toString(),

MyPrivateKeyPassword.toCharArray());

if (MyPrivateKey==null) {

Tools.PopInformationMessage(Name, "Private key CANNOT be retrieved");

} else {

Tools.PopInformationMessage(Name, "Private key can be retrieved");

System.out.println(MyPrivateKey.toString());

}

} catch (NoSuchAlgorithmException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (UnrecoverableKeyException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (NoSuchProviderException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (KeyStoreException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Example 610 – Working With a KeyStore

Using JXSE Private Keys, Certificates & KeyStores - 206

This example is performing the following:

1. We define a set of static variables that will be used later in the code. We also create astatic code section that will be executed as soon as the _610_Working_With_A_Key-

store class is referenced for the first time. This code will create a pair of corresponding

private key and certificate for later use.

2. We start by providing the user an opportunity to erase any existing file in the directory thatwill be used to create the keystore.

3. Then, we create the keystore and set a keystore password. We let the user know whetherit has been initialized successfully.

4. We load the keystore (which is empty) and fill it with the X509 certificate and the privatekey.

5. Next we reload the keystore and try to extract the X509 certificate and the private key. Welet the user know whether these operations are successful.

Example 620 – Custom PSE Peer Group & Joining

The following code example describes how to create custom PSE peer group and to join it:

...

public class _620_Creating_A_Custom_PSE_PeerGroup_Example {

public static final String Name = "Example 620";

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static final String MyPrincipalName = "Principal - " + Name;

public static final String MyPrivateKeyPassword = "PrivateKey Password - " + Name;

public static final String MyKeyStoreFileName = "MyKeyStoreFile";

public static final String MyKeyStoreLocation = "." + System.getProperty("file.separator") +

Name + File.separator + "MyKeyStoreLocation";

public static final String MyKeyStorePassword = "KeyStore Password - " + Name;

public static final String MyKeyStoreProvider = "KeyStore Provider - " + Name;

public static final File MyKeyStoreDirectory = new File(MyKeyStoreLocation);

public static final File MyKeyStoreFile = new File(MyKeyStoreLocation + File.separator

+ MyKeyStoreFileName);

public static final X509Certificate TheX509Certificate;

public static final PrivateKey ThePrivateKey;

public static final String PsePeerGroupName = "PSE peer group name";

public static final PeerGroupID PsePeerGroupID =

IDFactory.newPeerGroupID(PeerGroupID.defaultNetPeerGroupID, PsePeerGroupName.getBytes());

static {

// Static initialization of certificates

PSEUtils.IssuerInfo ForPSE = PSEUtils.genCert(Name, null);

Using JXSE Private Keys, Certificates & KeyStores - 207

TheX509Certificate = ForPSE.cert;

ThePrivateKey = ForPSE.issuerPkey;

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Preparing data

MyKeyStoreDirectory.mkdirs();

// Creating the key store

FileKeyStoreManager MyFileKeyStoreManager = new FileKeyStoreManager(

(String)null, MyKeyStoreProvider, MyKeyStoreFile);

MyFileKeyStoreManager.createKeyStore(MyKeyStorePassword.toCharArray());

if (!MyFileKeyStoreManager.isInitialized()) {

Tools.PopInformationMessage(Name, "Keystore is NOT initialized");

} else {

Tools.PopInformationMessage(Name, "Keystore is initialized");

}

// Loading the (empty) keystore

KeyStore MyKeyStore =

MyFileKeyStoreManager.loadKeyStore(MyKeyStorePassword.toCharArray());

// Setting data

X509Certificate[] Temp = { TheX509Certificate };

MyKeyStore.setKeyEntry(PID.toString(), ThePrivateKey,

MyPrivateKeyPassword.toCharArray(), Temp);

// Saving the data

MyFileKeyStoreManager.saveKeyStore(MyKeyStore, MyKeyStorePassword.toCharArray());

// Reloading the KeyStore

MyKeyStore = MyFileKeyStoreManager.loadKeyStore(MyKeyStorePassword.toCharArray());

// Retrieving Certificate

X509Certificate MyCertificate = (X509Certificate)

MyKeyStore.getCertificate(PID.toString());

if (MyCertificate==null) {

Tools.PopInformationMessage(Name, "X509 Certificate CANNOT be retrieved");

} else {

Tools.PopInformationMessage(Name, "X509 Certificate can be retrieved");

System.out.println(MyCertificate.toString());

}

// Retrieving private key

PrivateKey MyPrivateKey = (PrivateKey) MyKeyStore.getKey(PID.toString(),

MyPrivateKeyPassword.toCharArray());

if (MyPrivateKey==null) {

Tools.PopInformationMessage(Name, "Private key CANNOT be retrieved");

} else {

Tools.PopInformationMessage(Name, "Private key can be retrieved");

System.out.println(MyPrivateKey.toString());

}

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting the keystore

MyNetworkConfigurator.setKeyStoreLocation(MyKeyStoreFile.toURI());

MyNetworkConfigurator.setPassword(MyKeyStorePassword);

Using JXSE Private Keys, Certificates & KeyStores - 208

// Starting the network

PeerGroup MyNetPeerGroup = MyNetworkManager.startNetwork();

// Checking membership implementation

MembershipService NPGMembership = MyNetPeerGroup.getMembershipService();

Tools.PopInformationMessage(Name, "NetPeerGroup membership implementation:\n"

+ NPGMembership.getClass().getSimpleName());

// Creating a child group with PSE

PeerGroup ChildPeerGroup = MyNetPeerGroup.newGroup(

PsePeerGroupID,

createAllPurposePeerGroupWithPSEModuleImplAdv(),

PsePeerGroupName,

"Checking PSE..."

);

if (Module.START_OK != ChildPeerGroup.startApp(new String[0]))

System.err.println("Cannot start PSE peergroup");

// Checking membership implementation

MembershipService ChildGroupMembership = ChildPeerGroup.getMembershipService();

Tools.PopInformationMessage(Name, "Child group membership implementation:\n"

+ ChildGroupMembership.getClass().getSimpleName());

// Joining the peer group

AuthenticationCredential MyAuthenticationCredit = new

AuthenticationCredential( MyNetPeerGroup, "StringAuthentication", null );

StringAuthenticator MyStringAuthenticator = (StringAuthenticator)

ChildGroupMembership.apply(MyAuthenticationCredit);

MyStringAuthenticator.setAuth1_KeyStorePassword(MyKeyStorePassword);

MyStringAuthenticator.setAuth2Identity(PID);

MyStringAuthenticator.setAuth3_IdentityPassword(MyPrivateKeyPassword);

Credential MyCredential = null;

if (MyStringAuthenticator.isReadyForJoin()) {

MyCredential = ChildGroupMembership.join(MyStringAuthenticator);

}

if (MyCredential!=null) {

Tools.PopInformationMessage(Name, "Credentials created successfully");

} else {

Tools.PopInformationMessage(Name, "Credentials NOT created successfully");

}

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (NoSuchAlgorithmException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (UnrecoverableKeyException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (NoSuchProviderException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (KeyStoreException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IOException Ex) {

Using JXSE Private Keys, Certificates & KeyStores - 209

Tools.PopErrorMessage(Name, Ex.toString());

} catch (ProtocolNotSupportedException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

public static ModuleImplAdvertisement createAllPurposePeerGroupWithPSEModuleImplAdv() {

ModuleImplAdvertisement implAdv = CompatibilityUtils.createModuleImplAdvertisement(

PeerGroup.allPurposePeerGroupSpecID, StdPeerGroup.class.getName(),

"General Purpose Peer Group with PSE Implementation");

// Create the service list for the group.

StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv();

// set the services

paramAdv.addService(PeerGroup.endpointClassID, PeerGroup.refEndpointSpecID);

paramAdv.addService(PeerGroup.resolverClassID, PeerGroup.refResolverSpecID);

paramAdv.addService(PeerGroup.membershipClassID, PSEMembershipService.pseMembershipSpecID);

paramAdv.addService(PeerGroup.accessClassID, PSEAccessService.PSE_ACCESS_SPEC_ID);

// standard services

paramAdv.addService(PeerGroup.discoveryClassID, PeerGroup.refDiscoverySpecID);

paramAdv.addService(PeerGroup.rendezvousClassID, PeerGroup.refRendezvousSpecID);

paramAdv.addService(PeerGroup.pipeClassID, PeerGroup.refPipeSpecID);

paramAdv.addService(PeerGroup.peerinfoClassID, PeerGroup.refPeerinfoSpecID);

paramAdv.addService(PeerGroup.contentClassID, ContentServiceImpl.MODULE_SPEC_ID);

// Insert the newParamAdv in implAdv

XMLElement paramElement = (XMLElement) paramAdv.getDocument(MimeMediaType.XMLUTF8);

implAdv.setParam(paramElement);

return implAdv;

}

}

Example 620 – Custom PSE Peer Group & Joining

This example is performing the following:

1. Just like in the previous example, we create a keystore and load it with a X509 certificateand a private key.

2. Then, we create a custom PSE peer group using the same method as for a non-PSE peergroup. Notice that the module implementation advertisement references the PSE mem-bership ID and the PSE access service.

3. Next, we run the process to join the PSE peergroup.

Warning:Warning:Warning:Warning: the PSE access service implementation is still in experimental mode.

Simple Pipe Communication

Pipes and the Pipe Service are some of the most important features of JXTA and JXSE. They are

Using JXSE Simple Pipe Communication - 210

the natural means for peers to exchange end user messages. However, most developers willrarely (if ever) use these simple pipes in their software application. They will use other toolsprovided by JXSE: bidirectional pipes and JXTA sockets.

The code example presented in this section is a 2-in-1 example. With a single pair of peers, wewill show how to run the 2 types of JXTA pipes: UnicastType and PropagateType.

Chandra, The Rendezvous Listening to Messages

The following is the code used for Chandra, a rendezvous peer that will listen to messages com-ing from a pipe:

...

public class RendezVous_Chandra_Receiving_Messages implements PipeMsgListener {

// PipeService.UnicastType or PipeService.UnicastSecureType or PipeService.PropagateType

public static final String PipeType = PipeService.UnicastType;

// Static attributes

public static final String Name = "RendezVous Chandra, Receiving Messages";

public static final int TcpPort = 9722;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("."

+ System.getProperty("file.separator") + Name);

// Catching messages

public void pipeMsgEvent(PipeMsgEvent PME) {

// We received a message

Message ReceivedMessage = PME.getMessage();

String TheText = ReceivedMessage.getMessageElement("DummyNameSpace",

"HelloElement").toString();

// Notifying the user

Tools.PopInformationMessage(Name, "Received message:\n\n" + TheText);

}

public static PipeAdvertisement GetPipeAdvertisement() {

// Creating a Pipe Advertisement

PipeAdvertisement MyPipeAdvertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

PipeID MyPipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID, Name.getBytes());

MyPipeAdvertisement.setPipeID(MyPipeID);

MyPipeAdvertisement.setType(PipeType);

MyPipeAdvertisement.setName("Test Pipe");

MyPipeAdvertisement.setDescription("Created by " + Name);

return MyPipeAdvertisement;

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(

Using JXSE Simple Pipe Communication - 211

NetworkManager.ConfigMode.RENDEZVOUS, Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Saving the configuration

MyNetworkConfigurator.save();

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Retrieving the PSE membership service

MembershipService MyMembershipService = NetPeerGroup.getMembershipService();

// Waiting for other peers to connect to JXTA

Tools.PopInformationMessage(Name, "Waiting for other peers to connect to JXTA");

// Creating an input pipe

PipeService MyPipeService = NetPeerGroup.getPipeService();

MyPipeService.createInputPipe(GetPipeAdvertisement(),

new RendezVous_Chandra_Receiving_Messages());

// Displaying pipe advertisement to identify potential compilation issues

System.out.println(

RendezVous_Chandra_Receiving_Messages.GetPipeAdvertisement().toString());

// Going to sleep for some time

Tools.GoToSleep(60000);

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Resigning all credentials

MyMembershipService.resign();

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Chandra, the Rendezvous Listening to Messages

Chandra implements the PipeMsgListener interface which requires implementing the pipeMs-

gEvent(...) method. This method is necessary to handle messages received by a peer from a

pipe. For the sake of our example, it also implements a GetPipeAdvertisement(...) method

Using JXSE Simple Pipe Communication - 212

to retrieve the pipe advertisement that will be used by our peers who will communicate over apipe.

Chandra is performing the following operations:

1. We provide the user with an opportunity to erase any existing configuration.

2. Before we start the JXTA network, we set several configuration parameters in the Net-

workConfigurator.

3. We start Chandra as a rendezvous.

4. We wait for other peers to connect.

5. Once the user clicks OK on the displayed box, we create the input pipe and provide alistener that will be called each time a messaged is received. This listener will display thereceived message to the user.

6. We also print the pipe advertisement (the reason for this will be described further).

7. We sleep for 60 seconds. This will give the other peer enough time to send its message.

8. We display connected peers.

9. We stop the JXTA network.

Dimitri, The Edge Sending Messages

The following is the code used for Dimitri, an edge peer that sends a message to Chandra via apipe:

...

public class Edge_Dimitri_Sending_Messages implements OutputPipeListener {

public static final String Name = "Edge Dimitri, Sending Messages";

public static final int TcpPort = 9723;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("."

+ System.getProperty("file.separator") + Name);

// Catching connections to the pipe

public void outputPipeEvent(OutputPipeEvent OPE) {

try {

// Notifying the user

Tools.PopInformationMessage(Name,

"Someone connected to the pipe, sending hello message!");

// Retrieving the output pipe to the peer who connected to the input end

OutputPipe MyOutputPipe = OPE.getOutputPipe();

// Creating a Hello message !!!

Message MyMessage = new Message();

Using JXSE Simple Pipe Communication - 213

StringMessageElement MyStringMessageElement = new StringMessageElement("HelloElement",

"Hello from " + Name, null);

MyMessage.addMessageElement("DummyNameSpace", MyStringMessageElement);

// Sending the message

MyOutputPipe.send(MyMessage);

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Jack should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":"

+ RendezVous_Chandra_Receiving_Messages.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Saving the configuration

MyNetworkConfigurator.save();

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous connection with\n"

+ RendezVous_Chandra_Receiving_Messages.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Creating an ouput pipe

PipeService MyPipeService = NetPeerGroup.getPipeService();

MyPipeService.createOutputPipe(

RendezVous_Chandra_Receiving_Messages.GetPipeAdvertisement(),

new Edge_Dimitri_Sending_Messages());

// Displaying pipe advertisement to identify potential compilation issues

System.out.println(

RendezVous_Chandra_Receiving_Messages.GetPipeAdvertisement().toString());

// Going to sleep for some time

Tools.GoToSleep(60000);

Using JXSE Simple Pipe Communication - 214

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Dimitri, the Edge Sending Messages

Dimitri implements the OutputPipeListener interface which requires implementing the out-

putPipeEvent(...) method. This method is invoked each time an input pipe has been located.

This peer can then invoke the corresponding output pipe and send a message through it.

Dimitri is performing the following operations:

1. We provide the user with an opportunity to erase any existing configuration.

2. Before we start the JXTA network, we set several configuration parameters in the Net-

workConfigurator. This includes setting Chandra as a rendezvous seed.

3. We start Dimitri as an edge and wait until it connects to Chandra. We display a messagenotifying the connection to the rendezvous (or not).

4. We create the output pipe and provide a listener that will be called each time an input pipefor the given pipe advertisement is detected. This listener will then send a simple hellomessage via the corresponding output pipe.

5. We also print the pipe advertisement (the reason for this will be described further).

6. We sleep for 60 seconds.

7. We stop the JXTA network.

Running The Example

In order to establish a successful communication between Chandra and Dimitri, the following pro-cedure must be followed precisely. Failing to do so will result in wrong results or unexpected be-havior.

Using JXSE Simple Pipe Communication - 215

1. To chose the type of pipe (PipeService.UnicastType or PipeService.Propagat-

eType) that will be used between Chandra and Dimitri, modify the value of the PipeType

static attribute in the code of Chandra.

2. Recompile both Chandra and Dimitri. If you fail to do so, the example will not work. Bothpeers print the pipe advertisement they are using. If you have modified the PipeType and

failed to recompile both peers, you will notice a difference in the pipe type used by bothpeers. This can explain why the example is not working.

3. Start Chandra and wait until it starts waiting for others peer to connect (delete any existingconfiguration).

4. Start Dimitri and wait until it displays the ID of the rendezvous peer it has managed toconnect to (erase any existing configuration and allow Chandra to be a rendezvous seed).

5. Go back to Chandra and click OK on the box indicating that she is waiting for other peersto connect.

6. Go back to Dimitri and click OK on the box displaying the ID of the rendezvous peer it hasconnected to.

7. Click OK on boxes which will be displayed by Dimitri until he indicates that someone hasconnected to the pipe. Click OK to have him send a message. Sometimes, this messagecan appear twice.

8. Pretty quickly too, Chandra gets the message from Dimitri and displays it.

9. Click OK boxes until both Chandra and Dimitri stop their connection to the JXTA network.

This example describes how simple pipes can be used to communicate between peers. A rendez-vous connection between both peers is necessary to make sure both peers obtain routes to eachother. For the sake of clarity and simplicity, we did not have one of the peer fetch the pipe advert-isement from the other peer, which is an artificial situation. In reality, that would be necessary inorder to establish a pipe connection.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: Chandra and Dimitri are the leaders of two tribes that have decided to establishtrading routes between them. They have given a distinctive sign/name to their trading route. Thismeans that if one of them, or both, decide to move from one island to the other, the trading routeremains and they will still be able to use it to exchange goods.

One type of trading route they have decided to create includes a secret code system that prevents

Using JXSE Simple Pipe Communication - 216

any pirates from understanding the dried leaf messages they may try to steal from each other.

Unicast Secure Pipes

To operate unicast secure pipes, one should create a PSE group and join it. Then, a modified ver-sion of Chandra and Dimitri can be implemented with PipeService.UnicastSecure pipes. All

operations should be performed from the PSE group.

Bidirectional Pipe Communication

The example we have shown above enables a one way communication between two peers. Inpractice, bidirectional communication is often necessary between many peers. One could imple-ment two simple pipes between each peer to achieve this purpose, but JXSE offers bidirectionalpipes59.

Adelaide, The RendezVous At One End

The following is the code used for Adelaide, a rendezvous peer at one end of the bidirectionalpipe:

...

public class RendezVous_Adelaide_At_One_End implements PipeMsgListener {

// Static attributes

public static final String Name = "RendezVous Adelaide, at one end";

public static final int TcpPort = 9726;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public void pipeMsgEvent(PipeMsgEvent PME) {

// We received a message

Message ReceivedMessage = PME.getMessage();

String TheText = ReceivedMessage.getMessageElement("DummyNameSpace",

"HelloElement").toString();

// Notifying the user

Tools.PopInformationMessage(Name, "Received message:\n\n" + TheText);

}

public static PipeAdvertisement GetPipeAdvertisement() {

// Creating a Pipe Advertisement

PipeAdvertisement MyPipeAdvertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

PipeID MyPipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID, Name.getBytes());

MyPipeAdvertisement.setPipeID(MyPipeID);

MyPipeAdvertisement.setType(PipeService.UnicastType);

MyPipeAdvertisement.setName("Test BidiPipe");

MyPipeAdvertisement.setDescription("Created by " + Name);

59 There is a lurking bug in JXTA release 2.5 regarding connectivity behind NATs.

Using JXSE Bidirectional Pipe Communication - 217

return MyPipeAdvertisement;

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of the network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Waiting for other peers to connect to JXTA

Tools.PopInformationMessage(Name, "Waiting for other peers to connect to JXTA");

// Preparing the listener and creating the BiDiPipe

PipeMsgListener MyListener = new RendezVous_Adelaide_At_One_End();

JxtaServerPipe MyBiDiPipeServer = new JxtaServerPipe(NetPeerGroup,

GetPipeAdvertisement());

Tools.PopInformationMessage(Name, "Bidirectional pipe server created!");

MyBiDiPipeServer.setPipeTimeout(30000);

JxtaBiDiPipe MyBiDiPipe = MyBiDiPipeServer.accept();

if (MyBidiPipe != null) {

MyBiDiPipe.setMessageListener(MyListener);

Tools.PopInformationMessage(Name, "Bidirectional pipe connection established!");

// Sending a hello message !!!

Message MyMessage = new Message();

StringMessageElement MyStringMessageElement = new StringMessageElement(

"HelloElement", “Hello from " + Name, null);

MyMessage.addMessageElement("DummyNameSpace", MyStringMessageElement);

MyBiDiPipe.sendMessage(MyMessage);

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Sending a goodbye message !!!

MyMessage = new Message();

MyStringMessageElement = new StringMessageElement("HelloElement", "Goodbye from "

+ Name, null);

MyMessage.addMessageElement("DummyNameSpace", MyStringMessageElement);

MyBiDiPipe.sendMessage(MyMessage);

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Closing the bidi pipe

MyBiDiPipe.close();

Using JXSE Bidirectional Pipe Communication - 218

}

// Closing the bidi pipe server

MyBiDiPipe.close();

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Adelaide, The Rendezvous At One End

Adelaide is performing the following:

1. Adelaide implements the PipeMsgListener interface. This requires implementing the

pipeMsgEvent method to handle messages which will be received via the bidirectionalpipe.

2. For the sake of simplicity, Adelaide also implements a static method to retrieve the pipeadvertisement to be used by both peers to establish the bidirectional pipe.

3. We set some context information via static attributes as usual.

4. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

5. We start Adelaide as a rendezvous and wait until other peers connect to it.

6. We create a bidirectional pipe server which will be able to accept the request for bidirec-tional connections from other peers. We notify the user.

7. We wait for a maximum of 30 seconds for a bidirectional connection request from otherpeers.

8. If such a connection is established, we register a listener to collect messages sent by theother party.

a) We notify the user that a bidirectional connection has been established.

Using JXSE Bidirectional Pipe Communication - 219

b) We send a hello message to the other party and sleep for 10 seconds.

c) We send a goodbye message to the other party and sleep for 10 seconds.

d) We close the bidirectional pipe.

9. We stop the bidirectional pipe server.

10. We stop the JXTA network after displaying the list of connected peers.

Quinisela, The Edge At The Other End

The following is the code used for Quinisela, an edge peer at the other end of the bidirectionalpipe:

...

public class Edge_Quinisela_At_The_Other_End implements PipeMsgListener {

public static final String Name = "Edge Quinisela, at the other end";

public static final int TcpPort = 9725;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public void pipeMsgEvent(PipeMsgEvent PME) {

// We received a message

Message ReceivedMessage = PME.getMessage();

String TheText = ReceivedMessage.getMessageElement("DummyNameSpace",

"HelloElement").toString();

// Notifying the user

Tools.PopInformationMessage(Name, "Received message:\n\n" + TheText);

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Adelaide_At_One_End should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":"

+ RendezVous_Adelaide_At_One_End.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

Using JXSE Bidirectional Pipe Communication - 220

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous connection with\n"

+ RendezVous_Adelaide_At_One_End.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Preparing the listener and Creating the BiDiPipe

PipeMsgListener MyListener = new Edge_Quinisela_At_The_Other_End();

JxtaBiDiPipe MyBiDiPipe = new JxtaBiDiPipe(NetPeerGroup,

RendezVous_Adelaide_At_One_End.GetPipeAdvertisement(), 30000, MyListener);

Tools.PopInformationMessage(Name, "Bidirectional pipe created!");

// Sending a hello message !!!

Message MyMessage = new Message();

StringMessageElement MyStringMessageElement = new StringMessageElement("HelloElement",

"Hello from " + Name, null);

MyMessage.addMessageElement("DummyNameSpace", MyStringMessageElement);

MyBiDiPipe.sendMessage(MyMessage);

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Sending a goodbye message !!!

MyMessage = new Message();

MyStringMessageElement = new StringMessageElement("HelloElement", "Goodbye from " +

Name, null);

MyMessage.addMessageElement("DummyNameSpace", MyStringMessageElement);

MyBiDiPipe.sendMessage(MyMessage);

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Quinisela, the Edge at the Other End

Quinisela is performing the following:

1. Quinisela implements the PipeMsgListener interface. This requires implementing the

Using JXSE Bidirectional Pipe Communication - 221

pipeMsgEvent method to handle messages which will be received via the bidirectional

pipe.

2. We set some context information via static attributes as usual.

3. We provide the user with an opportunity to erase any existing configuration and to set Ad-elaide as a rendezvous. Usual NetworkConfigurator parameters are set.

4. We start Quinisela as an edge and wait until it connects to a rendezvous for maximum 2minutes.

5. We create a bidirectional pipe and wait for maximum 30 seconds for a connection with an-other peer.

6. If such a connection is established:

a) We notify the user that a bidirectional connection has been established.

b) We send a hello message to the other party and sleep for 10 seconds.

c) We send a goodbye message to the other party and sleep for 10 seconds.

7. We close the bidirectional pipe.

8. We stop the JXTA network.

Running The Example

In order to establish a successful communication between Adelaide and Quinisela, the followingprocedure must be performed:

1. Start Adelaide the rendezvous until it waits for connections from other peers (delete anyexisting configuration).

2. Start Quinisela until it manages to connect to Adelaide (delete any existing configurationand allow Adelaide as a rendezvous seed).

3. Go back to Adelaide and click OK on the box mentioning she is waiting for peers to con-nect.

4. Go back to Quinisela and click OK on his box.

5. Click OK on the next boxes showed by Adelaide and Quinisela (i.e., confirmations thatthey have managed to establish a bidirectional connection).

6. Click on OK on both sides to see the messages sent by each to the other...

Using JXSE Bidirectional Pipe Communication - 222

7. ...until both stop the JXTA network.

For the sake of simplicity, we did not have one of the peers fetch the advertisement from the oth-er, although in reality, most software applications would do so. Typically, every peer should run itsown bidirectional pipe server to allow other peers to establish bidirectional communications.

A very interesting feature of bidirectional pipes is the getRemotePeerAdvertisement(...)

method which allows one peer to know about the peer on the other side. This was not possiblewith simple pipes. Another interesting method is the connect(...) method which can be used

to try to establish a connection with a specific peer.

The last feature which makes bidirectional pipes very interesting is that unlike unicast pipes, theyare reliable, assuming that sent messages do not exceed 64K in size when received by the otherparty (do not forget the Matryoshka approach of messages in JXTA when they pass from one pro-tocol to the other).

JXTA Socket & Socket Server

JXTA sockets are like Java sockets. They allow peers to exchange streams of bytes and data-gram packets. The JXTA socket and JXTA Socket Server operate similarly to bidirectional pipes.

Lidong, The Rendezvous And JXTA Socket Server

The following is the code used for Lidong, a rendezvous peer acting as a JXTA socket server:

...

public class RendezVous_Lidong_The_JXTA_Socket_Server {

// Static attributes

public static final String Name = "RendezVous Lidong, the JXTA socket server";

public static final int TcpPort = 9731;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static PipeAdvertisement GetPipeAdvertisement() {

// Creating a Pipe Advertisement

PipeAdvertisement MyPipeAdvertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

PipeID MyPipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID, Name.getBytes());

MyPipeAdvertisement.setPipeID(MyPipeID);

MyPipeAdvertisement.setType(PipeService.UnicastType);

MyPipeAdvertisement.setName("Test Socket");

MyPipeAdvertisement.setDescription("Created by " + Name);

return MyPipeAdvertisement;

}

public static void main(String[] args) {

Using JXSE JXTA Socket & Socket Server - 223

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Waiting for other peers to connect to JXTA

Tools.PopInformationMessage(Name, "Waiting for other peers to connect to JXTA");

// Creating the JXTA socket server

int BackLog = 20;

int Timeout = 30000;

JxtaServerSocket MyJXTAServerSocket = new JxtaServerSocket(NetPeerGroup,

GetPipeAdvertisement(), BackLog, Timeout);

Tools.PopInformationMessage(Name, "JXTA socket server created");

Socket MySocket = MyJXTAServerSocket.accept();

if (MySocket != null) {

Tools.PopInformationMessage(Name, "Socket connection established");

// Retrieving the input streams

InputStream MyInputStream = MySocket.getInputStream();

DataInput MyDataInput = new DataInputStream(MyInputStream);

String IncomingMessage = MyDataInput.readUTF();

Tools.PopInformationMessage(Name, "Received socket message:\n\n" +

IncomingMessage);

// Retrieving the output stream

OutputStream MyOutputStream = MySocket.getOutputStream();

DataOutput MyDataOutput = new DataOutputStream(MyOutputStream);

// Sending a message

MyDataOutput.writeUTF("Hello from " + Name);

MyOutputStream.flush();

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Closing the streams

MyOutputStream.close();

MyInputStream.close();

// Closing the socket

MySocket.close();

}

// Closing the JXTA socket server

MyJXTAServerSocket.close();

Using JXSE JXTA Socket & Socket Server - 224

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Lidong, The Rendezvous and JXTA Socket Server

Lidong is performing the following:

1. For the sake of simplicity, Lidong implements a static method to retrieve the pipe advert-isement that will be used by both peers to establish the socket connection.

2. We set some context information via static attributes as usual.

3. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

4. We start Lidong as a rendezvous and wait until other peers connect to it.

5. We create a JXTA socket server and set the maximum delay for a connection to 30seconds. We notify the user.

6. We wait for a socket connection from other peers.

7. If such a connection is established, we notify the user.

a) We try to read a message from the JXTA socket and display it to the user when weget it.

b) We send a Hello message to the other party and flush the OutputStream. This is

necessary, otherwise JXTA may wait for more calls for information to be sent beforeactually sending the message to other peers. If we did not invoke the flush() meth-

od, the other party would most probably lock when trying to read data from the JXTAsocket.

c) We close the streams and the sockets.

Using JXSE JXTA Socket & Socket Server - 225

8. We close the JXTA socket server.

9. We stop the JXTA network after displaying the list of connected peers.

Ayrton, The Edge And JXTA Socket

The following is the code used for Ayrton, an edge peer creating a JXTA socket and connecting tothe JXTA Socket server:

...

public class Edge_Ayrton_The_JXTA_Socket {

public static final String Name = "Edge Ayrton, the JXTA socket";

public static final int TcpPort = 9730;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Lidong_The_JXTA_Socket_Server should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":" +

RendezVous_Lidong_The_JXTA_Socket_Server.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous connection with\n"

+ RendezVous_Lidong_The_JXTA_Socket_Server.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Creating the JXTA socket

JxtaSocket MySocket = new JxtaSocket(NetPeerGroup, null,

RendezVous_Lidong_The_JXTA_Socket_Server.GetPipeAdvertisement(),

30000, true);

Using JXSE JXTA Socket & Socket Server - 226

if (MySocket!=null) {

// Retrieving the output stream

OutputStream MyOutputStream = MySocket.getOutputStream();

DataOutput MyDataOutput = new DataOutputStream(MyOutputStream);

// Sending a message

MyDataOutput.writeUTF("Hello from " + Name);

MyOutputStream.flush();

// Retrieving the input streams

InputStream MyInputStream = MySocket.getInputStream();

DataInput MyDataInput = new DataInputStream(MyInputStream);

String IncomingMessage = MyDataInput.readUTF();

Tools.PopInformationMessage(Name, "Received socket message:\n\n"

+ IncomingMessage);

// Sleeping for 10 seconds

Tools.GoToSleep(10000);

// Closing the streams

MyOutputStream.close();

MyInputStream.close();

// Closing the socket

MySocket.close();

}

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Ayrton, The Edge and JXTA Socket

Ayrton is performing the following:

1. We set some context information via static attributes as usual.

2. We provide the user with an opportunity to erase any existing configuration and to setLidong as a rendezvous. Usual NetworkConfigurator parameters are set.

3. We start Ayrton as an edge and wait until it connects to a rendezvous for maximum 2minutes.

4. We create a JXTA socket using the common pipe advertisement with Lidong. We set themaximum delay for a connection to 30 seconds.

Using JXSE JXTA Socket & Socket Server - 227

5. If a connection is established:

a) We send a hello message to the other party. We flush the OutputStream to make

sure the other party won't block when trying to read data from the socket.

b) We try to read a message from the other party and display it to the user.

c) We close the streams and the JXTA socket.

6. We stop the JXTA network.

Running The Example

In order to establish a successful communication between Lidong and Ayrton, the following pro-cedure must be performed:

1. Start Lidong the rendezvous until it waits for connections from other peers (delete any ex-isting configuration).

2. Start Ayrton until he manages to connect to Lidong (delete any existing configuration andallow Lidong as a rendezvous seed).

3. Go back to Lidong and click OK on the box mentioning he is waiting for peers to connect.A message indicating that he has created a JXTA socket server is displayed.

4. Go back to Ayrton and click OK on the box mentioning that he has connected to a rendez-vous.

5. Go back to Lidong and click OK on the box mentioning that he has created a JXTA socketserver.

6. Pretty quickly, Lidong will mention that a JXTA socket connection has been established.

7. By clicking on OK from both sides, hello messages exchanged by both peers will be dis-played.

8. Carry on clicking OK on boxes until both peers stop the JXTA network.

As in previous examples, we did not have one of the peer fetch the advertisement from the other.Just as for bidirectional pipes, most peers will run their JXTA servers to accept socket connectionsfrom others.

Using JXSE JXTA Socket & Socket Server - 228

JXTA Multicast Socket

JXTA multicast sockets allow peers in peer groups to exchange datagrams with other peers of thesame peer group connected via a common JXTA multicast socket.

Hans, The Rendezvous, A Multicast Participant

The following is the code used for Hans, a rendezvous peer connected to a JXTA multicast sock-et:

...

public class RendezVous_Hans_A_Multicast_Participant {

// Static attributes

public static final String Name = "RendezVous Hans, a JXTA multicast socket participant";

public static final int TcpPort = 9731;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static PipeAdvertisement GetPipeAdvertisement() {

// Creating a Pipe Advertisement

PipeAdvertisement MyPipeAdvertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

PipeID MyPipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID, Name.getBytes());

MyPipeAdvertisement.setPipeID(MyPipeID);

MyPipeAdvertisement.setType(PipeService.PropagateType);

MyPipeAdvertisement.setName("Test Multicast");

MyPipeAdvertisement.setDescription("Created by " + Name);

return MyPipeAdvertisement;

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

Using JXSE JXTA Multicast Socket - 229

// Waiting for other peers to connect to JXTA

Tools.PopInformationMessage(Name, "Waiting for other peers to connect to JXTA");

// Creating the JXTA socket server

JxtaMulticastSocket MyMulticastSocket = new JxtaMulticastSocket(

NetPeerGroup, GetPipeAdvertisement());

Tools.PopInformationMessage(Name, "JXTA multicast socket created");

// Creating a datagram and sending it

String Message = "Hello from " + Name;

DatagramPacket MyDatagramPacket = new DatagramPacket(Message.getBytes(),

Message.length());

Tools.PopInformationMessage(Name, "Multicasting following message:\n\n" + Message);

MyMulticastSocket.send(MyDatagramPacket);

// Sleeping a little (10 seconds)

Tools.GoToSleep(10000);

// Closing the JXTA socket

MyMulticastSocket.close();

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Hans, The Rendezvous, a Multicast Participant

Hans is performing the following:

1. As in previous pipe examples, Hans implements a static method to retrieve the pipe ad-vertisement that will be used by both peers to establish a multicast connection.

2. We set some context information via static attributes as usual.

3. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

4. We start Hans as a rendezvous and wait until other peers connect to it.

5. We create a JXTA multicast socket and notify the user.

6. We create a hello datagram message, notify the user and send it.

7. We go to sleep for 10 seconds and close the multicast socket.

8. We stop the JXTA network after displaying the list of connected peers.

Using JXSE JXTA Multicast Socket - 230

Teyacapan, The Edge, Another Multicast Participant

The following is the code used for Teyacapan, an edge peer also connected to a JXTA multicastsocket:

...

public class Edge_Teyacapan_Another_Multicast_Participant {

public static final String Name = "Edge Teyacapan, another JXTA multicast socket participant";

public static final int TcpPort = 9735;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous_Hans_A_Multicast_Participant should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":" +

RendezVous_Hans_A_Multicast_Participant.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous connection with\n"

+ RendezVous_Hans_A_Multicast_Participant.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Creating the JXTA socket server

JxtaMulticastSocket MyMulticastSocket = new JxtaMulticastSocket(NetPeerGroup,

RendezVous_Hans_A_Multicast_Participant.GetPipeAdvertisement());

Tools.PopInformationMessage(Name, "JXTA multicast socket created");

// Reading a datagram

byte[] MyBuffer = new byte[1000];

DatagramPacket MyDatagramPacket = new DatagramPacket(MyBuffer, MyBuffer.length);

MyMulticastSocket.receive(MyDatagramPacket);

Using JXSE JXTA Multicast Socket - 231

String MyString = new String(MyDatagramPacket.getData(), 0,

MyDatagramPacket.getLength());

Tools.PopInformationMessage(Name, "Received multicast message:\n\n" + MyString);

//

// REM: To return a message to the sender only:

//

// String MyResponse = "Response";

// DatagramPacket DatagramReponse = new DatagramPacket(MyResponse.getBytes(),

// MyResponse.length());

//

// DatagramResponse.setAddress(MyDatagramPacket);

// MyMulticastSocket.send(DatagramResponse);

//

// Closing the JXTA socket

MyMulticastSocket.close();

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Teyacapan, The Edge, Another Multicast Participant

Teyacapan is performing the following:

1. We set some context information via static attributes as usual.

2. We provide the user with an opportunity to erase any existing configuration and to setHans as a rendezvous. Usual NetworkConfigurator parameters are set.

3. We start Teyacapan as an edge and wait until she connects to a rendezvous for maxim-um 2 minutes.

4. We create a JXTA multicast socket using the common pipe advertisement with Hans.

5. We read any incoming message and display it to the user. We also explain in commenthow a message could be returned to the peer who has sent the received message.

6. We close the JXTA multicast socket.

7. We stop the JXTA network.

Using JXSE JXTA Multicast Socket - 232

Running The Example

In order run the JXTA multicast socket example successfully, the following procedure must be per-formed:

1. Start Hans the rendezvous until he waits for connections from other peers (delete any ex-isting configuration).

2. Start Teyacapan until she manages to connect to Hans (delete any existing configurationand allow Hans as a rendezvous seed).

3. Go back to Hans and click OK on the box mentioning he is waiting for peers to connect. Amessage indicating that he has created a JXTA multicast socket is displayed.

4. Go back to Teyacapan and click OK on the box mentioning that she has connected to arendezvous. A message indicating that she has created a JXTA multicast socket is dis-played.

5. Go back to Hans and click OK on the box mentioning that he has created a JXTA multic-ast socket.

6. Pretty quickly, Hans will mention that he is going to multicast a message. Click on OK.

7. Teyacapan will display the received multicast message.

8. Carry on clicking OK on boxes until both peers stop the JXTA network.

As in previous examples, we did not have one of the peers fetch the advertisement from the otherpeer. More Teyacapan peers can be added to this example to explore the multicasting aspect ofsending messages via a JXTA multicast socket.

Implementing A Customized Service

Introduction

We are going to describe how to implement an astrology service, to have it loaded by an astrolo-ger and to have a customer request a prediction from that astrologer and to get an answer. Wewill start by describing how to generate module IDs before the astrology service itself and we willfinish with the description of peers.

Example 700 – Creating Module IDs

The following code describes how to create module IDs:

Using JXSE Implementing A Customized Service - 233

...

public class _700_Module_IDs_Creation_Example {

public static final String Name = "Example 700";

public static void main(String[] args) {

// Creating a new random module class ID

ModuleClassID MyModuleClassID = (ModuleClassID) IDFactory.newModuleClassID();

// Creating a new random module specification ID

ModuleSpecID MyModuleSpecID = IDFactory.newModuleSpecID(MyModuleClassID);

// Printing IDs

System.out.println(MyModuleClassID.toURI().toString() + "\n");

System.out.println(MyModuleSpecID.toURI().toString() + "\n");

}

}

Example 700 – Creating Module IDs

One should not forget that in JXSE, a service is a type of module. Three types of advertisementsdescribe modules in JXTA, but there are only two types of module IDs: ModuleClassID and

ModuleSpecID. The latter is created based on the former. These IDs are required in order to cre-

ate module advertisements.

Example 710 – Astrology Service

The following code implements an astrology service:

...

public class _710_Astrology_Service_Example implements Service, Runnable {

// Static

public static final String Name = "Astrology Service";

public static final String NameSpace = "AstrologyService";

public static final String CustomerNameElement = "CustomerName";

public static final String BirthDateElement = "CustomerBirthDate";

public static final String BirthLocationElement = "CustomerBirthLocation";

public static final String PredictionElement = "Prediction";

public static final String MyModuleClassIDString =

"urn:jxta:uuid-F7A712D25D3047B88656FD706AEDE8DB05";

public static final String MyModuleSpecIDString =

"urn:jxta:uuid-F7A712D25D3047B88656FD706AEDE8DBC6A510B2026F4FD59A7DFA4F6712142506";

public static ModuleClassID MyModuleClassID = null;

public static ModuleSpecID MyModuleSpecID = null;

static {

try {

MyModuleClassID = ModuleClassID.create(new URI(MyModuleClassIDString));

MyModuleSpecID = ModuleSpecID.create(new URI(MyModuleSpecIDString));

} catch (Exception Ex) {

Using JXSE Implementing A Customized Service - 234

Tools.PopErrorMessage(Name, Ex.toString());

}

}

// Not static

private PeerGroup ThePeerGroup = null;

private ID TheID = null;

private ModuleImplAdv TheImplementationAdvertisement = null;

private JxtaServerPipe MyBiDiPipeServer = null;

public static void main(String[] args) {

// Dummy main method for compilation

}

public _710_Astrology_Service_Example() {

}

public static PipeAdvertisement GetPipeAdvertisement() {

// Creating a Pipe Advertisement

PipeAdvertisement MyPipeAdvertisement = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

PipeID MyPipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID, Name.getBytes());

MyPipeAdvertisement.setPipeID(MyPipeID);

MyPipeAdvertisement.setType(PipeService.UnicastType);

MyPipeAdvertisement.setName("Astrology Service Pipe");

MyPipeAdvertisement.setDescription("Created by " + Name);

return MyPipeAdvertisement;

}

public static ModuleSpecAdvertisement GetModuleSpecificationAdvertisement() {

ModuleSpecAdvertisement Result = (ModuleSpecAdvertisement)

AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType());

Result.setCreator("The Astrologers");

Result.setDescription("Astrology Service");

Result.setModuleSpecID(MyModuleSpecID);

Result.setVersion("1.0");

Result.setPipeAdvertisement(GetPipeAdvertisement());

return Result;

}

public static ModuleImplAdvertisement GetModuleImplementationAdvertisement() {

ModuleImplAdvertisement Result = (ModuleImplAdvertisement)

AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType());

// Setting parameters

Result.setDescription("Astrology Service");

Result.setModuleSpecID(MyModuleSpecID);

Result.setProvider(Name);

Result.setCode(_710_Astrology_Service_Example.class.getName());

// Setting compatibility & binding

Result.setCompat(StdPeerGroup.STD_COMPAT);

// Retrieving the location of the .jar file

JFileChooser MyFileChooser = new JFileChooser();

File SelectedFile = null;

Tools.PopInformationMessage(Name,

"Retrieving the implementation location of the astrology service");

Using JXSE Implementing A Customized Service - 235

int TheReturnedValue = MyFileChooser.showOpenDialog(null);

if (TheReturnedValue == JFileChooser.APPROVE_OPTION) {

SelectedFile = MyFileChooser.getSelectedFile();

}

if (SelectedFile==null) {

Tools.PopWarningMessage(Name, "No file selected");

} else {

Result.setUri(SelectedFile.toURI().toString());

}

return Result;

}

public Service getInterface() {

return this;

}

public Advertisement getImplAdvertisement() {

return TheImplementationAdvertisement;

}

public ID getID() {

return TheID;

}

public void init(PeerGroup InPG, ID InID, Advertisement InAdvertisement)

throws PeerGroupException {

// Initialization

ThePeerGroup = InPG;

TheID = InID;

TheImplementationAdvertisement = (ModuleImplAdv) InAdvertisement;

}

public int startApp(String[] arg0) {

try {

MyBiDiPipeServer = new JxtaServerPipe(ThePeerGroup, GetPipeAdvertisement(), 5000);

Thread thread = new Thread(this);

thread.start();

Tools.PopInformationMessage(Name, "Start Successful");

return START_OK;

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

Tools.PopInformationMessage(Name, "Start Unsuccessful");

return START_DISABLED;

}

}

public void run() {

while (MyBiDiPipeServer != null) {

try {

Using JXSE Implementing A Customized Service - 236

JxtaBiDiPipe MyBiDiPipe = this.MyBiDiPipeServer.accept();

if (MyBiDiPipe != null) {

// Processing customers

Thread thread = new Thread(new CustomerHandler(MyBiDiPipe));

thread.start();

}

} catch (SocketTimeoutException Ex) {

// We don't care if we get a timeout after 5 seconds

// We try to accept a connection again

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

public void stopApp() {

// Closing bidipipe server

if (MyBiDiPipeServer != null) {

try {

MyBiDiPipeServer.close();

MyBiDiPipeServer = null;

Tools.PopInformationMessage(Name, "Stop Successful");

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

private static class CustomerHandler implements Runnable, PipeMsgListener {

private JxtaBiDiPipe MyJxtaBiDiPipe = null;

CustomerHandler(JxtaBiDiPipe InPipe) {

MyJxtaBiDiPipe = InPipe;

MyJxtaBiDiPipe.setMessageListener(this);

}

public static final int ComputeHoroscopeHash(String InString) {

int Result = 0;

if (InString != null) {

for (int i=0;i<InString.length();i++) {

Result = Result + (int) InString.charAt(i);

}

}

// Returning result

return ( Result % 3 );

}

public void pipeMsgEvent(PipeMsgEvent event) {

try {

Using JXSE Implementing A Customized Service - 237

long PredictionHash = System.currentTimeMillis();

// Retrieve the message

Message MyMessage = event.getMessage();

MessageElement MyMessageElement = MyMessage.getMessageElement(NameSpace,

CustomerNameElement);

PredictionHash = PredictionHash +

ComputeHoroscopeHash(MyMessageElement.toString());

MyMessageElement = MyMessage.getMessageElement(NameSpace, BirthDateElement);

PredictionHash = PredictionHash +

ComputeHoroscopeHash(MyMessageElement.toString());

MyMessageElement = MyMessage.getMessageElement(NameSpace, BirthLocationElement);

PredictionHash = PredictionHash +

ComputeHoroscopeHash(MyMessageElement.toString());

PredictionHash = PredictionHash % 3;

String Prediction = "";

switch ((int)PredictionHash) {

case 0: Prediction = "You will be rich!"; break;

case 1: Prediction = "You will be famous!"; break;

default: Prediction = "You need to make more sacrifices to the Gods!";

}

// Sending answer

MyMessage = new Message();

StringMessageElement MyStringMessageElement =

new StringMessageElement(PredictionElement, Prediction, null);

MyMessage.addMessageElement(NameSpace, MyStringMessageElement);

MyJxtaBiDiPipe.sendMessage(MyMessage);

// Closing the connection

MyJxtaBiDiPipe.close();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

public void run() {

// The pipeMsgEvent will be called when necessary

}

}

}

Example 710 – Astrology Service

We will describe the code in several parts:

Static And Non-Static Attributes

The static attributes of the astrology service not only includes its name, but also the text element

Using JXSE Implementing A Customized Service - 238

names that will be used when the astrologer and the customer will communicate with messages.The ModuleClassID and ModuleSpecID are recreated from previously generated strings.

The non-static attributes include a couple of attributes that will be set at initialization, but most im-portantly, a JxtaServerPipe which will be used to communicate with customers.

Static Methods

We define some static methods to retrieve advertisements: GetPipeAdvertisement(), Get-

ModuleSpecificationAdvertisement() and GetModuleImplementationAdvertise-

ment(). The pipe advertisement method will be used by the astrologer and the customer to cre-

ate a bidirectional pipe communication. The other methods are required to generate the minimumset of advertisements necessary to run this example. Typically, one would also include a methodto generate a module class advertisement, but it has not been implemented here.

In order to create the module implementation advertisement, we ask the user to indicate wherethe .jar file corresponding to the implementation of the astrology service can be implemented.

We will come back to this later.

Static Class

We also define a static inner class called CustomerHandler to handle customers' requests for

predictions. Each time a request arrives via the JxtaServerPipe, a new instance of the class is

created and started in a separate thread. The prediction is computed based on the received in-formation and sent back to the customer. The thread and the class die automatically.

Implementation Of Interfaces

The astrology service implements the Service and Runnable interface. The Service interface

requires implementing a couple of methods to initiate, start and stop the service. The Runnable

interface is required to run the JxtaServerPipe in a separate thread to accept pipe connections

from customers.

Metaphorically:Metaphorically:Metaphorically:Metaphorically: A method to predict ones future has been written in a book that only astrologershave. Each time they open their shop, they have the copy of their book ready for consultation.

RendezVous Joe, The Astrologer

The following is the code used for Joe, a rendezvous peer running the astrology service:

Using JXSE Implementing A Customized Service - 239

...

public class RendezVous_Joe_The_Astrologer {

// Static attributes

public static final String Name = "RendezVous Joe, The Astrologer";

public static final int TcpPort = 9745;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(

NetworkManager.ConfigMode.RENDEZVOUS,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Loading the astrology service

Tools.PopInformationMessage(Name, "Loading the astrology service");

Module MyAstrologyModule = NetPeerGroup.loadModule(

_710_Astrology_Service_Example.MyModuleClassID,

_710_Astrology_Service_Example.GetModuleImplementationAdvertisement());

// Starting the astrology service

Tools.PopInformationMessage(Name, "Starting the astrology service");

MyAstrologyModule.startApp(new String[0]);

// Waiting for other peers to connect to JXTA

Tools.PopInformationMessage(Name, "Waiting for other peers to connect to JXTA");

// Ending the service

Tools.PopInformationMessage(Name, "Click OK to end the astrology service");

MyAstrologyModule.stopApp();

// Retrieving connected peers

Tools.popConnectedPeers(NetPeerGroup.getRendezVousService(), Name);

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (ProtocolNotSupportedException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Using JXSE Implementing A Customized Service - 240

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

RendezVous Joe, The Astrologer

Joe is performing the following:

1. We set some context information via static attributes as usual for rendezvous peers.

2. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

3. We start Joe as a rendezvous and wait for the user to load the astrology service.

4. Once the user clicked OK, we load the astrology service using the loadModule(...)

method from the net peer group. We provide its module implementation advertisement asa parameter. JXSE will retrieve the location of the .jar file corresponding to the service

from this advertisement and load it.

5. Remark:Remark:Remark:Remark: In our example, the user will retrieve .jar file from its local PC (or device), but

in reality, it will most probably be located somewhere on the Internet.

6. We start the astrology service and wait for other peers to connect to JXTA.

7. After clicking OK, the user is given an opportunity to control the stopping of the astrologyservice.

8. Next, we stop the JXTA network after displaying the list of connected peers.

Edge Jill, The Customer

The following is the code used for Jill, an edge peer consulting Joe, the astrologer:

...

public class Edge_Jill_The_Customer implements PipeMsgListener {

public static final String Name = "Edge Jill, The Customer";

public static final int TcpPort = 9746;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("." +

System.getProperty("file.separator") + Name);

public void pipeMsgEvent(PipeMsgEvent PME) {

// We received a message

Message ReceivedMessage = PME.getMessage();

String TheText = ReceivedMessage.getMessageElement(

_710_Astrology_Service_Example.NameSpace,

Using JXSE Implementing A Customized Service - 241

_710_Astrology_Service_Example.PredictionElement).toString();

// Notifying the user

Tools.PopInformationMessage(Name, "Received message:\n\n" + TheText);

}

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Checking if RendezVous Joe should be a seed

MyNetworkConfigurator.clearRendezvousSeeds();

String TheSeed = "tcp://" + InetAddress.getLocalHost().getHostAddress() + ":"

+ RendezVous_Joe_The_Astrologer.TcpPort;

Tools.CheckForRendezVousSeedAddition(Name, TheSeed, MyNetworkConfigurator);

// Setting Configuration

MyNetworkConfigurator.setTcpPort(TcpPort);

MyNetworkConfigurator.setTcpEnabled(true);

MyNetworkConfigurator.setTcpIncoming(true);

MyNetworkConfigurator.setTcpOutgoing(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and to wait for a rendezvous connection with\n"

+ RendezVous_Joe_The_Astrologer.Name + " for maximum 2 minutes");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Disabling any rendezvous autostart

NetPeerGroup.getRendezVousService().setAutoStart(false);

if (MyNetworkManager.waitForRendezvousConnection(120000)) {

Tools.popConnectedRendezvous(NetPeerGroup.getRendezVousService(),Name);

} else {

Tools.PopInformationMessage(Name, "Did not connect to a rendezvous");

}

// Preparing the listener and Creating the BiDiPipe

PipeMsgListener MyListener = new Edge_Jill_The_Customer();

// Retrieving the pipe advertisement from the module implementation advertisement

ModuleSpecAdvertisement TheModuleSpecAdvertisement =

_710_Astrology_Service_Example.GetModuleSpecificationAdvertisement();

PipeAdvertisement ThePipeAdvertisement =

TheModuleSpecAdvertisement.getPipeAdvertisement();

JxtaBiDiPipe MyBiDiPipe = new JxtaBiDiPipe(NetPeerGroup, ThePipeAdvertisement,

30000, MyListener);

if (MyBiDiPipe.isBound()) {

Tools.PopInformationMessage(Name,

"Connection with astrology service established, asking for predictions!");

// Sending request for prediction message !!!

Message MyMessage = new Message();

StringMessageElement MyStringMessageElement = new StringMessageElement(

_710_Astrology_Service_Example.BirthDateElement, "04112036", null);

MyMessage.addMessageElement(_710_Astrology_Service_Example.NameSpace,

Using JXSE Implementing A Customized Service - 242

MyStringMessageElement);

MyStringMessageElement = new StringMessageElement(

_710_Astrology_Service_Example.BirthLocationElement, "New Jersey, USA", null);

MyMessage.addMessageElement(_710_Astrology_Service_Example.NameSpace,

MyStringMessageElement);

MyStringMessageElement = new StringMessageElement(

_710_Astrology_Service_Example.CustomerNameElement, Name, null);

MyMessage.addMessageElement(_710_Astrology_Service_Example.NameSpace,

MyStringMessageElement);

MyBiDiPipe.sendMessage(MyMessage);

// Sleeping for 5 seconds

Tools.GoToSleep(5000);

}

// Stopping the network and the bidipipe

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyBiDiPipe.close();

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

// Raised when access to local file and directories caused an error

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

// Raised when the net peer group could not be created

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Edge Jill, The Customer

Jill is performing the following:

1. Jill implements the PipeMsgListener interface. This requires implementing the

pipeMsgEvent method to handle messages which will be received from Joe.

2. We set some context information via static attributes as usual.

3. We provide the user with an opportunity to erase any existing configuration and to set Joeas a rendezvous. Usual NetworkConfigurator parameters are set.

4. We start Jill as an edge and wait until she connects to a rendezvous for maximum 2minutes.

5. We retrieve the module specification advertisement corresponding to the astrology serviceand we create a bidirectional pipe by extracting the corresponding pipe advertisement.We wait for maximum 30 seconds for a connection with Joe.

6. If such a connection is established, we send a request for prediction message to Joe and

Using JXSE Implementing A Customized Service - 243

set a listener for answers.

7. We give the user an opportunity to control when the bidirectional pipe and the networkshould be stopped.

Running The Example

In order to run the example successfully, the following procedure must be performed:

1. Compile the astrology service into a .jar file and copy it in a special directory on your

PC.

2. Start Joe the rendezvous until he waits for connections from other peers (delete any exist-ing configuration). You will be requested to provide the location of the astrology .jar file

created earlier.

3. Start Jill until she manages to connect to Joe (delete any existing configuration and allowJoe as a rendezvous seed).

4. Click OK to establish a pipe connection with Joe.

5. Click OK to have Jill send her request for prediction message to Joe.

6. The astrology service ran by Joe should automatically return an answer to Jill, who willdisplay it.

7. Click OK on the next boxes showed by Joe and Jill until both stop their JXTA network.

For the sake of simplicity, we did not have one of the peers fetch the module and pipe advertise-ments from the other, although in reality, most software applications would do so. This illustrateshow one can load and run a service on a peer for other peers.

One might be asked to join a peer group of astrologers before accessing this service. Some mon-itoring of the workload of each astrologer running this service could be implemented too to redirectcustomers. We have not implemented this here for the sake of clarity.

Self-Service Weather Forecasting Method

Typically, a self-service weather forecasting method could be implemented the same way as theastrology method and made accessible to other peers via a URI. The corresponding module im-

plementation advertisement would be published too, or fetched by peers willing to run the weatherforecasting method. This implementation would be downloaded and run as a service for othertribes.

Using JXSE Implementing A Customized Service - 244

Remark:Remark:Remark:Remark: We mentioned earlier that some services are implemented at a peer level and at a peergroup level. Typically, if all astrologers run the same implementation of astrology service withintheir peer group, this service will be available at a peer group level. When initialized, this service isgiven a unique ID, that is, the module class ID corresponding to the astrology service. Each astro-loger is running the astrology service with the same ID.

Some readers will have noticed that Jill only needs to find the module specification advertisementof the astrology service, not the module implementation advertisement. This is enough to connectto any astrologer.

If a service is implemented at a peer level, it would have its own module class ID and module spe-cification ID deriving from it. The module specification advertisement, containing the correspond-ing module specification ID, would be unique. Since other peers would not necessarily have ac-cess to a module implementation advertisement for this peer level service, they would not be ableto load it and run it themselves. All customers of that peer level service would connect to one peeronly via the corresponding module specification advertisement who would be published to any-one's attention.

Peer Information

Activation Of The Peer Information Service

In JXSE 2.6, the peer information service has been fully integrated. There is no need to generateclasses using ant anymore. However, it has not been activated. For more details on activation,refer to the Programmer's Guide 2.6 available at http://jxse.kenai.com.

Some original documentation remains available at:

https://jxse-metering.dev.java.net/docs/BuildingAndConfiguringMonitoring.pdf

and https://jxse-metering.dev.java.net/.

Ping

Most software developers will want to know whether a peer is still online or not. If one thinks aboutit, it is impossible to know for a given peer whether another peer is online or not. If one cannot es-tablish some connection with another peer, the reason cannot be guessed from the lack of con-nectivity only. There could be an issue with the network. The other peer might be online, but un-reachable.

Using JXSE Ping - 245

Moreover, if one can establish a connection now with another peer, it does not necessarily meanthat one will be able to establish a connection in the future too. Therefore, any informationgathered about one's capacity to establish a connection with another peer is degrading with time.

Do not forget that trying to extract any IP address from a known peer route or endpoint addressand pinging it is useless, since it may be the result of a NAT translation. Conversely, it is not be-cause one does not have a route to a peer that a peer is not online and accessible.

As we have mentioned it earlier, release 2.6 comes with a new endpoint service functionalitycalled isReachable(...). We will now describe how one can find out whether a connection to

another peer can be established or not. If a route can be established, then we know that the targetpeer is online.

Example 800 – Ping

The following is the code used to ping another peer:

...

public class _800_Adhoc_Ping_Example {

public static final String Name = "Example 800";

public static final int TcpPort = 9756;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("."

+ System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.ADHOC,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting Configuration

MyNetworkConfigurator.setUseMulticast(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name,

"Start the JXTA network and try to establish a route to:\n\n"

+ _810_Adhoc_Pong_Example.Name);

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Retrieving the endpoint service and the message transport

EndpointService MyEndpointService = NetPeerGroup.getEndpointService();

Tools.PopInformationMessage(Name, "Trying to reach "

+ _810_Adhoc_Pong_Example.Name + " without resolving");

Using JXSE Ping - 246

if ( MyEndpointService.isReachable(_810_Adhoc_Pong_Example.PID, false) ) {

Tools.PopInformationMessage(Name, "We can establish a route to: "

+ _810_Adhoc_Pong_Example.Name);

} else {

Tools.PopInformationMessage(Name, "We CAN'T establish a route to: "

+ _810_Adhoc_Pong_Example.Name);

}

Tools.PopInformationMessage(Name, "Trying to reach " + _810_Adhoc_Pong_Example.Name

+ " with resolving");

if ( MyEndpointService.isReachable(_810_Adhoc_Pong_Example.PID, true) ) {

Tools.PopInformationMessage(Name, "We can establish a route to: "

+ _810_Adhoc_Pong_Example.Name);

} else {

Tools.PopInformationMessage(Name, "We CAN'T establish a route to: "

+ _810_Adhoc_Pong_Example.Name);

}

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Example 800 - Ping

The Ping peer is performing the following:

1. We set some context information via static attributes as usual.

2. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

3. We start the JXTA network.

4. We try to find out whether we can establish a route to Pong, without attempting to resolvea route and notify the user of the result (which is negative).

5. Then, we try again by attempting to resolve a route. The result will be positive.

6. We stop the JXTA network.

Example 810 – Pong

The following is the code used to create a peer, called Pong, which will be ping-ed by peer Ping:

...

public class _810_Adhoc_Pong_Example {

Using JXSE Ping - 247

// Static attributes

public static final String Name = "Example 810";

public static final int TcpPort = 9755;

public static final PeerID PID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,

Name.getBytes());

public static final File ConfigurationFile = new File("."

+ System.getProperty("file.separator") + Name);

public static void main(String[] args) {

try {

// Removing any existing configuration?

Tools.CheckForExistingConfigurationDeletion(Name, ConfigurationFile);

// Creation of network manager

NetworkManager MyNetworkManager = new NetworkManager(NetworkManager.ConfigMode.ADHOC,

Name, ConfigurationFile.toURI());

// Retrieving the network configurator

NetworkConfigurator MyNetworkConfigurator = MyNetworkManager.getConfigurator();

// Setting more configuration

MyNetworkConfigurator.setUseMulticast(true);

// Setting the Peer ID

Tools.PopInformationMessage(Name, "Setting the peer ID to :\n\n" + PID.toString());

MyNetworkConfigurator.setPeerID(PID);

// Starting the JXTA network

Tools.PopInformationMessage(Name, "Start the JXTA network");

PeerGroup NetPeerGroup = MyNetworkManager.startNetwork();

// Stopping the network

Tools.PopInformationMessage(Name, "Stop the JXTA network");

MyNetworkManager.stopNetwork();

} catch (IOException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

} catch (PeerGroupException Ex) {

Tools.PopErrorMessage(Name, Ex.toString());

}

}

}

Exemple 810 - RendezVous Pong

Pong is performing the following:

1. We set some context information via static attributes as usual.

2. We provide the user with an opportunity to erase any existing configuration. Usual Net-

workConfigurator parameters are set.

3. We start Pong as a rendezvous and wait for Ping to ping it.

4. The user is given an opportunity to control when Pong should be stopped.

Using JXSE Ping - 248

Running the Example

In order to run the example successfully, the following procedure must be performed:

1. Start Pong.

2. Start Ping and perform the connectivity tests.

3. Stop Ping.

4. Stop Pong.

Warning:Warning:Warning:Warning: as mentioned earlier, unexpected disconnection between peers (for example, betweenan edge and its rendezvous) are not always detected and handled 'quickly'. This is a know issuewhich may impact the isReachable(...) functionality. Deep core code refactoring is required

and should be performed in a future release.

Miscellaneous

Typically, software developers will not interfere with the default implementation of JXTA servicesin other ways than described before. However, one may by-pass the service hierarchy and usethe endpoint service directly to send a message or invoke the resolver service to send customizedqueries.

Sending A Message With The Endpoint Service

Sending a message via the endpoint service of a peer requires retrieving that service from the cor-responding PeerGroup object and calling the getMessenger(...) method. This method takes

an endpoint address as a parameter, which can be retrieved from a locally stored route advertise-ment for example, and returns a Messenger object.

Next, the user can call the one of the sendMessage(...) method from the messenger. Some

versions allow specifying a target service and service parameter. This method returns a booleanindicating that the message was successfully sent, but it does not guarantee that it will be re-ceived. This is why bidirectional pipes (for example) are preferred over this method in terms of reli-ability.

Customized Queries

Those willing to send customized queries and query answers between peers will have to createthese with the ResolverQuery and ResolverResponse objects. Do not forget to set the target

handling service name in these objects to make sure the proper handler will get them. Next, send

Using JXSE Miscellaneous - 249

these queries and responses by calling the sendQuery(...) and sendResponse(...) meth-

od of the ResolverService, which is accessible from PeerGroup objects in each peer. A target

peer ID must be provided as a parameter when calling these methods.

At last, do not forget to register some listeners beforehand in each peer via the registerHand-

ler(...) method of the ResolverService, else queries and responses will be discarded.

About Registering Handlers In Services

Typically, software developers using JXTA/JXSE in a standard way will not need to register listen-ers in delivered services in other ways than described until now. If they need to register suchhandlers anyway, they should read the corresponding javadoc carefully.

JXSE Shell

There was a possibility to test and use JXTA and JXSE concepts with a Unix-like command shelldeveloped by the JXTA community. Unfortunately this project has not been maintained for JXSE2.6 because of a lack of volunteers and interest.

Information is accessible from https://jxse-shell.dev.java.net/.

Using JXSE JXSE Shell - 250

About The Future...

In the first edition of this book, several factors having an impact on the future JXTA were intro-duced and discussed. Today, we introduce more categories (P2P, JXTA and JXSE) to classifythese factors and add new ones.

...Of P2P

Perception vs. Facts

P2P is often associated with copyright infringement and sometimes with propagation of virus.These perceptions are, of course, not based on facts. When taking a look at details, one will no-tice that client-server based solutions are no more (or less) safe than P2P solutions.

About Needs That Have Shaped IT Solutions – Part II

As we mentioned earlier in this book, let's recall the needs that have shaped IT solutions. Remem-ber that these emerged from the client/server paradigm:

➢ Remote access to a resource

➢ Concurrent access to a resource

➢ Exchange of information between resources

➢ Collection, centralization and organization of information from resources

➢ Replication of resources

The client/server model was developed to deliver/obtain services that one's local machine couldnot provide. This paradigm was further supported by the Network Address Translation (NAT)mechanism, which meant that a PC could not be directly reached if it used a private address. TheP2P paradigm has been hampered in its development by this technical limitation, but NAT tra-versal solutions are now appearing.

Distributed Content

The concept of super peers introduced by Kazaa implied centralizing some information about con-tent available in a P2P system. Distributed hash table techniques were developed during the earlyMillenium boom to solve this issue: Chord, CAN, Tapestry, Pastry, Kademlia, Koorde...

About The Future... ...Of P2P - 251

All these techniques propose theoretical results for finding the node containing the searched in-formation matching a key. All these results are based on a value of 1 to establish a contact to a re-mote peer. Unfortunately, this is an unrealistic assumption, since we know that it is not alwayspossible to establish a direct connection to a peer. More effort involving multiple can be neces-sary.

Moreover, the purpose of P2P system is not to centralize content on super peers, which would beequivalent to central server systems. Super peers maintain pointers to peers offering the content.Therefore, more than one connection is required to connect to the peer offering the content.

It would be interesting to perform real measurements of connection cost using, for example, aMonte Carlo method on a representative sample or churn modeling.

CHURN

The churn is the term describing the joining and leaving of peers in a P2P system. The vitality andamount of available resources of a P2P system depends on its churn. Modeling churn is import-ant, because it is virtually impossible to test the design of P2P systems on a real scale, with thou-sands or millions of devices.

In 2006, Daniel Stutzbach and Reza Rejaie from the University of Oregon attempted to studychurn in different P2P systems, and more specifically the uptime and downtime of peers (i.e., ses-sion duration). Their findings indicate that sessions length seem to follow a Weibull distribution.

Economical

The economical and financial implications of new technologies have a big impact on adoption ofby private sector companies. If they can help save money or make money on the long term, theyalways appeal to many. Else, they don't.

Costs And Return On Investment

Contrary to many other technologies, JXTA does not require much resources, such as servers,bandwidth, and technicians to operate, since it relies mostly on the resources of each device tooperate the network. Its general design makes it more economical than traditional client/server ap-plications. Therefore, it is a competitive technology on the market regarding operational costs.

Other costs include training (i.e., time required to learn about JXTA) and software implementationor redesign costs. Some companies prefer not to invest in new technologies and to stay with thedevil they know. This logic makes economical sense, since they don't have to go through the effort

About The Future... ...Of P2P - 252

of rewriting their application or training their personnel. This strategy brings a kind of comfortwhich can be sufficient for them. If it does the job, why change it?

A common mistake when taking a look at costs is thinking at a micro level and not considering themacro level, or forgetting to take hidden costs into account. A complete analysis can cut bothways. It can result in a positive or negative surprise. This issue is not specific to JXTA, it applies toall technologies.

The balance of forces pushing for or against new technologies from an economical point-of-view isoften summarized in the return on investment. However, linear thinking rarely produces linear res-ults in finance and economy.

Let's explain this deeper with an example. Many companies have become quite wary about IT in-vestments since the end of the nineties. Many have invested fortunes in systems that were sup-posed to save them a lot of time and money, but the benefits never reached expectations. Somereaders may be tempted to attribute this to the Internet bubble, but that is a vague explanation.

Firstly, the Internet bubble was not caused by the Internet itself, but was the result of a change inthe financial methods used to valuate companies in the early nineties. Instead of only taking intoaccount the tangible assets and debts of companies, one would take into account the potentialprofit a company could make in the future. Since small Internet companies had the potential to ac-cess millions of customers with very little resources, they were valuated at sky level limits. It waseasy to make money on Wall Street at that time, you just had to invest in virtually anything relatedto IT or the Internet.

On the other side, the rise of the IT industry in the 1990's led many companies to adopt a “gowest, young man”-like attitude to capture markets and customers. Some developed more andmore complex products offering more and more functionalities to satisfy the customer's demandregardless of technologies' maturity and constraints. Products were delivered with bugs and thepromise of a solution in the next version. It was a time when customers would buy that. Unfortu-nately, complexity is the highway to bugs in software applications; it had to have some con-sequences.

This situation created a concurrent access on competent technical resources, which led to scarcityand exorbitant wages. The offer was far from meeting the demand and what happened had tohappened. Many small Internet companies never managed to live up to their expectations. In-vestors decided to stop investing and the bubble burst. This did not reduce the tension on demandfor competent resources which remained very high. This triggered India's and other countries'

About The Future... ...Of P2P - 253

boom in the IT industry.

Some pieces of software became incredibility expensive to maintain (i.e., much more than anticip-ated), not only because of the scarcity of technical competence, but also because of softwarecomplexity itself, destroying any return on investment previsions. IT Industry clients became muchmore demanding in the quality of software applications and cautious when investing in new sys-tems. They felt the financial pinch and did not forget it.

This illustrates that costs have major impacts in the adoption and evolution of technologies in gen-eral, but that these impacts are not linear or necessarily predictable on the long term. AlthoughJXTA offers some apparent economical benefit, we cannot rely on a linear or progressive predic-tion regarding its future level adoption using that criteria only.

Potential For Profit

We have seen that P2P technologies have been used in the past to exchange copyright protectedcontent over the Internet. We have also seen that this issue was not inherent or caused by P2Papplications themselves, but by the way they were designed.

The illegal copying of digitally protected content is a complex issue. It is comparable to photocopy-ing books or paper documents illegally. One cannot prevent it fully. Copyright laws help protectingauthors and mitigating this issue, but it is far from being perfect in this electronic age. There is apossibility to encrypt and to protect access to electronic documents. However, attempts on musicand video files have not been accepted very well by end users since they have the possibility tocreate their own digital content. The two fundamental questions are: where can one put controlfrom a technological and legal point-of-view? And where should this control be enforced?

Making profit by offering access to content or to services requires being capable of controlling whois accessing these resources. This has been made possible with client/server applications; whywouldn't it be possible with P2P applications? It is just a matter of controlling access to peers,rather than servers. The author strongly believes that JXTA based applications can be made prof-itable by implementing a proper access-to-resources license system to peers containing resourcesor offering services for example. This will raise more and more business attention sooner or later.

About The Future... ...Of P2P - 254

...Of JXTA

Technological

Simplification Of Complexity - Universality

If a technology can help in streamlining business operations or have a positive impact on opera-tional efficiency, there is a higher probability that it will be adopted. If it helps to develop new andefficient end-to-end processes, standardize behaviors or if it facilitates interoperability and com-munications on available platforms, its adoption factor will increase too.

JXTA can help software developers and engineers developing software applications without hav-ing to worry about Internet connectivity issues or protocol issues. It can be used to facilitate thecommunication and the exchange of services between heteroclite systems. The capacity to integ-rate diversity is one of its key features, making it very interesting to those who are looking forwardto integrate systems or to deploy applications on diverse systems and devices.

JXTA can be considered and used as a catalyst to simplify complex system by relying on its uni-versality.

New Applications

The set of applications based on JXTA and P2P concepts has most probably not reached its peakyet. Just like petrol was considered as a hassle on one's land at the end of 19 th century, it turnedout to be very profitable and to have thousands of applications in our economy today. JXTA is uni-versal in its intention and P2P has already demonstrated some surprising applications, such asphoning over the Internet with Skype. The author strongly believes that many software developersand architects will find new ways to use JXTA and P2P concepts in general as these will becomemore and more popular and understood.

Accountability & Vendor's Credibility

The traditional proprietary versus open source technology arguments apply to JXTA, since it ispart of the open source.

On one side, proprietary technologies engage the accountability and the credibility of those provid-ing it. This can make clients more comfortable, because they know that if there is an issue with thetechnology, the provider's profitability and credibility is on the line. But has this always been true inmarkets dominated by unique players (i.e., monopolies)? If there is no other choice available,

About The Future... ...Of JXTA - 255

where is the pressure on the provider to adapt? If there are other choices, how much does it costto shift to another technology? Is that barrier high? If yes, does it play in favor of the customer?

On the other side, open source technologies are free, but no one is really responsible for them.This can put a stress on the customer, since they cannot really blame anyone if there is an issue.Yet, several technologies coming from the open source have been pretty successful; for example,Linux and its multiple versions, MySQL (a database system) and Apache, which runs many webservers today. Many companies have adopted them regardless of the risk. It seems like sinceeveryone has an interest in seeing those free technologies work for the benefit of everyone; indi-viduals manage to make them work.

Economically speaking, some big companies have an interest in spending resources to makeopen source technologies work to satisfy their needs, because if they had to buy a product on themarket, it would cost them more to satisfy their needs. If many engineers are using these techno-logies, the training effort also diminishes.

Many public and private companies, have investigated and been pushing for universal IT stand-ards. Many have decided to use open source technologies, because they did not want to belocked with specific vendors anymore. The pendulum of the quality/price ratio of IT that was lost atthe beginning of the Millennium has come back to balance today. A couple of years ago, there hasbeen a trend from dominating IT software companies to provide their technologies for free in orderto stop the flow of developers who are moving to open source technologies. The rise of operation-al alternatives has created competition and some market efficiency.

However, there are two limits to the development an open source technology: a) one will contrib-ute to its development if and only if it helps him/her save some money globally and b) the contrib-utor must have revenues coming from side activities, else he/she will not be able to contribute. Ifone of these conditions is not met, the support for the development of a given open source tech-nology goes down and it may eventually be abandoned.

Educational

Documentation, Books And Tutorials

A technology can only be well adopted if it is properly and well documented. Software developersand architects need access to these documents to learn about the technology and how to use it.As for many open source technologies, access to proper documentation, books and tutorials havebeen JXTA's weakness, especially in recent years when the technology has undergone many

About The Future... ...Of JXTA - 256

changes.

Several books have been published about JXTA the year 2002. Today, most have become obsol-ete although some still have informative chapters. Nevertheless, today's newcomers to JXTA arestill facing difficulties understanding and setting up their own JXTA network. The purpose of thisbook is to help them bridge that knowledge gap and make JXTA more accessible to those inter-ested in using it.

The good news is that all those who have crossed the initial difficulties of learning about JXTA andof making it work are actually very happy with it. The author hopes that this book will acceleratethis learning process and that it will boost the JXTA adoption factor in general.

In addition, the Programmer's Guide version 2.6 contains a chapter describing what is happening'under the hood'.

Code Examples

Sometimes, just words in books and documents are not always as good as code examples whenit comes to understand new technologies. People learn in different ways and often need concreteexamples of code to understand how they should proceed to achieve their objectives.

This book also provides several small code examples. It has been written with the intention of hav-ing its readers understand JXTA concepts one by one and to let them use them in their own ap-plications as building blocks with little adaptation.

The Community

The JXTA trademark belongs to Sun Microsystems. Since the acquisition of Sun Microsystems byOracle, the future of the structure supporting the JXTA technology has been questioned. Sun's in-volvement has significantly diminished since release 2.5, although some individuals have re-mained available to answer technical questions.

Today, JXTA contributors still have to sign a Sun's Contributor Agreement (SCA), which funda-mentally protects Sun Microsystems for its usage of the technology in Glassfish60. Unfortunately,this administrative approval process has become very slow and reminders often had to be sent forfollow-up. It has become dysfunctional and yet, the JXTA community could do with more contribut-ors. It is essential for its development.

The board of directors is made of three members, one appointed by Sun Microsystem and 2 elec-

60 See https://glassfish.dev.java.net/.

About The Future... ...Of JXTA - 257

ted by the community. Unfortunately, the provisions of board rules leave little power to electedmembers when it comes to legal empowerment and decision making on fundamental issues. Thisis another dysfunctional issue of the current structure.

Three evolutions are possible:

• The situation stays as is, with its flaws.

• The community migrates to Apache, which requires Sun/Oracle's approval.

• The community decides to branch out under a new name, since the current code licenseallows it.

Only time will tell.

The Protocols

The latest version of the JXTA protocols is 2.0. Some areas need a refresh and clarification. Somemember of the community have been requesting a binary wiring of messages instead of usingXML. In fact, version 2 of binary wiring is already specified in the specifications, but has not beenimplemented yet.

JXTA vs. OSGi

Another lurking issue is the future of services in the JXTA protocols. Peers are allowed to fetchand load services, but as we know, Java is ill-equipped to implement these via .jar. On the other

side, OSGi has already solved this problem. Does it make sense to put more efforts in re-inventingthe wheel? Should JXTA stick to P2P issues only and delegate other issues to othertechnologies? The answer is probably yes.

...Of JXSE

Security

Security has become one of the key features that companies and users are looking for in softwareapplications. Information and access to information has become vital in the new economy. JXTA isallowing software developers and architects to use TLS 1.0 or to implement their own security sys-tem on the transportation layer offered by JXTA.

JXSE provides enough security for private communications and exchange of non-sensitive inform-ation. However, it is not sufficient to meet US administration standards for example. Providing ac-

About The Future... ...Of JXSE - 258

cess to TLS 1.1 cipher suites and to the possibility of revoking weak cipher suites would help insolving this issue.

Cache Pollution

The mechanism allowing signing advertisements and secured filtering of information exchangedbetween peers has not been finalized yet in JXSE. It is possible for anyone to pollute cache of re-mote peers using remote publication for example. A long term solution is required.

Conclusion

JXTA belongs to the open source and is available for free. It has every chances of becoming theleading P2P technology for software development, since this field remains to be investigated inthe IT industry on a broad scale. Therefore, one can reasonably expect that JXTA and P2P tech-nologies have their future ahead.

About The Future... Conclusion - 259

- 260

Appendix

Protocol Messages Types

Protocols Sub-Protocols Message

Peer Discovery Protocol - Discovery Query Message

Discovery Query Response

Peer Information Protocol - Pipe Query Message

Pipe Response Message

Peer Resolver Protocol - Resolver Query Message

Resolver Query Response

SRDI Message

Pipe Binding Protocol - Pipe Resolver Message

Rendezvous Protocol Message Propagation Protocol -

PeerView Protocol -

Rendezvous Lease Protocol Lease Request Message

Lease Granted Protocol

Lease Cancel Protocol

Endpoint Routing Protocol - Route Query Message

Route Response Message

NACK Message

Appendix - 261

Advertisement Attributes

The following pages provide the list of attributes for each advertisement defined by JXTA as ofversion 2.5.3 of the specification document.

Peer Advertisement

Attribute Description Required

<PID> Peer ID Yes

<GID> Peer Group ID Yes

<Name> Peer name No

<Desc> Peer description No

<Svc> Set of group services class IDs andparameter pairs

No

Peer Group Advertisement

Attribute Description Required

<GID> Peer Group ID Yes

<MSID> Module Specification ID of the Peer Group Yes

<Name> Peer Group Name No

<Desc> Peer Group description No

<Svc> Set of group services class IDs andparameter pairs

No

Module Class Advertisement

Attribute Description Required

<MCID> Module Class ID Yes

<Name> Class Name No

<Desc> Class description No

Module Specification Advertisement

Appendix Advertisement Attributes - 262

Attribute Description Required

<MSID> Module Specification ID Yes

<Vers> Version of the specification Yes

<Name> Specification name No

<Desc> Specification description No

<CRTR> Creator of the specification No

<SURI> URI to a document providing information about thisspecification

No

<Param> Any parameter to be interpreted by each JXTAimplementation

No

<jxta:PipeAdvertisement> Possibility to bind to a pipe input end of a nearbyrunning implementation of this specification. This isan embedded pipe advertisement.

No

<Proxy> Module Specification ID of a proxy module which canbe used to communicate with modules of thisspecification

No

<Auth> Module Specification ID of an authenticator modulethat may be required to communicate with modules ofthis specification

No

Module Implementation Advertisement

Attribute Description Required

<MSID> Module Specification ID Yes

<Comp> Compatibility element describing the environment in which thisimplementation may be executed.

Yes

<Code> Contains anything that is needed to load and execute the codeof this implementation. It can be the code itself.

No

<PURI> URI to package containing the code of this implementation if it isnot delivered in <Code> itself

No

<Prov> The provider of this implementation Yes

<Desc> URI to a document providing information about this specification No

<Param> Any parameter to be interpreted by each JXTA implementation No

Pipe Advertisement

Appendix Advertisement Attributes - 263

Attribute Description Required

<Id> Pipe ID Yes

<Type> Type of the pipe (JxtaUnicast,

JxtaUnicastSecure or JxtaPropagate)

No

<Name> Pipe Name No

Rendezvous Advertisement

Attribute Description Required

<RdvGroupId> Peer Group ID for which the peer is arendezvous

Yes

<RdvPeerId> Peer ID Yes

<RdvServiceName> Peerview to which the rendezvous peerbelongs (i.e., name of a service handler)

Yes

<Name> Name of the rendezvous peer No

<RdvRoute> Embedded route advertisement No

Route Advertisement

Attribute Description Required

<PID> Peer ID (not required in a context where thePeer ID is known)

No

<EA> Endpoint Address for the peer No

<DstPID> Destination Peer ID No

<Dst> Embedded Access Point Advertisement Yes

<Hops> Semi-ordered collection of Access PointAdvertisement

Access Point Advertisement

Access point advertisements are not described in terms of attributes, since they are made of a listof endpoint addresses for peers. Do not forget that a peer can publish several endpoint addressesfor multiple network communication protocols.

Appendix Advertisement Attributes - 264

Index

2

2-tier 21

A

Access Control 71, 142Implementation 152

Access Point Advertisement 56

Access Service 45, 72

AccessibilityLAN 96Subnet 96WAN 95

Acknowledgments 11

Address Pooling 109

Adelaide, The RendezVous At One End 217

ADHOC 144

Advertisement 47Access Point 264Attributes 262Caching 48Customized 198ERP 56Finding 188Module Class 262Module Implementation 263Module Specification 262Peer 262Peer Group 262Pipe 64, 263Registering a Customized Instance 202Remote Search 190RendezVous 264Retrieving and Flushing Local 188Route 264

AES 114, 117, 151

ALG 106

Alice, Bob and Eve 113

Aminah, The Other RendezVous 174

ANB 89

Anna, The Edge 169

Anonymity 28

Anti-Virus 17

Application layer 35

Application Layer Gateways 106

ARPANET 18

Artificial Network Boundaries 89

Astrologer 239

Astrology Service 234

Asymmetric Key 114

Attribute 70

Authentication Code 115

AuthorAbout the 11

Ayrton, The Edge And JXTA Socket 226

B

Behave Compliant NAT 108

BindingC/C++ 37JXME 37

Birthday Paradox 124

BitTorrent 28

Block Cipher Mode 151

Boat 39

Broadcasting 81

Bruce Schneier 12, 16, 131

Business Logic 21

C

C/C++ 37

CAN 251

Capacity 142

CBC 151

CDC 37

Centralized Computer System 20

Certificate Authority 115

Certificate Practice Statement 120

Certificate Revocation List 120

Certification ofCertificate Authority 120

Chandra, The Rendezvous Listening to Messages211

Chihiro, The Other Edge 175

Chord 251

CHURN 252

Cipher Suite 135

Cipher-Block Chaining (CBC) 151

CLDC 37

Client/Server 20

Cloud Computing 23

Clustering 21

Codats 50

Appendix Index - 265

Collision Issue 124

Communication ProtocolSuite 33

ConfigParam 159Loading From a URI 159

ConfigurationObjects 160

Configuration Mode 143

Configuration Parameters 159

Connected Device Configuration 37

Connected Limited Device Configuration 37

Connectivity Issues 163

Content 50

Copyright Infringement 17

Core layer 35

Correspondent Inference Theory 16

Counter (CTR) 151

CPS 120

CRL 120

Cryptography 151Assumptions 125Implementating Your Own Layer 151

CTR 151

Customer 241

D

Database 20

Datagram 82

Decentralization 19, 26

DES 137

Design Principles 20

Dictionary Attack 131

Diffie-Hellman 117

Digital Rights Management 126

Dimitri, The Edge Sending Messages 213

Direct Routing 80

Directory Services 123

Discovery Operations 188

Discovery Query Message 70

Discovery Query Response 70

Discovery Service 46

Distinctive Sign 39

Distributed Communication 19

Distributed Computing 23, 29

Divisible Problem 29

Domain Name System (DNS) 33

Dried Leaf 47

DRM 126

DutiesCertificate Authority 120

E

EDGE 144

Edge Probe 60

Edward E. Jones 16

Endpoint 54Receiving 63Sending 63

Endpoint Address 54

Endpoint Routing Protocol (ERP) 53, 54

Endpoint Service 46, 53

ERP 53

Exportation Limitations 151

F

Failure Notification 60

Firewall 83Overcoming 90

Forum 37

Freenet 28

Frequently Asked Questions (FAQ) 37

Full Cone 100

Full-Featured Edge Peer 143

FutureNet 88

G

Gaia 44

Gnutella 26

Grid Computing 23

Groove 16

Groove Networks 16

H

HairpinIssue 98

Handler 65

Handshake3-way 81

Hans, The Rendezvous, A Multicast Participant 229

Hash Function 116, 123

Hops 54

Host 80

HTTPDefault Port 149

I

IANA 83

ICE 107

Appendix Index - 266

ICE-TCP 108

ICMP 105

ICQ 24

ID 49Creation 183Creation Of A Peer 141Importation From Other Systems 141Well-known 74

IdentityDefinition in JXTA 140Issues 139

IETF 134

Ignition Process 73

IllusionDRM 126

Inclusion 142

Indirect Routing 80

Indivisible Problem 29

Internet 18

IntroductionSecure Communication 114

IP 80Address 80Addresses as Identities 139Automatic Change of Address 159Default Ports 149External 85Gateways 80Internal 85

IP Obstacles 97

IPv4 81

IPv6 81

Island 39

J

Jack, The Rendezvous 167

Java Cryptography Architecture 127

Java ME 37

JavadocsJXTA 154

Jill, The Customer 241

JKS 135

Joe, The Astrologer 239

JXME 37

JXSECommunity 36Configuration Mode 143Configuration Modes 144Cryptographic Layer 113Documentation 37

Shell 250Transportation Layer 90Using 153

JXTA 34Bootstrapping 74Concept Overview 40Core Specification 42First Connection 154Layer 34Peer Types 143Project 36Protocols 52Security Layer 135Specification Document 36Starting And Stopping 154Transportation Layer 89

JXTA Multicast Socket 229

JXTA Socket 223

JXTA Socket Server 223

K

Kademlia 251

Kazaa 27

Keith Davis 16

KeyAsymmetric 114Symmetric 114

Key Size 125

KeyStore 127Creation 128Types 135Working With 205

Kings & Queens 39

Koorde 251

L

LAN 80

Lease 61

Lease Cancel Message 61

Lease Granted Message 61

Lease Request Message 61

Lidong, The Rendezvous And JXTA Socket Server223

Load balancing 21

Local Configuration 154Creation 156Directory Structure 160Modifying 157Prevent Creation Of 155Retrieving 157Saving 157

Appendix Index - 267

M

MAC 116

Mainframe 18

MappingArbitrary 109Paired 109

MARS 151

Master Server 22

Matryoshka Doll 53

Maven 154

Maxime, The Socializer 190

MD5 123, 137

Membership Control 142

Membership Service 46, 72

Message 53Adding an Advertisement 197Creating An Empty 194Duplicate 61ERP 56Individual 58Loop 61Protocol Types... 261Sending With Endpoint Service 249

Message Authentication Code 116

Message Element 53Adding 194Retrieving 195

Message Propagation Protocol 58

MetaphorTribes-in-islands 39

Metaphors 42, 44, 48-50, 53-55, 60, 64, 66, 84, 89, 90,141, 155, 157, 158, 172, 173, 179, 184, 185, 188, 190,193, 203, 216, 239

Middleware 22

MIDP 37

Minimal Dialect 39

Minimal Edge Peer 143

Mobile Information Device Profile 37

Modern Cryptography 21

Module 50IDs Creation 233Implementation of 73

Module Class Advertisement 51

Module Class ID 51

Module Implementation Advertisement 52

Module Specification Advertisement 51

Module Specification ID 51

Monitor Filter 68

Monitor Listener 68

Monitor Report 68

Monitoring 142

Multi-tier 21

Multicasting 81Default IP Address 150Default Port 150

MultiplePeer In Same JVM 166

N

NACK Message 56

Napster 25

NapsterNapster 19

NAT 84Limitations 86Overcoming 91Traversal 97

NATBlaster 104

National Institute of Standards and Technology 114

NatTrav 104

Natural Network Boundaries 88

Needs 23

Neil Ferguson 131

Net Peer Group 43

NetBeans 153, 167

NetBeansCreating A Project 153

Network Address Translation 84

Network Administration 149

Network Communication 20

Network Configurator 157

Network Manager 155

Network Scope 147

Network Transport layer 80

New NAT Classification 102

Niels Ferguson 12

NIST 114

NNB 88

Nomadic 41, 56

NSA 125

NUTSS 103

O

OSGiConnection 160

Ouroboros 41, 117, 118

P

Appendix Index - 268

P2PBenefits 30Drawbacks 30Initial Objectives 29Introduction 16Pure 28Pure P2P network 28Reputation 16

P2PNAT 103

Panama 43

Participant Probe 60

Participant Referral Response 60

Participant Response 60

Pastry 251

PAT 86

PBP 63

PC 18

PDA 41

PDP 70

Peer 41Accessibility 95Advertisement 48Blind 95Creation 184Distant 95Inaccessible 90, 95Pockets 95Running Multiple ... on a Single Device 166

Peer Discovery Protocol (PDP) 70

Peer Group 43Advertisement 48As A Service 74Creation 141, 185Identity 141Parent 44

Peer Info Service 46

Peer Information Protocol (PIP) 68

Peer Information ServiceActivation 245

Peer Monitor Info 69

Peer Resolver Protocol (PRP) 65

Peer to Peer 16

PeerviewMessage 59Rendezvous 59

PeerView Protocol 59

Personal Computer 18

Personal Security Environment (PSE) 127

Ping 245

Ping

Instruction 105

PIP 68

PIP Query Message 69

PIP Response Message 69

PipeAdvertisement 64Bidirectional Communication 217JxtaPropagate 63JxtaUnicast 63JxtaUnicastSecure 63Simple Communication 210Unicast secure 217Unidirectional Asynchronous Unicast 63

Pipe Binding Protocol (PBP) 63

Pipe Resolver Message 64

Pipe Service 46

Pipes 50

PKCS#12 135

PKI 119

Platform layer 35

PlatformConfig 157

Port 82Blocked 83Listening 81, 82

Port Prediction 98

Prerequisites 15

Principal 123

Private KeyEncryption 135Exporting And Importing 203

Private Key System 114

Probe Message 59

Propagate Pipe Message Header 65

Propagation Control 59, 61

ProtocolUnderstanding The Role Of 32

Proxy 87, 146

ProxyOvercoming 92

PRP 65

PSEConfiguration 132

Public Key Infrastructure 119

Public Key System 114

Publication 48Local And Remote 194

Punching Holes 98

PWNAT 105

Q

Appendix Index - 269

Queries 20

QueryCustomized 249Multicasting 96

Quinisela, The Edge At The Other End 220

R

RC6 151

Relay 145Connectivity 182To Be or Not To Be? 147

Relay Peer 42, 143

Relay Service 91

RendezVous 145Automatic Reconnection 178Peer Connection to 61To Be or Not To Be? 148

Rendezvous Advertisement 60

Rendezvous Lease Protocol 61

Rendezvous Peer 42, 143

Rendezvous PeerConnection 59

Rendezvous Protocol (RVP) 58

Rendezvous Service 46, 58

RequirementsJXTA 41

Resolver Query Message 66

Resolver Response Message 66

Resolver Service 46, 65

Resolver SRDI Message 67

Resource 47

Response Message 59

Restricted Cone 100

RFCRFC 4787 109RFC 5245 107RFC 5382 108

RFC 5128 99

Rijndael 114

Rings 80

RIPEMD 123

Robert, The Relay 180

Route 55

RouteDirect 54

Route Advertisement 56

Route Query Message 56

Route Resolver Query 55

Route Response Message 56

Router 87Multicasting Versus Subnets 87

RSA 114

Ruler 41

RVP 58

S

Salt-And-Stretch 131

Salting 131

Seclusion 142

Secure Socket Layer (SSL) 134

Seed 28, 94

SeedImplementation 150Multiple Layer 149Number of 149

Segment 80

Self-Service 244

Serpent 151

Service 44About Implementation of... 146About Registering Handlers 250Astrology 40, 234Customized 233Implementation of 74Loading 77Peer Group Level Implementation 245Peer Level Implementation 245

Service layer 35

Service Metric 68

Service Monitor 68

Service Monitor Filter 68

Service Oriented Architecture 22

SETI 29

SHA 123, 131, 151

Shared Resource Distributed Index (SRDI) 66

Shell 250

Shutdown Notification 60

Sign 39

Skype 29, 255

Slave 22

SOA 22

SRDI service 67

STUN 99

STUNT 100STUNT #1 101

Subnet 80About... 150Configuration 150

Appendix Index - 270

Super node 27

Symmetric 100

Symmetric Key 114

T

Tapestry 251

TCP 81Handshake 81

Tebogo, The Jazz Fan 194

Teyacapan, The Edge, Another Multicast Participant231

Three Layer Cake 35

Three-tier 21

Tiger 123

Time Sharing 24

Time To Live (TTL) 26, 61, 65

TLS 63, 134, 135, 151, 258

Transport Layer Security 63

Transport Security Layer (TLS) 134

Tribe Language 39

Tribes 39

Tribes-in-Islands 39

Trojan Horse 83

TTL-less Version of STUNT 102

TURN 99

Twofish 151

U

UDP 82

Unicast 81

Unicast Secure Pipes 217

UniversalityP2P 32

UPnP 107

URI 15

URL 15

URN 15

V

Value 70

Virtual Private Network (VPN) 134

W

Weather Forecasting Method 40, 244

Web 2.0 23

Web Of Trust 121

World Peer Group 43

X

X.500 123Principal 123

X.509 122Automatic Certification Creation 128Exporting And Importing 203Registration 132

XML 35

Appendix Index - 271