![]()
This document covers the following topics:
This section describes installing and configuring the KnowNow Event Router on Windows 2000 and Solaris. The following topics are covered:
·
Verifying
the Event Router Installation
To install the KnowNow Event Router on Solaris:
a
Change to the /usr/local/kn directory. This
is the installation directory on solaris. When you change to it, you are making
it your current local directory.
b Start the Router in the foreground or the background. See commands below:
starting in
foreground: bin/nsd -f -t conf/knrouter.conf
starting in background: bin/nsd -t conf/knrouter.con
|
|
By default, the Router listens for requests on port 8000. To change the port number, edit the httpport variable at the top of the config file. You must restart the Router for the changes in the port number to take effect. |
c
To
start the Router automatically when the machine reboots, the Solaris
administrator needs to create a script in /etc/init.d for the Router and then symlink
into that script form /etc/rc2.d or /etc/rc3.d.
By default, the Event Router listens for requests on port 8000. To change the port number, edit the httpport variable, found near the top of the knrouter.conf file. The config file is located in the conf subdirectory where you installed the Event Router. You must restart the Router for changes in the port number to take effect.
This section describes how to configure the KnowNow Event Router on Windows 2000 and Solaris. The following topics are covered:
The following HTML-based utilities are installed with the Event Router.
·
KN
Test - Performs automated tests to ensure that the web browser, Event Router
and the JavaScript Microserver are functioning properly.
·
KN
Ping - Measures event routing round-trip latency and throughput over a connection
between the Event Router and a web browser.
·
KN
Explorer - Displays the contents of topics and events managed by the Event
Router in a web browser window.
·
KN
Config Utility - Allows you to manage and configure your Event Router.
When you start your Event Router, the Router IP address and the port number it is using are displayed either in the console window or in the log file. For example:
0.0.0.0:8000
When running one of the utilities, be sure to specify the host name and port number of the Event Router you wish to test.
·
To
use KN Ping, enter a number in the first text field (or leave it set to 100)
and click Run.
·
To
use KN Explorer, select the hyperlinks to navigate through the topic hierarchy.
·
To
use KN Test, follow the instructions provided with the utility.
·
To
use KN Config, follow the instructions provided with the utility.
For more information about the utilities or to download sample applications and components, visit:
The following sections discuss access control in the Event Router and clustering.
·
Access
Control in the KnowNow Event Router
The KnowNow Event Router allows administrators to control:
·
which
users can publish events to a particular topic
·
which
users can subscribe to a particular topic
·
which
users can create subtopics for a given topic
Configuration of the access control mechanisms takes place in three files:
·
passwd
- defines valid users and their passwords
·
group
- defines groups of users
·
perms
- defines the permissions given to specified users and groups
These three files can be found in the conf subdirectory of the KnowNow Event Router's install directory. See the Event Router Configuration File for parameters that must be edited to ensure authentication and authorization to work properly.
The three access control files are discussed in more detail below.
Entries in the passwd file are similar to UNIX/etc/passwd entries. The first field contains a username and the second filed contains the crypt() encrypted password for that user. The fields are separated by colons. Note that five (5) colons can optionally follow the encrypted password for compatibility with UNIX password editing tools. For example:
You need to use the passgen utility to create encrypted passwords. The passgen.exe is located in the /bin subdirectory. You give it a username and password on the command line and it spits out the encrypted entry for the passwd file. For example,
will give
which can be copied in to the passwd file by the administrator.
Entries in the group file are similar to UNIX/etc/group entries. The first field specifies a group name and the second field lists the users that are part of the group. The list of users in the second field must all be defined in the passwd file. Three colons separate the group name from the list of users in that group to maintain compatibility with UNIX group editing tools; comma delimiters are used to separate users. See the example below:
This file defines the permissions given to users and groups on the KnowNow Event Router. There are four commands valid in this file:
The parameters of the perms file have the following format:
·
ACTION--dengroup,
allowgroup, denyuser, or allowuser
·
INHERITANCE--inherit,
or noinherit, default is inherit
·
METHOD--GET,
POST, topic, notify, route
·
URL--the
path on the KnowNow Event Router
·
ENTITY--either
the name of a user or group, as specified in the passwd and group
files
For Example:
To allow user "jenkins" to GET or POST to the Router:
allowuser inherit GET /kn jenkins
allowuser inherit POST /kn jenkins
To deny user "steve" to GET or POST to the Router:
denyuser inherit GET /kn steve
denyuser inherit POST /kn steve
To restrict the topic/foobar such that only one user can publish to the topic, modify the code as follows. In this example, sophie is the only user who will be able to publish to the specified topic:
allowuser noinherit notify /kn/foobar sophie
To restrict the topic /foobar such that only one user can delete or modify the properties of the topic, modify your code as follows. In this example, steve is the only user who will be able to delete or modify the specified topic.
allowuser noinherit topic /kn/foobar/kn_routes steve
To restrict the topic /foobar such that only one user can add or edit routes out of a specific topic, modify your code as follows. In this example, olivia is the only user who will be able to add/edit routes out of a specified topic.
allowuser noinherit route /kn/foobar/ olivia
The URLs in the allowuser lines are the topic names prepended with the path on the server the Router is connected to. So in the default case, where nomad is listening on /kn, you prepend that to the topic names as above.
In addition to the allowuser parameter, you can also use allowgroup to restrict access to only specified groups. The denyuser and denygroup parameters can also be used to subtract permissions that have been allowed by the allowgroup parameter setting.
passwd file entries are htaccess-style passwds; only the first two fields are used by the server. You can specify that a user not have a password by leaving the second field blank. In this case, the user still has to give a username to access the topic, but can leave the password field of the http challenge blank.
This section describes how you restrict access to various operations in the Router: deleting a topic, attaching filters to a topic, attaching filters to a Router, fetching and uploading a config file, setting default event expiration times, and setting max queue lengths.
Any user that has the permission to add or edit a topic's properties also has the permission to delete the topic. You can restrict deletion of a topic by using the permissions file settings. For more information on the permissions file, refer to perms. Some topics may not be deleted. The Event Router specifically protects against anyone deleting:
·
/kn_filters
Filters can be added to any topics, except the subtopic topics. The following apply:
·
A
filter cannot be added to any topic containing /kn_subtopics
·
Filters
can be attached to special topics, such as /kn_config and /kn_statistics during the runtime of a Router;
however, the filters will not be persisted.
·
You
can fetch a copy of the config file by retrieving the config_file event in the /kn_config topic. The payload of the config_file event contains the contents of
the Router configuration file.
·
You
can replace the contents of an existing config file by posting a new config_file event to the /kn_config topic. The event must contain
the new configuration file within the payload of the event. When the Router
receives the event, it will:
·
make
a copy of the existing config file and write it to disk
·
write
the new config file (from the payload of the new config_file event to disk
·
restart
itself with the new configuration file.
|
|
The Router must be running without the -f option (on Solaris/Linux), or as a service on Windows to restart itself automatically. For more information on Router installation, refer to the Event Router Getting Started Guide. |
You can use the kn_default_kn_expires header to set a default expiration time for events within a topic. Events expire based on the following rules:
·
/kn_subtopics topics always have an event expiration time set to
infinity
·
/kn_routes topics default to having an event expiration time of
infinity
·
/kn_journals topics default to having an event expiration time of JournalReconnectTimeout (which defaults to 60 seconds).
The JournalReconnectTimeout parameter can be specified in the
configuration file.
·
All
other topics default to having an expiration time of default_kn_expires (which defaults to 3600
seconds). The default_kn_expires parameter can be specified in
the configuration file.
·
The
event expiration time of any topic (except /kn_subtopics topics) can be changed by using
the kn_default_kn_expires header. You can set this parameter using the set_topic_property Router command.
The following example will set the topic called "mytopic" to have a default event expiration time of 600 seconds:
do_method=set_topic_property;kn_to=/mytopic;kn_default_kn_expires=600
You can limit the maximum number of events that are contained within a topic at any given time by setting the kn_max_queue_size property on the topic. By default, topics can have an unlimited number of events. If the kn_max_queue_size parameter is used, the topic acts as a FIFO (first in, first out) queue where only the last n events will be stored. For instance, the following example will set a max event queue length of 50 in the topic "mytopic." If the topic has 50 unexpired events, and a new event arrives, the oldest event in the queue will immediately expire in order to make room for the new event:
do_method=set_topic_property;kn_to=/mytopic;kn_max_queue_lenght=50
Editing of the topics/config is restricted only to the root user.
Before you can use the authentication and authorization modules, make sure you use a text editor to uncomment the following lines in .conf and verify the setup of the authentication and authorization files:
# ns_param authentication_module "${bindir}/knauthenticate${ext}"
#ns_param authorization_module "${bindir}/knauthorize${ext}"
After you have uncommented the above lines, ensure that the following settings are uncommented and point to the correct files:
# Authentication module settings
ns_section ns/server/${servername}/module/knauthenticate"
ns_param passwordFilePath "${homedir}/conf/passwd"
#Authorization module settings
ns_section "ns/server/${servername}/module/knauthorize"
ns_param permsFilePath "${homedir}/conf/perms"
The tunnel_header option allows you to send additional http headers down a tunnel connection when it is opened. You can set as many tunnel_header statements as you like. The tunnel_header parameter(s) must be set in the nskn section of the config file. For example:
A cluster is when two or more Routers are configured into a cluster to provide:
·
machine
fail-over mechanism
All Routers in a cluster mirror each other to look and act like one Router.
|
|
Clustering Routers does not help improve performance or throughput. In fact, there is a slight amount of overhead associated with clustering which can cause a slight decrease in performance. |
The Failover mechanism allows for uninterrupted Router requests to happen even if one of the Routers in the cluster goes down. For example, if a cluster contains Router A, Router B, and Router C, and Router A in the cluster goes down, the other Router(s) continues to serve Router requests without interrupting service. However, you need to be careful when clustering machines to ensure data integrity.
Since there is no guaranteed ordering within an asynchronous distributed system such as a Router, it is important to understand how the cluster works to ensure that data remains in sync across all nodes in a cluster.
If you have multiple clients or an asynchronous client publishing update events to topics, you should feed all requests for those clients to a single node in the cluster. Otherwise, events crossing paths between cluster nodes will lead to inconsistency across the cluster.
For instance, if publishers P1 and P2 are both sending updates to a cluster with stock ticker and price information on IBM, the following situation could occur. Assume that P1 sends an event to node N1 with kn_id="IBM" and kn_payload="100". At the same time, P2 sends an event to node N2 with kn_id="IBM" and kn_payload="102". Each node will accept the request and pass it along to its peers. But due to latency issues, and the fact that the events are being duplicate-squashed and updated, it is possible that node N1 could end up with the opposite event as node N2. The current solution for this problem is to feed all incoming cluster requests to the same node. This can be accomplished using a load balancer. If one node goes down, the load balancer can switch to using the other node, and thus prevent the loss of routing service.
|
|
If a machine in the cluster goes down, and you restart the machine, it does not make any attempt to re-sync with the other machines. There is no transaction mechanism built into clustering; therefore, events (at any given time) may appear to be in a slightly different order. Ordering of events is not preserved across the nodes in a cluster. Therefore, topics may contain the same events, but they may be stored in a different order on each clustered Router. |
Clustering can also be used to increase the total number of connections to the Router. The number of connections on a Router is limited to the operating system's limits for open file descriptors. Solaris allows 64K file descriptors; whereas, Microsoft Windows and Linux allow 1K file descriptors each. You can exceed the operating system's limits by running several Routers in a cluster and distributing the connection load over multiple machines.
Router requests can be directed to any node in the cluster. The cluster module automatically takes each request and mirrors it across all of the other machines in the cluster. Therefore, every node in a cluster has the same topic hierarchy and receives all of the same events. However, the nodes in the cluster are not guaranteed to be exactly alike. The cluster configuration and route topology must be carefully planned to ensure that cluster nodes have the required level of similarity. For more information, refer to How to Cluster?
To run a cluster, you must first configure the cluster parameter, which is located in the nsknc section of the KNRouter configuration file. Before you can configure the cluster, you may need to uncomment the nsknc parameter in the modules section of the conf file. The cluster parameter takes a list of <host>:<port> combinations, separated by white space. There is no limit to the number of peers in the cluster, although practically 64 should be the limit. The default value is a dummy value that will not create any clusters.
The following example presents a scenario for setting up a cluster of two machines. See figure below:
set hostname http://www.mysite.com
For machine 1:
ns_section "ns/server/${servername}/module/nskn"
local_host foobar.com:8888:443
ns_section "ns/server/${servername}/module/nskn"
If you copy the config file from one machine in the cluster to another, make sure that the local_host statement is set up for that specific machine and not copied over for a different machine.
ns_section "ns/server/${servername}/module/nsknc"
Notice that the example defines a cluster made of two peers: one listens on IP address 1.2.3.4 at port 8080; the other, which resolves to the IP address the DNS returns for foo.bar.com, listens on port 8888. Notice also that quotes are necessary; however back slashes (\) are used to break lines for a cleaner code.

|
|
The config file for each machine in the cluster should be exactly the same except for the local host statement. |
·
On
each client cluster box, remember to set the hostname to the externally visible
DNS name of the cluster.
·
You
must keep the <host>:<port> combinations in sync with the top-level
"httpport" and
"address"
variables in the configuration file. Each peer must be able to recognize itself
as one of the values in the cluster list. Also, the client must ensure that the
nsknc module is loaded
at KNRouter run-time.
The existing entry for nsknc
in the "modules"
section is commented out by default.
·
Each
value in the cluster list must contain the exact same cluster value in their
local copy of the configuration file.
·
When
clustered, the cluster can receive SSL requests but the intercommunication
between clustered machines is only http. To ensure security, make sure that all
machines within the cluster are behind the same firewall. Clustering requires
HTTP communications to be enabled so that cluster members can communicate. If
you need HTTPS-only Routers to work in a cluster, use a firewall or load
balancer to block connections to port 80 on the cluster boxes (and only allow
HTTPS connections on port 443).
·
The
KnowNow Config Utility cannot be used through a load balance interface in a
cluster configuration. The recommended approach is that you get one version of
the .conf, perm, passwd, and group files just the way you want it, copy these files to each
of the cluster machines, and then restart the cluster machines.
The KnowNow Event Router uses Berkeley's SleepyCat database (see http://www.sleepycat.com/) to maintain a persistent state on disk. This allows the Router to be stopped and then restarted in the same state (that is, all of the topics and events that exist when a Router exits are available when the new Router starts).
|
|
Since there is no guaranteed ordering within an asynchronous distributed system such as a Router, events (at any given time) may appear to be in a slightly different order. |
Previous versions of the KnowNow Event Router (v1.2 and earlier) used a custom implementation to achieve this functionality. The v1.3 Router had an embedded implementation of the SleepyCat database to maintain persistent data. The v1.5 Router has a new dynamic SleepyCat module to maintain persistent information. The v1.5 Router is almost identical to the v1.3 module except for a few minor differences to the configuration file.
·
Version
1.7 persistent files are different than the earlier versions. The Router will
automatically upgrade to v1.7 when it's run. You cannot use the 1.7 database on
a 1.6 Router after it has been upgraded.
·
Old
persistent files (v1.2 and earlier) are not backwards compatible with the v1.3
or v1.5 Router formats. Starting a v1.3 or v1.5 Router will automatically
delete old persistence files (v1.2 or earlier).
·
v1.3
versions of the persistence files will automatically be upgraded to use the
v1.5 Router format the first time you use the v1.5 Router. However, you will
NOT be able to roll back to the v1.3 format once the Router has upgraded the
database.
The v1.5 Router supports the following configuration parameters for persistence. In the configuration file conf/knrouter.conf:
Under the KnowNow Persistence section (nsknp):
ns_section "ns/server/${servername}/module/nsknp";
ns_param persistence_file ${serverroot}/knrouter.prs;
ns_param persistence_interval 600;
Under the KnowNow section (nskn):
ns_section "ns/server/${servername}/module/nskn";
ns_param persistence_module "${bindir}/nsknp${ext}"
The persistence_file parameter specifies the location of the database file. If the file does not exist when the Router starts, it is created automatically. A temporary database directory is also created automatically, if it does not exist. The database directory is only needed while the Router is running and may be deleted by the Router or manually after the Router is shut down. The temporary database directory has the same name as the persistence file with the string _db appended. For example, when the Router is running you may see something like this:
/usr/local/knrouter/runtime/knrouter.prs //Database file
/usr/local/knrouter/runtime/knrouter.prs_db //Database directory
The persistence_interval parameter specifies how often non-atomic persistence information will be flushed out to disk. The interval is specified in seconds. In the example above, the Router flushes a snapshot of its state to disk every 600 seconds. This means that if the Router is abnormally terminated or crashes, it will only lose 600 seconds (at most) of information that cannot be recovered. The Router will always try to persist its state when it exits, so it is possible that even if the Router crashes, 100% may be recoverable.
The persistence_module parameter specifies the name of the persistence module. The persistence functionality of the v1.5 Router has been moved out of the Router core and into a module. This allows you to develop your own modules for handling persistence using the Router's persistence API functions. The default configuration includes a module for using the SleepyCat database for persistence. You may configure the Router to not persist any information about the Router by removing this statement from the configuration file.
The atomic_router parameter instructs the Router to flush all topic and event information to disk continuously (as events occur). This allows the Router to have the best chance to recover 100% of its state following a shut down or crash, but may have a slight performance penalty.
The atomic_topic parameter instructs the Router to continuously save a single topic's events to disk as they occur. This works in the same way as the atomic_router parameter, but only for one topic (per atomic_topic statement). Multiple topics can be run in atomic mode (without the whole Router being atomic) by specifying each atomic topic name with an atomic_topic statement in the configuration file.
The new persistence information should not be moved using regular file move/copy/rename commands. Using these commands could result in two potential problems:
·
if
the Router is running, it is likely that the copy of the database will be
inconsistent from the original or could even be corrupted (because the Router
could be in the middle of writing while you are copying).
·
the
database actually stores file-specific information within the database that
will become inconsistent if you copy, move, or rename the database using
standard file system commands, even if the Router is not running.
To get around this problem, use the db_kncopy utility to copy Router persistence information. This utility must be used every time you copy, move, or rename the persistence information. In addition, it can be used while the Router is actually running. The utility actually connects to the database, sets the necessary locks, and allows you to backup your persistence database without stopping the Router.
db_kncopy [-V] source_db destination_db
-V prints version information
source_db is the source database persistence file
destination_db is the destination database persistence file
The following example copies the knrouter.prs file to the backup.prs file .
db_kncopy knrouter.prs backup.prs
You can turn on SSL support for the Event Router by setting options in the config file.
# ns_param nsopenssl ${bindir}/nsopenssl${ext}
This setting is configured from the httpsport setting, common to the entire Event Router. The httpsport setting is located near the top of the configuration file; it sets the port on which to listen for SSL-encrypted connections. The default is 8443.
This setting is configured from the hostname setting, common to the entire Event Router
The CertFile parameter should point to the signed certificate file from the Certification Authority (CA). The KnowNow Event Router certificates need to be in PEM format, which can be generated by several public CAs, as well as by all the major CA infrastructure products. This file resides in the conf/ subdirectory, along with the configuration file.
The KeyFile parameter should point to the RSA private key for the router. This file resides in the conf/ subdirectory, along with the configuration file.
To enable SSL on a router, you must generate and install a certificate:
$ /usr/local/kn/bin/genrsa -out /usr/local/kn/conf/rsa.pem
$ /usr/local/kn/bin/req -new -key /usr/local/kn/conf/rsa.pem
·
Country
Name (2 letter code) [AU]:
·
State
or Province Name (full name) [Some-State]:
·
Locality
Name (e.g., city) []:
·
Organization
Name (e.g., company) [Internet Widgits Pty Ltd]:
·
Organizational
Unit Name (e.g., section) []:
·
Common
Name (e.g., YOUR name) []:
|
|
In the Common Name field, type the full hostname of the machine on which the router is running, for example, www.mycompany.com. |
|
|
All of the major certificate authorities generate free "developer" certificates. These certificates, which are signed by invalid CA roots, are still useful for testing purposes. Refer to their respective web sites for more information. |
This section describes how your applications can use HTTP and HTTPS to send information to and receive information from an Event Router. This chapter contains the following sections:
·
Understanding the Event Router
·
Events
The KnowNow Event Router enables application-to-application communication across the Internet by providing real-time event subscription and publication services. Each Event Router routes events from publishers to subscribers. The router can send and receive events from any application to many applications, including Web browsers, in real-time, anywhere on the Internet. The Event Router is reliable, secure, easily managed, and highly scalable. The Event Router can coexist with your existing application servers, databases, and enterprise application integration (EAI) solutions.
Any client application that is connected to an Event Router can act as an event publisher, a topic subscriber, or both. Topics themselves can also subscribe to other topics, allowing you to construct a hierarchy of topics and distribute one event into many topics or combine events from multiple topics into one new stream.

A topic is identified by a Uniform Resource Identifier (URI), for example:
To avoid naming conflicts, the topic name should start with a domain name, for example:
/knownow.com/chat/technology/xml
A topic name can contain roman letters, digits, slashes, underscores, dashes, periods, and non-ASCII characters.
Your application can create a topic by simply referencing the topic in a request to the Event Router.
When your application publishes an event, it always specifies a topic. The topic defines how the event is to be routed to all the subscribers of that topic. A route can point to another topic or to a generic listener.
Topics fall into three basic
categories: topics, meta-topics, and journals. Topics are the primary nodes in
a route topology where data is posted to. Topics may have meta-topics that are
used to store information relevant to the topic such as hierarchy and routing
data. Current meta-topics include
/kn_subtopics, and /kn_routes.
kn_subtopics
store events that correlate to a topic's children and /kn_routes
store events that correlate to the routes out of a topic. Meta-topics are
created only as needed.
Meta-topics provide a unique feature of
introspection to the Router. It is possible to subscribe to meta-topics in
exactly the same manner in which you subscribe to any other topic. For
instance, if you subscribe to a topic's
/kn_routes
meta-topic, you will receive events every time a route is added or removed from
the topic. The same principle applies to
/kn_subtopics.
Journals are topics that have a persistent connection to a client over special routes called tunnels. Events for tunnels are created in the /kn_routes topic of the journal, but may be used for introspection purposes only. For instance, you may subscribe to a journal's /kn_routes topic to monitor the events that are generated when a client connects to or disconnects from the Router over a persistent connection. But you would not be able to modify those events and impact the behavior of the tunnels in any way.
Each event processed by the Event Router contains a set of headers, consisting of a name and a value. Each name and value is a string of Unicode or UCS characters.
Headers may appear in any order within an event, but each header must have a unique name. The order of headers is not preserved. Headers and values may include any UCS or Unicode character (including reserved characters and characters not yet allocated) and may be of any length.
In the examples that follow, these tags are used to represent special characters:
·
NUL - A null character (character 0 , U+0000 ).
·
LF - The line feed character (character 10 , U+000A ).
A sample event might include the following headers:
·
A
header named "header1" with the value "value1".
·
A
header named "headerLFthree isNULlong" with the value "1".
·
A
header named "kn_id" with the value "979273892_861_2249".
You use either the HTTP GET or POST methods to send a request to an Event Router. For most requests, the Event Router will return a status event that indicates the success or failure of a previous request.
The HTTP POST method is preferred for some requests (route and notify) as it avoids lengthy URLs.
The GET method is preferred for request types whose results are intended to be cached for long periods of time, such as lib, blank, and whoami.
·
For
HTTP POST requests, parameters are sent as POST data in application/x-www-form-urlencoded format.
·
For
HTTP GET requests, parameters are sent as URL query strings in application/x-www-form-urlencoded format.
·
Parameters
and values use the UTF-8 character set encoding.
·
Path
information, the part of the URL path following the server URL, can be used to
specify a default topic for route and notify requests, but is not considered to
be a parameter.
·
Your
application can use the parameters described in HTTP Interface
Control to
select the desired Event Router operation or option.
·
Parameters
described in Headers required for all events are available as event headers
and, except where otherwise noted, are propagated along routes.
·
With
the exception of parameter names starting with kn , parameters not listed here are
generally available for use by your application as application-specific event
headers.
·
All
parameter names starting with kn_ are reserved for use by the Event
Router.
·
Parameters
described in Status event parameters are used in status events
generated by the Event Router to indicate the success or failure of a request.
Your application can use the HTTP Interface (Control) parameters to select operations and set Event Router options. Your application specifies one of the following do_method values and any of the required parameters for the desired operation.
If an HTTP GET request does not specify the do_method parameter and other parameters are provided, the Event Router will treat it as a route request. If an HTTP GET request specifies no parameters, the Event Router will treat it as a help request.
If an HTTP POST request does not specify the do_method parameter and other parameters are provided, the Event Router will treat the request as a notify request.
|
|
All topic and notify commands look at the kn_to parameter to see if the destination of the request is on the current Router. If the request is not on the current Router, the request is forwarded to the proper Router. All route commands look at the kn_from parameter to see if the source of the route is on the current Router. If it is not, the request is forwarded to the proper Router. The Router will proxy the request and then return the response information from the destination Router. |
|
Contains a single request in application/x-www-form-urlencoded format. Several kn_batch parameters may occur in a single batch request. |
||
|
Topics that have routes with the kn_deletion header set, will send a deletion event along the route any time an event is deleted from the topic. This event contains the same kn_id as the event that is being deleted, an empty payload, and a header set inside it as kn_deleted=true. |
||
|
This header is set to true, and sent along with deletion events. |
||
|
/postit or http://foo/kn/postit The Router looks at kn_from for Router commands. |
||
|
Selects a format, simple or js, for events returned in the HTTP response. See also kn_response_flush. |
||
|
The route's destination, such as /what/chat, http://foo/kn/what/chat If the kn_to parameter is not specified, kn_to defaults to the path information. The Router looks at kn_to for any topic or notification commands. |
||
|
The topic to publish the event to. The topic to which status events are redirected, for example: /who/anonymous/s/22690909/kn_journal) If this is not specified, status events will be returned in the HTTP response. |
||
|
A value to place in the kn_route_location header of status events, as described in Status Events. |
The following parameters are used in route requests to control the immediate transmission of previously-transmitted events along a new route. If multiple parameters are specified, the route will be populated with the events which meet all the criteria specified by the parameters.
|
|
do_max_n and do_max_age subscriptions cannot be used together. |
The Event Router generates status events to indicate the success or failure of most requests. Status events will also be generated for requests with unknown do_method values.
Separate status events are generated for each request contained within a batch request as well as a status event for the batch request itself.
If kn_status_to is not specified, the status events are returned in the body of the HTTP response and the status code and the reason phrase of the HTTP response are taken from the status field of the first status event. The kn_response_format parameter determines how the events are represented.
If kn_status_to has been specified, the HTTP response uses 204 No Content as the HTTP status code and reason phrase. In accordance with RFC 2616, there will be no response body. Instead, the events are forwarded to the topic whose URL is specified as the value of kn_status_to.
This section describes how you can define and use your own filters for performing custom data transformation on event contents or blocking event entirely. This section covers the following topics:
·
Understanding
the Filter API
·
Attaching
and Detaching Filters
As the Event Router processes events it receives, it can pass control to your filter plug-ins that you have created and configured. Filters can perform simple tasks, such as logging the contents of each event, or complex tasks, such as event data transformation or translation.
Filters you create can be attached to topics or to individual routes. When a filter is attached to a topic, control is passed to the filter each time an event is published to that topic. When a filter is attached to a route, control is passed to the filter each time an event is traversing the route. In either case, you can design your filter to examine and modify the contents of each event using criteria you specify.
Filters you create must be packaged as shared objects or DLLs, using the C++ API described in this section and in Event Router Module API.
Prior to starting the Event Router, the Router's configuration file must be modified to define the filters you wish to use. The configuration file entries also specify parameters that you may wish to pass to your filters, described later in this chapter.
The Event Router communicates with your filter plug-in using well-defined callback functions during three basic phases of operation; start-up, event filtering, and shutdown. Your filter plug-in must implement callback functions for each of these phases. For more information on the filter API, see Event Router Module API
When your filter plug-in is initialized at startup time, the Event Router will invoke your filter's KnModuleStart function. This function is called only once, so it's not required to be a threadsafe implementation.
Your filter plug-in's implementation of this function can provide any required initialization, such as connecting to an external system or initializing an internal XSLT engine.
Your filter plug-in can read configuration settings from the Event Router's knrouter.conf file, which can be configured to contain host names and login information for external systems the filter will use.
Upon completion, your plug-in's KnModuleStart implementation should return an indication of the overall success or failure of the initialization processing. If a failure indication is returned, the Event Router ignores the filter from that point on.
KN_EXPORT KnError KnModuleStart(const KnString &path, const KnSet &info)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnModuleStart()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Path = %s", path.c_str());
for (size_t i = 0; i < info.size(); ++i)
KnLog(KnLogNotice, "SAMPLE_FILTER: Info [%u] = %s : %s",
i, info[i].m_key.c_str(), info[i].m_value.c_str());
When the Event Router is shutting down, your filter plug-in's KnModuleStop function will be called. Your plug-in's implementation of this function should provide any necessary clean-up processing, such as disconnecting from any external system and freeing any resources that may have been allocated. This function is called only once, so it's not required to be a threadsafe implementation.
KN_EXPORT KnError KnModuleStop()
{
KnLog(KnLogNotice, "SAMPLE_FILTER: KnModuleStop()");
Once the Event Router has loaded your filter plug-in and called the KnModuleStart function, client applications can attach the filter to topics or routes within the Event Router. If a filter is attached to a topic, control is passed to the filter each time an event is published to that topic. When a filter is attached to a route, control is passed to the filter each time an event is traversing the route.
The KnFilterTopicAttach function is called each time your filter plug-in is attached to a topic. The KnFilterRouteAttach function is called each time your filter is attached to a route.
An individual filter may be attached multiple times within the Event Router's topic and route hierarchy. KnFilterTopicAttach/ KnFilterRouteAttach is like a constructor called with parameters for a particular instantiation of the filter.
|
|
Your KnFilterTopicAttach or the KnFilterRouteAttach implementation must be threadsafe. |
KnFilterTopicAttach always provides the URL of the topic that events are going into. KnFilterRouteAttach always contains destination URI of the route on which the plug-in has been attached. The client application attaching your filter may optionally specify a set of parameters to be passed as part of the attachment. This allows filters to be parameterized for each individual attachment just as a class can be instantiated as several different objects.
For example, you might create a generic XSLT transformer filter plug-in that is attached in five different locations. Each attachment of the same filter can be given its own XSLT sheet to govern the transform it will provide on an individual topic or route.
This sample implementation of KnFilterTopicAttach simply logs the passed parameters and the URI before returning.
KN_EXPORT KnError KnFilterTopicAttach(const KnString &filterParams, const KnString &uri, bool &transform)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicAttach()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());
// Do not allow the filter to modify events as they pass through
KN_EXPORT KnError KnFilterRouteAttach(const KnString &filterParams, const KnString &source, const KnString &dest, bool &transform)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteAttach()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());
// Allow the filter to modify events as they pass through
The KnFilterTopicDetach function is called whenever a filter is removed from a topic. KnFilterRouteDetach is called when a filter is detached from a route. Your implementation should clean up any per-attachment resources that may have been allocated.
|
|
Your KnFilterTopicDetach or the KnFilterRouteDetach implementation must be threadsafe. |
This sample implementation of KnFilterTopicDetach simply logs the passed parameters and the URI before returning.
KN_EXPORT KnError KnFilterTopicDetach(const KnString &filterParams, const KnString &uri)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicDetach()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());
KN_EXPORT KnError KnFilterRouteDetach(const KnString &filterParams, const KnString &source, const KnString &dest)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteDetach()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());
Your filter plug-in's KnFilterTopicEvent function is invoked by the Event Router whenever an event is being published to a topic. KnFilterRouteEvent is called when traversing a route to which the filter is attached. The KnFilterTopicEvent or the KnFilterRouteEvent callback is passed using the following arguments:
·
URL
of the topic for topic filters; for route filters, there is a source and
destination URL.
·
Event
as a KnApiEvent object.
·
Any
parameters associated with this attachment.
·
A
discard flag you can set to true (1) if you want the Event Router the throw the
event away.
|
|
Your See KnFilterTopicEvent/See KnFilterRouteEvent implementation must be threadsafe. Since See KnFilterTopicEvent/See KnFilterRouteEvent can be called simultaneously from multiple threads, make sure locks are used to serialize access to any shared data. |
Your implementation of the See KnFilterTopicEvent/See KnFilterRouteEvent function can:
·
Examine
the headers and values in the event and even modify the contents (if the filter
was attached as a transform filter).
·
Use
the KnEventPost function to send the event to another topic on the Event Router
or to URI anywhere on the internet.
·
Completely
block the event by setting the discard flag to true.
This sample implementation of KnFilterTopicEvent simply logs the passed parameters, the URI, and the event contents. It then sets the discard flag to true and returns.
KN_EXPORT KnError KnFilterTopicEvent(const KnString &filterParams, const KnString &uri, KnApiEvent &event, bool &discard)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicEvent()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());
// Print the contents of the event to the log file.
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_id: %s", event.getKnId().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_time_t: %s", event.getKnTimeT().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_expires: %s", event.getKnExpires().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_payload: %s", event.getKnPayload().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_id: %s", event.getKnRouteId().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_to: %s", event.getKnTo().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_from: %s", event.getKnFrom().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_location: %s", event.getKnRouteLocation().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event expiration time: %u", event.getExpirationTime());
// Tell the router to keep the event for its intended destination
KN_EXPORT KnError KnFilterRouteEvent(const KnString &filterParams, const KnString &source, const KnString &dest, KnApiEvent &event, bool &discard)
KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteEvent()");
KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());
// Print the contents of the event to the log file.
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_id: %s", event.getKnId().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_time_t: %s", event.getKnTimeT().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_expires: %s", event.getKnExpires().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_payload: %s", event.getKnPayload().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_id: %s", event.getKnRouteId().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_to: %s", event.getKnTo().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_from: %s", event.getKnFrom().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_location: %s", event.getKnRouteLocation().c_str());
KnLog(KnLogNotice, "SAMPLE_FILTER: Event expiration time: %u", event.getExpirationTime());
// Tell the router to keep the event for its intended destination
Each filter plug-in is named with a
topic name under the /kn_filters topic. For example, an XSLT filter
might be named /kn_filters/xslt.
Since filters are named with topics, client applications can traverse the
/kn_filters/kn_filters
hierarchy to determine the list of installed filters on a particular Event
Router.
For each Event Router filter you plan to make available to client applications, you must add an entry like the following to the nskn section of the Event Router's configuration file.
ns_param filter_module "${bindir}/sample_filter${ext}=/kn_filters/sample_filter"
For information on the client application APIs for attaching filters, refer to the language guide that is appropriate for your client application:
·
C
Microserver for Solaris Programmer's Guide
·
Microserver
for Java Programmer's Guide
·
Chapters
6 and 7 of the Event Router Programmer's Guide
·
C
Microserver for Solaris Programmer's Guide
This section describes how you can create and use your own Event Router modules that provide authorization or authentication for all Event Router requests. This section covers the following topics:
·
Understanding
the Security API
·
Configuring
the Security Module
The Event Router allows you to create security modules that provide user authentication or authorization. Authentication modules check the credentials supplied with a request, such as a user name and password, to validate a user. Authorization modules check the credentials supplied with a request to determine if access should be granted to a particular URL on the Event Router.
The security modules you create must be packaged as shared objects or DLLs, using the C++ API described in this chapter and in Event Router Module API.
|
|
Only one authentication module and only one authorization module can be configured for a given Event Router. |
Prior to starting the Event Router, the Router's configuration file must be modified to define the security modules you wish the Router to use. The configuration file entries also specify parameters that you may wish to pass to the module, described later in this chapter
The Event Router communicates with your security modules using well-defined callback functions for start-up and shutdown. Authorization and authentication modules must implement these callback functions. For more information on the module API, see Event Router Module API.
When your authorization module is initialized at startup time, the Event Router will invoke your module's KnModuleStart function.
As part of the initialization, the KnModuleStart implementation may do any necessary housekeeping, including connecting to an external system such as LDAP or RSA's SecurID®.
An authorization module will implement the KnModuleStart so that the KnSetRequestAuthorizeProc function is invoked to register the correct authorization function with the Event Router. The Event Router will pass control to the registered authorization function any time a request is received.
KN_EXPORT KnError KnModuleStart(
const KnString &path, const KnSet &serverInfo)
// get passwd file location from config
if (parseConfig(serverInfo) == KnErrorFailure)
if (parsePermsFile() == KnErrorFailure)
// register as the authorization procedure
if (KnSetRequestAuthorizeProc(authorizeProc) ==
An authentication module will implement KnModuleStart so that the KnSetRequestAuthenticateProc function is invoked to register the correct authentication function with the Event Router.
|
|
The Event Router will not invoke the registered authentication function directly. Instead, the authentication function must be invoked by the Authorization module. Though the samples shown use two separate modules, you are not required to de-couple the authorization and authentication functions: You can design a single Authorization module to provide both functions. |
KN_EXPORT KnError KnModuleStart(
const KnString &path, const KnSet &serverInfo)
// get passwd file location from config
if (parseConfig(serverInfo) == KnErrorFailure)
if (parsePasswordFile() == KnErrorFailure)
// register as the authentication procedure
if (KnSetUserAuthenticateProc(UserAuthProc) ==
Upon completion, your module's KnModuleStart implementation should return an indication of the overall success or failure of the initialization processing. On a failure indication, the Event Router ignores the module from that point on.
When the Event Router is shutting down, your module's KnModuleStop function will be called. Your module's implementation of this function should provide any necessary clean-up processing, such as disconnecting from any external system and freeing any resources that may have been allocated.
As the Event Router processes requests it receives, it passes control to the authorization function that was registered by your. In keeping with standard HTTP authentication conventions, control is passed to your registered authorization function before the Event Router has begun processing the request. The authorization function is given access to the unprocessed HTTP request in its entirety.
An authorization function is expected to return one of the following values:
·
KnErrorSuccess - access to the resource is allowed.
·
KnErrorUnauthorized - access to the resource cannot
be granted because the supplied credentials are incomplete.
·
KnErrorForbidden - access to the resource is
denied
Though the sample implementation shown in Sample implementation of an authorization function obtains password and permission information from static text files on a local file system, a module could obtain information from the Event Router's configuration file, HTTP request line parameters, cookies, or other sources.
|
|
The authorization callback is responsible for invoking the KnAuthenticateUser function. This will invoke the authentication callback registered by the authentication module. |
const KnRequest &req, const KnSet &headers, const KnSet ¶meters);
const KnString *denyString = 0;
const KnString *allowString = 0;
searchKeys(denyUser, req.url, &denyString);
searchKeys(allowUser, req.url, &allowString);
// We found no authorization entries for this url.
if ((denyString == 0) && (allowString == 0))
// We have auth data, did the user supply a username?
// If no username, let the browser popup an auth window.
if (req.authUser.length() == 0)
// spit out debug info if we're in debug mode.
KnLog(KnLogDebug, "knauthorize: user %s attempts access ...
// If user's password is incorrect, return UNAUTHORIZED
// Call the authentication function to check password
if (KnAuthenticateUser(req.authUser, req.authPasswd)
// is this user explicitly in the deny list?
(searchUserList(denyString, req.authUser)))
// is this user in the allow list?
(searchUserList(allowString, req.authUser)))
This section describes how you can set up the Authorization module and also describes different scenarios in which the Authorization module is invoked.
The Authorization module is called every time an application publishes data to the Event Router and also when an event traverses a route between two topics and on subscription requests.
To use the default Authorization module, make sure you use a text editor to uncomment the following lines in the knrouter.conf file and verify the setup of the authorization file:
ns_param authorization_module "${bindir}/knauthorize${ext}"
After you have uncommented the above lines, ensure that the following settings are uncommented and point to the correct files:
# Authorization module settings
ns_section "ns/server/${servername}/module/knauthorize"
ns_param permsFilePath "${homedir}/conf/perms"
To use the default Authorization module, you will also need to uncomment the Authentication module. See below:
# ns_param authentication_module "${bindir}/knauthenticate${ext}"
# Authentication module settings
ns_section "ns/server/${servername}/module/knauthenticate"
ns_param passwordFilePath "${homedir}/conf/passwd"
The illustration below shows how the Authorization module is invoked using an example with an Event Router and two applications.

Using the above picture as an example, you see that:
·
Scenario
#1: Application
B creates a
route from Topic X to Topic Y. The Authorization module in this
instance is invoked to ensure that Application B can subscribe to Topic
X
and write to Topic Y.
·
Scenario
#2: Application
A publishes an
event to Topic A and the Authorization module is called to ensure that the
user can publish data to Topic A.
·
Scenario
#3: Application
A publishes an
event to Topic X. In this scenario, the Authorization module is called before the
event is placed in Topic X and also when the event traverses the route from Topic
X to Topic
Y. The credentials used event
traversal are different:
·
Initial
Route Population (IRP): Application B may have requested to receive existing
events in Topic X (with do_max_n and do_max_age). Each event is passed through the
Authorization module using Application B's credentials to write to Topic Y.
·
Posts
to Topic X (after IRP is
complete): Application A POSTs an event to Topic
X. This causes the Router to
attempt to deliver the event to Topic Y. In this scenario, Application
A's credentials
are used when placing the event in Topic Y.
|
|
Additionally, the Authorization module is also called when the Router generates status events and places them into the subscriber's journal. |
KNError authorizeProc(const KnRequest &req, const KnSet &headers, const KnSet ¶meters);
KnString line; /* request line sent by the client */
KnString method; /* method requested by the client */
KnString protocol; /* protocol part of URL or empty */
KnString host; /* host part of URL or empty */
uint16_t port; /* port specified in url, or 0 */
KnString srcUrl; /* url where the request came from */
KnString dsturl; /* normalized url, without any query data */
KnString query; /* any query data appended to url */
KnString peer; /* ip address of the client */
double version; /* version of the client request */
KnString authUser; /* decoded user name */
KnString authPasswd; /* decoded user password */
size_t contentLength; /* number of bytes sent by the client */
Refer to knset.h in the include directory for the definition of knset.h.
|
|
The headers variable contains the http headers (as key-value pairs) sent in the request. The parameters variable contains all the user supplied parameters sent in the request (i.e. kn_to =/kn/foo) as key-value pairs. |
The Authorization Module is called to validate that you have rights to GET or POST to the Event Router. The dstUrl is set to "/kn" or to the value of the "url" specified in the nskn section of the Router's knrouter.conf file. The Authorization Module is also called every time an event is copied from one topic to another (traversing routes) and for every status event that is generated and written to your journal.
If the initial authorization passes, then the Router invokes the module again and specifies one of the following methods in the KnRequest argument:
The following calls and parameters are used when an event is published to the Event Router using POST and "do_method=notify ":
|
Parameter |
|
|
dstUrl |
If you POST an event to "/kn/what/test," but you do not have privileges to create "/kn/what/" but can create "/kn/what/test," then the Event Router will implicitly create "/kn/what." The Authorization Module will NOT be called when the topic "/kn/what " is created.
The following do_method commands will cause the authentication module to be invoked the " notify " method.
For more information on these do_methods, refer to Available do_method settings.
For an application to subscribe to a topic in the Router, a route from the source topic to the destination (could be the user's journal or another topic on this Router, or a URI) must be created.
This route is created in the kn_routes directory under the source topic. For example, if the application subscribes to "/kn/what/test," then the subtopic "/kn/what/test/kn_routes" will store the route that contains the details of this subscription.
The Authorization Module is invoked:
The following do_mthod commands will cause the Authorization module to be invoked using the "route " method:
·
delete_route
·
update_route
For more information on these do_methods, refer to Available do_method settings.
The "topic" operation includes the following do_method commands:
For more information on these do_methods, refer to Available do_method settings.
The Authorization Module is called,
·
Firstly,
to verify if you can POST to the "/kn " topic, i.e. can you post to the
Router. The parameters in this request are the same as in "notify".
·
Secondly,
to verify the actual topic operation. The parameters are the same as in "notify ", except that:
dstUrl = is the topic that is being manipulated. For example, "/kn/what/test"
The Authorization Module is invoked once for the following requests:
The Authorization Module is presented with all the HTTP headers that were sent with the requested operation. This allows applications to pass authentication credentials to the Router for use by the Authorization Module (for e.g. cookies).
The JavaScript Microserver uses status forwarding and batch mode to publish events. These cause the module to be invoked numerous times. The examples on the next few pages show invocations to the module for the following:
·
Subscribe
(Subscribe)
·
Publish
(Publish)
A subscription request from an application that uses the JavaScript Microserver generates twelve (12) events. The following example shows an HTML page loading the Microserver and subscribing to a topic:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmins="http://www.w3.org/1999/xhtml">
<title>Auth Check: Unsubscribe</title>
<!- - This test checks on the
<script type="text/javascript" src="/kn/?do_method=lib">
<script type="text/javascript">
topic = "/auth/check/subscribe";
rid = kn_subscribe(topic, receive_event);
alert("got an event on the subscription");
// - ->
</head>
<h1>Authorization check when subscribing</h1>
Following are various calls to the module when you view the previous page. Error cases have not been shown.
|
peer |
|
Parameter |
Value |
|
line |
"GET /AuthSubscribe.html HTTP/1.1" |
|
dstUrl |
"/AuthSubscribe.html" |
|
method |
|
|
line |
|
|
method |
"notify" |
|
dstUrl |
|
|
peer |
|
The following example shows an HTML page loading the JavaScript Microserver and publishing an event to the Router.
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>POST an event in an effort to check out Authentication and Authorization engine of the KN Event Router</title>
<script type="text/javascript" src="/kn/?do_method=lib">
<script type="text/javascript">
function waiting()
alert("setTimeout function called this in waiting module");
myEvent.kn_payload = "This is a auth check";
kn_publish(topic, myEvent, ({ onSuccess: function(e)
{alert("success"); succeed()},
{alert(e.status + " can't publish
to topic")}
</head>
These are the request parameters generated as a result of the "publish" action.
|
|
Execute steps 1 - 6 and 8 from the Subscribe authorization calls before executing #1 below. |
|
Value |
|
|
peer |
|
|
contentLength |
|
IP address of the client |
|
These are the request parameters generated as a result of the "Delete Topic" action from the Event Explorer. Note that the initial invocations to verify access to the Router, to the Microserver, and the Microserver's setup are omitted (steps 1-6 and 8):
|
"/kn" |
|
|
peer |
|
Parameter |
Value |
|
"kn/what/test" |
|
Q. What happens when Topic X is full
of events from several sources and a route is created to Topic X to Topic Y
with do_max_age
or do_max_n
specified?
A. This is referred to as Initial
Route Population (IRP), where the creation of a route may involve a delivery of
existing events from the source topic to the destination topic.
The Authorization Module is invoked to verify whether the creator of the route is allowed to read from Topic X. Additionally, the module is called for every event as it is read from Topic X and before it is written into Topic Y. At this time, the original publisher's credentials may be invalid (for example, cookie parameters). So for IRP, the route creator's credentials are used. Subsequent writes to Topic X will; however, use the credentials of the event publisher when the topic traverses this route.
Q. KnowNow uses a special topic "kn_journal" to hold events that need to be delivered to the subscribers. How does the Authorization Module work for this topic?
A. A journal topic is in essence a
URL that is accessible on the Internet. Microservers use the journal topic to
communicate between the Router and an application. Accordingly, the
Microservers set up a route to the kn_journal topic when an application subscribes to a topic. The
Event Router treats the kn_journal topic as just another topic and invokes the
Authorization Module for every event traversing the routes to this kn_journal
topic.
This functionality is useful for ensuring that you do not create a route from a topic into another user's journal.
This chapter describes how to use the JavaScript Microserver and contains the following sections:
·
Using the JavaScript Microserver
·
Simple Event Mapping Support
·
Writing Cross-Domain Web Applications
The JavaScript Microserver enables an application running in a web browser to communicate with the Event Router. The JavaScript Microserver is installed when you install Event Router, described in Installing the Event Router.
You use the JavaScript Microserver in your application by including it in your application code as, shown in the following example. The Microserver <script> element must be included at the very beginning of your application, inside the HTML <head> element and before any other <script> elements.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="/kn/?do_method=lib" type="text/javascript"></script>
Once the JavaScript Microserver is loaded, the page will stop its normal loading process and will be wrapped in a frameset. The frameset contains three frames that enable communication with Event Router:
·
A
visible frame where your application is loaded.
·
A
hidden post frame for sending requests to the Event Router.
·
A
hidden receive frame that receives events over a persistent HTTP connection to
the Event Router.

The JavaScript Microserver uses the top level of the hidden frameset, allowing the Microserver to persist even when frames in your application are reloaded. When your application is loaded in the visible frame of the frameset, the Microserver creates a kn object as a property of the browser window object.
Since your applications will always be contained within a frameset, this may affect the way you construct your DOM (Document Object Model) references to windows, frames, forms, and divs.
|
|
If you are using Microsoft's Internet Explorer and have installed the ActiveX Microserver for Windows, see JavaScript ActiveX Shim. |
The kn object, described on kn, provides your application with several methods for publishing events to a topic, subscribing to a topic, and unsubscribing from a topic.
Your application can use the kn.publish method to publish an event to a topic on the server. This method also gives you the option of providing status handler objects to be invoked after the event is published to handle the status event returned by the Event Router. This invokes the Router's notify method, and allows all parameters allowed by notify.
Your application must construct the event to be published as a JavaScript object and pass it to the kn.publish method. An event is simply a JavaScript object that has event header names as properties and corresponding event header values as property values. When you publish an event, the kn_id of the newly published event is returned.
The following example publishes an event with a user-defined kn_payload with the contents "Hello world!" and a custom property named specialProperty.
// then add some data to it...
myEvent.kn_payload = "Hello world!";
myEvent.specialProperty = "extra special value";
kn.publish("/my/topic", myEvent);
After your application publishes the event, the Event Router would receive an event with the headers shown below. The values set by your application are shown in boldface.
·
kn_route_checkpoint: 987107695_12462_2224
·
specialProperty: extra special value
Since the sample application does not specify the kn_id , a unique identifier is automatically generated, added to the event, and returned as a string for later use by your application.
myEvent.kn_payload = "Hello world!";
eventId =
kn.publish("/my/topic", myEvent);
Your application can also use the kn.publishForm method to copy input elements from an HTML form into a new event object and then publish the event to a specified topic.
Your application can use the kn.subscribe method to subscribe to a topic and then receive events that are published to that topic. Any events published to the subscribed topic will be forwarded to your client and the appropriate destination function, specified by your application, will be invoked. This invokes the Router's route method, and allows all parameters allowed by route.
The kn.subscribe method also gives you the option of defining the maximum number or age of events that should be returned to your application. You may also provide optional status handler objects to be invoked to handle status events returned by the Event Router.
The following example defines an event handler that alerts the user of the kn_payload for each event received and then subscribes to the topic /my/topic.
kn.subscribe("/my/topic",
onMessage);
The destination you specify for a subscription can be any of the following:
·
A
function or closure that accepts the received event as a parameter, as shown
above.
·
An
object with an onMessage method that accepts the received event as a parameter.
topic: kn.subscribe("/my/topic", "/postit");
javascript URI : kn.subscribe("/my/topic",
kn.subscribe("/my/topic", onMessage);
kn.subscribe("/my/topic", { onMessage: function (e) { alert(e.kn_id) } } );
The following properties modify a subscription:
The following example shows how to specify options such that a maximum of ten (10) events will be received by the subscription.
// first create the options object...
// finally, subscribe to the topic and pass the options object
kn.subscribe("/my/topic", onMessage, options);
You may find it helpful to use the short form of object notation. Simply put the property:value pairs inside curly braces when you define the object, as shown below:
kn.subscribe("/my/topic", onMessage, { do_max_n:10 })
When your application no longer wants to receive events from a topic, it must invoke the kn.unsubscribe method, specifying the kn_uri associated with the subscription. You may also provide optional Status Handler Objects to be invoked to handle status events returned by the Event Router.
anRid = kn.subscribe("/my/topic", onMessage);
Your application can use a status handler object to attach functions to status events received from the Event Router. Your application must create an object with three methods and then pass it to the kn.publish, kn.publishForm, kn.subscribe, or kn.unsubscribe method when you are unsubscribing from a topic.
·
onSuccess is called every time a request completes successfully.
·
onError is called every time a request fails.
·
onStatus is called whenever any status message is received. If onStatus
is defined, onError and onSuccess will not be called.
If your have installed the ActiveX Microserver and your web browser supports ActiveX, you can configure your web browser and design your applications to use a JavaScript Microserver Shim instead of the event transport mechanism described in See Understanding the Microserver Frames.
|
|
The JavaScript Shim can only be used with web browsers that support ActiveX and on machines where the ActiveX Microserver is installed. The ActiveX Microserver is described in the Microserver for Windows Programmer's Guide . |
Microsoft Internet Explorer's security setting may be changed using the Internet Options dialog.
|
|
These settings may allow harmful programs to run on your computer, so you may wish to place the application's URL in the special Trusted Sites security zone, and only change the settings for that zone. Consult with your system administrator before making changes which affect your web browser's security settings. |


To use the JavaScript Microserver ActiveX Shim, simply include the script element shown below, before including the JavaScript Microserver.
<!-- KnowNow JavaScript Microserver ActiveX Shim -->
<script
type="text/javascript"
src="/kn_apps/kn_lib/activex.js"></script>
<!-- KnowNow JavaScript Microserver -->
<script type="text/javascript" src="/kn?do_method=lib"></script>
This shim disables the frameset wrapping normally performed by the JavaScript Microserver. Most applications will not be affected by this change. None of the high-level API of the JavaScript Microserver is affected by the shim, with the following exceptions:
·
Due
to a bug in the Internet Explorer JavaScript-ActiveX bridge, NUL characters in received event
header names and values are not preserved, and prematurely terminate strings.
If the kn_options flag single is present, NUL characters have the same effect in outbound event header names
and values.
·
kn__submitRequest uses the ActiveX Microserver and
ignores the kn_options flag noforward . The kn_options flag single still has the usual effect.
·
kn__restartTunnel has no effect.
·
Unless
the kn_options flag quiet is present, failure to open the tunnel connection will present an
informational dialog briefly describing the shim configuration properties, and
instructing the user to make any necessary changes and reload the page.
The shim has several properties which you can set using either the command-line parameters or window properties. Window properties must be UTF-8 encoded and set before loading the KnowNow JavaScript Microserver.
This feature is for developers who wish to move an object from one platform to another. MIME types are used as the typing scheme, and it is recommended that users serialize their objects into an appropriate MIME type.
The Simple Event Mapping Support feature provides support for applications to map inbound events (coming in from subscriptions the applications have made) into objects/data types. It also allows applications to map objects, which they are attempting to publish, into events.
The mapping does not happen automatically. The application registers certain callbacks with the Microserver, requesting that when an event with a particular header or value inside is received on a particular subscription, the Microserver should call a particular callback to map the event data into an object and then process that object.
The JavaScript Microserver supports plain MIME types ("text/plain," "application/xml", "image/gif", etc.) as well as the RFC-proposed "+xml" extensions for XML-derived content types.
Following is a list of examples (in an order of de-serialization preference):
·
text/x-my-dtd+xml [for XML formats]
·
text/x-my-dtd [for non-XML formats]
·
text/*+xml [for generic XML text handling]
·
text/* [for generic text handling]
·
*/*+xml [for generic XML handling]
·
*/* [the universal fallback]
The default MIME type of an event is "text/plain".
On the publication side, the programmer will need to implement JavaScript serialization (toString) methods on all objects, then use them as kn_payload values, and specify appropriate MIME types in the content-type header.
{ "content-type": "application/x-js-date",
{ "content-type": "application/x-js-window",
On the subscription side, the programmer will need to register single-string-argument constructor functions corresponding to different MIME types or wildcards, and call kn.filter in event handlers to construct objects corresponding to events.
kn.setFilter("application/x-js-date", Date);
kn.setFilter("application/*", String);
alert("[" + (o ? o.constructor : typeof o) + "] : " + o);
Cross-domain web applications are applications where the HTML lives on a standard web server (or is being generated by an application server), but the application wants to embed the KnowNow JavaScript Microserver. The problem that you face is that the JavaScript security model in the browser does not allow the application, which comes from " apps.biz.com", to communicate with the KnowNow Event Router at "kn.biz.com ".
The JavaScript Microserver library offers a built-in option to allow the HTML application and Microserver to sidestep the JavaScript security restrictions imposed by the browser, thus making your application a cross-domain application.
To create a cross-domain web application, you must have the following:
·
an
intermediate level of knowledge of JavaScript
·
a
knowledge of the basic steps for writing a web application
·
a
web application that uses a single protocol, either HTTP or HTTPS
|
|
To run your application in Netscape 4, both servers must use the default port, either HTTP on port 80 or HTTPS on port 443. While you must use the default port, you must not specify the port in the URL. |
To make your application a cross-domain application, you need to do the following:
To enable cross-domain communication between your application and the Router, you must modify the javascript_domain and javascript_kn_server parameters in the Router's knrouter.conf file. You can modify the Router's configuration either by opening the knrouter.conf file in a text editor or by using the Event Router Configuration Utility packaged with the Router. For more information on using the Configuration Utility, please refer to the KnowNow Event Router Getting Started Guide.
The Microserver uses the javascript_domain parameter to set the document.domain property, which signals to the browser that the Router is part of the same security domain as the HTML pages (loaded from the application server).
Set the javascript_domain parameter to the common suffix of the application server and Router domain names, or, if you are using a single IP address (see Using a Single IP Address), use the domain or machine name. This parameter must be entirely in lowercase:
ns_param javascript_domain "biz.com"
The Microserver uses the javascript_kn_server parameter to determine the full URL for the Router's root event notification topic.
Set the javascript_kn_server parameter to the fully-qualified domain name for the Router followed by the kn_server pathname, "/kn ". If you are using a single IP address, use the domain or machine name and the portnumber (see Using a Single IP Address). This domain name must be identical to the one specified in the src attribute of the application's script tag, for example:
ns_param javascript_kn_server "http:\\kn.biz.com/kn"
|
|
It is important that you do not include a closing slash at the end of the kn_server pathname or any double slashes (other than the one following the "http:") when modifying the javascript_kn_server parameter because the value of kn_server is also used to resolve topic names. |
Once you have finished modifying the knrouter.conf file, you must re-start the Router.
Let us assume that the Router is hosted at kn.biz.com, and the pages that make up the application are being served from apps.biz.com. The src attribute of the <script> tag should contain the URL of the Router location including fully-qualified domain name. This ensures that the Microserver library is loaded at the correct location.
<html>
<title>My KnowNow Application</title>
<script type="text/javascript"
src+"http://kn.biz.com/kn/?do_method=lib"></script>
|
|
Use the fully-qualified domain name corresponding to the IP address of the Router to avoid JavaScript security issues. Also, the domain name must be entirely in lowercase. |
|
|
A cross-domain web application that uses document.open() may produce errors due to the browser's security limitations. |
An application may contain HTML pages that do not use the Microserver functionality but need scripting access to the other pages. For example, an application may use JavaScript across frames and framesets. These pages should contain a script tag that calls the do_method=whoami action of the KnowNow Event Router. This way, the browser will allow any JavaScript within these pages to interact with the other pages of the application.
<script type="text/javascript"
src="http://kn.biz.com/kn/?do_method=whoami"></script>
Alternatively, you can add a script tag to your application code that sets the document.domain property to the common suffix of the application and the Router host domain names.
You can have the application server and the Router on the same IP address, for example, with the application server using port 80, and the Router using port 8000.
|
|
You cannot run a cross-domain application on a single IP address if you want to support Netscape 4.x because Netscape 4.x requires both the application server and the Router to use HTTP on port 80 or HTTPS on port 443. |
The src attribute of the <script> tag should contain the URL of the Router, including fully-qualified domain name and portnumber. If you are not part of a domain, use the fully-qualified machine name instead.
<title>My KnowNow Application</title>
<script type="text/javascript"
src="http://kn.biz.com:8000/kn/?do_method=lib"></script>
This section provides a quick reference to the JavaScript Microserver as well as the associated variables, properties, and objects. This section includes the following:
·
self
·
kn
·
KN
·
String and Character Support
·
Using Command-Line Parameters
self refers to a Window, FRAME, or IFRAME object, where the JavaScript Microserver is active.
set in UTF-8 before including the Microserver library
The value supplied with this property is inserted into the main application's <frame> tag. If you do not want scroll bars, for example, set it as follows:
noresize="noresize" scrolling="no"
The global argument object, initialized when the Microserver library is loaded.
Holds the URI of a blank page which can be used in your application as the initial source for a frame in a frameset. It is in the same JavaScript browser security domain as the kn_server URL and provides kn_redrawCallback.
set in UTF-8 before including the Microserver library
Lists all of the options that will be enabled in the same format as used by kn_options, which overrides it.
set in UTF-8 before including the Microserver library
Describes the user identified by kn_userid in human-readable format. This may be a value supplied by the Event Router, a value given for the kn_displayname command-line argument, or a default value such as Guest User or Anonymous User.
set in UTF-8 before including the Microserver library
Serialization of initial event hash cache contents, loaded by the Microserver at startup using kn.setHashCache().
set in UTF-8 before including the Microserver library
A comma-separated list of language codes and optional quality values used when looking up localized messages; the default is the empty string (""), which disables localization. This is copied from the Accept-Language HTTP header by the Event Router. The following specification would indicate a preference for all types of Chinese, but an acceptance of U.S. English or other types of English when Chinese is unavailable.
set in UTF-8 before including the Microserver library
Initial value for kn.lastTag, the do_since_checkpoint value for the tunnel route.
The number of events allowed before a tunnel restart is performed. Used to tune memory consumption in older web browsers.
set in UTF-8 before including the Microserver library
Used in place of the URL query string, overriding the portion of the URL following the question mark.
Controls the number of filler bytes (from 0 to 4,095) sent when the Router detects a lull in the event stream for a particular tunnel connection.
The number of filler bytes is configurable using the kn_response_flush request parameter. If no value is supplied, the number of bytes is determined automatically. The JavaScript Microserver allows this parameter to be set before loading the Microserver by storing the value in the kn_response_flush property of the self object. See also, Parameters for kn_response_format.
set in UTF-8 before including the Microserver library
The URI of the Event Router to use; this URI must not end in the slash character ("/"). By default, kn_server contains the URI of the Event Router that supplied the JavaScript Microserver. That is, the server which satisfied the request for the do_method=lib script.
Contains localized versions of messages indexed by language code, then context, then original message. Use the kn_localize() and kn_localizeDefault() methods to define this table; use the kn_createContext() method to define new localization contexts, and use the $$() and $$_() methods or contextual specializations (such as $() and $-() for the default context) to use localized strings in your JavaScript program.
set in UTF-8 before including the Microserver library
Initial value for kn.tunnelID, the tunnel route kn_id.
set in UTF-8 before including the Microserver library
Initial value for kn.tunnelMaxAge, the do_max_age value for the tunnel route.
set in UTF-8 before including the Microserver library
Initial value for kn.tunnelURI, the tunnel route source topic URI.
set in UTF-8 before including the Microserver library
Identifies the user in the context of the web application. This may be a value supplied by the Event Router, a value given for the kn_userid command-line argument, or a default value such as guest or anonymous.
Usage
|
|
Description
|
|
Arguments
|
|
Returns
|
Returns a translation of the string or, if no localized version has been supplied, the original string. |
Usage
|
|
Description
|
Given a UTF-16 string, returns an array containing the corresponding UCS character codes. |
Arguments
|
|
Returns
|
Usage
|
kn_consumeEvents() |
Description
|
Handle dispatches from the leader. |
Arguments
|
|
Usage
|
|
Description
|
Default status handler for an unsuccessful event. |
Arguments
|
Usage
|
|
Description
|
Default status handler for handling the status event e. If handler is omitted, the status handler object is assumed to be this . |
Arguments
|
Usage
|
|
Description
|
Default status handler for successful status events. Returns without doing anything. |
Arguments
|
Usage
|
|
Description
|
Returns the application/x-www-form-urlencoded string for the router request e. |
Arguments
|
Usage
|
|
Description
|
Returns a textual representation of object recursive to the specified path. |
Arguments
|
Usage
|
|
Description
|
Opens a pop-up window and uses document.write() to fill the window with an HTML representation of object recursive to the specified path. |
Arguments
|
Usage
|
|
Description
|
Returns true if the window w is open and ready to use. Otherwise, returns false. |
Arguments
|
Usage
|
|
Description
|
Adds an entry to kn_strings containing a translation of the original message "original" using the context "ctx" into the specified language. If translation is null, the original message is used instead. |
Arguments
|
language is language into which "original" is translated. ctx is localization context name. original is the original message. translation is the translated message. |
Usage
|
kn_localizeDefault(language, "ctx" , "original" , translation) |
Description
|
Behaves exactly like kn_localize, except that it does not override existing message translations. |
Arguments
|
language is language into which "original" is translated. ctx is localization context name. |
Usage
|
kn_ _object(args…) |
Description
|
This function creates an object from a list of names and values. |
Arguments
|
args are optional arguments. |
Returns
|
|
See kn.publish.
See kn.publishForm.
Usage
|
kn_redrawCallback(w) |
Description
|
Called from kn_blank and used for kn.documents and KNDocument. |
Arguments
|
Usage
|
|
Description
|
Accepts an event in form style and converts it to a simple object, then dispatches it to the appropriate subscriber. |
Arguments
|
Usage
|
kn_ _submitRequest(e) |
Description
|
Submit (or possibly batch) a KN server request. |
Arguments
|
e is the router request to be submitted. |
Returns
|
Returns false until the request has been sent (or at least batched). |
Usage
|
kn_subscribe(topic, destination [,options, [status-handlers]]) |
Description
|
Subscribes the URL, closure, or object --specified by destination-- to the specified topic. |
Arguments
|
topic is the topic which is being subscribed to. destination is the URL, closure, or object. options contains options for the subscription. status-handlers is an optional handler to invoke for the resulting do_method=route request. If omitted, the default handlers are invoked. See also, Status Handler Objects. |
Returns
|
Usage
|
|
Description
|
|
Arguments
|
theWindow is the Window generating the event. |
Usage
|
|
Description
|
Returns the original string, given an escaped string generated by kn_escape. Reverses the transformation performed by kn_escape in a way that is portable across web browsers. |
Arguments
|
Usage
|
|
Description
|
Removes a subscription identified by rid, so that events published to that subscription's source topic will no longer be delivered. |
Arguments
|
rid is the subscription's route identifier. status-handlers is an optional status handler object to invoke. If omitted, the default handlers are invoked. See also, Status Handler Objects. |
Usage
|
|
Description
|
Given an encoded UTF-8 string, this method returns the corresponding decoded UTF-16 string. |
Arguments
|
Usage
|
|
Description
|
This callback is invoked when a tunnel route status event (aStatusEvent) is received. |
Arguments
|
aStatusEvent is the status event generated by the do_method=route request. |
Usage
|
|
Description
|
This callback is invoked when the tunnel connection closes. This callback is not completely reliable in Netscape browsers. |
This object represents a the JavaScript Microserver instance and provides functions for publishing events, establishing subscriptions to topics, and removing established subscriptions. The same kn object usually appears as a property of all frames in a window which access the same Event Router, although programmer customization and complex frameset layout can cause multiple Microserver instances to be created.
Describes the user identified by kn.userid. This may be a value supplied by the Event Router, a value given for the kn_displayname command-line argument, or a default value such as Guest User or Anonymous User.
The redraw string state for managed frames used for client-side content generation and for KNDocument, indexed by the Window name and containing these properties:
·
kn.documents[name].html - the redraw string.
·
kn.documents[name].state - a string describing the state
of the managed frame as "drawing" , "loading" , or "ready" .
·
kn.document[name].kn_onLoad() - the function to call when the
managed frame has finished reloading.
If debugging is disabled, this property contains information on the most recent error. When an error occurs in a web application using the JavaScript Microserver, the Microserver attempts to suppress the browser's normal error-handling behavior and record the error message in this string. Replacing the onerror handler or supplying the kn_debug command-line argument allows the browser to handle the error normally. Contains these properties:
·
kn.lastError.message - the error message text.
·
kn.lastError.url - the URL of the resource
containing the program that was running when the error occurred.
·
kn.lastError.line - the statement line number
where the error was trapped.
A Date object containing the time when the most recent error was trapped.
The browser window handle corresponding to the current session leader. When several interactive web applications are active in different windows of the same web browser session, only the session leader maintains a persistent connection to the Event Router. Closing the session leader window may cause a temporary disruption in event notification while a new window is chosen to lead the session, but no events should be lost.
The browser window handle corresponding to the outer-most frame using the JavaScript Microserver instance.
Contains a URL of the topic corresponding to the session leader's persistent connection to the event notification service. Subscribing a handler in the web browser to a topic automatically routes events to this URL. By default, the Microserver's frameset wrapping function sets this to the topic: /who/<xxx>/s/<NNN>/kn_journal where <xxx> is the kn.userid and <NNN> is a pseudo-random number up to eight digits in length, but this behavior may be overridden by setting the kn_tunnelURI property of the session leader window.
Identifies the authenticated user in the context of the web application. This may be a value supplied by the Event Router and it may be overridden by a value supplied with the kn_userid command-line argument. The default value is guest or anonymous.
Usage
|
kn.ADD_JOURNAL(options, handlers) |
Description
|
Adds a journal. This is the same as using the route command with a null kn_to or a kn_to that starts with javascript. |
Arguments
|
options - An object containing request parameters. Invokes the add_journal router method. See also, Available do_method settings. |
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the add_notify router method. See also, Available do_method settings. |
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the add_topic router method. See also, Available do_method settings. |
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the batch router method. See also, Available do_method settings. |
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the clear_topic router method. See also, Available do_method settings. |
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the delete_notify router method. See also, Available do_method settings. |
Returns
|
Usage
|
|
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the delete_route router method. See also, Available do_method settings. |
Returns
|
Usage
|
|
Description
|
Posts an event to the specified destination. |
Arguments
|
options - An object containing request parameters. Invokes the notify router method. See also, Available do_method settings. |
Usage
|
kn.ROUTE(options, handlers) |
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the route router method. See also, Available do_method settings. |
Usage
|
kn.SET_TOPIC_PROPERTY(options, handlers) |
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the set_topic_property router method. See also, Available do_method settings. |
Usage
|
kn.UPDATE_NOTIFY(options, handlers) |
Description
|
|
Arguments
|
options - An object containing request parameters. Invokes the update_notify router method. See also, Available do_method settings. |
Usage
|
|
Description
|
Updates an existing route. If the route does exist, only the headers that are set in the request will be changed. All other headers will remain the same. |
Arguments
|
|
Returns
|
Usage
|
kn.clearHandler(rid) |
Description
|
|
Arguments
|
rid is the route location for which the handler being removed. |
Usage
|
|
Description
|
An abbreviation for kn_inspectInWindow. |
Arguments
|
Usage
|
|
Description
|
Publishes an event to a topic on the Event Router and optionally provides status-handlers to be called after the event is published. The event to be published must be constructed as a JavaScript object before it is passed to the publish function. |
Arguments
|
topic is a string containing the topic to which you want to publish, such as: event is an object representing the event you want to publish. It should contain string properties for each do_method=notify parameter and event header you wish to send to the Event Router. See also, Status Handler Objects. |
Returns
|
Usage
|
|
Description
|
Copies element names and values from the specified form into a new event object, and uses kn.publish to publish the event to the specified topic. This function will not work for multiple selections, submit, or buttons. This function does not support file objects; it will publish a file's path, but not the file's contents. |
Arguments
|
topic is a string containing the topic to which you want to publish, such as: form is an object representing the form you want to publish. status-handlers is an object with three functions, one for each possible status events returned by the Event Router for the request. |
Returns
|
Usage
|
|
Description
|
|
Arguments
|
queue is an array of events. |
Usage
|
|
Description
|
A low-level local-only equivalent to kn_subscribe. |
Arguments
|
rid is a route location value. fxn is the handler function to call for matching events. It is invoked with two arguments, an event and obj. obj is the data object that is passed to fxn as the second argument. |
Usage
|
|
Description
|
Subscribes the specified URL, closure, or object to the specified topic. |
Arguments
|
topic is a string containing the topic to which you want to subscribe, such as: destination is the URL, closure, or Object with an onMessage method to which each received event will be passed. options defines the properties of this object which can modify the nature of the subscription. Specify only one of the following options: do_max_n specifies the maximum number of events to be received on this subscription. do_max_age specifies that all events published to the topic up to that many seconds before the subscription was opened should be fetched. Specifying "infinity" will fetch all events in the topic, regardless of their timestamp. For more on status handlers, refer to Status Handler Objects. |
Returns
|
A route URI that can later be passed to kn.unsubscribe to remove the subscription. |
Usage
|
|
Description
|
Removes a subscription identified by rid, so that events published to that subscription's source topic will no longer be delivered. |
Arguments
|
rid is the subscription's route identifier associated with the subscription that was returned by an earlier call to kn.subscribe . For more on status handlers, refer to Status Handler Objects. |
The KN object is a holder for some constants used in JavaScript string and character processing:
The string 0123456789ABCDEFabcdef. All valid hexadecimal digits are contained in this string. The first 16 character positions contain the sixteen uppercase hexadecimal digits in ascending order. The Microserver uses this string when recognizing or generating hexadecimal escape sequences in URL-escaped strings.
The maximum permitted UCS character value: 0x7FFFFFFF
The maximum permitted UTF-16/UCS-2 character value: 0xFFFF
The number 0xFFFD. U+FFFD is the UCS and Unicode replacement character. Unrecognized and unrepresentable characters are replaced by this character code in Unicode and UCS strings.
The kn_stringFromCharCode and kn_escape function automatically performs this mapping when given UCS character codes larger than KN.utf16max to encode. Similarly, the kn_unescape function produces this character in the UTF-16 output string for each illegal or unrepresentable URL-encoded UTF-8 sequence in the input string.
The first character of the UTF-16 high-half surrogate range: 0xDC00
The first character of the UTF-16 low-half surrogate range: 0xD800
The number 0x10FFFF, corresponding to the UCS and Unicode character U+10FFFF. This is the largest character code for which a UTF-16 encoding exists. Character codes larger than this are replaced by the KN.ucsNoChar value in UTF-16 strings.
All UTF-16 surrogate pairs are offset by this value after decoding: 0x10000
Mask applied to UTF-16 surrogate halves to extract useful values: 0x3FF
Shift applied to UTF-16 high surrogate halves to extract useful values: 10
Mask for UTF-8 continuation bytes: 0x3F
Shift for residual value upon encountering UTF-8 continuation bytes: 6
Create status handler objects to process the status events returned by the Event Router in response to requests. See also, Status Events.
The KnowNow Event Service Page library uses UTF-16 encoding for Unicode and UCS characters in JavaScript strings, but there is no byte order mark visible at the JavaScript level. This is backward-compatible with the UCS-2 character encoding employed by older web browsers, thus providing cross-browser access to a rich character set.
As a result, binary data in events should be encoded using the MIME Base64 encoding or a similar technique.
Named parameters can be passed to your application using parameters in the query string part of the URL or in kn_queryString. The query string is optional and appears following the path part of the URL, separated by a question mark.
·
Each
parameter has a name and a value separated by a single equals sign. Both the
parameter name and the parameter value are UTF-8 encoded and URL-escaped. The
same parameter may be set several times, but only the last value has any
effect.
·
Multiple
parameters can be given in either a semicolon-separated list or an
ampersand-separated list.
·
Parameter
values are available as string properties of the kn_argv object. For instance, the value
for a parameter named foo would be stored in kn_argv.foo.
·
Parameter
names starting with kn_ are reserved.
·
The
name and equals sign are optional for the special parameter kn_topic.
·
For
all other kn_ parameters the equals sign and value are optional.
Supplying one of these parameters with the value omitted is the same as
supplying the parameter with a boolean value of true.
The following command-line parameters have defined meanings:
|
Requests that your application start running immediately, rather than waiting for user input. You must implement support for this feature in your application, if you want to support kn_autostart. |
|
|
Comma-separated list of debugging options. Available options include: all - Turn on all debugging flags. events - Display an alert box every time an event is received posts - Display the contents of sent events in the posting frame. receipts - Display the contents of received events in the tunnel frame. routes - Display an alert box every time a subscription is canceled by the default message handler. |
|
|
Describes the user identified by kn.userid in human-readable format. Overrides the default value of kn.displayname. |
|
|
Comma-separated list of speed options. Available options include: fastdoc - Use document. open() for KNDocument single - Do not batch multiple requests. noforward - Do not forward status events to the tunnel frame. escape - Use JavaScript escape() instead of kn_escape() unescape - Use JavaScript unescape() instead of kn_unescape(). |
|
|
Initial event hash cache value, loaded by the Microserver at startup using kn.setHashCache(). |
|
|
A comma-separated list of language codes and optional quality values used when looking up localized messages. Overrides the default value of the kn_lang self property. |
|
|
Initial value for kn.lastTag_, a do_since_checkpoint value for the tunnel route. See also, kn_lastTag_. |
|
|
Controls the number of filler bytes (from 0 to 4,096) sent when the Router detects a lull in the event stream for a particular tunnel (i.e. a persistent connection for event notification). If this value is not supplied, the number of bytes is determined automatically. See also, kn_response_flush. |
|
|
Window name in which links to external resources should be followed, with _blank being the usual default. You must implement support for this feature in your application, if you want to support kn_target. |
|
|
Requests that event timestamps be displayed. You must implement support for this feature in your application, if you want to support kn_timestamp. |
|
|
Primary topic used by an application. You may choose to implement support for this feature in your application. |
|
|
Initial value for kn.tunnelID, the tunnel route kn_id. See also, kn_tunneIID. |
|
|
Initial value for kn.tunnelMaxAge, do_max_age value for the tunnel route. See also, kn_tunnelMaxAge. |
|
|
Initial value for kn.tunnelURI, the tunnel route source topic URI. See also, kn_tunnelURI. |
|
|
Identifies the user in the context of the web application. Overrides the default value of kn.userid. See also, kn_userid. |
The following examples illustrate how
to use the command-line options described above. All examples assume that your
application's URL is
.../MyApp/.
|
kn_argv.color is set to the string red and kn_argv.flavor is set to the string spicy . |
|
|
JavaScript escape() and unescape() will be used instead of kn_escape( ) and kn_unescape(). |
This section provides a quick reference to the C++ filter API functions provided for modules you can create for event filtering and security.
This section is broken into the following sections:
Your module provides implementations of the following functions. These functions will be invoked by the Event Router at various stages.
These functions are required of all modules:
These functions are required only for filter modules:
|
KN_EXPORT KnError KnFilterTopicEvent( |
|
Description
|
This function is invoked by the Event Router each time an event is passed to a topic that has the filter attached. Your implementation of this function can access the contents of the event and do one of the following: - Examine the event and do nothing - Examine the event and
discard it, preventing it from reaching its - Modify the event and allow it to continue to its destination. - Examine the event, then create and post one or more new events to any destination For details on obtaining and setting event contents, see the KnApiEvent class get and set methods. |
Arguments
|
filterParams is the filter parameters, if any were passed into the router when the filter was attached via the kn_filterparams header. event is the event that is being passed to the topic or along the route. discard can be set to true (1) to discard the event and prevent it from reaching its destination. Set the discard flag to false to allow event, modified or not, to reach its destination. |
Returns
|
|
|
KN_EXPORT KnError KnFilterRouteEvent( |
|
Description
|
This function is invoked by the Event Router each time an event is passed along a route. Your implementation of this function can access the contents of the event and do one of the following: Examine the event and do nothing Examine the event and discard it, preventing it from reaching its destination. Modify the event and allow it to continue to its destination. Examine the event, then create and post one or more new events to any destination For details on obtaining and setting event contents, see the KnApiEvent class get and set methods. |
Arguments
|
filterParams is the filter parameters, if any were passed into the router when the filter was attached via the kn_filterparams header. sourceUri is the topic where the event originated from. destUri is the route destination if the filter was attached to a route. event is the event that is being passed to the topic or along the route. discard can be set to true (1) to discard the event and prevent it from reaching its destination. Set the discard flag to false to allow event, modified or not, to reach its destination. |
Returns
|
|
Description
|
This function is invoked when the Event Router is shutting down. Your implementation should perform any needed resource clean up. |
Returns
|
|
This class is used to represent an event and provides methods for retrieving and setting the event's contents.
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
Description
|
Reflects whether the event can be modified. Permission is determined by the attach function. |
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
name is the name of the head whose value is to be retrieved. |
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
|
KnError setHeader( |
|
Description
|
|
Parameters
|
name is the name of the header whose value is to be modified. |
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
Description
|
|
Parameters
|
|
Returns
|
|
Include File
|
|
See Also
|
|
This structure is used to represent a request sent to an Event Router and contains members that represent the request's contents.
KnString line; /* request line sent by the client */
KnString method; /* method requested by the client */
KnString protocol; /* protocol part of URL or empty */
KnString host; /* host part of URL or empty */
uint16_t port; /* port specified in url, or 0 */
KnString srcUrl; /* url where the request came from */
KnString dsturl; /* normalized url, without any query data */
KnString query; /* any query data appended to url */
KnString peer; /* ip address of the client */
double version; /* version of the client request */
KnString authUser; /* decoded user name */
KnString authPasswd; /* decoded user password */
size_t contentLength; /* number of bytes sent by the client */