Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-jquery-embedded-dojo-accordion-panes
Packt
08 Oct 2009
4 min read
Save for later

jQuery Embedded in Dojo Accordion Panes

Packt
08 Oct 2009
4 min read
Basic DOJO 123 accordion In my earlier article I had used the version of the Toolkit which had the accordion in the Widgets. In the latest version which I am using, the accordion is found in digit/layout. The code is similar to that in the earlier article. Basically you create a accordion container and then place the accordion panes inside the container. In referencing the Dojo library I am using part of the references from the Dojo Toolkit 123 installed on my local IIS and part of the reference from the AOL site (uses the 1.0.0 script). Listing 1: AccordionOrig.htm: A basic accordion with three panes [DOJO 123] <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Accordion Pane with jQueries</title> <style type="text/css"> @import "http://localhost/Dojo123/dojo123/dijit/themes/tundra/tundra.css"; @import "http://localhost/Dojo123/dojo123/dojo/resources/dojo.css" </style> <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script> <script type="text/javascript"> dojo.require("dojo.parser"); dojo.require("dijit.layout.AccordionContainer"); </script> </head> <body class="tundra"> <div dojoType="dijit.layout.AccordionContainer" duration="200" style="margin-right: 30px; width: 400px; height: 400px; overflow: scroll"> <!--Pane 1 --> <div dojoType="dijit.layout.AccordionPane" selected="true" title="Page 1" style="color:red;overflow: scroll; background-color:#FFFF80;"> <!--Pane 1 content--> <p >Test 1</a></p > </div> <!--Pane 2 --> <div dojoType="dijit.layout.AccordionPane" title="Page 2" style="overflow: scroll;background-color:#FFFF80;"> <!--Pane 2 content--> <p >Test 2</p > </div> <!-- Pane 3--> <div dojoType="dijit.layout.AccordionPane" title="Page 3" style="color:magenta;overflow: scroll;background-color:#FFFF80;"> <!--Pane 3 content--> <p >Test 3</a></p > </div> </div> </body> </html> This page when browsed to, will display the accordion as shown in Figure 1. This was cross-browser compatible in the following browsers: IE 6.0, Opera 9.1, Firefox 3.0.5, and Safari 3.2.1. The page did not render correctly (all panes completely open) in Google Chrome 1.0.154.43. Figure 1 jQuery API Components used in the article jQuery 1.3 downloaded from this site is used as a source for the script. From the API reference only two simple components were chosen to be embedded in the panes - the Selector and the Effects. The slideUp() effect where in, when you click on the code sensitive area the region of the area on the web page slides up. H1 Selector styled using jQuery Using jQuery you can selectively apply style to tags, ids, etc. In the example shown in the code that follows the H1 tag is styled using jQuery. Listing 2: H1SelectorJQry.htm: Tag styling with jQuery <html> <head></head> <body> <script language="JavaScript" src="http://localhost/JayQuery/jquery-1.3.min.js"> </script> <h1>Jquery inside a DOJO Accordion Pane</h1> <script type="text/JavaScript"> $(document).ready(function(){ $("h1").css("color", "magenta");}); </script> </body> <html> In the above, the jQuery code (inside the script tags) renders the h1 tag in the color shown as in Figure 2. Figure 2 jQuery Effect: slideUp() The htm page with the listing 3 when browsed to, displays a pale green 300 x 300 square corresponding to the styling of the p tag as shown in Figure 4. When clicked anywhere inside this square, the square slides up and disappears. This is the slideUp() effect. Listing 3: p_slideUp.htm: Jquery Effect <html> <head></head> <body> <script language="JavaScript" src="http://localhost/JayQuery/jquery-1.3.min.js"> </script> <div><p style="width:300; height:300; background-color:palegreen; color:darkgreen;">Test</p></div> <script type="text/JavaScript"> $("p").click(function () { $(this).slideUp(); }); </script> </body> <html> This page gets displayed as shown in Figure 3. When you click anywhere in the pale green area the "P" region slides up. Figure 3
Read more
  • 0
  • 0
  • 2636

article-image-troubleshooting-nagios-30
Packt
08 Oct 2009
8 min read
Save for later

Troubleshooting Nagios 3.0

Packt
08 Oct 2009
8 min read
Troubleshooting Web Interface There might be cases where accessing the Nagios URL shows an error instead of the welcome screen. If this happens, it can be due to various reasons, for example, because the web server has not started, or the Nagios related configuration setup is incorrect, or permissions on the Nagios directories are incorrect. The first thing that we should check is whether Apache is working properly. We can manually run the check_http plugin from Nagios. If the web server is up and running, we should see something similar to what is shown here:  # /opt/nagios/plugins/check_http -H 127.0.0.1HTTP OK HTTP/1.1 200 OK - 296 bytes in 0.006 seconds and if Apache is not running currently, the plugin will report an error similar to the following one: # /opt/nagios/plugins/check_http -H 127.0.0.1HTTP CRITICAL - Unable to open TCP socket If it was stopped, start it by running /etc/init.d/apache2 start. The next step is to check whether the http://127.0.0.1/nagios/ URL is working properly. We can also use the same plugin for this. The -u argument can specify the exact link to access, and -a allows you to specify the username and password to be authorized. It is passed in the form of <username>:<password>. # /opt/nagios/plugins/check_http -H 127.0.0.1 u /nagios/ -a nagiosadmin:<yourpassword>HTTP OK HTTP/1.1 200 OK - 979 bytes in 0.019 seconds We can also check the actual CGI scripts by passing a URL to one of the scripts: # /opt/nagios/plugins/check_http -H 127.0.0.1 u /nagios/cgi-bin/tac.cgi -a nagiosadmin:<yourpassword>HTTP OK HTTP/1.1 200 OK - 979 bytes in 0.019 seconds If any of these checks return any HTTP code other than 200, it means that this is the problem. If the code is 500, it means that Apache is not configured correctly. In such cases, the Apache error log contains useful information about any potential problems. On most systems, including Ubuntu Linux, the filename of the log is /var/log/apache2/error.log. An example entry in the error log could be: [error] [client 127.0.0.1] need AuthName: /nagios/cgi-bin/tac.cgi In this particular case, the problem is the missing AuthName directive for CGI scripts. Internal errors can usually be resolved by making sure that the Nagios-related Apache configuration is correct. If this does not help, it is worth checking other parts of the configuration, especially the ones related to virtual hosts and CGI configuration. Commenting out parts of the configuration can help in determining which parts of the configuration are causing problems. Another possibility is that either the check for /nagios/ or the check for the /nagios/cgi-bin/tac.cgi URL returned code 404. This code means that the page was not found. In this case, please make sure that Apache is configured according to the previous steps. If it is, then it's a good idea to enable more verbose debugging to a custom file. The following Apache 2 directives can be added either to /etc/apache2/conf.d/nagios or to any other file in Apache configuration: LogFormat "%h %l %u "%r" %>s %b %{Host}e %f" debuglogCustomLog /var/log/apache2/access-debug.log debuglog The first entry defines a custom logging format that also logs exact paths to files. The second one enables logging with this format to a dedicated file. An example entry in such a log would be: 127.0.0.1 - - "GET /nagios/ HTTP/1.1" 404 481 127.0.0.1 /var/www/nagios This log entry tells us that http://127.0.0.1/nagios/ was incorrectly expanded to the /var/www/nagios directory. In this case, the Alias directive describing the /nagios/ prefix is missing. Making sure that actual configuration matches the one provided in the previous section will also resolve this issue. Another error that you can get is 403, which indicates that Apache was unable to access either CGI scripts in /opt/nagios/sbin, or Nagios static pages in /opt/nagios/share. In this case, you need to make sure that these directories are readable by the user Apache is running as. The error might also be related to the directories above /opt/nagios or /opt. One of these might also be inaccessible to the user Apache is running as, which will also cause the same error to occur. If you run into any other problems, it is best to start with making sure that Nagios related configuration matches the examples from the previous section. It is also a good idea to reduce the number of enabled features and virtual hosts in your Apache configuration. Troubleshooting Passive Checks It' s not always possible to set up passive checks correctly the first time. In such cases, it is a good thing to try to debug the issue one step at a time in order to find any potential problems. Sometimes the problem could be a configuration issue, while in other cases, it could be an issue such as the mistyping of the host or service name. One thing worth checking is whether the Web UI shows changes after you have sent the passive result check. If it doesn't, then at some point, things are not working correctly. The first thing you should start with is enabling the logging of external commands and passive checks. To do this, make sure that the following values are enabled in the main Nagios configuration file: log_external_commands=1log_passive_checks=1 In order for the changes to take effect, a restart of the Nagios process is needed. After this has been done, Nagios will log all commands passed via the command pipe and log all of the passive check results it receives. The first issue, a common problem, is that an application or script cannot write data to the Nagios command pipe. In order to test this, simply change to the user your scripts are running as, and try the following command: user@ubuntuserver:~$ echo "TEST" >/var/nagios/rw/nagios.cmd If the command above runs fine, and no errors are reported, then your permissions are set up correctly. If an error shows up, you should add the user to the nagioscmd group. The next thing to do is to manually send a passive check result to the Nagios command pipe and check whether the Nagios log file was received and parsed correctly. To test this, run the following command: echo "['date +%s'] PROCESS_HOST_CHECK_RESULT;host1;2;test" >/var/nagios/rw/nagios.cmd The name, host1, needs to be replaced with an actual host name from your configuration. A few seconds after running this command, the Nagios log file should reflect the command that we have just sent. You should see the following lines in your log: EXTERNAL COMMAND: PROCESS_HOST_CHECK_RESULT;host1;2;test[1220257561] PASSIVE HOST CHECK: host1;2;test If both of these lines are in your log file, then we can conclude that Nagios has received and parsed the command correctly. If only the first line is present, then it means that either the global option to receive passive host check results is disabled, or it is disabled for this particular object. The first thing you should do is to make sure that your main Nagios configuration file contains the following line: accept_passive_host_checks=1 Next, you should check your configuration to see whether the host definition has passive checks enabled as well. If not, simply add the following directive to the object definition: passive_checks_enabled 1 If you have misspelled the name of the host object, then the following will be logged: Warning: Passive check result was received for host host01',but the host could not be found! In this case, make sure that your host name is correct. Similar checks can also be done for services. You can run the following command to check if a passive service check is being handled correctly by Nagios: echo "['date +%s'] PROCESS_SERVICE_CHECK_RESULT;host1;APT;0;test" >/var/nagios/rw/nagios.cmd Again, host1 should be replaced by the actual host name, and APT needs to be an existing service for that host. After a few seconds, the following entries in Nagios log file would indicate the result has been successfully parsed: EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;host1;APT;0;testPASSIVE SERVICE CHECK: host1;APT;0;test If the second line is not in the log file, either the option to accept service passive checks is disabled on a global basis, or this particular service has the option to accept passive check results disabled. You should start by making sure that your main Nagios configuration file contains the following line: accept_passive_service_checks=1 You should also make sure that the service definition has passive checks enabled as well, and if not, add the following directive to the object definition: passive_checks_enabled 1 If you have misspelled the name of the host or service, then the following will be logged: Warning: Passive check result was received for service APT' on host host1', but the service could not be found!
Read more
  • 0
  • 0
  • 2159

article-image-schema-validation-using-sax-and-dom-parser-oracle-jdeveloper-xdk-11g
Packt
08 Oct 2009
6 min read
Save for later

Schema Validation using SAX and DOM Parser with Oracle JDeveloper - XDK 11g

Packt
08 Oct 2009
6 min read
The choice of validation method depends on the additional functionality required in the validation application. SAXParser is recommended if SAX parsing event notification is required in addition to validation with a schema. DOMParser is recommended if the DOM tree structure of an XML document is required for random access and modification of the XML document. Schema validation with a SAX parser In this section we shall validate the example XML document catalog.xml with XML schema document catalog.xsd, with the SAXParser class. Import the oracle.xml.parser.schema and oracle.xml.parser.v2 packages. Creating a SAX parser Create a SAXParser object and set the validation mode of the SAXParser object to SCHEMA_VALIDATION, as shown in the following listing: SAXParser saxParser=new SAXParser();saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION); The different validation modes that may be set on a SAXParser are discussed in the following table; but we only need the SCHEMA-based validation modes: Validation Mode Description NONVALIDATING The parser does not validate the XML document. PARTIAL_VALIDATION The parser validates the complete or a partial XML document with a DTD or an XML schema if specified. DTD_VALIDATION The parser validates the XML document with a DTD if any. SCHEMA_VALIDATION The parser validates the XML document with an XML schema if any specified. SCHEMA_LAX_VALIDATION Validates the complete or partial XML document with an XML schema if the parser is able to locate a schema. The parser does not raise an error if a schema is not found. SCHEMA_STRICT_VALIDATION Validates the complete XML document with an XML schema if the parser is able to find a schema. If the parser is not able find a schema or if the XML document does not conform to the schema, an error is raised. Next, create an XMLSchema object from the schema document with which an XML document is to be validated. An XMLSchema object represents the DOM structure of an XML schema document and is created with an XSDBuilder class object. Create an XSDBuilder object and invoke the build(InputSource) method of the XSDBuilder object to obtain an XMLSchema object. The InputSource object is created with an InputStream object created from the example XML schema document, catalog.xsd. As discussed before, we have used an InputSource object because most SAX implementations are InputSource based. The procedure to obtain an XMLSchema object is shown in the following listing: XSDBuilder builder = new XSDBuilder();InputStream inputStream=new FileInputStream(new File("catalog.xsd"));InputSource inputSource=new InputSource(inputStream);XMLSchema schema = builder.build(inputSource); Set the XMLSchema object on the SAXParser object with setXMLSchema(XMLSchema) method: saxParser.setXMLSchema(schema); Setting the error handler As in the previous section, define an error handling class, CustomErrorHandler that extends DefaultHandler class. Create an object of type CustomErrorHandler, and register the ErrorHandler object with the SAXParser as shown here: CustomErrorHandler errorHandler = new CustomErrorHandler();saxParser.setErrorHandler(errorHandler); Validating the XML document The SAXParser class extends the XMLParser class, which provides the overloaded parse methods discussed in the following table to parse an XML document: Method Description parse(InputSource in) Parses an XML document from an org.xml.sax.InputSouce object. The InputSource-based parse method is the preferred method because SAX parsers convert the input to InputSource no matter what the input type is. parse(java.io.InputStream in) Parses an XML document from an InputStream. parse(java.io.Reader r) Parses an XML document from a Reader. parse(java.lang.String in) Parses an XML document from a String URL for the XML document. parse(java.net.URL url) Parses an XML document from the specified URL object for the XML document. Create an InputSource object from the XML document to be validated, and parse the XML document with the parse(InputSource) object: InputStream inputStream=new FileInputStream(newFile("catalog.xml"));InputSource inputSource=new InputSource(inputStream);saxParser.parse(inputSource); Running the Java application The validation application SAXValidator.java is listed in the following listing with additional explanations: First we declare the import statements for the classes that we need. import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import oracle.xml.parser.schema.*;import oracle.xml.parser.v2.*;import java.io.IOException;import java.io.InputStream;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.helpers.DefaultHandler;import org.xml.sax.InputSource; We define the Java class SAXValidator for SAX validation. public class SAXValidator { In the Java class we define a method validateXMLDocument. public void validateXMLDocument(InputSource input) {try { In the method we create a SAXParser and set the XML schema on the SAXParser. SAXParser saxParser = new SAXParser();saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);XMLSchema schema=getXMLSchema();saxParser.setXMLSchema(schema); To handle errors we create a custom error handler. We set the error handler on the SAXParser object and parse the XML document to be validated and also output validation errors if any. CustomErrorHandler errorHandler = new CustomErrorHandler();saxParser.setErrorHandler(errorHandler);saxParser.parse(input);if (errorHandler.hasValidationError == true) {System.err.println("XML Document hasValidation Error:" + errorHandler.saxParseException.getMessage());} else {System.out.println("XML Document validateswith XML schema");}} catch (IOException e) {System.err.println("IOException " + e.getMessage());} catch (SAXException e) {System.err.println("SAXException " + e.getMessage());}} We add the Java method getXMLSchema to create an XMLSchema object. try {XSDBuilder builder = new XSDBuilder();InputStream inputStream =new FileInputStream(new File("catalog.xsd"));InputSource inputSource = newInputSource(inputStream);XMLSchema schema = builder.build(inputSource);return schema;} catch (XSDException e) {System.err.println("XSDException " + e.getMessage());} catch (FileNotFoundException e) {System.err.println("FileNotFoundException " +e.getMessage());}return null;} We define the main method in which we create an instance of the SAXValidator class and invoke the validateXMLDocument method. public static void main(String[] argv) {try { InputStream inputStream = new FileInputStream(new File("catalog.xml")); InputSource inputSource=new InputSource(inputStream); SAXValidator validator = new SAXValidator(); validator.validateXMLDocument(inputSource); } catch (FileNotFoundException e) { System.err.println("FileNotFoundException " + e.getMessage()); }} Finally, we define the custom error handler class as an inner class CustomErrorHandler to handle validation errors. private class CustomErrorHandler extends DefaultHandler {protected boolean hasValidationError = false;protected SAXParseException saxParseException = null;public void error(SAXParseException exception){hasValidationError = true;saxParseException = exception;}public void fatalError(SAXParseException exception){hasValidationError = true;saxParseException = exception;}public void warning(SAXParseException exception){}}} Copy the SAXValidator.java application to SAXValidator.java in the SchemaValidation project. To demonstrate error handling, add a title element to the journal element. To run the SAXValidator.java application, right-click on SAXValidator.java in Application Navigator, and select Run. A validation error gets outputted. The validation error indicates that the title element is not expected.
Read more
  • 0
  • 0
  • 6063

article-image-notifications-and-events-nagios-30-part1
Packt
08 Oct 2009
16 min read
Save for later

Notifications and Events in Nagios 3.0-part1

Packt
08 Oct 2009
16 min read
There's lots what Nagios can do, and how it can make your life easier. Imagine that you set up Nagios to send a text message to your mobile during day time. It can also send you a message on Jabber or MSN. Imagine that you also make Nagios stop notifying you when your workstation is not online. Even though the above examples above seem complicated, they are actually quite simple to implement. It's a matter of combining event handlers with custom variables, and a little ingenuity. A service that will check if a user's workstation is present can have an event handler to automatically enable and disable host and/or service notifications for a contact or contact group. It's also possible to set up your monitoring to notify managers if the issue has not been fixed within a certain period of time. Based on the importance of a host or service, these can be different managers that are notified and different time periods after which the notification is sent. Nagios can also be used to notify emergency response teams, so that if a problem is not fixed in a short period of time, they will assist in recovering from the potential after effects of this problem. There are cases when you want Nagios to perform one or more actions if a service starts or stops malfunctioning. For instance, you might have a web server set up to retry five times before a failure becomes a hard state for Nagios. In such a case, you can also configure Nagios to try restarting itself after the third soft failure —if it fails, it will move to a hard state after the next two failures. In case the restart succeeds, a hard state will not even get recorded and only a soft failure will get logged. Nagios is able to integrate itself with other applications that can send commands to Nagios directly and can report the status of host or service checks. Sending commands can be used by Nagios web interface, but you might as well use it inside your application or event handlers for various objects. Effective Notifications This section covers notifications in depth and describes the details of how Nagios can tell other people about what is happening. We will discuss a simple approach, as well as a more complex approach on how notifications can make your life easier. Probably, most people already know that a plain email notification about a problem may not always be the right thing to do. As people's inboxes get cluttered with emails, the usual approach is to create rules to move certain messages that they don't even look at to separate folders. There's a pretty good chance that if people start getting a lot of notifications that they won't need to react to, they'll simply ask their favorite mailing program to move these messages into a 'do not look in here unless you have plenty of time' folder. Moreover, in such cases, if there is an issue they should be handling, they will most probably not even see the notification email. This section talks about the things that can be implemented in your company to make notifications more convenient to the IT staff. Limiting the amount of irrelevant information sent to various people tends to increase their response time, as they will have much less information to filter out. At this point, it's worth mentioning that there's another easy solution. Again, most people do not use it even though it offers a very flexible set up in an easy way. The approach is to create multiple contacts for a single person. For example, you can set up different contacts when you're at work, when you're offline, and define a profile to not to disturb you too much during the night. The first issue that many Nagios administrators overlook is the ability to create more than one notification command. In this way, Nagios can try to notify you on both instant messaging (such as Jabber, Gtalk, MSN, or Yahoo) and email. It can also send you an SMS. A disadvantage is that at some point, you might end up receiving SMSes at 2 AM about an outage of a machine that may well be down for the next 3days and is not critical. For example you can set up the following contacts to handle various times of the day in a different fashion: jdoe-workhours would be a contact that will only receive notifications during working hours; notifications will be carried out using both the corporate IM system and an email jdoe-daytime would be a contact that will only receive notifications between 7 AM and 10 PM, excluding working hours; notifications will be sent as a text or a pager message, and an email jdoe-night would be a contact that will only receive notifications between 10 PM and 7 AM; notifications will only be sent out as an email All entries would also contain contactgroups pointing to the same groups that the single jdoe contact entry used to contain. This way, the other objects such as hosts, services, or contact groups related to this user would not be affected. All entries would also reside in the same file; for example, contacts/jdoe.cfg. The main drawback of this approach is that logging on to the web interface would require using one of the users above or keeping the jdoe contact without any notifications, just to be able to log on to the interface. The example above combined both the creation of multiple contacts and use of multiple notification commands to achieve a convenient way of getting notified about a problem. Using only multiple contacts also works fine. Another approach to the problem is to define different contacts for different ways of being notified—for example, jdoe-email, jdoe-sms, and jdoe-jabber. This way, you can define different contact methods for various time periods—instant messages during working hours, SMSes while on duty, and an email when not at work. Another important issue is to make sure that as few people as possible are notified of the problem. Imagine there is a host without an explicit administrator assigned to it. A notification about a problem gets sent out to 20 different people. In such a case, either each of them will assume that someone else will resolve the problem, or people will run into a communication problem over discussing who will actually handle it. Teams that cooperate tightly with each other usually solve these issues naturally—knowledgeable people start discussing a solution and a natural person to solve the issue comes out of the discussion. However, the teams that are distributed across various locations or that have poor communication skills will run into problems in such cases. This is why, it is a good idea to either nominate a coordinator who will assign tasks as they arise, or try to maintain a short list of people responsible for each machine. If you need to make sure that other people will investigate the problem if the original owner of the machine cannot do it immediately, then it is a good idea to use escalations for this purpose. These are described later in this article. Previously, we mentioned that notifications only via email may not always be the best thing to do. For example, they don't work well for situations that require fast response times. There are various reasons behind this. Firstly, emails are slow—even though the email lands on your mail server in a few seconds, people usually only poll their emails every few minutes. Secondly, people tend to filter emails and skip those that they are not interested in. Another good reason why emails should not always be used is that they stay on your email account until you actually fetch and read them. If you have been on a 2-week vacation and a problem has occurred, should you still be worried when you read it after you get back? Has the issue been resolved already? If your team needs to react to problems promptly, using email as the basic notification method is definitely not the best choice. Let's consider what other possibilities exist to notify users of a problem effectively. As already mentioned, a very good choice is to use instant messaging or SMS (Simple Messaging Service) messages as the basic means of notification, and only use email as a last resort. Some companies might also use the client-server approach to notify the users of the problems, perhaps integrated with showing Nagios' status only for particular hosts and services. NagiosExchange has plenty of available solutions you can use for handling notifications effectively. The first and the most powerful option is to use Jabber for notifications. There is an existing script for this that is available in the contributions repository on the Nagios project website. This is a small Perl script that sends messages over Jabber. You may need to install additional system packages to handle Jabber connectivity from Perl. On Ubuntu, this requires running the following command: root@ubuntu1:~# apt-get install libnet-jabber-perl If you are using CPAN to install Perl packages, then simply run the following command: root@ubuntu1:~# cpan install Net::Jabber In order to use the notification plugin, you will need to customize the script—change the SERVER, PORT, USER, and PASSWORD parameters to an existing account. Our recommendation is to create a separate account to use only for Nagios notifications—you will need to set up authorization for each user that you want to send notifications to. As you plan to monitor servers and potentially even outgoing Internet connectivity, it would not be wise to use public Jabber servers for reporting errors. Therefore, it would be a good idea to set up a private Jabber server, probably on the same host on which the Nagios monitoring system is running. If you plan to have a more comfortable setup, you can also use Tkabber as a Jabber client, and write a plugin that reads object's cache and the current status from the Nagios host and shows an up-to-date report for hosts that you are the owner of. Information on reading Nagios output can be found on my Tclmentor blog Another possibility is to send messages over SMB/CIFS protocol. This way, you can send messages directly to the computers, assuming people are running the Microsoft Windows operating system. There is also the possibility of receiving messages using Samba package on UNIX machines. This requires having the smbclient command installed. On Ubuntu, this requires running the following command: root@ubuntu1:~# apt-get install smbclient A simple command definition example that uses smbclient directly to send messages to the specified host name is as follows: define command{command_name notify_host_via_smbclientcommand_line printf "Host notification: $NOTIFICATIONTYPE$nnHost: $HOSTNAME$nState: $HOSTSTATE$Address: $HOSTADDRESS$nInfo: $HOSTOUTPUT$" |smbclient -M $_CONTACTSMBHOSTNAME$} The preceding example uses the $_CONTACTSMBHOSTNAME$ macro definition. It maps to the _SMBHOSTNAME custom variable defined for a specified contact. In order for Windows XP and 2003 to show the messages from other users correctly, you will need to enable the Messenger service. This can be done by running the following command as the system administrator, or as a user with administrator privileges: C> net start Messenger Another way to communicate problems to the users is to use text messages, also known as SMS. This is a very sensitive issue because if your system is not properly configured, it can send a message in the middle of a night about a noncritical thing that can be fixed within the next 5 working days. There is a very useful package for handling of SMS sending called SMSServerTools. It allows the configuration of email and web gateways, as well as sending text messages over dedicated GSM (Global System for Mobile Communication) terminals. The tool offers the ability to queue text messages so that it handles a higher number of messages to be sent by the appropriate means. GSM terminals work in a manner similar to a typical mobile phone. They use a standard SIM card and have a normal GSM phone module that is used to send SMS messages. Terminals are usually connected via a serial port or USB connection. Your server can then send messages by sending commands to the terminal. GSM terminals use the same command convention as phone modems, although each model uses a different set of commands. For information on how you can send SMS messages over it, please refer the terminal's user manual. Current mobile phones also offer cheap Internet connectivity, and smart devices offer the possibility to write custom applications in Java, .NET, and many other languages including Python and Tcl. Therefore, you can also make a client-server application that queries the server for the status of selected hosts and services. It can even be unified with a notification command that pushes the changes down to the application immediately. These are only a few of the possibilities that you can use to communicate problems more effectively. Other possibilities include a ready-to-use client-server application (visit http://www.nagiosexchange.org/Notifications.35.0.html?tx_netnagext_pi1[p_view]=182) that allows the sending of notifications to people directly to their desktop machines. One interesting notification command allows you to choose other commands to use based on user availability on Jabber—this sends messages over Jabber if the user is are available and uses SMSes or emails otherwise. (Visit http://www.nagiosexchange.org/Notifications.35.0.html?&tx_netnagext_pi1[p_view]=1036). There are also tools to send messages to ICQ users and ones that use VoIP technology to provide you with predefined wave messages or output from a speech synthesis system. Escalations A common problem with resolving problems is that a host or a service may have blurred ownership. Often, there is no single person responsible for a host or service, which makes things harder. It is also typical to have a service with subtle dependencies on other things, which by themselves are small enough not to be monitored by Nagios. In such a case, it is good to include lower management in the escalations so that they are able to focus on problems that haven't been resolved in a timely manner. Here is a good example: a database server might fail because a small Perl script that is run prior to actual start and clean things up has entered an infinite loop. The owner of this machine gets notified. But the question is who should be fixing it? Should it be the script owner? Or perhaps, should it be the database administrator? In IT reality, this often ends up in a series of throwing ball into each other's yards without solving anything. In such cases, escalations are a great way to solve such complex problems. In the previous example, if the problem is not been resolved after two hours, the IT team coordinator or manager would be notified. Another hour later, he would get another email. At that point, he would schedule an urgent meeting with the developer who owns the script, and the database admin, to discuss how this could be solved. Of course, in real-world scenarios, escalating to management alone would not solve all problems. However, often, situations need a coordinator that will take care of communicating issues between teams and trying to find a company-wide solution. Business-critical services also require much higher attention. In such cases, it is a real benefit for the company if it has an escalation ladder that can be followed for all major problems. Nagios offers many ways to set up escalations, depending on your needs. Escalations do not need to be sent out just after a problem occurs—that would create confusion and prevent smaller problems from being solved. Usually, escalations are set up so that additional people are informed only if a problem has not been resolved after a certain amount of time. From a configuration point of view, all escalations are defined as separate objects. There are two types of objects—hostescalation and serviceescalation. Escalations are configured so that they start and stop being active along with the normal host or service notifications. This way, if you change the notification_ interval directive in host or service definition, the times at which escalations start and stop will also change. A sample escalation for company's main router is as follows: define hostescalation{host_name mainroutercontactgroups it-managementfirst_notification 2last_notification 0notification_interval 60escalation_options d,u,r} The following table describes all available directives for defining a host escalation. Items in bold are required when specifying an escalation. Option Description host_name Defines host names that escalation should be defined for; separated by comma hostgroup_name Defines host group names for all members of which groups escalation should be defined for; separated by comma contacts List of all contacts that should receive notifications related to this escalation; separated by comma; at least one contact or contact group needs to be specified for each escalation contactgroups List of all contacts groups that should receive notifications related to this escalation, separated by comma; at least one contact or contact group needs to be specified for each escalation first_notification Number of notifications after which this escalation becomes active; setting this to 0 causes notifications to be sent until host recovers from problem; see description below last_notification Number of notifications after which this escalation stop being active; see description below notification_interval Specifies number of minutes between sending notifications related to this escalation escalation_period Specifies time period during which escalation should be valid; if not specified defaults to 24 hours a day 7 days a week escalation_options Specifies which notification types for host states should be sent, separated by comma; should be one or more of the following: d - host DOWN state u - host UNREACHABLE state r - host recovery (UP state) Service escalations are defined in a very similar way to host escalations. You can specify one or more hosts or host groups, as well as a single service description. Service escalation will be associated with this service on all hosts mentioned in the host_name and hostgroup_name attributes. The following is an example of a service escalation for an OpenVPN check on the company's main router: define serviceescalation{host_name mainrouterservice_description OpenVPNcontactgroups it-managementfirst_notification 2last_notification 0notification_interval 60escalation_options w,c,r} The following table describes all available directives for defining a service escalation. Items in bold are required when specifying an escalation.
Read more
  • 0
  • 0
  • 3905

article-image-taxonomy-and-thesauri-drupal-6
Packt
08 Oct 2009
6 min read
Save for later

Taxonomy and Thesauri in Drupal 6

Packt
08 Oct 2009
6 min read
What and Why? Taxonomy is described as the science of classification. In terms of how it applies to Drupal, it is the method by which content is organized using several distinct types of relationship between terms. Simple as that! This doesn't really encompass how useful it is, though, but before we move on to that, there is a bit of terminology to pick up first: Term: A term used to describe content (also known as a descriptor) Vocabulary: A grouping of related terms Thesaurus: A categorization of content that describes is similar to relationships Taxonomy: A categorization of content into a hierarchical structure Tagging: The process of associating a term (descriptor) with content Synonym: Can be thought of as another word for the current term. It may help to view the following diagram in order to properly grasp how these terms inter-relate. This serves to illustrate the fact that there are two main types of vocabulary. Each type consists of a set of terms, but the relationships between them are different in that a taxonomy deals with a hierarchy of information, and a thesaurus deals with relationships between terms. The terms (shown as small boxes) and their relationships (shown as arrows) play a critical role in how content is organized. One of the things that makes the Drupal taxonomy system so powerful, is that it allows content to be categorized on the fly (as and when it is created). This unburdens administrators because it is no longer necessary to moderate every bit of content coming into the site in order to put it into pre-determined categories. We'll discuss these methods in some detail in the coming sections, but it's also worth noting quickly that it is possible to tag a given node more than once. This means that content can belong to several vocabularies, at once. This is very useful for cross-referencing purposes because it highlights relationships between terms or vocabularies through the actual nodes. Implementing Controlled Taxonomies in Drupal The best way to talk about how to implement some form of categorization is to see it in action. There are quite a few settings to work with and consider in order to get things up and running. Let's assume that the demo site has enlisted a large number of specialists who will maintain their own blogs on the website so that interested parties can keep tabs on what's news according to the people in the know. Now, some people will be happy with visiting their blog of choice and reading over any new postings there. Some people, however, might want to be able to search for specific topics in order to see if there are correlations or disagreements between bloggers on certain subjects. As there is going to be a lot of content posted once the site has been up and running for a few months, we need some way to ensure that specific topics are easy to find, regardless of who has been discussing them on their blogs. Introduction to Vocabularies Let's quickly discuss how vocabularies are dealt with in the administration tool in order to work out how to go about making sure this requirement is satisfied. If you click on the Taxonomy link under Content management, you will be presented with a page listing the current vocabularies. Assuming you have created a forum before, you should have something like this: Before we look at editing terms and vocabularies, let's take a look at how to create a vocabulary for ourselves. Click on the add vocabulary tab to bring up the following page that we can use to create a vocabulary, manually: By way of example, this vocabulary will deal with the topic of hunting. This vocabulary only applies to blog entries because that is the only content (or node) type for which it is enabled—you can select as many or as few as you like, depending on how many content types it should apply to. Looking further down the page, there are several other options that we will discuss in more detail, shortly. Clicking on Submit adds this vocabulary to the list, so that the main page now looks like this: So far so good, but this will not be of much use to us as it stands! We need to add some terms (descriptors) in order to allow tagging to commence. Dealing with Terms Click on add terms link for the Hunting vocabulary to bring up the following page: The term Trapping has been added here, with a brief description of the term itself. We could, if we choose, associate the term Poaching with Trapping by making it a related term or synonym (of course, you would need to create this term first in order to make it a related term). Click on the Advanced options link to expose the additional features, as shown here: In this case, the term Trapping is specified as being related to Poaching and by way of example, gin traps is a synonym. Synonyms don't actually do anything useful at the moment, so don't pay too much mind to them yet, but there are modules that expose additional functionality based on related terms and synonyms, such as the Similar by Terms module. The Parents option at the start of the Advanced options warrants a closer inspection, but as it relates more closely to the structure of hierarchies, we'll look at it in the section on Hierarchies that's coming up. For now, add a few more terms to this vocabulary so that the list looks something like this: It's now time to make use of these terms by posting some blog content. Posting Content with Categories Enabled Using any account with the requisite permissions to add blog content, attempt to post to the site. You should now be able to view the newly inserted Hunting category, as shown here: Now comes the clever bit! Once this blog node has been posted, users can view the blog as normal, except that it now has its term displayed along with the post (bottom right): Where does the descriptor link take us? Click on the term, in this case Canned hunting, and you will be taken to a page listing all of the content that has been tagged with this term. This should really have you quite excited, because with very little work, users can now find focused content without having to look that hard—this is what content management is all about!
Read more
  • 0
  • 0
  • 2450

article-image-notifications-and-events-nagios-30-part2
Packt
08 Oct 2009
15 min read
Save for later

Notifications and Events in Nagios 3.0- part2

Packt
08 Oct 2009
15 min read
External Commands Nagios offers a very powerful mechanism for receiving events and commands from external applications—the external commands pipe. This is a pipe file created on a file system that Nagios uses to receive incoming messages. The name of the file is rw/nagios.cmd and it is located in the directory passed as the localstatedir option during compilation. Following the compilation and installation instructions and the given guidelines, the file name will be /var/nagios/rw/ nagios.cmd. The communication does not use any authentication or authorization—the only requirement is to have write access to the pipe file. An external command file is usually writable by the owner and the group; the usual group used is nagioscmd. If you want a user to be able to send commands to the Nagios daemon, simply add that user to this group. A small limitation of the command pipe is that there is no way to get any results back and so it is not possible to send any query commands to Nagios. Therefore, by just using the command pipe, you have no verification that the command you have just passed to Nagios has actually been processed, or will be processed soon. It is, however, possible to read the Nagios log file and check if it indicates that the command has been parsed correctly, if necessary. An external command pipe is used by the web interface to control how Nagios works. The web interface does not use any other means to send commands or apply changes to Nagios. This gives a good understanding of what can be done with the external command pipe interface. From the Nagios daemon perspective, there is no clear distinction as to who can perform what operations. Therefore, if you plan to use the external command pipe to allow users to submit commands remotely, you need to make sure that the authorization is in place as well so that it is not possible for unauthorized users to send potentially dangerous commands to Nagios. The syntax for formatting commands is easy. Each command must be placed on a single line and end with a newline character. The syntax is as follows: [TIMESTAMP] COMMAND_NAME;argument1;argument2;...;argumentN TIMESTAMP is written as UNIX time—that is the number of seconds since 1970-01-01 00:00:00. This can be created by using the date +%s system command. Most programming languages also offer the means to get the current UNIX time. Commands are written in upper case. This can be one of the commands that Nagios should execute, and the arguments depend on the actual command. For example, to add a comment to a host stating that it has passed a security audit, one can use the following shell command: echo "['date +%s'] ADD_HOST_COMMENT;somehost;1;Security Audit;This host has passed security audit on 'date +%Y-%m-%d'">/var/nagios/rw/nagios.cmd This will send an ADD_HOST_COMMENT command (visit http://www.nagios.org/developerinfo/externalcommands/commandinfo.php? command_id=1) to Nagios over the external command pipe. Nagios will then add a comment to the host, somehost, stating that the comment originated from Security Audit. The first argument specifies the host name to add the comment to; the second tells Nagios if this comment should be persistent. The next argument describes the author of the comment, and the last argument specifies the actual comment text. Similarly, adding a comment to a service requires the use of the ADD_SVC_COMMENT command (visit http://www.nagios.org/developerinfo/externalcommands/ commandinfo.php? command_id=1) . The command's syntax is very similar to the ADD_HOST_COMMENT command except that the command requires the specification of the host name and service name. For example, to add a comment to a service stating that it has been restarted, you should use the following echo "['date +%s'] ADD_SVC_COMMENT;router;OpenVPN;1;nagiosadmin;Restarting the OpenVPN service" >/var/nagios/rw/nagios.cmd The first argument specifies the host name to add the comment to; the second is the description of the service to which Nagios should add the comment. The next argument tells Nagios if this comment should be persistent. The fourth argument describes the author of the comment, and the last argument specifies actual comment text. You can also delete a single comment or all comments using the DEL_HOST_ COMMENT (visit http://www.nagios.org/developerinfo/externalcommands/ commandinfo.php? command_id=3), DEL_ALL_HOST_COMMENTS (visit http://www. nagios.org/developerinfo/externalcommands/commandinfo.php? command_ id=13), and DEL_SVC_COMMENT (visit http://www.nagios.org/developerinfo/externalcommands/commandinfo.php? command_id=4) or DEL_ALL_SVC_COMMENTS commands (visit http://www.nagios.org/developerinfo/externalcommands/ commandinfo.php? command_id=14). Other commands worth mentioning are related to scheduling checks on demand. Very often, it is necessary to request that a check be carried out as soon as possible; for example, when testing a solution. This time, let's create a script that schedules a check of a host, all services on that host, and a service on a different host, as follows: #!/bin/shNOW='date +%s'echo "[$NOW] SCHEDULE_HOST_CHECK;somehost;$NOW" >/var/nagios/rw/nagios.cmdecho "[$NOW] SCHEDULE_HOST_SVC_CHECKS;somehost;$NOW" >/var/nagios/rw/nagios.cmdecho "[$NOW] SCHEDULE_SVC_CHECK;otherhost;Service Name;$NOW" >/var/nagios/rw/nagios.cmdexit 0 The commands SCHEDULE_HOST_CHECK (visit http://www.nagios.org/ developerinfo/externalcommands/commandinfo.php? command_id=127) and SCHEDULE_HOST_SVC_CHECKS (http://www.nagios.org/developerinfo/externalcommands/commandinfo.php?command_id=30) accept a host name and the time at which the check should be scheduled. The SCHEDULE_SVC_CHECK command (visit http://www.nagios.org/developerinfo/externalcommands/ commandinfo.php? command_id=29) requires the specification of a service description as well as the name of the host to schedule the check on. Normal scheduled checks, such as the ones scheduled above, might not actually take place at the time that you scheduled them. Nagios also needs to take allowed time periods into account as well as checking whether checks were disabled for a particular object or globally for the entire Nagios. There are cases when you'll need to force Nagios to do a check—in such cases, you should use SCHEDULE_FORCED_HOST_CHECK (visit http://www.nagios. org/developerinfo/externalcommands/commandinfo.php? command_id=128), SCHEDULE_FORCED_HOST_SVC_CHECKS (visit http://www.nagios.org/developerinfo/externalcommands/commandinfo.php? command_id=130) and SCHEDULE_FORCED_SVC_CHECK (visit http://www.nagios.org/developerinfo/ externalcommands/commandinfo.php? command_id=129) commands. They work in exactly the same way as described above, but make Nagios skip the checking of time periods, and ensure that the checks are disabled for this particular object. This way, a check will always be performed, regardless of other Nagios parameters Other commands worth using are related to custom variables, introduced in Nagios 3. When you define a custom variable for a host, service, or contact, you can change its value on the fly with the external command pipe. As these variables can then be directly used by check or notification commands and event handlers, it is possible to make other applications or event handlers change these attributes directly without modifications to the configuration files. A good example would be that the IT staff registers its presence via an application without any GUI. This application periodically sends information about the latest known IP address, and that information is then passed to Nagios assuming that the person is in the office. This would later be sent to a notification command to use that specific IP address while sending a message to the user. Assuming that the user name is jdoe and the custom variable name is DESKTOPIP, the message that would be sent to the Nagios external command pipe would be as follows: [1206096000] CHANGE_CUSTOM_CONTACT_VAR;jdoe;DESKTOPIP;12.34.56.78 This would cause a later use of $_CONTACTDESKTOPIP$ to return a value of 12.34.56.78. Nagios offers the CHANGE_CUSTOM_CONTACT_VAR (visit http://www.nagios.org/developerinfo/externalcommands/commandinfo.php? command_id=141), CHANGE_CUSTOM_HOST_VAR (visit http://www.nagios.org/developerinfo/ externalcommands/commandinfo.php?command_id=139), and CHANGE_CUSTOM_ SVC_VAR (visit http://www.nagios.org/developerinfo/externalcommands/commandinfo.php?command_id=140) commands for modifying custom variables in contacts, hosts and, services accordingly. The commands explained above are just a very small subset of the full capabilities of the Nagios external command pipe. For a complete list of commands, visit http:// www.nagios.org/developerinfo/externalcommands/commandlist.php, where the External Command List can be seen. External commands are usually sent from event handlers or from the Nagios web interface. You will find external commands most useful when writing event handlers for your system, or when writing an external application that interacts with Nagios. Event Handlers Event handlers are commands that are triggered whenever the state of a host or  service changes. They offer functionality similar to notifications. The main difference is that the event handlers are called for each type of change and even for each soft state change. This provides the ability to react to a problem before Nagios notifies it as a hard state and sends out notifications about it. Another difference is what the event handlers should do. Instead of notifying users that there is a problem, event handlers are meant to carry out actions automatically. For example, if a service defined with max_check_attempts set to 4, the retry_ interval set to 1, and the check_interval is set to 5, then the following example illustrates when event handlers would be triggered, and with what values, for $SERVICESTATE$, $SERVICESTATETYPE$, and $SERVICEATTEMP$ macro definitions: Event handlers are triggered for each state change—for example, in minutes, 10, 23, 28, and 29. When writing an event handler, it is necessary to check whether an event handler should perform an action at that particular time or not. See the following example for more details. A typical example might be that your web server process tends to crash once a month. Because this is rare enough, it is very difficult to debug and resolve it. Therefore, the best way to proceed is to restart the server automatically until a solution to the problem is found. If your configuration has max_check_attempts set to 4, as in the example above, then a good place to try to restart the web server is after the third soft failure check—in the previous example, this would be minute 12. Assuming that the restart has been successful, the diagram shown above would look like this: Please note that no hard critical state has occurred since the event handler resolved the problem. If a restart cannot resolve the issue, Nagios will only try it once, as the attempt is done only in the third soft check. Event handlers are defined as commands, similar to check commands. The main difference is that the event handlers only use macro definitions to pass information to the actual event handling script. This implies that the $ARGn$ macro definitions cannot be used and arguments cannot be passed in the host or service definition by using the ! separator. In the previous example, we would define the following command: define command{command_name restart-apache2command_line $USER1$/events/restart_apache2$SERVICESTATE$ $SERVICESTATETYPE$ $SERVICEATTEMPT$} The command would need to be added to the service. For both hosts and services, this requires adding an event_handler directive that specifies the command to be run for each event that is fired. In addition, it is good to set event_handler_enabled set to 1 to make sure that event handlers are enabled for this object. The following is an example of a service definition: define service{host_name localhostservice_description Webserveruse apacheevent_handler restart-apache2event_handler_enabled 1} Finally, a short version of the script is as follows: #!/bin/sh# use variables for argumentsSERVICESTATE=$1SERVICESTATETYPE=$2SERVICEATTEMPT=$3# we don't want to restart if current status is OKif [ "$SERVICESTATE" != "OK" ] ; then# proceed only if we're in soft transition stateif [ "$SERVICESTATETYPE" == "SOFT" ] ; then# proceed only if this is 3rd attempt, restartif [ "$SERVICESTATEATTEMPT" == "3" ] ; then# restarts Apache as system administratorsudo /etc/init.d/apache2 restartfififiexit 0 As we're using sudo here, obviously the script needs an entry in the sudoers file to allow the nagios user to run the command without a password prompt. An example entry for the sudoers file would be as follows: nagios ALL=NOPASSWD: /etc/init.d/apache2 This will tell sudo that the command /etc/init.d/apache2 can be run by the user nagios and that asking for passwords before running the command will not be done. According to our script, the restart is only done after the third check fails. Assuming that the restart went correctly, the next Nagios check will notify that Apache is running again. As this is considered a soft state, Nagios has not yet sent out any notifications about the problem If the service would not restart correctly, the next check will cause Nagios to set this failure as a hard state. At this point, notifications will be sent out to the object owners. You can also try performing a restart in the second check. If that did not help, then during the third attempt, the script can forcefully terminate all Apache2 processes using the killall or pkill command. After this has been done, it can try to start the service again. For example: # proceed only ifthis is 3rd attempt, restartif [ "$SERVICESTATEATTEMPT" == "2" ] ; then# restart Apache as system administratorsudo /etc/init.d/apache2 restartfi# proceed only ifthis is 3rd attempt, restartif [ "$SERVICESTATEATTEMPT" == "3" ] ; then# try to terminate apache2 process as system administratorsudo pkill apache2# starts Apache as system administratorsudo /etc/init.d/apache2 startfi Another common scenario is to restart one service if another one has just recovered—for example, you might want to restart email servers that use a database for authentication if the database has just recovered from a failure state. The reason for doing this is that some applications may not handle disconnected database handles correctly—this can lead to the service working correctly from the Nagios perspective, but not allowing some of the users in due to internal problems. If you have set this up for hosts or services, it is recommended that you keep flapping enabled for these services. It often happens that due to incorrectly planned scripts and the relations between them, some services might end up being stopped and started again. In such cases, Nagios will detect these problems and stop running event handlers for these services, which will cause fewer malfunctions to occur. It is also recommended that you keep notifications set up so that people also get information on when flapping starts and stops. Modifying Notifications An interesting new feature in Nagios 3 is the ability to change various parameters related to notifications. These parameters are modified via an external command pipe, similar to a few of the commands shown in the previous section. A good example would be when Nagios contact persons have their workstations connected to the local network only when they are actually at work (which is usually the case if they are using notebooks), and turn their computers off when they leave work. In such a case, a ping check for a person's computer could trigger an event handler to toggle that person's attributes. Let's assume that our user jdoe has two actual contacts—jdoe-email and jdoejabber, each for different types of notifications. We can set up a host corresponding to the jdoe workstation. We will also set it up to be monitored every five minutes and create an event handler. The handler will change the jdoe-jabber's host and service notification time period to none on a hard host down state. On a host up state change, the time period for jdoe-jabber will be set to 24x7. This way, the user will only get Jabber notifications if he or she is at work. Nagios offers commands to change the time periods during which a user wants to receive notifications. The commands for this purpose are: CHANGE_CONTACT_HOST_ NOTIFICATION_TIMEPERIOD ( http://www.nagios.org/developerinfo/ externalcommands/commandinfo.php? command_id=153 ) and CHANGE_CONTACT_ SVC_NOTIFICATION_TIMEPERIOD ( http://www.nagios.org/developerinfo/externalcommands/commandinfo.php?command_id=152 ). Both commands take the contact and the time period name as their arguments. An event handler script that modifies the user's contact time period based on state is as follows #!/bin/shNOW='date +%s'CONTACTNAME=$1-jabberif [ "$2,$3" = "DOWN,HARD" ] ; thenTP=noneelseTP=24x7fiecho "[$NOW] CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD;$CONTACT;$TP" >/var/nagios/rw/nagios.cmdecho "[$NOW] CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD;$CONTACT;$TP" >/var/nagios/rw/nagios.cmdexit 0 The command should pass $CONTACTNAME$, $SERVICESTATE$, and $SERVICESTATETYPE$ as parameters to the script. In case you need a notification about a problem sent again, you should use the SEND_CUSTOM_HOST_NOTIFICATION or SEND_CUSTOM_SVC_NOTIFICATION command. These commands take host or host and service names, additional options, author name, and comments that should be put in the notification. Options allow specifying if the notification should also include all escalation levels (a value of 1), if Nagios should skip time periods for specific users (a value of 2) as well as if Nagios should increment notifications counters (a value of 4). Options are stored bitwise so a value of 7 (1+2+4) would enable all of these options. The notification would be sent to all people including escalations; it will be forced, and the escalation counters will be increased. Option value 3 means it should be broadcast to all escalations as well, and the time periods should be skipped. To send a custom notification about the main router to all users including escalations, you should send the following command to Nagios [1206096000] SEND_CUSTOM_HOST_NOTIFICATION;router1;3;jdoe;RESPOND ASAP
Read more
  • 0
  • 0
  • 4284
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-microsoft-office-excel-programming-using-vsto-30
Packt
08 Oct 2009
10 min read
Save for later

Microsoft Office Excel Programming Using VSTO 3.0

Packt
08 Oct 2009
10 min read
Microsoft Office Excel is the most frequently-used Microsoft application and one of the leading spreadsheet programs available. A spreadsheet program is a program that uses a huge grid to display data in rows and columns. The spreadsheet program can then be used to do calculation, data manipulation, and various similar tasks, against this data. Programming in Excel Microsoft Office Excel is one of the powerful Office tools that provides uncomplicated data management. It is loaded with features such as graphing, charting, pivot tables, and calculation. Even though Excel is loaded with numerous features for users, there may be some functionality that cannot be achieved by using the standard Microsoft Excel environment. In Microsoft Office Excel 2007, automation is a great mechanism for populating business documents (for example, reports) with data from backend system. This can be achieved by using VSTO 3.0 and Visual Studio 2008. Microsoft Office Excel 2007 is more programmable than ever before with support for Visual Studio Tools for Office. VSTO is aimed at Microsoft Office Excel users who want to develop Excel-based applications for other Microsoft Office Excel users. VSTO 3.0 is shipped with all of the newly-enhanced Excel objects, including improved features for building Microsoft Office based solutions. VSTO 3.0 is loaded with new features, including support for Windows form controls from within Microsoft Office tools customization. It provides the support for using .NET frameworks, objects and classes for Microsoft Office tools customization. For example, System.Data is the .NET frameworks object that can be used inside the Excel solution to process database operations. This new feature is tightly integrated with the Visual Studio 2008 IDE and gives you the comfort of design time customization of Excel documents for data display and UI customization. Similar to other Microsoft Office Tools, with Microsoft Office Excel 2007 customization using VSTO 3.0, you have two levels of customization— document-level customization and application-level customization. Document-level customization is a solution created for document-level programming and is specific to the document that is part of that particular solution. Application-level customization is a solution created for application-level programming and is specific to the application, and therefore common to all documents based on that application. In a simple Hello World demonstration, let's learn about the document level customization approach. We'll step through a simple task, showing how to create an Excel document that will display a Hello World message on startup. Hello World example using Visual Studio 2008 Open Visual Studio 2008, and create a new Excel 2007 Workbook project. Select New Project. Under Office select 2007, and then select the Excel 2007 Workbook template and name the project ExcelHelloWorld, as shown in the following image: The document selection dialog box is displayed. At this point, you need to choose the template for your design. In this example, you select a new blank template and click on the OK button. Refer to the following screenshot: The solution will be created with all of the supporting files required for our development of an Excel solution. Each solution is created with three worksheets, with default names: Sheet1, Sheet2, and Sheet3 for the workbook you're going to customize , as shown in the following image. The number of sheets in a new workbook depends on the settings in Excel. The following image also shows you the Excel-supported controls, placed on the leftmost side of the Visual Studio 2008 toolbox panel. You can also see the visual representation of Excel 2007 inside Visual Studio 2008. Let's write our Hello World message in a cell when we load the Excel 2007 document. Write the following code inside the ThisWorkbook.cs file. // The Startup event of workbook in our Excel solution// Startup event common to all Office application// Startup event will be fired at the start of the applicationprivate void ThisWorkbook_Startup(object sender,System.EventArgs e){// Creating the instance of active WorkSheet of Excel DocumentExcel.Worksheet AuthorWorkSheet = ThisApplication.ActiveSheetas Excel.Worksheet;// Get the range using number index through Excel cellsby setting AuthorExchange to an Excel range object starting at(1,1) and ending at (1,1)Excel.Range AuthorExcelRange = ThisApplication.get_Range(AuthorWorkSheet.Cells[1, 1],AuthorWorkSheet.Cells[1, 1]);// Setting the value in the cellAuthorExcelRange.Value2 = "Hello! this is my VSTO program forExcel 2007";} The following screenshot results after adding and executing the preceding code: Manipulation Microsoft Office Excel is one of the most comprehensive data management tools for all kinds of users. It is a tool that can be easily understood and quickly learnt. The most important feature of Microsoft Office Excel is its capability to manipulate data from different sources. Excel is one of the most powerful and user-friendly data manipulation applications. You could use Excel to predict what's ahead for your business by creating detailed financial forecasts. This powerful application has pivot table functionality that allows you to drop in your data and rearrange it to answer all kinds of business data analysis type questions. Excel helps you to build various useful analytical tools such as your monthly sales report and product sales growth analysis more easily and flexibly. Excel offers you formulae and functions that will help you to perform complex financial calculations without any manual errors. Excel can provide you with a graphical presentation of your business data by using charts and graphs. Want to know your growth levels for a specific product sales range? Check which parts of your business are performing worse? The pivot table provides more information from your business in depth. Every application in this computer world works with data. The data can be in any form and can belong to different sources. The key question for data management is where to place the data. You manage the data in two ways: data managed outside the program and data managed inside the program. The data managed outside the program includes data managed in a database, a file system, and so on. Data managed inside the program includes data in different worksheets within the workbook, embedded images, and so on. Data manipulation For users who are not satisfied with the default features in Microsoft Office Excel, VSTO programming makes Excel more flexible, and provides a development tool for the creation of custom solutions for data manipulation and data analysis. Custom programming using VSTO 3.0 improves most part of the Microsoft Office Excel solution. Custom programming using VSTO 3.0 provides a wide range of advantages, including saving time by automating most of the frequently-performed tasks, reducing errors due to manual operations, as well as enforcing standards for data processing, and building the capability to seamlessly integrate with other applications seamlessly. Reading worksheet cells There are many ways to manipulate data and write to the cells in an Excel worksheet. Let's see some of these ways. We can read worksheet cells directly through the Cells property of the sheets, rows, and columns, and can set a value directly by using the cell's row and column index. Open Visual Studio 2008 and create a new Excel solution. Refer to the previous example for full instructions of how to do this. Write the following code inside the ThisWorkbook.cs file. In this sample explanation, you are writing data into the worksheet by using the Cells object. // The Startup event of workbook in our Excel solutionprivate void ThisWorkbook_Startup(object sender,System.EventArgs e){// Set value for Cells row and column index// Text data in Sheet1 cellsGlobals.Sheet1.Cells[3, 3] = "Set my data";} We can also read the worksheet and write data to the cells by using the Range object. In this case, you are creating the range and setting the text data for the range in the Excel worksheet. Open Visual Studio 2008 and create a new solution, as before. Write the following code inside the ThisWorkbook.cs file . In this demonstration, you read the worksheet through the range of cells and set the value by reading through cell ranges. private void ThisWorkbook_Startup(object sender,System.EventArgs e){// Setting value in ExcelSheet cells through reading range objectExcel.Range AuthorExcelSheetRange = Globals.Sheet1.Range["A2","B2"];// Text data for the range A2 to B2AuthorExcelSheetRange.Value2 = "Set my data";} Let's see a demonstration of how to read data from an external data file and display this inside our Excel cells. In this demonstration, you will see how the data from the text (.txt) file is displayed in the spreadsheet. Opening a text file as a workbook using VSTO We'll now see how to open the text file as a workbook by using VSTO and C# programming. This saves time and makes the user more comfortable in accessing the text file while processing the data. Open Visual Studio 2008 and create a new solution, as before. Write the following code inside the ThisWorkbook.cs file: // Opening Text file as workbookprivate void ThisWorkbook_Startup(object sender,System.EventArgs e){// In the workbook objects, file path as parameter in Opentextproperty this.Application.Workbooks.OpenText(@"C:TechBooks.txt",// Value 1 is, the row from which it will read data in the textfile missing, 1,// Checks for delimits for text parsingExcel.XlTextParsingType.xlDelimited,// Text Enumeration valueExcel.XlTextQualifier.xlTextQualifierNone,missing, missing, missing, true, missing, missing, missing,missing, missing, missing, missing, missing, missing);} Connecting with Microsoft SQL Server 2008 database Microsoft SQL Server 2008 is a relational database management system developed by Microsoft Corporation. Microsoft SQL Server is used to manage a huge volume of data along with relation and Metadata information for this data. VSTO provides support for manipulating the data from your database inside Excel using ADO.NET classes. The preceding figure demonstrates how an Excel 2007 object is used to interact with the Microsoft SQL Server database. Let's see how to connect with a relational database management system, retrieve data from the database, and finally display it in our Excel spreadsheet. This demonstration shows you how to retrieve data from a Microsoft SQL Server 2008 database and place the retrieved data into the worksheet cells. Open Visual Studio 2008 and create a new solution, as usual. Write the following code inside the ThisWorkbook.cs file. // Namespace for SQL Server connectionusing System.Data.SqlClient;// Startup event of the workbookprivate void ThisWorkbook_Startup(object sender,System.EventArgs e){// Opening SQL connection for Microsoft SQL Server 2008// WINNER the database server contains the databse called ProductsSqlConnection MySQLConnection = new SqlConnection(@"DataSource=WINNER;Initial Catalog=Products;Integrated Security=True");// Passing SQL command textSqlCommand MySQLCommand = new SqlCommand("SELECT * FROMBooks", MySQLConnection);MySQLConnection.Open();// SQL reader to read through data from DatabaseSqlDataReader MySQLReader = MySQLCommand.ExecuteReader();// Get the active sheet of current applicationExcel.Worksheet MyWorkSheet = this.Application.ActiveSheet asExcel.Worksheet;// Header for the columns set in the Value2 properties((Excel.Range)MyWorkSheet.Cells[1, 1]).Value2 = "Book Name";((Excel.Range)MyWorkSheet.Cells[1, 2]).Value2 = "Author Name";// Indexerint i = 2;// Loop to read through the database returned datawhile (MySQLReader.Read()){// Writing the data from the database table column BookName((Excel.Range)MyWorkSheet.Cells[i, 1]).Value2 =MySQLReader["BookName"];// Writing the data from the database table column Author((Excel.Range)MyWorkSheet.Cells[i, 2]).Value2 =MySQLReader["Author"];i++;}// Dispose the SQL commandMySQLCommand.Dispose();// Closing SQL connection after using it.MySQLConnection.Close();} The following screenshot displays data retrieved from Microsoft SQL Server 2008 database and the data being displayed in the worksheet cells. In this demonstration, you learned how to connect with a Microsoft SQL Server 2008 database in order to get data and populate it in a workbook. This is just one of the ways of manipulating data outside of a workbook.
Read more
  • 0
  • 0
  • 10339

article-image-cep-and-soa-six-letters-are-better-three
Packt
08 Oct 2009
11 min read
Save for later

CEP and SOA: Six Letters Are Better than Three

Packt
08 Oct 2009
11 min read
Overview Around a decade ago, it was possible for a single, precocious developer to build an entire SOA-like platform single-handedly. Granted, it was not an easy task to construct a service container and surround it with robust connection management, application security, transaction management, and reliable messaging, but it was at least an attainable goal. It was a proud achievement to build a toy application server or MOM platform in one’s basement. Those were simpler times. Today’s SOA suite is far too vast for one person to build, and uses computer science that is more advanced than a basement hacker can contend with. In the first place, today’s services—as I argue in my new book SOA Cookbook (Packt, 2008)—are designed as processes rather than simple method calls. Building an SOA process engine means brushing up on, or learning from scratch, Finite State Automata, Petri Nets, and, perhaps, the Pi Calculus. Additionally, these processes use business rules to decide on next actions. Building the required rules engine presupposes proficiency in forward-chaining rule definitions, the RETE algorithm, and, possibly, genetic algorithms. Toy SOA is a relic of the past; today’s SOA requires a large team of very smart people. Still, for all its might, today’s SOA is merely reactive. An SOA process provides a business function that reacts to requests. If the function is requested ten thousand times, the process is run ten thousand times. It is not in SOA’s mandate to make sense of trends, or to find suspicious happenings, across those ten thousand invocations. SOA’s job is to be a workhorse, serving the requests. It is not an anomaly watchdog or a slice-and-dice business analysis tool. Still, many enterprises seek just such a capability. Not surprisingly, SOA vendors are starting to add Complex Event Processing (CEP) to their solution. CEP listens on the bus for the same events that pass in and out of SOA processes, but—unlike SOA—is concerned mainly with the detection of patterns that emerge across events. It does this, as we’ll discuss, by applying event-pattern matching rules to the events. CEP thus relies on both SOA’s event bus and its rules engine. Not only does CEP fit in the SOA architecture, but also provides the watchdog capability that business stakeholders find so valuable. CEP and SOA CEP isn’t a new technology but is only now gaining traction in the marketplace. David Luckham wrote the definitive book on CEP (The Power of Events, Addison Wesley), which was published in 2002. Over the years several academic implementations have been developed, notably Stanford’s Rapide and Cornell’s Cayuga. Numerous CEP startups failed in the early days of CEP, during the rise and fall of dotcom in the late 1990s. It was to help market one of these companies, ePatterns, that Luckham started work on his book. The company didn’t pan out, as Luckham reminisces in his article “A Short History of Complex Event Processing Part 3: The Formative Years.” (http://complexevents.com/?p=553), but the book lived on, becoming the bible of events. Until recent years, the most established commercial implementations came from small vendors, such as Coral8 and Streambase. But within the past few years the major SOA vendors—who had previously kept arms-length from CEP, doubtful of its market potential— have started to incorporate CEP into their stacks. IBM, for instance, recently acquired Coral8. TIBCO aggressively sells its CEP tool, BusinessEvents, in its SOA and BPM deals. Oracle, thanks to its BEA acquisition, offers a product called “Oracle” CEP. The combined SOA/CEP offering is encouraging, because CEP’s value comes not from its intrinsic value but from its contribution to an overall solution. SOA vendors, in a sense, have been in the “overall solution” business for years. They promote the idea that business architecture should be built on services, and they provide a platform on which to build those services. But what’s always been missing was a tool to watch the services, to make sense of what’s happening operationally. What CEP and SOA have in common is events. Both technologies use events, but for different purposes. SOA processes use events to drive control flow. An SOA process is started by an event, and during the course of its execution waits for further events to propel it forward. Events in SOA, in effect, force process transitions. Most SOA processes not only receive events but also send events. When a process sends an event, another process receives it. Elaborate choreographies arise when the processes of multiple organizations engage in conversations of events. CEP, by contrast, is a rules engine that uses events to trigger rule evaluations. CEP is constantly listening on the SOA bus for events. As we explore in more detail below, by using event pattern matching rules, CEP is able to infer causal connections between seemingly disparate events. CEP can also aggregate a set of inconsequential low-level events into a single, business-meaningful complex event. In stock trading, for example, a customer’s purchase of shares is the combination of four events (keeping it simple): The customer’s request to the broker to buy the shares The broker’s placement of the order The result of the order, including the price at which the shares were bought The broker’s response back to the customer. When CEP detects these four events, it publishes a complex event—BuyOrderCompleted, let’s call it—back to the bus, where interested listeners may pick it up. The following figure illustrates the sequence of steps; this design is discussed in more detail below. CEP can also detect breakdowns in the buy order. For example, if the broker fails to respond back to the customer in a timely fashion, CEP can easily spot this and publish a BuyOrderBrokerResponseLate event. CEP can also spot anomalies that span multiple orders. For example, it can detect suspicious broker activities like a buy-ahead, in which the broker, when directed by a customer to buy shares, buys his own lot of shares first, and sells them after placing the customer’s order. (The broker makes a nice profit from this furtive trade; the customer’s order, when large enough, drives the price up, so when the broker sells, he comes out ahead.) It would be fiendishly difficult to build a detection mechanism for buy-aheads into SOA processes; CEP, as a watchdog off to the side, is much better equipped. This trade monitoring example is one of many CEP use cases. CEP use cases arise naturally from SOA use cases. If events move through the bus to drive services and processes, there is bound to be some important business reason to infer complex events from them. Indeed, many CEP use cases require SOA. Fraud detection, for example, which checks for anomalies in transactions on an account, must reside on an SOA platform with processes in place to perform transactions on accounts. The fraud detection rules must understand the structure of the account events and the protocol governing how they are exchanged. CEP in the SOA Stack The following figure shows where CEP fits in the stack offered by major SOA vendors. The three layers of the operational stack, shown on the right side of the diagram, are the Enterprise Service Bus (ESB), the Orchestration/Service Engine, and the BPM engine. The Orchestration Engine runs SOA processes, and it uses the ESB, which acts as a full-featured message broker, to send and receive events to its partner systems. Processes that involve both system and human work are split between the Orchestration Engine and the BPM Engine. A workflow process running on the BPM Engine invokes SOA processes in the Orchestration Engine to perform system actions; an SOA process running on the Orchestration Engine uses processes in the BPM Engine to delegate human work. You can refer SOA Cookbook (Packt, 2008) for an expanded discussion of the stack. CEP and its cousin Business Activity Monitoring (BAM) are shown as pieces off to the side. They are the not part of the core operational SOA platform, but rather provide an important business monitoring capability. BAM, in most implementations, is a summary view of business processes in the system. Like CEP, it observes the progress of operational processes, though it handles this data somewhat differently. BAM’s purpose is to create a rolled-up, read-only data view. CEP, in contrast, tries to infer complex events that can trigger follow-on actions. Both CEP and BAM funnel (as the figure shows) have large volume of events from the operational stack, reducing all that chatter to a smaller set. The following table maps this stack to vendors. We consider the four major SOA vendors: IBM, Oracle, BEA, and TIBCO. BAM is omitted from the table; CEP is our focus. Vendor BPM Orchestration ESB CEP TIBCO iProcess BusinessWorks ActiveMatrix Service Grid/Bus BusinessEvents BEA AquaLogic BPM Weblogic Integration AquaLogic Service Bus Oracle CEP Oracle "Fusion" BPA Suite "Fusion" BPEL Process Manager "Fusion" Enterprise Service Bus Oracle CEP (acquired from BEA) IBM Websphere Process Server, FileNet Websphere Process Server, Websphere Interchange Server Websphere Enterprise Service Bus, Websphere Message Broker Coral8 (recent acquisition) The operational stack supports a distributed architecture in which the activities of client applications and partner services, both internal and external to the organization, are coordinated by orchestration processes. Clients and partners communicate with these processes through the ESB. Internal connections typically use MOM queues to access the bus; external connections use SOAP over HTTP. The orchestration processes, besides coordinating partner activities, also interface with backend systems (databases, mainframes, and so on) and use BPM to delegate manual work to human actors. The following figure illustrates this architecture. CEP consists of a set of rules that listen for events from the bus. (A publish-subscribe messaging infrastructure allows CEP to get these events without disrupting the operational processes.) CEP rules, as we discussed above, infer complex events from these operational events. They send complex events back on the bus on orchestration queues, where, as we discuss further below, they are picked up and handled by CEP-aware orchestration processes. CEP must be sufficiently scalable to handle the high volume of events on the bus. There is more to this than sheer processing speed. CEP, like most rule-based systems, is stateful. It keeps its state (i.e., its current set of asserted facts) in a datastore called Working Memory. For performance reasons, Working Memory should be kept in physical memory, and paged out to disk when necessary. Using an RDBMS instead of memory would prove to be simply too slow and only a few commercial databases can handle updates at the volumes of events on a bus anyway. This memory should be fault-tolerant, given the business criticality of CEP. Such an implementation is full of the sort of thorny performance design issues in which SOA vendors have the greatest expertise. BAM works somewhat differently from CEP. Orchestration and BPM processes have state, and BAM uses this state, combined with business data from backend systems, to present a consolidated view of the state of the processes. For example, rather than tracking just order processes, BAM might also track the orders themselves, as they appear in the backend order system. In the previous figure, we labeled this piece as BAM/BI (for business intelligence), because most BAM implementations by themselves lack the ability to incorporate application data. Combining process state with application data often requires the combination of BAM and some sort of BI or analytics tool. Whereas BAM merely presents a view of the system, CEP, by creating events that it has inferred from its observations, serves as an active participant. SOA platforms with CEP are self-healing; CEP watches what’s happening operationally and sounds up when it detects a significant occurrence. The dotted line in the previous figure from CEP to BAM suggests that complex events created by CEP could be incorporated into the BAM dashboard. Thus, the BAM dashboard for the trading application could show statistics on completed orders or buy-aheads per broker. The mechanism by which CEP notifies BAM of complex events is implementation-specific.
Read more
  • 0
  • 0
  • 2476

article-image-jquery-ui-dialog-part-1
Packt
08 Oct 2009
8 min read
Save for later

jQuery UI—The Dialog: Part 1

Packt
08 Oct 2009
8 min read
The following screenshot shows a dialog widget and the different elements that it is made of: A basic dialog A dialog has a lot of default behavior built-in, but few methods are needed to control it programmatically, making this a very easy widget to use that is also highly configurable. Generating it on the page is very simple and requires a minimal underlying mark-up structure. The following page contains the minimum mark-up that's required to implement the dialog widget: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.dialog.css"> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.resizable.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Dialog Example 1</title> </head> <body> <div id="myDialog" class="flora" title="This is the title">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti. Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div> <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.dialog.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.resizable.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.draggable.js"></script> <script type="text/javascript"> //define function to be executed on document ready $(function(){ //create the dialog $("#myDialog").dialog(); }); </script> </body></html> Dialog properties An options object can be used in a dialog's constructor method to configure various dialog properties. Let's look at the available properties: Save this as dialog1.html in the jqueryui folder. A few more source files are required, specifically the ui.resizable.js and ui.draggable.js files and the flora.resizable.css stylesheet. The JavaScript files are low-level interaction helpers and are only required if the dialog is going to be resizable and draggable. The widget will still function without them. The dialog flora theme file is a mandatory requirement for this component, although the resizable one isn't. Other than that, the widget is initialized in the same way as other widgets. When you run this page in your browser, you should see the default dialog widget shown in the previous screenshot, complete with draggable and resizable behaviors. One more feature that I think deserves mentioning here is modality. The dialog comes with modality built-in, although it is disabled by default. When modality is enabled, a modal overlay element, which covers the underlying page, will be applied. The dialog will sit above the overlay while the rest of the page will be below it. The benefit of this feature is that it ensures the dialog is closed before the underlying page becomes interactive again, and gives a clear visual indicator that the dialog must be closed before the visitor can proceed. Custom dialog skins The dialog's appearance is easy to change from the flora theme used in the first example. Like some of the other widgets, certain aspects of the default or flora themes are required to make the widget function correctly. Therefore, when overriding styles, we need to be careful to just override the rules related to the dialog's display. When creating a new skin for the default implementation, including resizable behavior, we have a lot of new files that will need to be created. Apart from new images for the different components of the dialog, we also have to create new images for the resizing handles. The following files need to be replaced when skinning a dialog: dialog-e.gif dialog-n.gif dialog-ne.gif dialog-nw.gif dialog-s.gif dialog-se.gif dialog-sw.gif dialog-title.gif dialog-titlebar-close.png dialog-titlebar-close.png To make it easier to remember which image corresponds to which part of the dialog, these images are named after the compass points at which they appear. The following image illustrates this: Note that these are file names as opposed to class names. The class names given to each of the different elements that make up the dialog, including resizable elements, are similar, but are prefixed with ui- as we'll see in the next example code. Let's replace these images with some of our own. In a new file in your text editor, create the following stylesheet: .flora .ui-dialog, .flora.ui-dialog { background-color:#99ccff;}.flora .ui-dialog .ui-dialog-titlebar, .flora.ui-dialog.ui-dialog-titlebar { background:url(../img/dialog/my-title.gif) repeat-x; background-color:#003399;}.flora .ui-dialog .ui-dialog-titlebar-close, .flora.ui-dialog.ui-dialog-titlebar-close { background:url(../img/dialog/my-title-close.gif) no-repeat; }.flora .ui-dialog .ui-dialog-titlebar-close-hover, .flora.ui-dialog.ui-dialog-titlebar-close-hover { background:url(../img/dialog/my-title-close-hover.gif) norepeat;}.flora .ui-dialog .ui-resizable-n, .flora.ui-dialog .ui-resizable-n { background:url(../img/dialog/my-n.gif) repeat center top;}.flora .ui-dialog .ui-resizable-s, .flora.ui-dialog .ui-resizable-s { background:url(../img/dialog/my-s.gif) repeat center top;}.flora .ui-dialog .ui-resizable-e, .flora.ui-dialog .ui-resizable-e { background:url(../img/dialog/my-e.gif) repeat right center; }.flora .ui-dialog .ui-resizable-w, .flora.ui-dialog .ui-resizable-w { background:url(../img/dialog/my-w.gif) repeat left center;}.flora .ui-dialog .ui-resizable-ne, .flora.ui-dialog .ui-resizable-ne{ background:url(../img/dialog/my-ne.gif) repeat;}.flora .ui-dialog .ui-resizable-se, .flora.ui-dialog .ui-resizable-se{ background:url(../img/dialog/my-se.gif) repeat;}.flora .ui-dialog .ui-resizable-sw, .flora.ui-dialog .ui-resizable-sw{ background:url(../img/dialog/my-sw.gif) repeat;}.flora .ui-dialog .ui-resizable-nw, .flora.ui-dialog .ui-resizable-nw{ background:url(../img/dialog/my-nw.gif) repeat;} Save this as dialogTheme.css in the styles folder. We should also create a new folder within our img folder called dialog. This folder will be used to store all of our dialog-specific images. All we need to do is specify new images to replace the existing ones used by flora. All other rules can stay the same. In dialog1.html, link to the new file with the following code, which should appear directly after the link to the resizable stylesheet: <link rel="stylesheet" type="text/css" href="styles/dialogTheme.css"> Save the change as dialog2.html. These changes will result in a dialog that should appear similar to the following screenshot: So you can see that skinning the dialog to make it fit in with your existing content is very easy. The existing image files used by the default theme give you something to start with, and it's really just a case of playing around with colors in an image editor until you get the desired effect. Dialog properties An options object can be used in a dialog's constructor method to configure various dialog properties. Let's look at the available properties: Property Default Value Usage autoOpen true Shows the dialog as soon as the dialog method is called bgiframe true Creates an <iframe> shim to prevent <select> elements showing through the dialog in IE6 - at present, the bgiframe plugin is required, although this may not be the case in future versions of this widget buttons   {} Supplies an object containing buttons to be used with the dialog dialogClass ui-dialog Sets additional class names on the dialog for theming purposes draggable true Makes the dialog draggable (use ui.draggable.js) height 200(px) Sets the starting height of the dialog hide none Sets an effect to be used when the dialog is closed maxHeight none Sets a maximum height for the dialog maxWidth none Sets a maximum width for the dialog minHeight 100(px) Sets a minimum height for the dialog minWidth 150(px) Sets a minimum width for the dialog modal false Enables modality while the dialog is open overlay {} Object with CSS properties for the modal overlay position center Sets the starting position of the dialog in the viewport resizable true Makes the dialog resizable (also requires ui.resizable.js) show none Sets an effect to be used when the dialog is opened stack true Causes the focused dialog to move to the front when several dialogs are open title none Alternative to specifying title on source element width 300(px) Sets the original width of the dialog
Read more
  • 0
  • 0
  • 1768

article-image-interacting-students-using-moodle-19-part-1
Packt
08 Oct 2009
11 min read
Save for later

Interacting with the Students using Moodle 1.9 (part 1)

Packt
08 Oct 2009
11 min read
We are going to carry out a role-play activity. This activity will be geography-based, but the Moodle activities are the same for any subject. Hopefully, this will help you gain some ideas for your own teaching. Having learned about the course of a river and about the landscape at the location where the river meets the coast, the students are now going to be given the job of developers—planning and designing a riverside campsite. The students will undertake various tasks during the project, all of them within Moodle. We, the teachers, having set the scene, are going to sit back and observe their progress, online. When the entire mini-project is complete, we're going to get them to tell us, personally, how much they feel they have learned. We can use their responses to plan our future Moodle activities. How do we do all this? The words in bold above are examples of activities that we can do in Moodle. There are others too, but for you—as a newbie—these activities are more than enough. To set up any of them, we first need to turn editing on, either via the button on the upper right of the screen, or via the Administration block. Then, in the topic section where we want to add our activity, we click on the space next to Add an activity…. This will bring up a list of options, which might vary depending upon your particular Moodle course. The following screenshot shows some typical options that might show up when you click Add an activity....Be aware that Certificate and Game don't appear in standard Moodle courses. Getting our class to reflect and discuss Have you ever come across a child who is too shy to speak up in class but then produces the most thoughtful written work? Moodle is Godsend for these students, because it has a forum and a chat facility, both of which enable classes and their teachers to have a discussion without actually being together, in the same room. And often, the shy child will happily have their say online, where they can plan it out first and feel comfortable without the interference of their peers. We're going to set some homework where the students will discuss, in general, the kinds of things to keep in mind when planning a riverside campsite. Hopefully, someone will realize it's not a good idea to have it too close to the water. Time for action-setting up a discussion forum on Moodle Let's create an online discussion area for the students to share their views and comments. This discussion area is called the Forum. With editing turned on, click on Add an activity and select Forum. As a result, the following information will appear on the screen. In the Forum type field, click on the drop-down arrow and choose Single Simple Discussion (we'll investigate on the other options later). In the Forum name field, enter some text that will invite your students to click on it to join the discussion. In the Message field, enter your starting topic, with images and hyperlinks, if you wish. Change the option Force everyone to be subscribed to Yes, if you want people to get an email every time somebody adds their comments or suggestions to the forum. Leave the option Read tracking as it is, and people can decide whether to track read or unread messages. The option, Maximum attachment size lets you decide how big a file or an image people can attach with a message. Grade—alter these settings to give each post a mark. But be aware that this will put younger children off. You can put a number in the Post threshold for blocking option if you want to limit the number of posts that a student can make. Click on Save and return to course. What just happened? We have just set up an online discussion area (forum) on a specific topic for our class. Let's go back to our course page and click on the forum that we just prepared. The final output will look like this: Our students will see an icon (usually with two faces) that will prompt them to join the preliminary discussion on where best to locate the campsite. They'll click on the Reply link at the bottom (as you can see in the preceding screenshot), to post their response. How do we moderate the forum? Hopefully, we can just read the students' responses and let them discuss the topic amongst themselves. But as a teacher, we do have three other options: We can edit the response posted by the student (change the wording if it's inappropriate). We can delete the post altogether. We can reply to it when we think it is really important to do so. A student only has the option to reply (as you see if you click on Student view at the upper right of the course page). When we need to get rid of an unsuitable post, or perhaps alter the wording of something one of our students has typed, this extra power we teachers have is helpful. For our starter discussion, we chose a Single Simple Discussion as we wanted the students to focus totally on one issue. However, in other situations, you might need a slightly different type of forum. So the following table gives a brief overview of the other kinds that are available, and explains how you could use them: Name What it does Why use it Single Simple Discussion Only one question they can all answer Best for focused discussions-they can't get distracted Standard forum  Everyone can start a new topic More scope for older students Q and A Pupils must answer first before they can see any replies Useful for avoiding peer pressure issues Each person posts 1 discussion Pupils can post ONE new topic only Handy if you need to restrict posting but still allow some freedom Why use a forum? Here are a few other thoughts on forums, based on my own experiences: A cross-year or cross-class forum can be useful, as the older students can pass on their experiences to the younger students. For example, each year my first year high school students make a volcano as a homework project. As they enter their second year, they use a dedicated forum to pass on their wisdom and answer technical questions sought by the inexperienced first-year students—who are about to begin their own creations. A homework exercise could be set on a forum, as a reflective plenary to the learning done in the class. Once, my class watched a documentary based on the Great New Orleans flood of 2004, and the students were asked, on a forum, to imagine they had been there. They had to suggest some words or phrases to describe their feelings—which we then collated into the next lesson to make poems about the flood. Let's add a little bit of confusion. Instead of simply asking a question, why not make a statement that you know will inspire, annoy, and divide the students. As a result, you can see the variety in the responses. I once posted the topic: “If people live near rivers, and their homes get flooded out, it is surely their own fault for living near rivers. Why should the rest of us have to help them?” In response to this, some violently disagreed with the statement—quoting examples from developing countries, whereas some agreed with the statement—and were then blasted down by their classmates for doing so. But at least the forum got visited! Carrying on the conversation in real time—outside of school A discussion forum, as illustrated above, is a useful tool to get the children to think and to contribute their ideas. It has an advantage over the usual class discussion, in that the shyer pupils are more likely to open up in such discussion forums. However, there is no spontaneity involved. You might post a comment in the morning, and the response may arrive at dinnertime, and so on. Why not combine the advantages of online communication with the advantages of a real time conversation, and make a Moodle chat room? If your students live several miles away from each other, as my students do, and are keen to get on with the project, Moodle chat rooms can have real benefits. We can set a time for the chat—say, Saturday afternoon. This would be a time when we can be present too, if we wish, and the students can move ahead with their plans even though they're not with each other in the classroom. Even though this implementation has its own drawbacks, it provides us with a set-up. Eventually, we can see how it goes and then think about how best we can use it. Time for action-setting up a chat room in Moodle Let's create a chat room where the students can have a chat even when they are not in the same classroom. This way, they can share their views, comments, and suggestions. With editing turned on, go to Add an activity, and select the Chat option. In the Name of this chat room field, enter an appropriate title for the discussion. In the Introduction text field, type in what the discussion is going to be about. For the Next chat time option, choose when you want to open the chat room. For the Repeat sessions option, choose whether you want to chat regularly, or just once. For the Save past sessions option, choose how long, if at all, to keep a record of the conversation. It is up to you to decide whether to allow everyone to view the past sessions or not. For now, you can ignore the Common module settings option. Click on Save and Display. What just happened? We have set up the place and time on Moodle for our students to talk to each other—and even with us if necessary—online. Students will see an icon—usually a speech bubble—on the course page, alongside the name given to the chat. The students just have to click on the icon at the correct time for the chat. When the room is open, they will see this: Clicking on the link will take the students to a box where they'll be able to see their user photo (if they have one) and the time at which they have entered the chat. When others join in, their photos will be shown, and the time of their arrival will be recorded. You talk by typing into the long box at the bottom of the screen, and when submitted, your words appear in the larger box above it. This can get quite confusing if a lot of people are typing at the same time, as the contributions appear one under the other, and do not always follow on from the question or response to which they are referring. Why use Chat? (and why not?) I have to confess that I have switched off the ability for people to use Chat on my school's Moodle site. Chat does have one advantage over the Forum, which is that you can hold discussions in real time with the others who are not physically present in the same room as you. This could be useful on occasions, such as when the teacher is absent from school (but available online). He or she can contact the class at the start of the lesson to check whether they know what they are doing. The students in our school council use Chat for meetings out of school hours, as do our school Governors. You can also read the transcript of a chat (the chat log) after it has happened. However, everyone really has to stay focused on the discussion topic, otherwise, you risk having nothing but a list of trite comments, and no real substance. I've found this to be the case with younger children. Personally, I find a single and a simple discussion in a Forum to be of much more value, than Chat. However, you can try using Chat and see what you think. Your experience could be different from mine.
Read more
  • 0
  • 0
  • 2524
article-image-developing-seam-applications
Packt
08 Oct 2009
10 min read
Save for later

Developing Seam Applications

Packt
08 Oct 2009
10 min read
Seam application architecture As most enterprise Java developers are probably familiar with JSF and JSP, we will be using this as the view technology for our sample applications. Facelets is the recommended view technology for Seam-based applications once we have a solid understanding of Seam. In a standard Java EE application, Enterprise Application Resource (EAR) files contain one or more Web Application Resource (WAR) files and one or more sets of Java Archive (JAR) files containing Enterprise JavaBeans (EJB) functionality. Seam applications are generally deployed in exactly the same manner as depicted in the following diagram. It is possible to deploy Seam onto a servlet-only container (for example, Tomcat) and use POJOs as the server-side Seam components. However, in this situation, we don't get any of the benefits that EJBs provide, such as security, transaction handling, management, or pooling. Seam components Within Seam, components are simple POJOs. There is no need to implement any interfaces or derive classes from a Seam-specific base class to make Seam components classes. For example, a Seam component could be: A simple POJO a stateless Session Bean a stateful Session Bean a JPA entity and so on Seam components are defined by adding the @Name annotation to a class definition. The @Name annotation takes a single parameter to define the name of the Seam component. The following example shows how a stateless Session Bean is defined as a Seam component called calcAction. package com.davidsalter.seamcalculator; @Stateless @Name("calcAction") public class CalcAction implements Calc { ... } When a Seam application is deployed to JBoss, the log output at startup lists what Seam components are deployed, and what type they are. This can be useful for diagnostic purposes, to ensure that your components are deployed correctly. Output similar to the following will be shown in the JBoss console log when the CalcAction class is deployed: 21:24:24,097 INFO [Initialization] Installing components...21:24:24,121 INFO [Component] Component: calcAction, scope: STATELESS, type: STATELESS_SESSION_BEAN, class: com.davidsalter.seamcalculator.CalcAction, JNDI: SeamCalculator/CalcAction/local Object Injection and Outjection One of the benefits of using Seam is that it acts as the "glue" between the web technology and the server-side technology. By this we mean that the Seam Framework allows us to use enterprise beans (for example, Session Beans) directly within the Web tier without having to use Data Transfer Object (DTO) patterns and without worrying about exposing server-side functionality on the client. Additionally, if we are using Session Beans for our server-side functionality, we don't really have to develop an additional layer of JSF backing beans, which are essentially acting as another layer between our web page and our application logic. In order to fully understand the benefits of Seam, we need to first describe what we mean by Injection and Outjection. Injection is the process of the framework setting component values before an object is created. With injection, the framework is responsible for setting components (or injecting them) within other components. Typically, Injection can be used to allow component values to be passed from the web page into Seam components. Outjection works in the opposite direction to Injection. With Outjection, components are responsible for setting component values back into the framework. Typically, Outjection is used for setting component values back into the Seam Framework, and these values can then be referenced via JSF Expression Language (EL) within JSF pages. This means that Outjection is typically used to allow data values to be passed from Seam components into web pages. Seam allows components to be injected into different Seam components by using the @In annotation and allows us to outject them by using the @Out annotation. For example, if we have some JSF code that allows us to enter details on a web form, we may use an <h:inputText …/> tag such as this: <h:inputText value="#{calculator.value1}" required="true"/> The Seam component calculator could then be injected into a Seam component using the @In annotation as follows: @In private Calculator calculator; With Seam, all of the default values on annotations are the most likely ones to be used. In the preceding example therefore, Seam will look up a component called calculator and inject that into the calculator variable. If we wanted Seam to inject a variable with a different name to the variable that it is being injected into, we can adorn the @In annotation with the value parameter. @In (value="myCalculator") private Calculator calculator; In this example, Seam will look up a component called myCalculator and inject it into the variable calculator. Similarly, if we want to outject a variable from a Seam component into a JSF page, we would use the @Out annotation. @Out private Calculator calculator; The outjected calculator object could then be used in a JSF page in the following manner: <h:outputText value="#{calculator.answer}"/> Example application To see these concepts in action, and to gain an understanding of how Seam components are used instead of JSF backing beans, let us look at a simple calculator web application. This simple application allows us to enter two numbers on a web page. Clicking the Add button on the web page will cause the sum of the numbers to be displayed. This basic application will give us an understanding of the layout of a Seam application and how we can inject and outject components between the business layer and the view. The application functionality is shown in the following screenshot. The sample code for this application can be downloaded from the Packt web site, at http://www.packtpub.com/support. For this sample application, we have a single JSF page that is responsible for: Reading two numeric values from the user Invoking business logic to add the numbers together Displaying the results of adding the numbers together <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head> <title>Seam Calculator</title> </head> <body> <f:view> <h:form> <h:panelGrid columns="2"> Value 1: <h:inputText value="#{calculator. value1}" /> Value 2: <h:inputText value="#{calculator. value2}" /> Add them together gives: <h:outputText value=" #{calculator.answer} "/> </h:panelGrid> <h:commandButton value="Add" action= "#{calcAction.calculate}"/> </h:form> </f:view> </body> </html> We can see that there is nothing Seam-specific in this JSF page. However, we are binding two inputText areas, one outputText area, and a button action to Seam components by using standard JSF Expression Language. JSF EL Seam Binding calculator.value1 This is bound to the member variable value1 on the Seam component called calculator. This value will be injected into the Seam component. calculator.value2 This is bound to the member variable value2 on the Seam component called calculator. This value will be injected into the Seam component. calculator.answer This is bound to the member variable answer on the Seam component called calculator. This value will be outjected from the Seam component. calcAction.calculate This will invoke the method calculate() on the Seam component called calcAction. Our business logic for this sample application is performed in a simple POJO class called Calculator.java. package com.davidsalter.seamcalculator; import java.io.Serializable; import org.jboss.seam.annotations.Name;@Name("calculator") public class Calculator { private double value1; private double value2; private double answer; public double getValue1() { return value1; } public void setValue1(double value1) { this.value1 = value1; } public double getValue2() { return value2; } public void setValue2(double value2) { this.value2 = value2; } public double getAnswer() { return answer; } public void add() { this.answer = value1 + value2; } } This class is decorated with the @Name("calculator") annotation, which causes it to be registered to Seam with the name, "calculator". The @Name annotation causes this object to be registered as a Seam component that can subsequently be used within other Seam components via Injection or Outjection by using the @In and @Out annotations. Finally, we need to have a class that is acting as a backing bean for the JSF page that allows us to invoke our business logic. In this example, we are using a Stateless Session Bean. The Session Bean and its local interface are as follows. In the Java EE 5 specification, a Stateless Session Bean is used to represent a single application client's communication with an application server. A Stateless Session Bean, as its name suggests, contains no state information; so they are typically used as transaction façades. A Façade is a popular design pattern, which defines how simplified access to a system can be provided. For more information about the Façade pattern, check out the following link: http://java.sun.com/blueprints/corej2eepatterns/Patterns/SessionFacade.html Defining a Stateless Session Bean using Java EE 5 technologies requires an interface and an implementation class to be defined. The interface defines all of the methods that are available to clients of the Session Bean, whereas the implementation class contains a concrete implementation of the interface. In Java EE 5, a Session Bean interface is annotated with either the @Local or @Remote or both annotations. An @Local interface is used when a Session Bean is to be accessed locally within the same JVM as its client (for example, a web page running within an application server). An @Remote interface is used when a Session Bean's clients are remote to the application server that is running within a different JVM as the application server. There are many books that cover Stateless Session Beans and EJB 3 in depth, such as EJB 3 Developer's Guide by Michael Sikora, published by Packt Publishing. For more information on this book, check out the following link: http://www.packtpub.com/developer-guide-for-ejb3 In the following code, we are registering our CalcAction class with Seam under the name calcAction. We are also Injecting and Outjecting the calculator variable so that we can use it both to retrieve values from our JSF form and pass them back to the form. package com.davidsalter.seamcalculator; import javax.ejb.Stateless; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.Name; @Stateless @Name("calcAction") public class CalcAction implements Calc { @In @Out private Calculator calculator; public String calculate() { calculator.add(); return ""; } } package com.davidsalter.seamcalculator; import javax.ejb.Local; @Local public interface Calc { public String calculate(); } That's all the code we need to write for our sample application. If we review this code, we can see several key points where Seam has made our application development easier: All of the code that we have developed has been written as POJOs, which will make unit testing a lot easier. We haven't extended or implemented any special Seam interfaces. We've not had to define any JSF backing beans explicitly in XML. We're using Java EE Session Beans to manage all of the business logic and web-tier/business-tier integration. We've not used any DTO objects to transfer data between the web and the business tiers. We're using a Seam component that contains both state and behavior. If you are familiar with JSF, you can probably see that adding Seam into a fairly standard JSF application has already made our development simpler. Finally, to enable Seam to correctly find our Seam components and deploy them correctly to the application server, we need to create an empty file called seam.properties and place it within the root of the classpath of the EJB JAR file. Because this file is empty, we will not discuss it further here. To deploy the application as a WAR file embedded inside an EAR file, we need to write some deployment descriptors.
Read more
  • 0
  • 0
  • 2126

article-image-slider-dynamic-applications-using-scriptaculous-part-2
Packt
08 Oct 2009
4 min read
Save for later

Slider for Dynamic Applications using script.aculo.us (part 2)

Packt
08 Oct 2009
4 min read
Code usage for sliders with options We are now done with the most important part of the slider: the implementation of the slider in our applications. But wait, we need the slider to suit our applications, right? So let's customize our slider with options. We have mentioned earlier that track is the range of values. So let's first define the range for our slider. window.onload = function() { new Control.Slider('handle1' , 'track1', { axis:'vertical', range:$R(1,100)} The range option uses the Prototypes' objectRange instance. Hence, we declare it using $R (minimum, Maximum). Everything looks neat until here. Let's add some more options to our constructor, onSlide(). Using the onSlide() callback every time, we drag the slider and the callback is invoked. The default parameter passed to onSlide() is the current slider value. window.onload = function() { new Control.Slider('handle1' , 'track1', { axis:'vertical', range:$R(1,100), onSlide: function(v) { $('value1').innerHTML = "New Slide Value="+v;} }} We have added a div called value1 in our HTML code. On dragging the slider, we will update the value1 with the current slider value. OK, so let's see what happened to our slider to this point. Check out the following screenshot: Impressed? And, we are not done yet. Let's add more options to the slider now. You may ask me, what if the slider in the application needs to be at a particular value by default? And I will say use the sliderValue option. Let's make our slider value 10 by default. Here is the snippet for the same: window.onload = function() {      new Control.Slider('handle1' , 'track1',     {   axis:'vertical',   range:$R(1,100),   sliderValue: 10,   onSlide: function(v) { $('value1').innerHTML = "New Slide                                                 Value="+v;}} And, you should see the slider value at 10 when you run the code. Now your dear friend will ask, what if we don't want to give the range, but we need to pass the fixed set of values? And you proudly say, use the values option. Check out the usage of the values options in the constructor. window.onload = function() { new Control.Slider('handle1' , 'track1', { range:$R(1,25), values:[1, 5,10,15,20,25], onSlide:function(v){ $('value1').innerHTML = "New Slide Value="+v;} } );} We have added a set of values in the array form and passed it to our constructor. Let's see what it looks like. Tips and tricks with the slider After covering all the aspects of the slider feature, here is a list of simple tips and tricks which we can make use of in our applications with ease. Reading the current value of the slider script.aculo.us "genie" provides us with two callbacks for the slider to read the current value of the slider. They are: onSlide onChange Both these callbacks are used as a part of options in the slider. onSlide contains the current sliding value while the drag is on. The callback syntax is shown as follows: onSlide: function(value) {// do something with the value while sliding. Write or Edit thevalue //of current slider value while sliding} onChange callback will contain the value of the slider while the sliding or the drag event ends. After the drag is completed and if the value of the slider has changed then the onChange function will be called. For example, if the slider's current value is set to 10 and after sliding we change it to 15, then the onChange callback will be fired. The callback syntax is shown as follows: onChange: function(value){// do anything with the "changed" and current value} Multiple handles in the slider Now, a thought comes to our mind at this point: Is it possible for us to have two handles in one track? And, the mighty script.aculo.us library says yes! Check out the following code snippet and screenshot for a quick glance of having two handles in one track: HTML code<div id="track1"><div id="handle1"></div><div id="handle2"></div></div> JavaScript code for the same: window.onload = function() { new Control.Slider(['handle1','handle2'] , 'track1');} Now, check out the resulting screenshot having two handles and one track: The same can also be applied for the vertical slider too.
Read more
  • 0
  • 0
  • 2130

article-image-liferay-mail-and-sms-text-messenger-portlet
Packt
08 Oct 2009
5 min read
Save for later

Liferay Mail and SMS Text Messenger Portlet

Packt
08 Oct 2009
5 min read
Working with Mail Portlet For the purpose of this article, we will use an intranet website called book.com  which is created  for a fictions company named "Palm Tree Publications". In order to let employees manage their emails, we can use the Liferay Mail portlet. As an administrator of "Palm Tree Publications", you need to create a Page called "Mail" under the Page, "Community" at the Book Lovers Community Public Pages and also add the Mail portlet in the Page, "Mail". Experiencing Mail Management First of all, login as "Palm Tree". Then, let's do the above as follows: Add a Page called "Mail" under the Page "Community" at the Book Lovers Community Public Pages, if the Page is not already present. If the Mail portlet is not already present, add it in the Page, "Mail" of the Book Lovers Community where you want to manage mails. You will see the Mail portlet as shown in the following figure. Let's assume that we set up the mail domain as "cignex.com" in the Enterprise Admin portlet for testing purposes, as we have a mail engine with this mail domain already. Of course, you could set up the mail domain as "book.com", or something else, if you had a mail engine with this mail domain in your hand. As an editor of the editorial department, "Lotti Stein", you may want to manage your mails in the mail domain, "cignex.com". You can first choose a user name for your personal company the email address, say "admin1234" and register. Let's do it as follows: Login as "Lotti Stein". Go to the Page "Mail" under the Page, "Community", at the Book Lovers community Public Pages. Locate the Mail portlet. Input the value for User name as "admin1234". Click the Register button. Your new email address is "admin1234@cignex.com". This email address will also serve as your login, as shown in the following figure. You can now check for new messages in your inbox, by clicking the Inbox link first. Then, you can view the Unread messages, and either Check Mail or create a New mail, as shown in the following figure: You can go to the Page of Mail management by clicking on any link of Unread Messages, or Check Mail button or New button. Further, you can manage emails through the Mail portlet of your current account. Email management includes the following features (as shown in the following figure): Create a New email. Check Mail. Reply to an email. Reply All emails. Forward emails. Delete emails. Print emails, and Search. Note that the first email with the subject, "Users in Staging server", is sent through the SMS Text Messenger portlet. For more details, refer to the forthcoming section. How to Set up Mail Server? In order to make the Mail portlet work, we have to set up a mail server with IMAP, POP and SMTP protocols. Suppose that the Enterprise "Palm Tree Publications" has a mail server with the domain "exg3.exghost.com", an account "admin@cignex.com/admin1234", and protocol IMAP, POP and SMTP. As an administrator, you need to integrate this mail server with IMAP, POP and SMTP protocol in Liferay. Let's do it as follows: Find the file ROOT.xml in $TOMCAT_DIR/conf/Catalina/localhost. Find the mail configuration first. Then configure it as follows: <!-- Mail --><Resourcename="mail/MailSession"auth="Container"type="javax.mail.Session"mail.imap.host="exg3.exghost.com"mail.imap.port="143"mail.pop.host="exg3.exghost.com"mail.pop.port="110"mail.store.protocol="imap"mail.transport.protocol="smtp"mail.smtp.host="exg3.exghost.com"mail.smtp.port="2525"mail.smtp.auth="true"mail.smtp.starttls.enable="true"mail.smtp.user="admin@cignex.com"password="admin1234"mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"/> In short, a Mail portlet is an AJAX web-mail client. We can configure it to work with any mail server. It reduces page refreshes, since it displays message previews and message lists in a dual pane window. How to Set up Mail Portlet? If you have proper Permissions, you can change the preferences of the Mail portlet. To change the preferences, you can simply click the Preferences icon to the upper right of the Mail portlet. With the Recipients tab selected, you can find potential recipients from the Directory (Enabled or Disabled) and the Organization (My Organization or All Available). Click the Save button after making any changes. Using the Filters tab, you can set the values to filter emails associated with an email address to a Folder. Click the Save button after making any changes. Note that the maximum number of email addresses is ten. This number is also configurable at the portal-ext.properties Similarly, the Forward Address tab allows all emails to be forwarded to the email address you want. Enter one email address Per Line. Remove all entries to disable email forwarding. Select Yes to leave, or No to not leave a copy of the forwarded message. Click the Save button after making any changes. Further, the Signature tab also allows you to set up your signature using HTML text editor. The signature you have set up will be added to each outgoing message. Click the Save button after making any changes. The Vacation Message tab allows you to set up vacation messages using HTML text editor. The vacation message notifies others of your absence (as shown in the following figure). Click the Save button after making any changes.
Read more
  • 0
  • 0
  • 3715
article-image-social-bookmarking-wordpress-plugin
Packt
08 Oct 2009
6 min read
Save for later

Social Bookmarking with WordPress Plugin

Packt
08 Oct 2009
6 min read
You will learn these by creating a Social Bookmarking type of plugin that adds a Digg button to each post on your blog As you probably know, Digg is a very popular service for promoting interesting content on the Internet. The purpose of a Digg button on your blog is to make it easier for Digg users to vote for your article and also to bring in more visitors to your blog. The plugin we'll create in this article will automatically insert the necessary code to each of your posts. So let's get started with WordPress plugin development! Plugging in your first plugin Usually, the first step in plugin creation is coming up with a plugin name. We usually want to use a name that is associated with what the plugin does, so we will call this plugin, WP Digg This. WP is a common prefix used to name WordPress plugins. To introduce the plugin to WordPress, we need to create a standard plugin header. This will always be the first piece of code in the plugin file and it is used to identify the plugin to WordPress. Time for action – Create your first plugin In this example, we're going to write the code to register the plugin with WordPress, describe what the plugin does for the user, check whether it works on the currently installed version of WordPress, and to activate it. Create a file called wp-digg-this.php in your favorite text editor. It is common practice to use the plugin name as the name for the plugin file, with dashes '-' instead of spaces. Next, add a plugin information header. The format of the header is always the same and you only need to change the relevant information for every plugin: <?php /* Plugin Name: WP Digg This Version: 0.1 Description: Automatically adds Digg This button to your posts. Author: Vladimir Prelovac Author URI: http://www.prelovac.com/vladimir Plugin URI: http://www.prelovac.com/vladimir/wordpress-plugins/ wp-digg-this */ ?> Now add the code to check the WordPress version: /* Version check */ global $wp_version; $exit_msg='WP Digg This requires WordPress 2.5 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>'; if (version_compare($wp_version,"2.5","<")) { exit ($exit_msg); } ?> Upload your plugin file to the wp-content/plugins folder on your server using your FTP client. Go to your WordPress Plugins admin panel. You should now see your plugin listed among other plugins: This means we have just completed the necessary steps to display our plugin in WordPress. Our plugin can be even activated now—although it does not do anything useful (yet). What just happened? We created a working plugin template by using a plugin information header and the version check code. The plugin header allows the plugin to be identified and displayed properly in the plugins admin panel. The version check code will warn users of our plugin who have older WordPress versions to upgrade their WordPress installation and prevent compatibility problems. The plugin information header To identify the plugin to WordPress, we need to include a plugin information header with each plugin. The header is written as a PHP comment and contains several fields with important information. This code alone is enough for the plugin to be registered, displayed in the admin panel and readied for activation. If your future plugin has more than one PHP file, the plugin information should be placed only in your main file, the one which will include() or require()  the other plugin PHP files. Checking WordPress versions To ensure that our plugin is not activated on incompatible WordPress versions, we will perform a simple WordPress version check at the very beginning of our code. WordPress provides the global variable $wp_version that provides the current WordPress version in standard format. We can then use PHP function version_compare() to compare this and our required version for the plugin, using the following code: if (version_compare($wp_version,"2.6","<")) { // do something if WordPress version is lower then 2.6 } If we want to stop the execution of the plugin upon activation, we can use the exit() function with the error message we want to show. In our case, we want to show the required version information and display the link to the WordPress upgrade site. $exit_msg='WP Digg This requires WordPress 2.6 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>'; if (version_compare($wp_version,"2.6","<")) { exit ($exit_msg); } While being simple, this piece of code is also very effective. With the constant development of WordPress, and newer versions evolving relatively often, you can use version checking to prevent potential incompatibility problems. The version number of your current WordPress installation can be found in the footer text of the admin menu. To begin with, you can use that version in your plugin version check (for example, 2.6). Later, when you learn about WordPress versions and their differences, you'll be able to lower the version requirement to the minimal your plugin will be compatible with. This will allow your plugin to be used on more blogs, as not all blogs always use the latest version of WordPress. Checking the plugin You can go ahead and activate the plugin. The plugin will be activated but will do nothing at this moment. Time for Action – Testing the version check Deactivate the plugin and change the version check code to a higher version. For example, replace 2.6 with 5.0. if (version_compare($wp_version,"5.0","<")) Re-upload the plugin and try to activate it again. You will see a WordPress error and a message from the plugin: What just happened? The version check fails and the plugin exits with our predefined error message. The same thing will happen to a user trying to use your plugin with outdated WordPress installation, requiring them to update to a newer version. Have a go Hero We created a basic plugin that you can now customize. Change the plugin description to include HTML formatting (add bold or links to the description). Test your plugin to see what happens if you have two plugins with the same name (upload a copy of the file under a different name).
Read more
  • 0
  • 0
  • 7031

article-image-dial-plans-sipxecs-40
Packt
08 Oct 2009
7 min read
Save for later

Dial Plans in sipXecs 4.0

Packt
08 Oct 2009
7 min read
The communication system's Dial Plan is a collection of Dial Rules. The purpose of the Dial Plan is to control the routing of calls based on dialed numbers. Different Dial Rules within the Dial Plan are selected by matching dialed number patterns (the user part of a SIP URL). The following types of dial rules can be created in sipXecs: Voicemail: This is used to configure the system Voicemail server. Custom: This is used to build custom call routing to gateways. Long Distance: This is used to route long-distance dialed calls. Local: This is used to route local phone calls to gateways. Emergency: This is used for emergency call routing to gateways. International: This is used for routing calls to international destinations to gateways. Attendant: This is used for routing calls to auto attendants defined in the system. Dial Plan configuration is located under the System menu. Clicking on the Dial Plan menu item will display the following page: As seen in the above screenshot, there are some default dial rules already created, that allow the administration to simply add gateways and enable them. Existing Dial Rules can be edited by clicking on the rule's name. Additionally new rules can be created with the Add New Rule  drop-down menu. Dial rules are processed in the order that they are listed so more specific dial plan entries should be listed near the top. Additionally, if a dial rule is matched and the user does not have permission to use the dial plan entry the call will fail. Voicemail dial rule There is typically only one voicemail per phone system. Its purpose is to control how voicemail is routed for mailboxes and how the voicemail system is accessed. The following screenshot shows the default Voicemail system settings:     The following options are available in Voicemail Dial Rules: Enabled: Dial rules can be enabled or disabled in the system as the administrator wishes. A rule might be disabled if it is being tested or if a temporary rule gets created to address a particular problem. Name: This is a descriptive name for the dial rule. Description: This is a description of what the dial rule is for, to help in documentation. Internal station extension length: The number of digits used for internal extensions in your installation. Add another voicemail rule if you have phones with different length extensions. Voicemail extension: The number dialed to reach the voicemail server. This can be left empty to disable Voicemail. Voicemail inbox prefix: The number dialed when directly dialing or forwarding a call to a user's voicemail box. Voicemail type: The Voicemail type can be set to Internal Voicemail Server or Exchange Voicemail Server. Microsoft Exchange 2007 can be used as an alternative to the internal Voicemail Server. Select Exchange Voicemail Server and enter its name or IP address into the field provided. For every user or group of users, the desired voicemail server needs to be selected. Select the Permissions tab in the Users menu to do this. Choose only either the internal voicemail server or Exchange 2007 as these do not work when both confi gured on the system. Note: Due to a Microsoft problem Message Waiting Indication (MWI) does not work with Exchange 2007. Other external voicemail servers can be used instead of Exchange 2007 using this configuration. Voicemail host: IP address or name of the voicemail server. Leave empty if the voicemail server runs on the same computer as the call server. Schedule: All dial plan entries can be allowed to operate based on a schedule. Voicemail is typically not scheduled. Custom dial rules Custom dial rules are very useful for controlling special call scenarios. For example, if you are connecting a gateway to another PBX that has extensions 400: 599, a custom dial rule could be configured to send calls to that gateway when a three digit number is passed that begins with a 4 or a 5. The following screenshot show the custom Dial Rule page: The following options are available for custom Dial Rules: Enabled: Dial rules can be enabled or disabled in the system as the administrator wishes. A rule might be disabled if it is being tested or if a temporary rule gets created to address a particular problem. Name: A descriptive name for the dial rule. Description: More information about this dial rule and what it is used for. Dialed Number: Defines the digits that this rule will match. Any number of prefixes and trailing digits can be added with the Add hyperlink. Prefixes: Prefixes are the initial part of a dialed number (or SIP URL). A prefix can be integers (for example,2), ranges (for example, 1-5), or lists (for example, 2, 3, 4). Any number of digits (Suffix): Defines how many digits will follow the prefix. Values from 0 to 18 or Any Number of Digits can be selected. Required Permissions: Defines the user permissions required to access the dial rule. 900 Dialing, Attendant Directory, International Dialing, Local Dialing, Long Distance Dialing, Mobile Dialing, Record System Prompts, Toll Free, or Voice Mail. Resulting Call: Defines what digits besides the dialed digits will be sent to the gateway. Dial(new prefix): Allows the administrator to change the prefix that will be passed to the gateway. This entry may be left blank to drop the prefix that was detected (when Matched suffix is selected in the following drop-down menu). And append (Suffix): The and append drop-down menu item can have one of three values; Nothing, Matched suffix, or Entire dialed number. Schedule: A schedule can be defined that determines when the custom dial rule can be used. Gateways: A list of gateways available to this dial rule. See the Adding gateway section earlier in this article for information about gateway selection and user locations. Long distance dial rules Long distance dial rules are used by the system to control whether the users are permitted to dial long-distance numbers or to select different gateways for least-cost routing of calls. The default long distance Dial Rule is disabled by default in the system. The rule is triggered by a number consisting of a PSTN prefix followed by the Long Distance prefix and a variable part starting with one of the patterns specified in the Area Codes field. The following settings are available for long distance dial rules (click on Show Advanced Settings to see all of the dial rule's options): Enabled: Dial rules can be enabled or disabled in the system as the administrator wishes. A rule might be disabled if it is being tested or if a temporary rule gets created to address a particular problem. Name: A descriptive name for the dial rule. Description: More information about this dial rule and what it is used for. Permission : Defines the user permissions a user must have to use this dial rule. Treat PSTN prefix as optional : If this is checked the caller does not have to dial the PSTN prefix (following). Dialing the PSTN prefix is optional by default. This item is only shown if Show Advanced Options is selected. PSTN prefix : The prefix dialed by the caller and dropped before the call is sent to the gateway. The Long Distance prefix is always sent to the gateway. Treat long distance prefix as optional: If this is checked the caller does not have to dial the long distance prefix. This item is only shown if Show Advanced Options is selected. Long distance prefix: The prefix dialed by the caller and sent to the gateway. Area codes  : Optional comma-separated list of prefixes that specify the dialed numbers to which this rule applies. If the Area Codes field is empty the rule will match any number starting with the PSTN prefix followed by the Long distance prefix. External number length: The number of digits in the resulting number sent to the gateway. The PSTN prefix and the long distance prefix are not counted. Valid values are—Any number of digits and 5-15 digits. Schedule: A schedule can be defined that determines when the custom dial rule can be used. Gateways: A list of gateways available to this dial rule. See the Adding gateway section earlier in this article for information about gateway selection and user locations. The resulting call is sent to the gateways specified in the gateway list in the order gateways are listed.
Read more
  • 0
  • 0
  • 4122
Modal Close icon
Modal Close icon