Skip to main content

Discover custom advertisement

3 replies [Last post]
sammathew456
Offline
Joined: 2007-11-20
Points: 0

Hi, I am trying to discover a custom advertisement using Discoveryservice.getLocalAdvertisements but I am getting 0 records. Can u please help me in this regard?

Message was edited by: sammathew456

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
hamada
Offline
Joined: 2003-06-12
Points: 0

You also ought to look at the AdvertisementTutorial, as it provides the proper way creating and registering the new the advertisement. Keep in mind that in order for a node to be able to discover such advertisement it must have the new advertisement registered.

Mohamed

staltec
Offline
Joined: 2008-01-15
Points: 0

Hi,

I had the same problem with a custom advertisement and registering the new type solved it. Thanks :-)

Bye

ivarulz
Offline
Joined: 2007-08-17
Points: 0

This is some code I copied from a book, and it worked:

I apologize for not mentioning the book, but i forgot the name.
----------------------------------------------------------------
/**
* An abstract class defining an advertisement containing the elements used to
* describe a user�s presence status. A user is assumed to be uniquely described
* by his or her email address.
*/
public abstract class PresenceAdvertisement extends Advertisement {
/**
* The root element for the advertisement�s XML document.
*/
private static final String advertisementType = "PresenceAdvertisement";
/**
* The email address identifying the user whose presence information this
* advertisement describes.
*/
private String emailAddress = null;
/**
* A simple name for the user specified by the advertisement�s email address.
*/
private String name = null;
/**
* The Peer ID locating the peer on the network.
*/
private String peerID = null;

/**
* A simple descriptor identifying the user�s presence status. The user can
* indicate that he or she is online, offline, busy, or away.
*/
private int presenceStatus = PresenceService.OFFLINE;

/**
* Returns the advertisement type for the advertisement�s document.
*
* @return the advertisement type String.
*/
public static String getAdvertisementType() {
return advertisementType;
}

/**
* Returns the email address String describing the user whose presence status
* is described by this advertisement.
*
* @return the email address for the advertisement.
*/
public String getEmailAddress() {
return emailAddress;
}

/**
* Returns a unique identifier for this document. There is none for this
* advertisement type, so this method returns the null ID.
*
* @return the null ID.
*/
public ID getID() {
return ID.nullID; //TODO: investigate
}

/**
* Returns the simple name for the user described by this advertisement.
* continues 352 Chapter 11 A Complete Sample Application
*
* @return the user�s name.
*/
public String getName() {
return name;
}

/**
* Returns the Peer ID of the user described by this advertisement.
*
* @return the Peer ID of the user.
*/
public String getPeerID() {
return peerID;
}

/**
* Returns the presence status information of the user described by this
* advertisement.
*
* @return the user�s status information.
*/
public int getPresenceStatus() {
return presenceStatus;
}

/**
* Sets the email address String describing the user whose presence status is
* described by this advertisement.
*
* @param emailAddress
* the email address for the advertisement.
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}

/**
* Listing 11.2 Continued Creating the Presence Service 353 Sets the simple
* name for the user described by this advertisement.
*
* @param name
* the user�s name.
*/
public void setName(String name) {
this.name = name;
}

/**
* Sets the Peer ID identifying the peer�s location on the P2P network.
*
* @param peerID
* the Peer ID for the advertisement.
*/
public void setPeerID(String peerID) {
this.peerID = peerID;
}

/**
* Sets the presence status information of the user described by this
* advertisement.
*
* @param presenceStatus
* the user�s status information.
*/
public void setPresenceStatus(int presenceStatus) {
this.presenceStatus = presenceStatus;
}

---------------------------------------------------

/**
* An implementation of the PresenceAdvertisement abstract class. This class is
* responsible for parsing and formatting the XML document used to define
* presence information for a peer.
*/
public class PresenceAdv extends PresenceAdvertisement {
private static final Logger _logger = Logger.getLogger(PresenceAdv.class);

/**
* A convenient constant for the XML MIME type.
*/
private static final String mimeType = "text/xml";
/**
* The element name for the presence advertisement�s email address info.
*/
private static final String tagEmailAddress = "EmailAddress";
/**
* The element name for the presence advertisement�s simple name info.
*/
private static final String tagName = "Name";
/**
* The element name for the presence advertisement�s Peer ID.
*/
private static final String tagPeerID = "PeerID";
/**
* The element name for the presence advertisement�s status info.
*/
private static final String tagPresenceStatus = "PresenceStatus";

/**
* An Instantiator used by the AdvertisementFactory to instantiate this class in
* an abstract fashion.
*/
public static class Instantiator implements AdvertisementFactory.Instantiator {
/**
* Returns the identifying type of this advertisement.
*
* @return the name of the advertisement�s root element.
*/
public String getAdvertisementType() {
_logger.debug("Invoking Instantiator.getAdvertisementType()");
return PresenceAdvertisement.getAdvertisementType();
}

/**
* Returns a new PresenceAdvertisement implementation instance.
*
* @return a new presence advertisement instance.
*/
public Advertisement newInstance() {
_logger.debug("Invoking Instantiator.newInstance()");
return new PresenceAdv();
}

/**
* Instantiates a new PresenceAdvertisement implementation instance populated
* from the given root element.
*
* @param root
* the root of the object tree to use to populate the advertisement
* object.
* @return a new populated presence advertisement instance.
*/
public Advertisement newInstance(Element root) {
_logger.debug("Invoking Instantiator.newInstance()");
return new PresenceAdv(root);
}
};

/**
* Creates a new presence advertisement.
*/
public PresenceAdv() {
super();
}

/**
* Creates a new presence advertisement by parsing the given stream.
*
* @param stream
* the InputStream source of the advertisement data.
* @exception IOException
* if the advertisement can�t be parsed from the stream.
*/
public PresenceAdv(InputStream stream) throws IOException {
super();
StructuredTextDocument document = (StructuredTextDocument) StructuredDocumentFactory
.newStructuredDocument(new MimeMediaType(mimeType), stream);
readAdvertisement(document);
}

/**
* Creates a new presence advertisement by parsing the given document.
*
* @param document
* the source of the advertisement data.
*/
public PresenceAdv(Element document) throws IllegalArgumentException {
super();
readAdvertisement((TextElement) document);
}

/**
* Returns a Document object containing the advertisement�s document tree.
*
* @param asMimeType
* the desired MIME type for the advertisement rendering.
* @return the Document containing the advertisement�s document object tree.
* @exception IllegalArgumentException
* thrown if either the email address or the Peer ID is null.
*/
public Document getDocument(MimeMediaType asMimeType)
throws IllegalArgumentException {
// Check that the required elements are present.
if ((null != getEmailAddress()) && (null != getPeerID())) {
PipeAdvertisement pipeAdv = null;
StructuredDocument document = (StructuredTextDocument) StructuredDocumentFactory
.newStructuredDocument(asMimeType, getAdvertisementType());
Element element;
// Add the Peer ID information.
element = document.createElement(tagPeerID, getPeerID());
document.appendChild(element);
// Add the email address information.
element = document.createElement(tagEmailAddress, getEmailAddress());
document.appendChild(element);
// Add the display name information, if any.
if (null != getName()) {
element = document.createElement(tagName, getName());
document.appendChild(element);
}
// Add the presence status information.
element = document.createElement(tagPresenceStatus, Integer
.toString(getPresenceStatus()));
document.appendChild(element);
return document;
} else {
throw new IllegalArgumentException("Missing email address or peer ID!");
}
}

/**
* Parses the given document tree for the presence advertisement.
*
* @param document
* the object containing the presence advertisement data.
* @exception IllegalArgumentException
* if the document is not a presence advertisement, as expected.
*/
public void readAdvertisement(TextElement document)
throws IllegalArgumentException {
_logger.debug("START readAdvertisement()");
_logger.debug("PARAM document=" + document);
_logger.debug("PARAM document.name=" + document.getName());

if (document.getName().equals(getAdvertisementType())) {
Enumeration elements = document.getChildren();
while (elements.hasMoreElements()) {
TextElement element = (TextElement) elements.nextElement();
// Check for the email address element.
if (element.getName().equals(tagEmailAddress)) {
setEmailAddress(element.getTextValue());
continue;
}
// Check for the display name element.
if (element.getName().equals(tagName)) {
setName(element.getTextValue());
continue;
}
// Check for the email address element.
if (element.getName().equals(tagPresenceStatus)) {
setPresenceStatus(Integer.parseInt(element.getTextValue()));
continue;
}
// Check for the Peer ID element.
if (element.getName().equals(tagPeerID)) {
setPeerID(element.getTextValue());
continue;
}
}
} else {
_logger.debug("Not a PresenceAdvertisement document!");
}

_logger.debug("EDN readAdvertisement()");
}

/**
* continues 360 Chapter 11 A Complete Sample Application Returns an XML String
* representation of the advertisement.
*
* @return the XML String representing this advertisement.
*/
public String toString() {
try {
StringWriter out = new StringWriter();
StructuredTextDocument doc = (StructuredTextDocument) getDocument(new MimeMediaType(
mimeType));
doc.sendToWriter(out);
return out.toString();
} catch (Exception e) {
return "";
}
}

@Override
public String[] getIndexFields() {
return null;
}
}
-----------------------------------------------------------
/**
* An interface for the Presence service, a service that allows peers to
* exchange presence status information specifying their current status
* (offline, online, busy, away). This interface defines the operations that a
* developer can expect to use to manipulate the Presence service, regardless of
* which underlying implementation of the service is being used.
*/
public interface PresenceService extends Service
{
/**
* The module class ID for the Presence class of service.
*/
public static final String refModuleClassID =
"urn:jxta:uuid-E63A37E6AA6E428D83CCFDEEC3213F5A05";
/**
* A status value indicating that a user is currently online but is temporarily
* away from the device.
*/
public static final int AWAY = 3;
/**
* A status value indicating that a user is currently online but is busy and
* does not want to be disturbed.
*/
public static final int BUSY = 2;
/**
* A status value indicating that a user is currently offline.
*/
public static final int OFFLINE = 0;
/**
* A status value indicating that a user is currently online.
*/
public static final int ONLINE = 1;
/**
* Add a listener object to the service. When a new Presence Response Message
* arrives, the service will notify each registered listener.
*
* @param listener
* the listener object to register with the service.
*/
public void addListener(PresenceListener listener);
/**
* Announce updated presence information within the peer group.
*
* @param presenceStatus
* the updated status for the user identified by the email address.
* @param emailAddress
* the email address used to identify the user associated with the
* presence info.
* @param name
* a display name for the user associated with the presence info.
*/
public void announcePresence(int presenceStatus, String emailAddress,
String name);
/**
* Sends a query to find presence information for the user specified by the
* given email address. Any response received by the service will be dispatched
* to registered PresenceListener objects.
*
* @param emailAddress
* the email address to use to find presence info.
*/
public void findPresence(String emailAddress);
/**
* Removes a given listener object from the service. Once removed, a listener
* will no longer be notified when a new Presence Response Message arrives.
*
* @param listener
* the listener object to unregister.
*/
public boolean removeListener(PresenceListener listener);
}

------------------------------------------------------------------------------
/**
* The implementation of the PresenceService interface. This service builds on
* top of the Discovery service to provide the functionality for requesting and
* providing presence information.
*/
public class PresenceServiceImpl implements PresenceService, DiscoveryListener {
public static final Logger _logger = Logger.getLogger(PresenceServiceImpl.class);

/**
* The Module Specification ID for the Presence service.
*/
public static final String refModuleSpecID =
"urn:jxta:uuid-E63A37E6AA6E428D83CCFDEEC3213F5A04DC42591C684B8BA542F18779FF28C206";
/**
* The default expiration timeout for published presence advertisements. Set
* to 1 minute.
*/
private static final int DEFAULT_EXPIRATION = 1000 * 60 * 1;
/**
* The default lifetime for published presence advertisements. Set to 1
* minutes.
*/
private static final int DEFAULT_LIFETIME = 1000 * 60 * 5;
/**
* The element name for the presence advertisement�s email address info.
*/
private static final String tagEmailAddress = "EmailAddress";
/**
* The Discovery service used to publish presence information.
*/
private DiscoveryService discovery = null;
/**
* The Module Implementation advertisement for this service.
*/
private Advertisement implAdvertisement = null;
/**
* The local Peer ID.
*/
private String localPeerID = null;
/**
* The peer group to which the service belongs.
*/
private PeerGroup peerGroup = null;
/**
* A unique query ID that can be used to track a query.
*/
private int queryID = 0;
/**
* The set of listener objects registered with the service.
*/
private Vector registeredListeners = new Vector();

/**
* PresenceServiceImpl constructor comment.
*/
public PresenceServiceImpl() {
super();
}

/**
* Add a listener object to the service. When a new Presence Response Message
* arrives, the service will notify each registered listener. This method is
* synchronized to prevent multiple threads from altering the set of
* registered listeners simultaneously.
*
* @param listener
* the listener object to register with the service.
*/
public synchronized void addListener(PresenceListener listener) {
registeredListeners.addElement(listener);
}

/**
* Announce presence status information to the peer group.
*
* @param presenceStatus
* the current status to announce.
* @param emailAddress
* the user�s email address.
* @param name
* the user�s display name.
*/
public void announcePresence(int presenceStatus, String emailAddress,
String name) {
_logger.debug("START announcePresence()");
_logger.debug("PARAM presenceStatus=" + presenceStatus);
_logger.debug("PARAM emailAddress=" + emailAddress);
_logger.debug("PARAM name=" + name);

if (discovery != null) {
_logger.debug("Creating presenceAdv");

PresenceAdvertisement presenceInfo = (PresenceAdvertisement)
AdvertisementFactory.newAdvertisement(PresenceAdvertisement.getAdvertisementType());

// In some earlier versions of JXTA, registering the
// advertisement doesn�t work properly. To work around this,
// simply instantiate the advertisement implementation directly.
// This is not the recommended way to get an advertisement.
// The recommended way is shown in the commented line
// preceeding this comment.
// TODO:PresenceAdvertisement presenceInfo = new PresenceAdv();

// Configure the new advertisement.
presenceInfo.setPresenceStatus(presenceStatus);
presenceInfo.setEmailAddress(emailAddress);
presenceInfo.setName(name);
presenceInfo.setPeerID(localPeerID);
try {
// Publish the advertisement locally.
discovery.publish(presenceInfo, DEFAULT_EXPIRATION, DEFAULT_LIFETIME);
} catch (IOException e) {
System.out.println("Error publishing locally: " + e);
}
// Publish the advertisement remotely.
discovery.remotePublish(presenceInfo, DEFAULT_LIFETIME);
}

_logger.debug("END announcePresence()");
}

/**
* Handle notification of arriving discovery response messages, determine
* whether the response contains presence information, and, if so, dispatch
* the presence information to registered PresenceListeners.
*
* @param event
* the object containing the discovery response.
*/
public void discoveryEvent(DiscoveryEvent event) {
_logger.debug("START discoveryEvent()");
_logger.debug("PARAM event=" + event);

DiscoveryResponseMsg response = event.getResponse();
// Extract the PresenceAdvertisement from the response.
Enumeration responses = response.getResponses();
while (responses.hasMoreElements()) {
String responseElement = (String) responses.nextElement();
// Check for null response advertisement.
if (null != responseElement) {
// Parse the advertisement.
try {
ByteArrayInputStream stream = new ByteArrayInputStream(
responseElement.getBytes());

// TODO::PresenceAdvertisement advertisement = (PresenceAdvertisement)
/* AdvertisementFactory.newAdvertisement( new
MimeMediaType("text/xml"), stream);*/

// In some earlier versions of JXTA, registering the
// advertisement doesn�t work properly. To work around
// this, simply instantiate the advertisement
// implementation directly. This is not the recommended
// way to get an advertisement. The recommended way
// is shown in the commented line preceeding this
// comment.
PresenceAdvertisement advertisement = new PresenceAdv(stream);
// Dispatch the advertisement to the registered presence
// listeners.
Enumeration listeners = registeredListeners.elements();
while (listeners.hasMoreElements()) {
PresenceListener listener = (PresenceListener) listeners
.nextElement();
// Notify the listener of the presence update.
listener.presenceUpdated(advertisement);
}
} catch (IOException e) {
e.printStackTrace();
// Obviously not a response to our query for presence
// information. Ignore the error.
System.out.println("Error in discoveryEvent: " + e);
}
} else {
System.out.println("Response advertisement is null!");
}
}
_logger.debug("END discoveryEvent()");
}

/**
* Sends a query to find presence information for the user specified by the
* given email address. Any response received by the service will be
* dispatched to registered PresenceListener objects.
*
* @param emailAddress
* the email address to use to find presence info.
*/
public void findPresence(String emailAddress) {
_logger.debug("START findPresence()");
_logger.debug("PARAM emailAddress=" + emailAddress);

// Make sure the service has been started.
if (discovery != null) {
_logger.debug("Searching ...");
// Send a remote discovery for presence information.
discovery.getRemoteAdvertisements(null, DiscoveryService.ADV,
tagEmailAddress, emailAddress, 1, null);
// Do a local discovery for presence information.
try {
Enumeration enuM = discovery.getLocalAdvertisements(
DiscoveryService.ADV, tagEmailAddress, emailAddress);
while (enuM.hasMoreElements()) {
PresenceAdvertisement advertisement = (PresenceAdvertisement) enuM.nextElement();
// Dispatch the advertisement to the registered presence
// listeners.
Enumeration listeners = registeredListeners.elements();
while (listeners.hasMoreElements()) {
PresenceListener listener = (PresenceListener) listeners.nextElement();
// Notify the listener of the presence update.
listener.presenceUpdated(advertisement);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

_logger.debug("END findPresence()");
}

/**
* Returns the advertisement for this service. In this case, this is the
* ModuleImplAdvertisement passed in when the service was initialized.
*
* @return the advertisement describing this service.
*/
public Advertisement getImplAdvertisement() {
return implAdvertisement;
}

/**
* Returns an interface used to protect this service.
*
* continues 372 Chapter 11 A Complete Sample Application
*
* @return the wrapper object to use to manipulate this service.
*/
public Service getInterface() {
// We don�t really need to provide an interface object to protect
// this service, so this method simply returns the service itself.
return this;
}

/**
* Initialize the service.
*
* @param group
* the PeerGroup containing this service.
* @param assignedID
* the identifier for this service.
* @param implAdv
* the advertisement specifying this service.
* @exception PeerGroupException
* is not thrown ever by this implementation.
*/
public void init(PeerGroup group, ID assignedID, Advertisement implAdv)
throws PeerGroupException {
_logger.debug("START init()");
_logger.debug("PARAM group=" + group);
_logger.debug("PARAM assignedID=" + assignedID);
_logger.debug("PARAM implAdv=" + implAdv);

// Save the module�s implementation advertisement.
implAdvertisement = (ModuleImplAdvertisement) implAdv;
// Save a reference to the group of which that this service is
// a part.
peerGroup = group;
// Get the local Peer ID.
localPeerID = group.getPeerID().toString();
// Register the advertisement type.
// In some earlier versions of JXTA, registering the advertisement
// doesn�t work properly. To work around this, you can instead
// simply instantiate the advertisement implementation directly.
// This is not the recommended way to get an advertisement.
// In this class, I�ve used the workaround in the discoveryEvent
// and accouncePresence methods, but I�ve provided the
// as well.

AdvertisementFactory.registerAdvertisementInstance(
PresenceAdvertisement.getAdvertisementType(),
new PresenceAdv.Instantiator());

_logger.debug("END init()");
}

/**
* Remove a given listener object from the service. Once removed, a listener
* will no longer be notified when a new Presence Response Message arrives.
* This method is synchronized to prevent multiple threads from altering the
* set of registered listeners simultaneously.
*
* @param listener
* the listener object to unregister.
*/
public synchronized boolean removeListener(PresenceListener listener) {
return registeredListeners.removeElement(listener);
}

/**
* Start the service.
*
* @param args
* the arguments to the service. Not used.
* @return 0 to indicate the service started.
*/
public int startApp(String[] args) {
_logger.debug("START startApp()");
_logger.debug("PARAM args=" + args);
_logger.debug("peergroup=" + peerGroup);

// Now that the service is being started, set the DiscoveryService
// object to use to publish presence information.
//TODO: see getParentGroup()
discovery = peerGroup.getParentGroup().getDiscoveryService();
if (discovery == null) {
_logger.debug("STALLED. DiscoveryService not available");
return Module.START_AGAIN_STALLED;
}
// Add ourselves as a listener.
discovery.addDiscoveryListener(this);

_logger.debug("END startApp()");

return 0;
}

/**
* Stop the service.
*/
public void stopApp() {
if (discovery != null) {
// Unregister ourselves as a listener.
discovery.removeDiscoveryListener(this);
discovery = null;
// Empty the set of listeners.
registeredListeners.removeAllElements();
}
}
}

good luck