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
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1802 Articles
article-image-managing-discounts-vouchers-and-referrals-php-5-ecommerce
Packt
21 Jan 2010
3 min read
Save for later

Managing Discounts, Vouchers, and Referrals with PHP 5 Ecommerce

Packt
21 Jan 2010
3 min read
Discount codes Discount codes are a great way to both entice new customers into a store, and also to help retain customers with special discounts. The discount code should work by allowing the customer to enter a code, which will then be verified by the store, and then a discount will be applied to the order. The following are discount options we may wish to have available in our store: A fixed amount deducted from the cost of the order A fixed percentage deducted from the cost of the order The shipping cost altered, either to free or to a lower amount Product-based discounts (although we won't cover this one in the article) It may also be useful to take into account the cost of the customer's basket; after all if we have a $5 discount code, we probably wouldn't want that to apply for orders of $5 or lower, and may wish to apply a minimum order amount. Discount codes data When storing discount codes in the framework, we need to store and account for: The voucher code itself, so that we can check that the customer is entering a valid code Whether the voucher code is active, as we may wish to prepare some voucher codes, but not have them usable until a certain time, or we may wish to discontinue a code A minimum value for the customer's basket, either as an incentive for the customer to purchase more or to prevent loss-making situations (for example a $10 discount on a $5 purchase!) The type of discount: Percentage: To indicate that the discount amount is a percentage to be removed from the cost Fixed amount deducted: To indicate that the discount amount is a fixed amount to be removed from the order total Fixed amount set to shipping: To indicate that the discount amount is to be the new value for the shipping cost Discount amount; that is, the amount of discount to be applied The number of vouchers issued, if we wish to limit the number of uses of a particular voucher code An expiry date, so that if we wish to have the voucher code expire, codes with a date after the stored expiry date would no longer work Discount codes database The following table illustrates this information as database fields within a table: The default value for num_vouchers is -1, which we will use for vouchers that are not limited to a set number of issues. Field Type Description ID Integer (Primary Key, Auto increment) For the framework to reference the code Vouchercode Varchar The code the customer enters into the order Active Boolean If the code can be used Min_basket_cost Float The minimum cost of the customer's basket for the code to work for them Discount_operation ENUM('-',%','s') The type of discount Num_vouchers Integer Number of times the voucher can be used Expiry timestamp The date the voucher code expires, and is no longer usable The following code represents this data in our database: CREATE TABLE `discount_codes` (`ID` INT( 11 ) NOT NULL AUTO_INCREMENT ,`vouchercode` VARCHAR( 25 ) NOT NULL ,`active` TINYINT( 1 ) NOT NULL ,`min_basket_cost` FLOAT NOT NULL ,`discount_operation` ENUM( '-', '%', 's' ) NOT NULL ,`discount_amount` FLOAT NOT NULL ,`num_vouchers` INT( 11 ) NOT NULL DEFAULT '-1',`expiry` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,PRIMARY KEY ( `ID` )) ENGINE = INNODB DEFAULT CHARSET = latin1 AUTO_INCREMENT =1;
Read more
  • 0
  • 0
  • 6045

article-image-lesson-solutions-using-moodle-19-part-1
Packt
21 Jan 2010
10 min read
Save for later

Lesson Solutions using Moodle 1.9: Part 1

Packt
21 Jan 2010
10 min read
One of the most challenging aspects of course development often involves simply determining how to select and organize your material. It is very important to be strategic about the type of material you select. Needless to say, every item used in your course should tie directly to course outcomes, and you should make sure that all your items are used in some way. Beyond that, putting the material in your course can feel fairly confusing. Fortunately, Moodle makes it easy to select, incorporate, and organize your content. Moodle also helps you lead students through the material in a way that will maximize the chances of them finishing your course and successfully achieving learning outcomes. Before we go any further, it is worthwhile to take a moment to clarify lessons in Moodle. The terminology can be a bit confusing. In Moodle, a lesson is an activity that fits well within the object-oriented approach of Moodle. It is important to keep in mind that the idea of a lesson in Moodle is fairly limited, and will work within the overall traditional notion of lessons. Selecting and sequencing content for lessons In this section, we'll discuss the best way to select content for your lessons, and how to arrange it so that the students naturally progress to the kinds of competence they need to demonstrate when they get ready for their final assessments. Create conditions for learning Everyone has experienced the pain of a bad lecture when there is just absolutely nothing that reaches out and captures one's imagination. You squirm, you daydream, and then, when it's over, you can't recall a single thing that was said. In that situation, one can safely say that not much learning took place, not just because the delivery might have been ineffectual, but even more compellingly because the speaker failed to ever connect with his/her audience. The educational psychologist Robert Gagne studied the problem of developing ideal learning conditions and, after years of research published his findings in a book titled Conditions of Learning released in 1965. Basically, he discovered that to create ideal learning conditions, there are nine instructional events that must take place. The first event, which he describes as "gaining attention", is critical. If you intellectually stimulate the learners, you're activating receptors in their brain, and they are more likely to pay attention. Once you've gained their attention, you should develop activities that will do the following: Inform learners of objectives and create levels of expectation Stimulate recall of prior learning that relates to your course objectives Present instructional content Guide your students by creating categories and sequences Encourage performance and practice Provide feedback (either automatically or personally) Assess performance Apply knowledge to job or other activity Gagne's "instructional events" are not set in stone, but they are very useful as you put your course together. Notice that they are heavily weighted towards performance, which is not too surprising as Gagne was a resolute behaviorist. Other theorists such as Vygotsky might lean more heavily toward social learning and put more emphasis on the discussion forums. Employ scaffolding Scaffolding is a concept that was developed by Bruner (1975), who used Vygotsky's notions of social and imitative learning in order to explain how people learn from each others in groups and classrooms. Vygotsky held that children learn as they observe teachers and others and, as they adopt practices, they are coached by others to modify their behaviors until they conform to the norm. Bruner took the idea further and proposed that a good way to help students learn is to have a model (a teacher) perform the activity, and then assist the student until he/she is able to perform independently and freely. Bruner thought of the support that is gradually taken away as "scaffolding". If you learned to ride a bicycle as a child, you probably used training wheels, so it might be more comfortable to think of this as a "training wheel" approach. At any rate, wherever and whenever you can, let your students see partially worked problems, and work on the problems with them. Peers can also be training wheels or scaffolding for each other as well, as they provide partial solutions, model essays, and partially-solved problems in anticipation of being able to do things independently. Use chunking to help build concepts Have you ever felt utterly lost in a maze of too much information?, Have you heard anyone remarking that "he/she couldn't see the forest for the trees"? In each case, the problem was that of too many small bits of information and not enough large, organizing sets or categories. To address that problem, educational psychologists have developed a concept they call "chunking", which is basically grouping small items into sets. Essentially, you are mentally recoding low-information content and grouping them together. Ideally, the total number of units will decrease, and what you'll be left with is a small number of high-information "chunks". Chunks are easier to work with than thousands of individual pieces, just as it's easier to pick up a necklace than a thousand individual beads. As you develop your content, think of ways to organize, classify, and categorize to help students access and retrieve information from their working memory. Keep in mind that these are good activities to employ early in the lesson as you seek to help students master the lower-level and foundational cognitive tasks such as identify, define, and describe. Get students involved early Why make students take risks? Why make them introduce themselves, respond to questions, and interact? While it's true that some students will feel a certain amount of discomfort as they make themselves vulnerable, the rewards for the intellectual and emotional risk-taking are very high. They will feel a sense of affiliation, and the essentially dehumanizing e-learning space will become more human, more socially relevant to their lives. Another key consideration is that students are able to practice higher-level cognitive tasks in the discussion board area. They can evaluate, analyze, and synthesize topics on a deeper level through intellectual interaction with peers. Keep it lively Gaining attention is something that you'll need to do throughout the class. Students will constantly need to be stimulated, refreshed, and refocused. Not only will you stimulate the receptors in their brains, you'll also help them formulate their own conversation with the content. As for questions in their minds, be sure to relate the content to something practical and relevant—in the world, in their lives, in their prior knowledge—and then encourage them to discuss and debate. Keeping it lively not only keeps their attention, it also motivates students to return to the course and will help them maintain a high level of enthusiasm. Keep focused There are a number of ways to keep students focused on what you're wanting them to learn. The key is to mix it up, and not repeat the same attention-getting tactics, or you'll risk having students totally tune it out. Try many different strategies—add points, add a video snippet, interject a question, add a graphic or diagram, incorporate a practice quiz or game. Use media strategically Some instructors fall into the trap of media overload. The students may be studying Shakespeare's Hamlet, so they put up links to a hundred different video clips of Shakespearean plays. Yes, one or two are great, after a while, the overload can be distracting. As you select media, put it in a location where the student needs to pause to reflect on content or relate to it in a new way. You can also sequence the media so that it occurs when students may be starting to get bored or losing their focus. Media can help you refocus the students. Diagnostic and developmental/remedial content With Moodle you can design your course so that it builds in material to help students who may need more time, help, and practice on certain aspects of the lessons. For example, you can build in "Test Yourself!" diagnostic quizzes, which can help pinpoint where a student needs to focus more. This sounds a lot like the old pretest and posttest approach, but the difference is that it occurs within your lesson and students can stop along the way to get help. For example, an algebra course could include little "spot check" diagnostic quizzes. They could lead to a review section that is not required for the entire class, but for special needs. It's like having a private tutor. Reward practice The more the students practice, the more likely they are to feel good about their ability to perform, both in real-life applications as well as in their final assignments or tests. So, be sure to provide many opportunities for students to practice, and also for them to receive feedback, either automated or personalized from you or a peer. However, be careful that your quizzes and practice activities are similar in structure, content, and feel to their "high stakes" assignments. If they are not, the students will be discouraged. Also, be sure that the questions and the levels are the same as in the graded assignments. Don't make the final quiz too hard or too easy. Align content, levels of difficulty, time limitations, and testing conditions to those the students will experience later. Build confidence for final graded performance All the content and the activities in your lesson should build toward the students' final performance, whether a final essay, test, or presentation. By the time they reach the end of the lesson, the students should know what to expect and feel comfortable about what lies ahead. Furthermore, they should have a good idea of where to go when they feel lost or have questions. For example, they may be able to refer to a repository of supplemental readings or solved problems, or they can ask questions in the discussion board. At any rate, they always feel as though there is a supportive presence, either in the course itself or in access to the instructor and fellow students. Getting started: A simple example The following screenshot shows a very basic instructional lesson in Moodle. Note that it is essentially a website, and it contains text, links, and an embedded graphic. In fact, it is written in HTML. It is a brief lesson, and so does not have a large number of components. Essentially, the lesson is introducing a concept (the relationship between distance and perspective). It is engaging the student's curiosity by asking a question and then providing an illustrative graphic. The instruction involves testing the student's knowledge by using a "jump question". If you get it right, you proceed to the next item, and if you get it wrong, you're either taken back to the instructional page or jump to a remedial page. However, the jump question could just as easily ask a student what he/she is interested in learning next, or some other exploratory question. When the student clicks on the Continue button at the bottom of the lesson page, he/she is taken to a question page, as shown next: Each answer displays a different feedback. If the student answers correctly, he/she is taken to the next instructional page. An incorrect answer takes the student to a remedial page. This is the normal sequence for a lesson in Moodle. Later, we'll discuss how we can make the best use of the Lesson module.
Read more
  • 0
  • 0
  • 1486

Packt
20 Jan 2010
8 min read
Save for later

SOA Management—OSB (aka ALSB) Management

Packt
20 Jan 2010
8 min read
Introducing Oracle Service Bus (OSB) In any distributed system, components that run on a distributed platform need to communicate or exchange messages with each other. In SOA based systems, services need to interact or exchange messages with other services also. Oracle Service Bus is a product that provides a platform for interaction and message exchange between services. Integration of disparate services can be a challenge. There could be a difference in messaging models—some services may support the synchronous model, whereas other services may support the asynchronous model. Some services may support HTTP protocol, whereas other services may support JMS protocol. Oracle Service Bus provides helps in solving many of these challenges by providing the following features: Support for different protocols, such as HTTP(s), FTP, JMS, E-mail, Tuxedo, and so on Support for different messaging models, such as point-to-point model, publish-subscribe model Support for different message formats, such as SOAP, E-mail, JMS, XML, and so on Support for different content types such as XML, binary, and so on Data transformation using XLST and Xquery—data mapping from one format to another format through declarative constructs Besides the integration support, OSB provides features that help in managing runtime for the integration of services. Some features are: Load balancing: Load balancing is very important when traffic volume between services is very high. Load balancing also helps to achieve high availability. Content-based routing: Routing to appropriate service based on content is very valuable in the changing business environment. OSB provides loosely-coupled bus architecture, where all services and consumers of services can be plugged into, and OSB becomes a central place for defining mediation rules between services and consumers, as shown next: At implementation level, OSB is a set of J2EE applications that run on top of WebLogic J2EE container. It uses various J2EE constructs like Enterprise Java Bean, data source, connectors, and so on. OSB uses a database for storing the reporting data. OSB can be deployed in a single server model or clustered server model. Generally, in a production environment a clustered model is used, where multiple WebLogic Servers are used for load balancing and high-availability. In such setups, multiple WebLogic Servers are front-ended by a load balancer. The following figure depicts one such clustered deployment. OSB constructs There are some constructs specific to OSB—let's learn about those constructs. Proxy service OSB provides mediation between consumer and provider services. This mediation is loosely coupled where a consumer service makes a call to intermediate service, and the intermediate service performs some transformation and routes it to producer service. This intermediate service is hosted by OSB and called Proxy service. Business service Business service is a representation of actual producer service. Business service controls the call to business service, it knows about the business service endpoint. In case of failure in calling producer service, it can retry the operation. In case there are multiple producer services, it knows about the endpoint of each producer service and provides load balancing across those endpoints. Message flow Message flow is a set of steps that are executed by the proxy service before it routes to the business service. It includes steps for data transformation, validation, reporting, and so on. Supported versions Enterprise Manager provides OSB management from release 10.2.0.5 onwards. The following is the support matrix for EM against different versions of OSB management: EM Version OSB 2.6 OSB 2.6.1 OSB 3.0 OSB 10gR3 10.2.0.5 Yes Yes Yes Yes To manage or monitor OSB from Enterprise Manager 10.2.0.5, some patches are needed on OSB servers. The following table lists the patch number for each supported OSB release: OSB version Patch ID 2.6, 2.6.1 B8SZ 3.0 SWGQ 10gR3 7NPS The SmartUpdate patching tool that comes with WebLogic installation can be used to apply these patches. Before downloading or applying these patches, check Enterprise Manager documentation for any updates on patch Ids. Discovery of Oracle Service Bus Oracle Service Bus gets discovered as part of WebLogic domain, managed server discovery.We know how Enterprise Manager Agent discovers WebLogic domain and managed servers. Along with domain, cluster and managed server targets, OSB targets are also created and persisted in the Enterprise Manager repository. Just like WebLogic domain and server targets, OSB can also be discovered and monitored, either by remote agent or local agent. In case you want to use OSB service's provisioning feature you will need to discover/monitor OSB in the local agent mode. In the local agent mode, the agent is installed where the domain admin server is running. In the remote agent mode, the agent can be on any other host on the same network. After discovery you will see the Oracle Service Bus target on the Middleware tab of the EM homepage. The following screenshot shows the OSB target on the Middleware tab. Monitoring OSB and OSB services Under the BPEL monitoring section, we learnt about the BPEL eco system that included BPEL PM, dehydration store, database listener, host, and so on, and how Enterprise Manager provides support for modeling of BPEL eco system as system. Enterprise Manager provides similar support for managing and monitoring OSB eco system. Monitoring OSB For monitoring OSB, you can go to the OSB homepage, where you can see the status and availability of OSB. It shows some other details like the host, name of the WebLogic Server Domain where OSB is installed. It also shows some coarse-grained historical view of traffic metrics—where it shows message/error/security violation rates for all the services. On the Home page there is an option to create an infrastructure system and service. The steps for creating an infrastructure system service is exactly the same as BPEL, so we will not repeat those steps and will leave it as an exercise. The following screenshot shows one such homepage after the infrastructure system services are created. OSB uses Java Message Service (JMS) queues for receiving, scheduling, dispatching of messages, it's very important to monitor JMS queues for OSB. From the OSB homepage, click on JMS Performance, and you will see the performance of JMS queues used by OSB. The following screenshot shows one such page. You can see the metrics for message inflow and messages pending. Monitoring OSB services OSB service monitoring can be divided into two parts—proxy service that receives the requests and business service that dispatches the requests. Proxy service metrics also include the metrics in message flow, where message flow processes the request. Monitoring proxy services Performance of proxy services represents the performance seen by consumers of OSB. Besides that, proxy services are hosted by OSB servers. Enterprise Manager collects some very useful metrics for proxy services. These metrics are: Status of proxy service Throughput metrics at proxy service and endpoint level Performance metrics at proxy service level and endpoint level Error metrics at service level and end point level Security violation at proxy service level To monitor the performance of message flow, there are some fine-grained metrics available, these metrics include throughput, error rate, and performance at each step in the message flow. Let's go through the console screens for OSB service monitoring. Go to the OSB Services tab from OSB homepage, on that page you will see a listing of all the services that include proxy as well as business services. You will see every proxy and business services is part of some project. OSB provides a construct project under which different services can be created; project is just a means to categorize different services. The following screenshot shows such a page where you can see the list of all the projects and services. For each service you see metrics related to throughput, errors, violations, and performance. Once you click on one of the services, you will see a page where the metrics and other details of proxy service are listed. On this page, you can see the throughput and performance chart for the proxy service. You will also see a section for the EM service model that represents a proxy service. This model is similar to the model that we had for the BPEL process. This mode has three entities: Infrastructure service: This service represents all of the components in the OSB eco system. Availability service: This service represents all of the availability tests for an OSB proxy service endpoint, it could include SOAP tests, Web transactions etc. Aggregate service: This service is just an aggregate of the previous two services. Using this service, you can monitor all of the required metrics in one place. You can see the performance of your IT infrastructure as well as the performance of partner links in one place.
Read more
  • 0
  • 0
  • 2743

article-image-shipping-and-tax-calculations-php-5-ecommerce
Packt
20 Jan 2010
8 min read
Save for later

Shipping and Tax Calculations with PHP 5 Ecommerce

Packt
20 Jan 2010
8 min read
Shipping Shipping is a very important aspect of an e-commerce system; without it customers will not accurately know the cost of their order. The only situation where we wouldn't want to include shipping costs is where we always offer free shipping. However, in that situation, we could either add provisions to ignore shipping costs, or we could set all values to zero, and remove references to shipping costs from the user interface. Shipping methods The first requirement to calculate shipping costs is a shipping method. We may wish to offer a number of different shipping methods to our customers, such as standard shipping, next-day shipping, International shipping, and so on. The system will require a default shipping method, so when the customer visits their basket, they see shipping costs calculated based off the default method. There should be a suitable drop-down list on the basket page containing the list of shipping methods; when this is changed, the costs in the basket should be updated to reflect the selected method. We should store the following details for each shipping method: An ID number A name for the shipping method If the shipping method is active or not, indicating if it should be selectable by customers If the shipping method is the default method for the store A default shipping cost, this would: Be pre-populated in a suitable field when creating new products; however, when the product is created through the administration interface, we would store the shipping cost for the product with the product. Automatically be assigned to existing products in a store when a new shipping method is created to a store that already contains products. This could be suitably stored in our database as the following: Field Type Description ID Integer, Primary Key, Auto Increment ID number for the shipping method Name Varchar The name of the shipping method Active Boolean Indicates if the shipping method is active Default_cost Float The default cost for products for this shipping method This can be represented in the database using the following SQL: CREATE TABLE `shipping_methods` (`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`name` VARCHAR( 50 ) NOT NULL ,`active` BOOL NOT NULL ,`is_default` BOOL NOT NULL ,`default_cost` DOUBLE NOT NULL ,INDEX ( `active` , `is_default` )) ENGINE = INNODB COMMENT = 'Shipping methods'; Shipping costs There are several different ways to calculate the costs of shipping products to customers: We could associate a cost to each product for each shipping method we have in our store We could associate costs for each shipping method to ranges of weights, and either charge the customer based on the weight-based shipping cost for each product combined, or based on the combined weight of the order We could base the cost on the customer's delivery address The exact methods used, and the way they are used, depends on the exact nature of the store, as there are implications to these methods. If we were to use location-based shipping cost calculations, then the customer would not be aware of the total cost of their order until they entered their delivery address. There are a few ways this can be avoided: the system could assume a default delivery location and associated costs, and then update the customer's delivery cost at a later stage. Alternatively, if we enabled delivery methods for different locations or countries, we could associate the appropriate costs to these methods, although this does of course rely on the customer selecting the correct shipping method for their order to be approved; appropriate notifications to the customer would be required to ensure they do select the correct ones. For this article we will implement: Weight-based shipping costs: Here the cost of shipping is based on the weight of the products. Product-based shipping costs: Here the cost of shipping is set on a per product basis for each product in the customer's basket. We will also discuss location-based shipping costs, and look at how we may implement it. To account for international or long-distance shipping, we will use varying shipping methods; perhaps we could use: Shipping within state X. Shipping outside of state X. International shipping. (This could be broken down per continent if we wanted, without imposing on the customer too much.) Product-based shipping costs Product-based shipping costs would simply require each product to have a shipping cost associated to it for each shipping method in the store. As discussed earlier, when a new method is added to an existing store, a default value will initially be used, so in theory the administrator only needs to alter products whose shipping costs shouldn't be the default cost, and when creating new products, the relevant text box for the shipping cost for that method will have the default cost pre-populated. To facilitate these costs, we need a new table in our database storing: Product IDs Shipping method IDs Shipping costs The following SQL represents this table in our database: CREATE TABLE `shipping_costs_product` (`shipping_id` int(11) NOT NULL, `product_id` int(11) NOT NULL,`cost` float NOT NULL, PRIMARY KEY (`shipping_id`,`product_id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; Weight-based shipping costs Depending on the store being operated from our framework, we may need to base shipping costs on the weights of products. If a particular courier for a particular shipping method charges based on weights, then there isn't any point in creating costs for each product for that shipping method. Our framework can calculate the shipping costs based on the weight ranges and costs for the method, and the weight of the product. Within our database we would need to store: The shipping method in question A lower bound for the product weight, so we know which cost to apply to a product A cost associated for anything between this and the next weight bound The table below illustrates these fields in our database: Field Type Description ID Integer, primary key, Auto Increment A unique reference for the weight range Shipping_id Integer The shipping method the range applies to Lower_weight Float For working out which products this weight range cost applies to Cost Float The shipping cost for a product of this weight The following SQL represents this table: CREATE TABLE `shipping_costs_weight` (`ID` int(11) NOT NULL auto_increment,`shipping_id` int(11) NOT NULL,`lower_weight` float NOT NULL,`cost` float NOT NULL,PRIMARY KEY (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; To think about: Location-based shipping costs One thing we should still think about is location-based shipping costs, and how we may implement this. There are two primary ways in which we can do this: Assign shipping costs or cost surpluses/reductions to delivery addresses (either countries or states) and shipping methods Calculate costs using third-party service APIs These two methods have one issue, which is why we are not going to implement them—that is the costs are calculated later in the checkout process. We want our customers to be well informed and aware of all of their costs as early as possible. As mentioned earlier, however, we could get round this by assuming a default delivery location and providing customers with a guideline shipping cost, which would be subject to change based on their delivery address. Alternatively, we could allow customers to select their delivery location region from a drop-down list on the main "shopping basket" page. This way they would know the costs right away. Regional shipping costs We could look at storing: Shipping method IDs Region types (states or countries) Region values (an ID corresponding to a list of states or countries) A priority (in some cases, we may need to only consider the state delivery costs, and not country costs; in others cases, it may be the other way around) The associated costs changes (this could be a positive or negative value to be added to a product's delivery cost, as calculated by the other shipping systems already) By doing this, we can then combine the delivery address with the products and lookup a price alteration, which is applied to the product's delivery cost, which has already been calculated. Ideally, we would use all the shipping cost calculation systems discussed, to make something as flexible as possible, based on the needs of a particular product, particular shipping method or courier, or of a particular store or business. Third-party APIs The most accurate method of charging delivery costs, encompassing weights and delivery addresses is via APIs provided by couriers themselves, such as UPS. The following web pages may be of reference: http://www.ups.com/onlinetools http://answers.google.com/answers/threadview/id/429083.html Using such an API, means our shipping cost would be accurate, assuming our weight values were correct for our products, and we would not over or under charge customers for shipping costs. One additional consideration that third-party APIs may require would be dimensions of products, if their costs are also based on product sizes.
Read more
  • 0
  • 0
  • 16015

article-image-movable-type-5-introduction
Packt
18 Jan 2010
4 min read
Save for later

Movable Type 5: An Introduction

Packt
18 Jan 2010
4 min read
I’ve been a longtime user of MT, since version 3.2, and have followed its evolution closely from the inside out. When the beta-test and release-candidate versions of MT5 were released for public testing, I jumped on them and got my hands as dirty as I could, cloning my own MT4-driven site and testing it out in a separate MT5 instance (almost everything, plugins included, worked as-is). With each set of changes, I’ve also identified a couple of gotchas and potential problems that new users will want to keep an eye out for, and that any current MT user will want to be mindful of when they upgrade. Pages And Sites: Getting (Re)Organized The single biggest outward change to Movable Type is a reworking of how blogs are organized. Movable Type 4 introduced the ability to create and edit individual HTML pages in a folder hierarchy, each styled with the same templates used to create one’s blog. With MT5, this is paired with a new meta-organizational feature: the ability to create "websites" as an adjunct to one’s blog. A website contains a page hierarchy, but is kept as physically distinct as possible from a blog, so one site could contain a number of different blogs. This way, one could create a set of pages that changed very little—a corporate mission statement, an about-us page, personnel, etc.—and keep them entirely distinct, not just in the file hierarchy but in terms of permissions and editability. It’s another step towards making MT into a general content management system—or, at least, to add CMS-like features to the program to make it that much more powerful generally. One downside to this new behavior is that it throws first-timers and MT4 users for a bit of a loop. You can’t just create a blog—rather, you have to create a website (even if it’s just an empty one) and then create a blog under it. The blog and the website can share the same page hierarchy as long as nothing’s formally published in the website, or at least as long as no pages from one overwrite the other. Databases: MySQL All The Way Sometimes a new version of a product means features are dropped rather than added. Movable Type 5 is no exception, since it removes support for a number of database products. Oracle and Microsoft SQL Server are now only supported in the Enterprise edition of the product; some (SQLite and Postgres) have been relegated to plug-ins. Several things were behind this decision. First, MySQL has by and large been the database that people have used with Movable Type (and with blogging generally). It’s free, it’s been ported to most every platform of significance, and it’s already accumulated a large enough user base—both with Movable Type and other blogging programs—that consolidating on it as a standard would probably not inconvenience too many people. The second decision: convenience of support. It’s easier to support one commonly-used (and free) database system instead of several that are both free and commercial. If you’ve been using SQLite or PostgreSQL as your database, MovableType.org has some migration instructions for moving to MySQL. The short version: create a backup of your site/blog through MT itself, make a new installation of MT 5 on a MySQL instance, and restore the blog in MT. I’ve jumped through these exact hoops myself, so a word of caution. If you’re dealing with a really big blog (more than, say, 10MB) and you’re hosting the blog on a remote server, your best bet is to send the backup file to someone at the host and have them perform it for you locally. Part of the reason the MT full-system backup process is a bit clunky is because it is typically done through the progam’s web interface; it’s not something that can be done through a command line. (There is a third-party command-line backup solution for MT—but it’s been written for MT4, so there’s no guarantee it works with MT5, and it hasn’t been updated since 2008.)
Read more
  • 0
  • 1
  • 1889

article-image-showcasing-personnel-facultystaff-directory-using-plone-3
Packt
18 Jan 2010
6 min read
Save for later

Showcasing Personnel with Faculty/Staff Directory using Plone 3

Packt
18 Jan 2010
6 min read
(For more resources on Plone, see here.) Faculty/Staff Directory is practically a departmental web site in a box, but it doesn't stop there. The product is general enough to serve in non-academic settings as well. It is also not limited to people; it has been repurposed to such diverse applications as cataloguing tea leaves. It really is a general-purpose taxonomy engine—albeit with an academic bent in many of its naming choices. This article is an exploration of a product that will likely provide the framework for much of your site. We'll tour its features, get ideas on how they're commonly used in a school setting, and, finally, get a sneak peek into the future of the product. Install the product Faculty/Staff Directory depends on several other products: membrane, Relations, and archetypes.schemaextender. Thus, the easiest way to get it, as documented in its readme, is by adding Products.FacultyStaffDirectory to your buildout.cfg, like so: [buildout]eggs = ...(other eggs)... Products.FacultyStaffDirectory Then, shut down Zope, and run buildout. After starting up Zope again, install FacultyStaffDirectory in the Add-on Products control panel, and you're ready to go. Test drive Faculty/Staff Directory Faculty/Staff Directory (FSD) is tremendously flexible; you can use it as a simple list of phone numbers or as the foundation supporting the rest of your site. In this section, we take FSD for a spin, with ample pit stops along the way to discuss alternative design possibilities. Keep in mind that FSD's features are given to creative repurposing. We'll not only see their typical uses but some more inventive ones as well. Create a directory and choose global roles Faculty/Staff Directory centers around the idea of collecting people in a central folder called, fittingly, a faculty/staff directory. Our first step is to create that folder. Once you've installed FSD in the Add-on Products control panel, choose a place in your site where you would like to place a personnel directory, and add a faculty/staff directory there. You'll be prompted for two things: Title (which is usually something like People) and a selection of Roles. These roles, part of FSD's optional user-and-group integration, are granted site-wide to all people in the directory. Thus, as with the similarly scoped roles in the Users and Groups control panel, it's best to use them sparingly: choose only Member or, if you don't intend the people represented in your Directory to log in, no roles at all. Most roles should be assigned on a per-folder basis using the Sharing tab, and FSD provides facilities for that as well, as we discuss later in the Integrate users and groups section. Add people Now that you have a place to keep them, it's time to add actual personnel. FSD represents people through the aptly named Person type. A fully tricked-out person might look like this: People, without exception, live directly inside the faculty/staff directory—though they often appear to be elsewhere, as we will soon see. Each person can track the following information: Basic Information   Access Account ID Doubling as the object ID (or "short name") of the person, this field should contain the person's institution-wide login name. If you choose to take advantage of FSD's user-and-group integration, this is how logged-in users are matched with their Person objects. The name of this field and its validation requirements can be changed (and should be, in most deployments) in the Faculty/Staff Directory control panel under Site Setup. Name First, middle, and last names, as well as a suffix such as Ph. D or Jr. Image A picture of the person in GIF, JPEG, or PNG format, for use on their page and in some listings. It will be automatically scaled as necessary. Classifications Classifications are FSD's most prominent way to group people. This is a convenient place to assign one or more when creating a person. Departments Another way of grouping people. See Group People, below, for an in-depth comparison of all the various types of groupings. Password If the Person objects provide user passwords option in the FSD control panel is on, one can log into the Plone site using the Access Account ID as a username and the contents of this field as a password. Personal Assistant(s) Other people who should have access to edit this person's information (excluding password and the fields under User Settings). Contact Information   Email This email address is run through Plone's spam armoring, as yet not widely cracked, before being displayed to visitors. An alternative armoring method ("somebody AT here DOT edu") is available from the FSD control panel under Site Setup. Street Address City State Postal Code Phone The required format of the Office Phone field, along with its example text, can be set in the FSD control panel-a must for installations outside the United States and Canada. Professional Information   Job Titles As many job titles as you care to provide, one per line. These are all listed on the person's page. Biography A rich text field for the person's biographical information. Since this field can contain all the formatting you can muster-headings, images, and all-it is a wonderful thing to abuse. Fill it with lists of published journal articles, current projects, and anything else appropriate to show on the person's page. Education A plain text field where every line represents a conferred degree, certification, or such. Web Sites A list of URLs, one per line, to display on the person's page. There is no option to provide link text for these URLs, so you may wish to embed links in the Biography field instead. Committees Specialties The committees and specialties to which this person belongs. See the full discussion of FSD's various methods of grouping people under Group People, below. User Settings   Language Content Editor If you leave FSD's user-and-group integration enabled for the Person type, these duplications of the standard Plone options will apply. Integration can be disabled on a type-by-type basis in the FSD control panel under Site Setup. That's a lot of information, but you can fill out only what you'll use. Fields left blank will be omitted from directory pages, labels and all. For more thorough customization, you can write a Faculty/Staff Directory extender product to hide inapplicable fields from your content providers or to collect information that FSD doesn't ordinarily track. Here's how to add people to the directory: From within the directory, pull down the Add new… menu, and choose Person. Fill out some of the person's attributes. Be sure to assign at least one classification to each person, but don't worry about departments, specialties, or committees yet, as we're about to cover them in detail.
Read more
  • 0
  • 0
  • 3133
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 $19.99/month. Cancel anytime
article-image-navigating-pages-xaml-browser-applications
Packt
18 Jan 2010
4 min read
Save for later

Navigating Pages in XAML Browser Applications

Packt
18 Jan 2010
4 min read
Page navigation is an important part of application development and Windows Presentation Foundation supports navigation in two types of applications. These are the standalone application and the XAML browser application also known as XBAP applications. In addition to navigation between pages in the application it also supports navigation to other types of content such as HTML, objects and XAML files. Implementing a page Page class is one of the classes supported by WPF and you can use hyperlinks declaratively to go from page to page. You could also go from page to page programmatically using the NavigationService. In this article navigation using hyperlinks will be described. Page can be viewed as a package that consists of content which may be of many different kinds such as .NET framework objects, HTML, XAML, etc. Using the page class you can implement a Page which is a navigable object with XAML content. You implement a page declaratively by using the following markup: <Page /> Page is the root element of a Page which requires XAML namespace in its declaration as shown above. The Page can contain only one child element and you may simplify the snippet to just: <Page > <Page.Content> <!-- Page Content --> Hello, XAML</Page.Content></Page> Since a Page has the content you can access any content on the page by the dot notation Page.content as shown here above. Creating a Page in Visual Studio 2008 When you use Visual Studio 2008 you can create a WPF Browser application in C# as shown in the New Project window (opened with File | New Project...). When you create the project as above you will be creating a project which has a Page element as shown in the figure. Page1.xaml has both a preview window as well as XAML markup in a tabbed arrangement as shown here. Page1 is a named page object with a class [x:Class="Page1"]. You can review the content shown in the earlier snippet by taking out the extra namespace from the page shown here. The contents on a page can consist of other objects such as controls which can be used for various activities one of which is navigating from page to page. These controls can provoke events which can be implemented both as mark up and code that supports the page(also known as code behind). The page created by Visual Studio provides the necessary configuration to interact with the page as shown in Page1.xaml in the above figure and the code behind page shown in the figure below. The default page created by Visual Studio fulfils the three necessary criteria for a page with which you can interact by providing the following: x:Class="Page1" this markup attribute enables the MS Build engine to build a Page1 partial class which has the same name as the attribute of x:Class namely "Page1" This requires the inclusion of a namespace provided by the second namespace declaration The generated class should implement an InitializeComponent and the default page has this implemented as show above Configuring a Start Page When the application starts you need to specify that the browser should bring up a designated page. In order to support this the browser application requires an infrastructure to host the application and the WPF's Application class provides the necessary information in the form of an ApplicationDefinition file. In the XBAP application we have created you may review the information in the Application definition as shown here. You can specify the start up page as the application starts by specifying it in the Application definition as shown in the next figure. Without the StartupURI the page does not get displayed. The StartupURI can also be specified in a Startup event handler. Page appearance in the browser As the application starts up you may want to control how the page hosted in the window appears. You can set certain properties declaratively as shown where the WindowTitle, WindowWidth, WindowHeight, Title can all be set. The first three items are what you will see when the page gets displayed. For example consider the following xaml mark up: <Page x_Class="WPFSharp_Nav01.Page1" WindowWidth="500" WindowHeight="200" Title="Pagex" Background="Blue" WindowTitle="What is this?" > <TextBox Width="400" Height="25">Hello, XAML Browser App</TextBox></Page> The page gets displayed as shown when the application starts up. The WindowWidth is the outer width and the WindowHeight is the outer height of the browser window.
Read more
  • 0
  • 0
  • 3273

article-image-working-cxf-tool
Packt
18 Jan 2010
9 min read
Save for later

Working with CXF Tool

Packt
18 Jan 2010
9 min read
Invoking a web service using the Java client A web service exposes a set of operations over the network, typically via HTTP protocol. In order to invoke the web services, the web service client needs to know the following information: What operations are exposed by the web service The input and output message formats required to access the service operations What protocol, for instance HTTP or JMS, to use to invoke the web service The URL location of the web service All of the above information is contained in the standard XML descriptor called WSDL (Web Service Description Language). The WSDL file provides a format contract between the web service provider and the web service client. The web service client typically inspects the WSDL file to determine what operations are exposed by the web service, what parameters need to be supplied to invoke the web service operation and to formulate the request, and invokes the web service over the supported protocol. Similarly, the web service clients need to write the code to inspect the response and convert it into the required format. CXF hides the complexity of creating web service clients by providing the WSDL to Java command line tool, which takes a WSDL file and generates client code. The client code can be used by developers with no changes to invoke the web services. In this section, we will look at how to generate client code from an existing WSDL. For this example, we will take a real world scenario, where we will invoke a .NET service located over the Web using the Java client generated by the WSDL to Java tool. This shows the true power of web service interoperability, where applications implemented in different languages can communicate with each other. The process of generating web service clients does not differ for web services implemented in different languages, as you generate web service clients from WSDL and XML Schema definitions. Before invoking the .NET service, let's examine the WSDL to determine which operations are exposed by the web service. Analyzing the service WSDL definition We will invoke a publicly available .NET web service located at http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx?wsdl. This web service retrieves US Theaters and Movie Showtime information based on a valid US zip code and a radius supplied by the web service clients. The .NET web service is a WS-I compliant web service. The Web Services Interoperability Organization (WS-I), an open industry organization, was formed to promote web services interoperability across platforms, operating systems, and programming languages. One concrete product of WS-I is the Basic Profile. Basic Profile narrows the scope of specifications to a reasonable set of rules and guidelines that are best suited to help interoperability. If you type in the given URL in the browser, you see the WSDL definition, as shown in the following screenshot: Let's analyze the important sections of the WSDL file to get an understanding of which operations are exposed by the movie information web service and which message formats are required to invoke the web service. The web service provides two operations, GetTheatersAndMovies and GetUpcomingMovies, as shown in listing below. For this article, we will focus on how to invoke the GetTheatersAndMovies operation. The GetTheatersAndMovies takes the GetTheatersAndMoviesSoapIn message as the input and provides GetTheatersAndMoviesSoapOut as the output message. <wsdl:portType name="MovieInformationSoap"> <wsdl:operation name="GetTheatersAndMovies"> <wsdl:documentation >This method will retrieve a list of all theaters and the moviesplaying today.</wsdl:documentation> <wsdl:input message="tns:GetTheatersAndMoviesSoapIn" /> <wsdl:output message="tns:GetTheatersAndMoviesSoapOut" /> </wsdl:operation></wsdl:portType> The web service client invokes the GetTheatersAndMovies operation to get theater and movie information. The input to the GetTheatersAndMovies operation is the GetTheatersAndMoviesSoapIn XML message. The GetTheatersAndMoviesSoapIn message references the GetTheatersAndMovies element, which defines the actual XML schema definition for the input message. The following is the code listing of GetTheatersAndMovies schema definition: <s:element name="GetTheatersAndMovies"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="zipCode" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="radius" type="s:int" /> </s:sequence> </s:complexType></s:element> The GetTheatersAndMovies contains an element zipCode of type String and radius which is of type integer that needs to be passed as input by the web services client as an input to the GetTheatersAndMoviesSoapIn operation. The minOccurs and maxOccurs attribute associated with zipCode and radius is used to specify the minimum and maximum occurrence of the element inside a GetTheatersAndMovies element. The zipCode and radius element can appear only once inside a GetTheatersAndMovies element as it specifies the value of maxOccurs="1". If maxOccurs has the value Unbounded, then it implies that multiple occurrences of the element can exist. Similarly, the GetTheatersAndMoviesResponse specifies the output message format for the response. The following is the code listing of the GetTheatersAndMoviesResponse schema definition. We will break down the schema for better understanding: The GetTheatersAndMoviesResponse schemaThe following shows the definition of GetTheatersAndMoviesResponse. The GetTheatersAndMoviesResponse contains an element ArrayOfTheater. <s:element name="GetTheatersAndMoviesResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="GetTheatersAndMoviesResult" type= "tns:ArrayOfTheater" /> </s:sequence> </s:complexType></s:element> The ArrayOfTheater SchemaThe following shows the definition of ArrayOfTheater schema.The ArrayOfTheater is an array which consists of Theatre elements.The maxOccurs="unbounded" specifies that multiple occurrences of Theatre elements can exist in an ArrayOfTheater element. <s:complexType name="ArrayOfTheater"> <s:sequence> <s:element minOccurs="0" maxOccurs= "unbounded" name="Theater" nillable= "true" type="tns:Theater" /> </s:sequence></s:complexType> The Theater SchemaThe Theater elements consist of the Name and Address elements of type String, which specifies the name and address of the Theater and an array of ArrayOfMovie element. <s:complexType name="Theater"> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Address" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Movies" type="tns:ArrayOfMovie" /> </s:sequence></s:complexType> The ArrayOfMovie SchemaThe following is the ArrayOfMovie definition. The ArrayOfMovie is an array which consists of Movie elements. The maxOccurs="unbounded" specifies that multiple occurrences of Movie elements can exist in an ArrayOfMovie element. <s:complexType name="ArrayOfMovie"> <s:sequence> <s:element minOccurs="0" maxOccurs= "unbounded" name="Movie" nillable= "true" type="tns:Movie" /> </s:sequence></s:complexType> The Movie SchemaThe Movie element contains details of movies such as ratings, names of the movies, running times and show times represented as String type. <s:complexType name="Movie"> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Rating" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="RunningTime" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="ShowTimes" type="s:string" /> </s:sequence></s:complexType> Based on the Schema definitions above, the CXF WSDL2Java tool generates Java code that maps to these XML elements. The web service clients communicate with the web services using these generated Java objects to invoke a Java method representing the GetTheatersAndMoviesoperation and leave the SOAP XML to Java conversion and low level implementation details with the CXF framework. The SOAP address in the WSDL file specifies the location of the service, which is http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx, as shown in the listing below: <wsdl:service name="MovieInformation"> <wsdl:port name="MovieInformationSoap" binding= "tns:MovieInformationSoap"> <soap:address location="http://www.ignyte.com/webservices/ ignyte.whatsshowing.webservice/moviefunctions.asmx" /> </wsdl:port> <wsdl:port name="MovieInformationSoap12" binding= "tns:MovieInformationSoap12"> <soap12:address location="http://www.ignyte.com/webservices/ ignyte.whatsshowing.webservice/moviefunctions.asmx" /> </wsdl:port> </wsdl:service></wsdl:definitions> We will now look at how to generate the web service client code for the Movie information web service. Building and running the Java web service clients The source code and build files for the example are available in the wsdl2Java folder of the downloaded source code. We will follow the steps below to build and execute the web service client: Generate the web service clients Analyze the generated artifacts Modify the generated code Build the web service client Run the web service client Generate the web service clients We will use the Ant build script (build.xml) for generating the web service client code and building the project code as shown below. Navigate to the wsdl2java folder of the downloaded source code. Execute the cxfWSDLToJava target by navigating to the wsdl2java folder and running the following command: ant cxfWSDLToJava The following figure shows the output generated upon running the ant command: The cxfWSDLToJava ant target calls the CXF tool apache.cxf.tools.wsdlto.WSDLToJava to generate web service client code based on the URL http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx?wsdl The following is a code snippet of ant target cxfWSDLToJava in build.xml: <target name="cxfWSDLToJava"> <java classname="org.apache.cxf.tools.wsdlto.WSDLToJava" fork="true"> <arg value="-client"/> <arg value="-d"/> <arg value="src"/> <arg value="http://www.ignyte.com/webservices/ignyte. whatsshowing.webservice/moviefunctions.asmx?wsdl"/> <classpath> <path refid="cxf.classpath"/> </classpath> </java></target> WSDLToJava generates JAX-WS compliant Java code for the services defined in the WSDL document. Based on the parameters passed, it can generate the starting point of the code for developing the web service client and service. The client option, as shown in above snippet, generates the client code. The following is a list of augments and descriptions supported by the WSDLToJava tool extracted as it is from the CXF website—http://cwiki.apache.org/CXF20DOC/wsdl-to-java.html
Read more
  • 0
  • 0
  • 3678

article-image-selecting-dom-elements-using-mootools-12-part-1
Packt
07 Jan 2010
7 min read
Save for later

Selecting DOM Elements using MooTools 1.2: Part 1

Packt
07 Jan 2010
7 min read
In order to successfully and effortlessly write unobtrusive JavaScript, we must have a way to point to the Document Object Model (DOM) elements that we want to manipulate. The DOM is a representation of objects in our HTML and a way to access and manipulate them. In traditional JavaScript, this involves a lot (like, seriously a lot) of code authoring, and in many instances, a lot of head-banging-against-wall-and-pulling-out-hair as you discover a browser quirk that you must solve. Let me save you some bumps, bruises, and hair by showing you how to select DOM elements the MooTools way. This article will cover how you can utilize MooTools to select/match simple (like, "All div elements") up to the most complex and specific elements (like, "All links that are children of a span that has a class of awesomeLink and points to http://superAwesomeSite.com MooTools and CSS selectors MooTools selects an element (or a set of elements) in the DOM using CSS selectors syntax. Just a quick refresher on CSS terminology, a CSS style rule consists of: selector { property: property value; } selector: indicates what elements will be affected by the style rule. property: the CSS property (also referred to as attribute). For example, color is a CSS property, so is font-style. You can have multiple property declarations in one style rule property value: the value you want assigned to the property. For example, bold is a possible CSS property value of the font-weight CSS property. For example, if you wanted to select a paragraph element with an ID of awesomeParagraph to give it a red color (in hexadecimal, this is #ff0), in CSS syntax you'd write: #awesomeParagraph { color: #ff0; } Also, if I wanted to increase its specificity and make sure that only paragraph elements that have an ID of awesomeParagraph is selected: p#awesomeParagraph { color: #ff0;} You'll be happy to know that this same syntax ports over to MooTools. What's more is that you'll be able to take advantage of all of CSS3's more complex selection syntax because even though CSS3 isn't supported by all browsers yet, MooTools supports them already. So you don't have to learn another syntax for writing selectors, you can use your existing knowledge of CSS - awesome, isn't it? Working with the $() and $$() functions The $() and $$() functions are the bread and butter of MooTools. When you're working with unobtrusive JavaScript, you need to specify which elements you want to operate on. The dollar and dollars functions help you do just that - they will allow you to specify what elements you want to work on. Notice, the dollar sign $ is shaped like an S, which we can interpret to mean 'select'. The $() dollar function The dollar function is used for getting an element by it's ID, which returns a single element that is extended with MooTools Element methods or null if nothing matches. Let's go back to awesomeParagraph in the earlier example. If I wanted to select awesomeParagraph, this is what I would write: $('awesomeParagraph’) By doing so, we can now operate on it by passing methods to the selection. For example, if you wanted to change its style to have a color of red. You can use the .setStyle() method which allows you to specify a CSS property and its matching property value, like so $('awesomeParagraph').setStyle('color', '#ff0'); The $$() dollars function The $$() function is the $() big brother (that's why it gets an extra dollar sign). The $$() function can do more robust and complex selections, can select a group, or groups of element’s and always returns an array object, with or without selected elements in it. Likewise, it can be interchanged with the dollar function. If we wanted to select awesomeParagraph using the dollars function, we would write: $$('#awesomeParagraph') Note that you have to use the pound sign (#) in this case as if you were using CSS selectors. When to use which If you need to select just one element that has an ID, you should use the $() function because it performs better in terms of speed than the $$() function. Use the $$() function to select multiple elements. In fact, when in doubt, use the$$() function because it can do what the $() function can do (and more). A note on single quotes (') versus double quotes ("")The example above would work even if we used double quotes such as $("awesomeParagraph") or $$("#awesomeParagraph") ") - but many MooTools developers prefer single quotes so they don’t have to escape characters as much (since the double quote is often used in HTML, you'll have to do "in order not to prematurely end your strings). It's highly recommended that you use single quotes - but hey, it's your life! Now, let's see these functions in action. Let's start with the HTML markup first. Put the following block of code in an HTML document: <body> <ul id="superList"> <li>List item</li> <li><a href="#">List item link</a></li> <li id="listItem">List item with an ID.</li> <li class="lastItem">Last list item.</li> </ul></body> What we have here is an unordered list. We'll use it to explore the dollar and dollars function. If you view this in your web browser, you should see something like this: Time for action – selecting an element with the dollar function Let's select the list item with an ID of listItem and then give it a red color using the .setStyle() MooTools method. Inside your window.addEvent('domready') method, use the following code: $('listItem').setStyle('color', 'red'); Save the HTML document and view it on your web browser. You should see the 3rd list item will be red. Now let's select the entire unordered list (it has an ID of superList), then give it a black border (in hexadecimal, this is #000000). Place the following code, right below the code the line we wrote in step 1: $('superList').setStyle('border', '1px solid #000000'); If you didn't close your HTML document, hit your browser's refresh. You should now see something like this: Time for action – selecting elements with the dollars function We'll be using the same HTML document, but this time, let's explore the dollars function. We're going to select the last list item (it has a class of lastItem). Using the .getFirst(), we select the first element from the array $$() returned. Then, we're going to use the .get() method to get its text. To show us what it is, we'll pass it to the alert() function. The code to write to accomplish this is: alert( $$('.lastItem').getFirst().get('text') ); Save the HTML document and view it in your web browser (or just hit your browser's refresh button if you still have the HTML document from the preview Time for action open). You should now see the following: Time for action – selecting multiple sets of elements with the dollars function What if we wanted to select multiple sets of elements and run the same method (or methods) on them? Let's do that now. Let's select the list item that has an <a> element inside it and the last list item (class="lastItem") and then animate them to the right by transitioning their margin-left CSS property using the .tween() method. Right below the line we wrote previously, place the following line: $$('li a, .lastItem').tween('margin-left', '50px'); View your work in your web browser. You should see the second and last list item move to the right by 50 pixels. What just happened? We just explored the dollar and dollars function to see how to select different elements and apply methods on them. You just learned to select: An element with an ID (#listItem and #superList) using the dollar $() function An element with a class (.lastItem) using the dollars $$() function Multiple elements by separating them with commas (li and .lastItem) You also saw how you can execute methods on your selected elements. In the example, we used the .setStyle(), .getFirst(), get(), and .tween() MooTools methods. Because DOM selection is imperative to writing MooTools code, before we go any further, let's talk about some important points to note about what we just did.
Read more
  • 0
  • 0
  • 7823

article-image-selecting-dom-elements-using-mootools-12-part-2
Packt
07 Jan 2010
7 min read
Save for later

Selecting DOM Elements using MooTools 1.2: Part 2

Packt
07 Jan 2010
7 min read
Time for action – using pseudo-classes to zebra stripe a table Let's set up the markup for our HTML table - it'll have three columns and six rows listing my favorite movies in order. Pseudo-class example HTML table markup: <body><table width="100%" cellpadding="1" cellspacing="0"> <!-- column headings --> <tr> <th>Rank</th> <th>Movie</th> <th>Genre</th> </tr> <tr> <td>1</td> <td>The Matrix</td> <td>Action</td> </tr> <tr> <td>2</td> <td>Die Hard</td> <td>Action</td> </tr> <tr> <td>3</td> <td>The Dark Knight</td> <td>Action</td> </tr> <tr> <td>4</td> <td>Friday</td> <td>Comedy</td> </tr> <tr> <td>5</td> <td>Love Actually</td> <td>Drama</td> </tr></table></body> Our HTML table should look like this: To color even rows with a light gray color, write this line of code (again, we use the .setStyle() method): $$('table tr:even').setStyle( 'background-color', '#ebebeb' ); Save your work. View your document in a web browser. You should see something like this: Now we're going to style the odd rows. This time, instead of .setStyle(), we're going to use the .setStyles() method so that we can supply more than one CSS property/CSS property value pair to be implemented. Here's the code to accomplish what we set out to do (which you can place right below the code in step 1): $$('table tr:odd').setStyles( { 'background-color' : '#252525', 'color' : '#ffffff'} ); Save your work and view your work in a web browser. Your HTML table that contains my favorite movies of all time should now looks like this: What just happened? We just learned one of the many ways where pseudo-class selectors are helpful. In this case, we took a regular HTML table and zebra striped it so that we have different styles at alternating rows. To zebra stripe our HTML table, we used the :even and :odd pseudo-class selectors to change the background color of even row with a light gray color (#ebebeb in hexadecimal) and all odd rows of our tables with a dark gray background (#252525) with a white foreground color (#ffffff). A couple of notes on the :odd and :even pseudo-class selectorsThe :odd and :even pseudo-classes aren't available in W3C specifications; although the concept of using them is the same, they are custom MooTools pseudo-class selectors.Secondly, the index of each one starts at 0. Because of this, using :even would select the first element  (index 0) and third child elements because their index is actually 0 and 2, respectively. So they're kind of switched around in the conventional sense of odd and even. Other Pseudo-class selectors There are nine MooTools pseudo-class selectors as of version 1.2: Pseudo-class Selector Description :contains Matches elements that contain a particular text string. For example, matching all <div>'s with the text "I love MooTools" is $$('div:contains(I love MooTools)') :empty Matches elements that don't contain anything. For example, $$(div:empty) would match this: <div></div> :enabled Matches elements that are enabled. Usually used in <input> tags. :even Matches all child elements that have an even index. For example, if there are four paragraphs, using $$('p:even') would select the first and third paragraphs (remember that the index starts at 0). :first-child Matches the first child element (i.e. the child with an index of 0). For example, if there are four paragraphs in a <div> element, using $$('div p:first-child') would select the first paragraph inside the <div> element. :last-child Matches the last child element (i.e. the child with the highest index). For example, if there are four paragraphs in a <div> element, using $$('div p:last-child') will select the fourth paragraph inside the <div> element. :not Matches elements that do not match a particular selector. For example, matching all paragraphs that do not have the class .intro would be $$('p:not(.intro)'). :nth-child Matches the nth expression child element. You can use mathematical expressions. For example, $$('div:nth-child(3n+1)') would select the first div (3(0)+1 = index 0 position), 4th div (3(1)+1 = index 4 position)... 3(n)+1 index position. You can also use, as an argument: even, odd, first, and last as in div:nth-child(even) which is exactly like the :even pseudo-class selector. :odd Matches all child elements with an odd index. For example, If there are four paragraphs, using $$('p:odd') would select the second paragraph and fourth paragraph (index 1 position and index 3 position). :only-child Matches all elements that are the only children of  the only child element. For example, $$(p:only-child) would match the paragraph <div><p>only child></p></div> but will not match these paragraphs <div>><p>not an only child></p>><p>not only child></p></div> because it has a sibling paragraph. Working with attribute selectors If you thought MooTools can't get any cooler with element selection - well, it gets much better. MooTools also implements CSS3's Attribute Selectors. An Attribute Selector allows you to select elements based on their CSS attributes, also commonly referred to as properties in MooTools. For example, an <input> tag's type is considered one of its attributes (or properties), so is its class <input type=”text” name=”query” value=”” /> In MooTools (as well as CSS3), the syntax for an attribute selector is as follows: element[attribute=attribute value] For example, if we wanted to select all <input> elements with a type of text, we would write: $$('input[type=text]'); Attribute selector operators Attribute selectors can match attribute values various ways using Attribute selector operators. The following table depicts a list and description of each attribute selector operator. Operator Description = Matches attribute value exactly and literally. For example, $$('a[class=myLinkClass]') will match all <a> elements with the class of myLinkClass. != Matches all elements with the attribute value that is not the value given. For example, $$('a[class!=myLinkClass]') will select all <a> elements that doesn't have the class of myLinkClass. ^= Matches all elements with attribute value that starts with the value given. For example, $$('img[src^=big]') will match all images with the src attribute value the begins with the word big, such as big-picture.png or biggiesmalls.jpg. $= Matches all elements with the attribute value that ends with the value given. For example, $$('img[src$=.jpg]') will select all images that end with .jpg - useful in selecting particular file extensions. Attribute Selector example: styling different types of links Often, you want to indicate to a user what a particular type of link is. For example, you may want to indicate to the user that a particular link goes to another website or that a link is a mailto: link that will open up their default email client. Perhaps, you want to highlight all links that point to a particular domain name like sixrevisions.com.
Read more
  • 0
  • 0
  • 1596
article-image-working-events-mootools-part-1
Packt
07 Jan 2010
9 min read
Save for later

Working with Events in MooTools: Part 1

Packt
07 Jan 2010
9 min read
We have a lot of things to cover in this article, so hold on to your seats and enjoy the ride! What are Events, Exactly? Events are simply things that happen in our web pages. MooTools supports all HTML 4.01 event attributes like onclick and onmouseout, but the framework refers to them without the "on"  prefix (click instead of onclick, mouseout instead of onmouseout). What's neat about MooTools is that it not only extends HTML 4.01 event attributes with a few of its own, but also ensures that methods and functions that deal with web page events work across all web browsers by providing us with a solid, built-in object called Events. Event is part of the Native component of MooTools, and is also referred to as the Event hash. You can read the official W3C specifications on events, in the HTML 4.01 Specification, section 18.2.3, under Intrinsic Events:http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.3 We'll go over all of the available event attributes in MooTools so you can learn what stuff we can listen to. There are several events that we can detect or "listen to". We can, for the sake of discussion, divide them into five groups: window events, form events, keyboard events, mouse events, and MooTools custom events. Window Events Window events refer to activities that occur in the background. There are only two window events. HTML Event attribute / MooTools event name What is it? onload / load This event occurs when the window and images on the page has fully loaded and/or when all of the iFrames in the page have loaded. It can be used for monitoring when the web page has fully loaded (such as when you want to know if all images have been downloaded). onunload / unload This even happens when a window or an iFrame is removed from the web page. It has limited use. Form events There are events that occur within Form elements (such as <input> elements), and we'll refer to these as form events. For example, the onfocus  event is triggered when the user clicks on an input field (you'll see this in action in this article), effectively focusing on that particular input field. Some of these events apply event to non-form elements. HTML Event attribute / MooTools event name What is it? onblur / blur This event occurs when an element loses focus, either because the user has clicked out of it, or because the user used the Tab key to move away from it. This is helpful for monitoring the instant the user loses focus on a particular element. onchange / change This event happens when the element loses focus or when its original value has changed. This is helpful for knowing when the user starts typing in a input text field or textarea, or when a user selects a different option in a select drop-down element. onfocus / focus This event is the opposite, of the blur event: it is triggered when the user focuses on an element. This is useful for watching when the user highlights a form field or when they have navigated to it using the Tab key. onreset / reset This event only applies to form elements. This event is triggered when the form has been reset to its default values. onselect / select This event happens when the user highlights (selects) text in a text field. onsubmit / submit This event is only for form elements. This event occurs when the user submits a web form. Keyboard events There are events that happen when a user presses on a keyboard input device; let's call these keyboard events. For example, the onkeypress event is triggered when you press any key on your keyboard. HTML Event attribute / MooTools event name What is it? onkeydown / keydown This event occurs when the user holds down a keyboard key. onkeypress / keypress This event is triggered whenever the user presses a keyboard key. onkeyup /keyup This event happens when the user releases a key. Mouse events There are several HTML event properties that allow you to deal with activities related to the mouse. Clicking, moving, double-clicking, and hovering are all mouse events. HTML Event attribute / MooTools event name What is it? onclick / click This event occurs whenever the user uses the mouse button to click on an element. ondblclick / dblclick This even occurs whenever the user double-clicks on an element. onmousedown / mousedown This event occurs when the mouse button is held down. onmouseup / mouseup This even occurs when the mouse button is released. onmousemove / mousemove This event occurs when the mouse is moved. onmouseout / mouseout This event occurs when the mouse pointer is removed from the target element. onmouseover / mouseover This event occurs when the mouse pointer enters the target element. MooTools Custom Mouse Events MooTools supplies us with three custom events that extend the standard mouse events. MooTools event name What is it? mouseenter This event is triggered when the user's mouse pointer enters an element, but does not fire again when the mouse goes over a children element (unlike mouseover). This is useful for detecting the mouseover event once in nested element structures, such as <li><a>item</a></li>. If we were to use the mouseover event, it would be triggered twice, once for <li> and once again for <a>. mouseleave This event works similarly to mouseenter in that it is triggered only once when the mouse pointer exits the target element. Unlike the mouseout event, which will be triggered more than once for nested element structures. mousewheel This even is triggered when the scroller on a mouse is used (available in most modern mice input devices, usually situated in between the left and right mouse buttons). Adding Event Listeners We can attach event listeners to elements on a web page using the addEvent and addEvents method. By doing so, we're able to find out whenever that event happens, as well as execute a function to react to them. Adding event listeners is the basis for interactivity and is where JavaScript (and subsequently) MooTools has gained its popularity. Imagine being able to perform an operation whenever a user hovers over an image, or clicks on a link, or whenever the user submits a form -- the possibilities are endless. Adding a single event listener The addEvent method allows you to add one event listener to an element method and follows the format: $(yourelement).addEvent(event, function(){}) For example, in the following code block, we attach a click event listener for all <a> elements. When the user clicks on any hyperlink on our web page, it runs a function that opens up an alert dialog box that says You clicked on a hyperlink. $$('a').addEvent('click', function(){ alert('You clicked on a hyperlink');}); In a moment, we'll create a simple web form the highlights the input field that the user is focused on. Time for action – Highlighting focused fields of web forms Let's start with our web form's HTML. We'll use <input> and <textarea> tags that will hold our user's information as well as provide them a means to submit the web form (input type="button").We use the <label>  tag to indicate to the user what information to put inside each form field. <form action="" method="get"> <p><label for="Name">Name: </label> <input name="Name" type="text"></p> <p><label for="Email">Email: </label> <input name="Email" type="text"></p> <p><label for="Comment">Comment: </label> <textarea name="Comment" cols="" rows=""></textarea></p> <p><input name="Submit" type="button" value="Submit"></p></form> With the above markup, this is how our form looks like: Our web form is a bit dull, so how about we spruce it up a bit with some CSS? Read the comments to gain insight on some of the more important CSS properties to take a note off. /* Center the fields using text-align:center */form { width:300px; border:1px solid #b1b8c2; background-color:#e3e9f2; text-align:center; padding:25px 0;}label { display:block; font:12px normal Verdana, Geneva, sans-serif;}/* Give the input and textarea fields a 1px border */input, textarea { width:250px; border:1px solid #5c616a;}textarea { height:100px;}p { text-align:left; display:block; width:250px; overflow:auto; padding:0; margin:5px 0;}/* We will give fields that are currently focused on the .focus class which will give them a distinct thicker border and background color compared to the other input fields */.focused { border:3px solid #b1b8c2; background-color: #e8e3e3;} With just a few styles, our simple web form has transformed to a more attractive form field. Let us move onto the JavaScript. We use the addEvent method to add an event listener for the form event, onfocus. When the user focuses on a particular field, we run a function that adds the .focus CSS class on that field we declared as a style rule in step 2. We'll also remove .focus class on other fields on the web page. window.addEvent('domready', function(){ var els = $$('input, textarea') els.addEvent('focus', function(){ els.removeClass('focused'); this.addClass('focused'); })}); Now, when you focus on a form field, it will be highlighted with a thick blue border and with a lighter blue background. Users who use the Tab key to navigate in between form fields will appreciate this feature since they'll clearly see which field is active. What just happened? In the previous example, we created a simple and interactive web form that highlights the current field the user has active. We did this by using the addEvent method, adding an event listener for the focus form event. When the user focuses on a particular input field, we ran a function that adds the .focusCSS class which highlights the focused field <input> or <textarea>with a thick blue border with a light blue background. By highlighting active fields in a web form, we have just improved our form's usability by providing visual feedback about which field the user is currently on.
Read more
  • 0
  • 0
  • 2136

article-image-working-events-mootools-part-2
Packt
07 Jan 2010
10 min read
Save for later

Working with Events in MooTools: Part 2

Packt
07 Jan 2010
10 min read
Removing, Cloning, and Firing off Events Besides adding event listeners, other operations you may want to do are removing events from an element, cloning events from other elements, and firing off events for elements manually. We'll go through each one of these operations. Removing events from elements There are instances when you want to remove an event listener that you've added to an element. One reason would be that you only want to an element to be triggered once, and after that event has been triggered, you no longer want to trigger it again. To ensure it only fires once, you should remove the event once certain conditions have been met. Removing a single event from elements There are two methods available to you for removing events from elements. The first is removeEvent() which removes a single specified event. Time for action – removing an event Let's say you have some hyperlinks on a page, that when clicked, will alert the user that they have clicked a hyperlink, but you only wanted to do it once. To ensure that the warning message appears only once, we'll have to remove the event after it has been fired. This type of thing may be utilized for instructional tips: when the user sees an unfamiliar interface element, you can display a help tip for them, but only once - because you don't want the tip to keep showing up every single time they perform an action. First, let's put some links on a web page. <a href="#">Hyperlink 1</a> <a href="#">Hyperlink 2</a> Next, let's create a function object that we will call whenever a click event happens on any of the links on our page. When the function fires, it will open up an alert box with a message, and then it will remove the click event  from all <a> elements on the web page. // Create an function objectvar warning = function() { alert('You have clicked a link. This is your only warning'); // After warning has executed, remove it $$('a').removeEvent('click', warning);}; Now we add a click event listener that will fire off the warning function object. // Add a click event listener which when triggered, executes the //warning function$$('a').addEvent('click', warning); Our script should look like the following window.addEvent('domready', function(){ // Create an function object that will be executed when a //click happens var warning = function() { alert('You have clicked a link. This is your only warning'); // After warning has executed, remove it from all <a> //elements on the web page $$('a').removeEvent('click', warning); }; // Add a click event listener which when triggered, executes the //warning function $$('a').addEvent('click', warning);}); Test in your web browser by clicking on any of the hyperlinks on the page. The first time you click, you'll see an alert dialog box with our message. The second (or third, forth, fifth… you get the picture) time you click on any hyperlink, the alert dialog box will no longer show up. Removing a type of event, or all events, from elements If you want to remove a type of event on an element (or set of elements), or if you want to remove all events regardless of its type from an element, you have to use the removeEvents method. To remove a type of event from an element, you pass the type of event you want to remove as a parameter of the removeEvents method. For example, if you wanted to remove all click events that were added using MooTools addEvent method from an element called myElement, you would do the following: $('myElement').removeEvents('click'); If instead, you wanted to remove all events that myElement has regardless of the type of event it has, then you would simply run removeEvents as follows: $('myElement').removeEvents(); Cloning events from another element What if you wanted to copy all event listeners from another element. This could be useful in situations where you clone an element using the clone MooTools element method. Cloning an element doesn't copy the event listeners attached to it, so you also have to run the cloneEvents method on the element being cloned if you wanted to also port the event listeners to the copy. To clone the events of an element, follow the format: // clone the elementvar original = $(‘originalElement’);var myClone = original.clone();// clone the events from the originalmyClone.cloneEvents(original); Firing off Events Sometimes you want to fire off events manually. This is helpful in many situations, such as manually firing off an event listener functions that is triggered by another event. For example, to fire off a click event on myElement without having the user actually clicking on myElement, you would do the following: $('myElement').fireEvent('click'); Time for action – firing off a click event Imagine that you have a hyperlink with a click event listener attached to it, that when triggered, alerts the user with a message. But you also want to fire off this alert message when the user presses the Ctrl key. Here's how you'd do this: First, let us place a hyperlink in an HTML document. We'll put it inside a <p> element and tell the users that clicking on the hyperlink or pressing the Ctrl key will open up an alert dialog box. <body> <p>Show a warning by clicking on this link: <a href="#">Click me</a>. Alternatively, you can show the warning by pressing the <strong>Ctrl</strong> key on your keyboard.</p></body> Next, let's add an event to <a> elements. We'll use the addEvent method to do this. // Add a click event$$('a').addEvent('click', function(){ alert('You either clicked a link or pressed the Ctrl key.');}); Now we have to add another event listener onto our HTML document that watches out for a keydown event. The function that the event listener executes will check if the key pressed is the Ctrl key by using the control Event method which returns a Boolean value of true if the Ctrl key is pressed. If the key that was pressed is the Ctrl key, we ask it to fire the click event function that we set in all our a elements by using the fireEvent method with click as its parameter. // Add a keydown event on our web pagewindow.addEvent('keydown', function(e){// If the keypress is the Ctrl key // manually fire off the click event if(e.control) { $$('a').fireEvent('click'); }}); All together, our MooTools script should look like this: window.addEvent('domready', function(){ // Add a click event $$('a').addEvent('click', function(){ alert('You either clicked a link or pressed the Ctrl key.'); }); // Add a keydown event on our web page window.addEvent('keydown', function(e){ // If the keypress is the Ctrl key // manually fire off the click event if(e.control) { $$('a').fireEvent('click'); } });}); Test your HTML document in the web browser. Click on the “Click me” link. It should show you the alert message we created. Press the Ctrl key as well. It should also open up the same alert message we created. The MooTools Event Object The MooTools Event object, which is part of the Native component, is what allows us to create and work with events. It's therefore worth it to take a bit of time to explore the Events object. Using Event Object Methods There are three Event methods: preventDefault, stopPropagation, stop. Preventing the default behavior Events usually has a default behavior; that is, it has a predefined reaction in the instance that the event is triggered. For example, clicking on a hyperlink will direct you to the URL that href property is assigned to. Clicking on a submit input field will submit the form to the value that the action property of the form element is assigned to. Perhaps you want to open the page in a new window, but instead of using the non-standard target property on an <a> element, you can use JavaScript to open the page in a new window. Or maybe you need to validate a form before submitting it. You will want to prevent the default behaviors of an event doing either one of these things. You can use the preventDefault method to do so. Time for action – preventing the default behavior of a hyperlink Imagine that you have a list of hyperlinks that go to popular sites. The thing is, you don't want your website visitors to ever get to see them (at least coming from your site). You can prevent the default behavior of your hyperlinks using the preventDefault method. Here is the HTML markup for a list of <a> elements that go to popular websites. Place it inside an HTML document. <h1>A list of links you can't go to.</h1><ul> <li><a href="http://www.google.com/">Google</a></li> <li><a href="http://www.yahoo.com/">Yahoo!</a></li> <li><a href="http://digg.com/">Digg</a></li> </ul> We will warn the user with an alert dialog box that tells them they can't access the links, even when they click on it. We'll fire this alert dialog box when a user clicks on it. Notice the e argument in the function? That is the event object that is passed into the function, allowing us to access events' methods and properties. $$('a').addEvent('click', function(e){alert('Sorry you can't go there. At least not from this page.'); }); Open your HTML document in a web browser and verify that the links still open their destination, since we haven't prevented the default yet. You will, however, see the alert dialog box we set up in step 2, showing you that, indeed, the click event listener function fires off. Now we will prevent the links from opening by using the preventDefault method. We'll just add the following line above the alert(); line: e.preventDefault(); Test the document again in your web browser. Clicking on any hyperlink opens the alert dialog box, but doesn't open the hyperlink. Preventing event bubbling Event bubbling occurs when you have an element inside another element. When an event is triggered from the child element, the same event is triggered for the parent element, with the child element taking precedence by being triggered first. You can prevent event bubbling using the stopPropagation method. Let's explore the concept of event bubbling and how to prevent it from occurring (if you want to), using the stopPropagation event method.
Read more
  • 0
  • 0
  • 4045

article-image-developing-web-service-cxf
Packt
07 Jan 2010
9 min read
Save for later

Developing a Web Service with CXF

Packt
07 Jan 2010
9 min read
In this article we will basically study the sample Order Processing Application and discuss the following points: Developing a service Developing a client The Order Processing Application The objective of the Order Processing Application is to process a customer order. The order process functionality will generate the customer order, thereby making the order valid and approved. A typical scenario will be a customer making an order request to buy a particular item. The purchase department will receive the order request from the customer and prepare a formal purchase order. The purchase order will hold the details of the customer, the name of the item to be purchased, the quantity, and the price. Once the order is prepared, it will be sent to the Order Processing department for the necessary approval. If the order is valid and approved, then the department will generate the unique order ID and send it back to the Purchase department. The Purchase department will communicate the order ID back to the customer. For simplicity, we will look at the following use cases: Prepare an order Process the order The client application will prepare an order and send it to the server application through a business method call. The server application will contain a web service that will process the order and generate a unique order ID. The generation of the unique order ID will signify order approval. In real world applications a unique order ID is always accompanied by the date the order was approved. However, in this example we chose to keep it simple by only generating order ID. Developing a service Let's look specifically at how to create an Order Processing Web Service and then register it as a Spring bean using a JAX-WS frontend. The Sun-based JAX-WS specification can be found at the following URL: http://jcp.org/aboutJava/communityprocess/final/jsr224/index.html JAX-WS frontend offers two ways of developing a web service—Code-first and Contract-first. We will use the Code-first approach, that is, we will first create a Java class and convert this into a web service component. The first set of tasks will be to create server-side components. In web service terminology, Code-first is termed as the Bottoms Up approach, and Contract-first is referred to as the Top Down approach. To achieve this, we typically perform the following steps: Create a Service Endpoint Interface (SEI) and define a business method to be used with the web service. Create the implementation class and annotate it as a web service. Create beans.xml and define the service class as a Spring bean using a JAX-WS frontend. Creating a Service Endpoint Interface (SEI) Let's first create the SEI for our Order Processing Application. We will name our SEI OrderProcess. The following code illustrates the OrderProcess SEI: package demo.order; import javax.jws.WebService; @WebService public interface OrderProcess { @WebMethod String processOrder(Order order); } As you can see from the preceding code, we created a Service Endpoint Interface named OrderProcess. The SEI is just like any other Java interface. It defines an abstract business method processOrder. The method takes an Order bean as a parameter and returns an order ID String value. The goal of the processOrder method is to process the order placed by the customer and return the unique order ID. One significant thing to observe is the @WebService annotation. The annotation is placed right above the interface definition. It signifies that this interface is not an ordinary interface but a web service interface. This interface is known as Service Endpoint Interface and will have a business method exposed as a service method to be invoked by the client. The @WebService annotation is part of the JAX-WS annotation library. JAX-WS provides a library of annotations to turn Plain Old Java classes into web services and specifies detailed mapping from a service defined in WSDL to the Java classes that will implement that service. The javax.jws.WebService annotation also comes with attributes that completely define a web service. For the moment we will ignore these attributes and proceed with our development. The javax.jws.@WebMethod annotation is optional and is used for customizing the web service operation. The @WebMethod annotation provides the operation name and the action elements which are used to customize the name attribute of the operation and the SOAP action element in the WSDL document. The following code shows the Order class: package demo.order;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "Order")public class Order { private String customerID; private String itemID; private int qty; private double price; // Contructor public Order() { } public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public String getItemID() { return itemID; } public void setItemID(String itemID) { this.itemID = itemID; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }} As you can see, we have added an @XmlRootElement annotation to the Order class. The @XmlRootElement is part of the Java Architecture for XML Binding (JAXB) annotation library. JAXB provides data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without having the developers know about XML and SOAP parsing. CXF uses JAXB as the default data binding component. The @XmlRootElement annotations associated with Order class map the Order class to the XML root element. The attributes contained within the Order object by default are mapped to @XmlElement. The @XmlElement annotations are used to define elements within the XML. The @XmlRootElement and @XmlElement annotations allow you to customize the namespace and name of the XML element. If no customizations are provided, then the JAXB runtime by default would use the same name of attribute for the XML element. CXF handles this mapping of Java objects to XML. Developing a service implementation class We will now develop the implementation class that will realize our OrderProcess SEI. We will name this implementation class OrderProcessImpl. The following code illustrates the service implementation class OrderProcessImpl: @WebServicepublic class OrderProcessImpl implements OrderProcess { public String processOrder(Order order) { String orderID = validate(order); return orderID; }/** * Validates the order and returns the order ID**/ private String validate(Order order) { String custID = order.getCustomerID(); String itemID = order.getItemID(); int qty = order.getQty(); double price = order.getPrice(); if (custID != null && itemID != null && !custID.equals("") && !itemID.equals("") && qty > 0 && price > 0.0) { return "ORD1234"; } return null; }} As we can see from the preceding code, our implementation class OrderProcessImpl is pretty straightforward. It also has @WebService annotation defined above the class declaration. The class OrderProcessImpl implements OrderProcess SEI. The class implements the processOrder method. The processOrder method checks for the validity of the order by invoking the validate method. The validate method checks whether the Order bean has all the relevant properties valid and not null. It is recommended that developers explicitly implement OrderProcess SEI, though it may not be necessary. This can minimize coding errors by ensuring that the methods are implemented as defined. Next we will look at how to publish the OrderProcess JAX-WS web service using Spring configuration.   Spring-based server bean What makes CXF the obvious choice as a web service framework is its use of Spring-based configuration files to publish web service endpoints. It is the use of such configuration files that makes the development of web service convenient and easy with CXF. Spring provides a lightweight container which works on the concept of Inversion of Control (IoC) or Dependency Injection (DI) architecture; it does so through the implementation of a configuration file that defines Java beans and its dependencies. By using Spring you can abstract and wire all the class dependencies in a single configuration file. The configuration file is often referred to as an Application Context or Bean Context file. We will create a server side Spring-based configuration file and name it as beans.xml. The following code illustrates the beans.xml configuration file: <beans xsi_schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension- soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <jaxws:endpoint id="orderProcess" implementor="demo.order.OrderProcessImpl" address="/OrderProcess" /></beans> Let's examine the previous code and understand what it really means. It first defines the necessary namespaces. It then defines a series of <import> statements. It imports cxf.xml, cxf-extension-soap.xml, and cxf-servlet.xml. These files are Springbased configuration files that define core components of CXF. They are used to kick start CXF runtime and load the necessary infrastructure objects such as WSDL manager, conduit manager, destination factory manager, and so on. The <jaxws:endpoint> element in the beans.xml file specifies the OrderProcess web service as a JAX-WS  endpoint. The element is defined with the following three attributes: id—specifies a unique identifier for a bean. In this case, jaxws:endpoint is a bean, and the id name is orderProcess. implementor— specifies the actual web service implementation class. In this case, our implementor class is OrderProcessImpl. address— specifies the URL address where the endpoint is to be published. The URL address must to be relative to the web context. For our example, the endpoint will be published using the relative path /OrderProcess. The <jaxws:endpoint> element signifies that the CXF internally uses JAX-WS frontend to publish the web service. This element definition provides a short and convenient way to publish a web service. A developer need not have to write any Java class to publish a web service.
Read more
  • 0
  • 0
  • 3329
article-image-cxf-architecture
Packt
07 Jan 2010
8 min read
Save for later

CXF architecture

Packt
07 Jan 2010
8 min read
The following figure shows the overall architecture: Bus Bus is the backbone of the CXF architecture. The CXF bus is comprised of a Spring-based configuration file, namely, cxf.xml which is loaded upon servlet initialization through SpringBusFactory. It defines a common context for all the endpoints. It wires all the runtime infrastructure components and provides a common application context. The SpringBusFactory scans and loads the relevant configuration files in the META-INF/cxf directory placed in the classpath and accordingly builds the application context. It builds the application context from the following files: META-INF/cxf/cxf.xml META-INF/cxf/cxf-extension.xml META-INF/cxf/cxf-property-editors.xml The XML file is part of the installation bundle's core CXF library JAR. Now, we know that CXF internally uses Spring for its configuration. The following XML fragment shows the bus definition in the cxf.xml file. <bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl" /> The core bus component is CXFBusImpl . The class acts more as an interceptor provider for incoming and outgoing requests to a web service endpoint. These interceptors, once defined, are available to all the endpoints in that context. The cxf.xml file also defines other infrastructure components such as BindingFactoryManager, ConduitFactoryManager, and so on. These components are made available as bus extensions. One can access these infrastructure objects using the getExtension method. These infrastructure components are registered so as to get and update various service endpoint level parameters such as service binding, transport protocol, conduits, and so on. CXF bus architecture can be overridden, but one must apply caution when overriding the default bus behavior. Since the bus is the core component that loads the CXF runtime, many shared objects are also loaded as part of this runtime. You want to make sure that these objects are loaded when overriding the existing bus implementation. You can extend the default bus to include your own custom components or service objects such as factory managers. You can also add interceptors to the bus bean. These interceptors defined at the bus level are available to all the endpoints. The following code shows how to create a custom bus: SpringBeanFactory.createBus("mycxf.xml") SpringBeanFactory class is used to create a bus. You can complement or overwrite the bean definitions that the original cxf.xml file would use. For the CXF to load the mycxf.xml file, it has to be in the classpath or you can use a factory method to load the file. The following code illustrates the use of interceptors at the bus level: <bean id="cxf" class="org.apache.cxf.bus.spring.SpringBusImpl"> <property name="outInterceptors"> <list> <ref bean="myLoggingInterceptor"/> </list> </property></bean><bean id="myLogHandler" class="org.mycompany.com.cxf.logging. LoggingInterceptor"> ...</bean> The preceding bus definition adds the logging interceptor that will perform logging for all outgoing messages. Frontend CXF provides the concept of frontend modeling, which lets you create web services using different frontend APIs. The APIs let you create a web service using simple factory beans and JAX-WS implementation. It also lets you create dynamic web service clients. The primary frontend supported by CXF is JAX-WS. JAX-WS JAX-WS is a specification that establishes the semantics to develop, publish, and consume web services. JAX-WS simplifies web service development. It defines Java-based APIs that ease the development and deployment of web services. The specification supports WS-Basic Profile 1.1 that addresses web service interoperability. It effectively means a web service can be invoked or consumed by a client written in any language. JAX-WS also defines standards such as JAXB and SAAJ. CXF provides support for complete JAX-WS stack. JAXB provides data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without the developers seeing XML and SOAP parsing. JAXB specification defines the binding between Java and XML Schema. SAAJ provides a standard way of dealing with XML attachments contained in a SOAP message. JAX-WS also speeds up web service development by providing a library of annotations to turn Plain Old Java classes into web services and specifies a detailed mapping from a service defined in WSDL to the Java classes that will implement that service. Any complex types defined in WSDL are mapped into Java classes following the mapping defined by the JAXB specification. As discussed earlier, two approaches for web service development exist: Code-First and Contract-First. With JAX-WS, you can perform web service development using one of the said approaches, depending on the nature of the application. With the Code-first approach, you start by developing a Java class and interface and annotating the same as a web service. The approach is particularly useful where Java implementations are already available and you need to expose implementations as services. You typically create a Service Endpoint Interface (SEI) that defines the service methods and the implementation class that implements the SEI methods. The consumer of a web service uses SEI to invoke the service functions. The SEI directly corresponds to a wsdl:portType element. The methods defined by SEI correspond to the wsdl:operation element. @WebServicepublic interface OrderProcess { String processOrder(Order order);} JAX-WS makes use of annotations to convert an SEI or a Java class to a web service. In the above example, the @WebService annotation defined above the interface declaration signifies an interface as a web service interface or Service Endpoint Interface. In the Contract-first approach, you start with the existing WSDL contract, and generate Java class to implement the service. The advantage is that you are sure about what to expose as a service since you define the appropriate WSDL Contract-first. Again the contract definitions can be made consistent with respect to data types so that it can be easily converted in Java objects without any portability issue. WSDL contains different elements that can be directly mapped to a Java class that implements the service. For example, the wsdl:portType element is directly mapped to SEI, type elements are mapped to Java class types through the use of Java Architecture of XML Binding (JAXB), and the wsdl:service element is mapped to a Java class that is used by a consumer to access the web service. The WSDL2Java tool can be used to generate a web service from WSDL. It has various options to generate SEI and the implementation web service class. As a developer, you need to provide the method implementation for the generated class. If the WSDL includes custom XML Schema types, then the same is converted into its equivalent Java class. Simple frontend Apart from JAX-WS frontend, CXF also supports what is known as 'simple frontend'. The simple frontend provides simple components or Java classes that use reflection to build and publish web services. It is simple because we do not use any annotation to create web services. In JAX-WS, we have to annotate a Java class to denote it as a web service and use tools to convert between a Java object and WSDL. The simple frontend uses factory components to create a service and the client. It does so by using Java reflection API. The following code shows a web service created using simple frontend: // Build and publish the serviceOrderProcessImpl orderProcessImpl = new OrderProcessImpl();ServerFactoryBean svrFactory = new ServerFactoryBean();svrFactory.setServiceClass(OrderProcess.class);svrFactory.setAddress("http://localhost:8080/OrderProcess");svrFactory.setServiceBean(orderProcessImpl);svrFactory.create(); Messaging and Interceptors One of the important elements of CXF architecture is the Interceptor components. Interceptors are components that intercept the messages exchanged or passed between web service clients and server components. In CXF, this is implemented through the concept of Interceptor chains. The concept of Interceptor chaining is the core functionality of CXF runtime. The interceptors act on the messages which are sent and received from the web service and are processed in chains. Each interceptor in a chain is configurable, and the user has the ability to control its execution. The core of the framework is the Interceptor interface. It defines two abstract methods—handleMessage and handleFault. Each of the methods takes the object of type Message as a parameter. A developer implements the handleMessage to process or act upon the message. The handleFault method is implemented to handle the error condition. Interceptors are usually processed in chains with every interceptor in the chain performing some processing on the message in sequence, and the chain moves forward. Whenever an error condition arises, a handleFault method is invoked on each interceptor, and the chain unwinds or moves backwards. Interceptors are often organized or grouped into phases. Interceptors providing common functionality can be grouped into one phase. Each phase performs specific message processing. Each phase is then added to the interceptor chain. The chain, therefore, is a list of ordered interceptor phases. The chain can be created for both inbound and outbound messages. A typical web service endpoint will have three interceptor chains: Inbound messages chain Outbound messages chain Error messages chain There are built-in interceptors such as logging, security, and so on, and the developers can also choose to create custom interceptors.
Read more
  • 0
  • 0
  • 3166

article-image-enhancing-your-math-teaching-using-moodle-19-part-1
Packt
06 Jan 2010
6 min read
Save for later

Enhancing Your Math Teaching using Moodle 1.9: Part 1

Packt
06 Jan 2010
6 min read
There are many topics to explore in this article, so let's make a start with mathematical PowerPoint presentations. PowerPoint and Mathematics We have already seen how we can use the Microsoft Equation Editor to include mathematics notation in Microsoft Word documents (we copied them from the document into our Moodle course). Microsoft PowerPoint also includes the Equation Editor, and we can use this facility to create some quite elegant online explanations of difficult mathematical ideas. Here is a quick recap (using Microsoft PowerPoint instead of Microsoft Word): Click the slide to which you want to add an equation. On the Insert menu, click Object. In the Object type list, click Microsoft Equation 3.0 (if Microsoft Equation 3.0 is not listed, then you will need to install it. See http://support.microsoft.com/kb/228569). In the Equation Editor, use the buttons and menus to type your equation. To return to Microsoft PowerPoint, on the File menu in Equation Editor, click Exit. The equation will now be included on your slide. Add a special Equation Editor button to any Microsoft Office application toolbar. For example in Office 2003, in the View menu, point to Toolbars, and then click Customize. Click the Commands tab, and in the Categories list, click Insert. In the Commands box, click Equation Editor, and then drag it from the Commands box to a gray area within any toolbar. Then click Close. Click on the new toolbar button to install and display the Equation Editor. Quickly crafting a Pythagorean PowerPoint I'm guessing you're going to be fairly familiar with PowerPoint, so let's make a start by creating a basic presentation, showing our students how they can transpose/rearrange an equation. I'm going to be showing my students how they can find the missing length in a right-angled triangle. Note that I'm an Office 2003 user running Windows Vista. If you aren't using the same version of Office or the same operating system as me, then as you follow my examples your screen might look different from mine: The first step is to create a new presentation. For the first page of this presentation, I've added a new slide and used the Title, Text, and Content layout: I've searched for a Creative Commons image of a ladder on Flickr and drawn a schematic using Microsoft PowerPoint's built-in drawing tools. Here is the completed slide: In the next slides, let's demonstrate how we can turn the ladder problem into a Pythagorean Theorem/algebra problem (without being too scary about the algebra). Let's animate the slide to allow the students to recall the theorem: Now, allow the students to check if they got it right. Right-click on an object and select Custom Animation… to make the presentation a little more interactive: Now I've recalled the Pythagorean Theorem, which I need to relate back to the ladder problem. Again, I've used animations to make the slide interactive: I'm going to complete the presentation by giving my students a little guidance on algebraic transposition and then that's it—I'm done! I hope you'll agree that with some simple custom animations we've made this PowerPoint far more engaging and entertaining than it would otherwise be. Want to avoid creating a truly boring PowerPoint presentation? Navigate your browser to http://www.youtube.com and search for Don McMillan's video on how NOT to use PowerPoint! Uploading to Moodle I could simply upload the PowerPoint as is to my course files area, but I'm a bit worried that without my describing what's going on in the presentation, it isn't going to make a lot of sense to my students. To overcome this problem, I'm going to record an audio commentary. You can insert sound directly into your slides either from the main menu (Insert) or via the Insert tab in Microsoft PowerPoint 2007's ribbon. Providing an audio commentary The presentation I crafted in the previous section is fine on its own, and I do use something similar as part of my face-to-face teaching. But I want my students to be able to study this example in their own time and, to that end, I would like to enhance it with an audio commentary. There are three basic ways I can achieve this (aside from inserting audio into each slide). Each has its own advantages and disadvantages: Record a separate audio track and allow the students to listen to the audio following the presentation at their own pace—almost like a read-along story Upload the presentation to SlideShare and use SlideShare's built-in audio recording tools to narrate the PowerPoint Record a screencast. Either upload it directly to our Moodle course or to a content sharing website (that is, YouTube or TeacherTube) In the following sections we'll investigate each option in turn. Recording a separate narration—using Audacity to narrate a slideshow A great way to record a narration is by using Audacity. Audacity is an extremely popular, free recording and audio editing tool. Download the latest version from http://audacity.sourceforge.net/download/. Once you have Audacity installed, it is very easy to use. Let's record a narration: The first task, before we begin recording, is to write a script. There's nothing worse than listening to a badly prepared or rambling presentation, so let's make sure it's tightly scripted: When you are ready to begin recording your commentary, press Audacity's "record" button: When you are finished recording, press the "stop" button. Don't worry about making mistakes or there being pregnant pauses because we can easily edit these out in the next step. When you have finished, the recording is displayed: Audacity is loaded with many great audio editing features, so by way of an example, I'm going to pick just one: Fade Out. Use the selection tool to select the final segment of your recording: From the main menu, select Effect | Fade Out. Try experimenting with some of the other audio options that are available: When you are happy with your recording, you'll need to save it. From the main menu, select File | Export as MP3…. Choose a suitable filename and location and click on the Save button. Complete the ID3 Tag dialog: Hit the OK button and Audacity creates your new MP3 file. That's it. We're done! Recording a narration—recap When my PowerPoint is included in my Moodle course, it will be viewed by students who won't have the benefit (or curse) of my commentary when I am giving my face-to-face teaching. It would be great if we could also include an audio commentary so that students can follow the presentation in their own time, at their own pace. To that end we've just used the free audio recording and editing tool, Audacity, to create an audio commentary for our PowerPoint presentation.
Read more
  • 0
  • 0
  • 2259
Modal Close icon
Modal Close icon