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

How-To Tutorials

7018 Articles
article-image-facelets-components-jsf-12
Packt
30 Nov 2009
12 min read
Save for later

Facelets Components in JSF 1.2

Packt
30 Nov 2009
12 min read
One of the more advanced features of the Facelets framework is the ability to define complex templates containing dynamic nested content. What is a template?The Merriam-Webster dictionary defines the word "template" as "a gauge, pattern, or mold (as a thin plate or board) used as a guide to the form of a piece being made" and as "something that establishes or serves as a pattern." In the context of user interface design for the Web, a template can be thought of as an abstraction of a set of pages in the web application.A template does not define content, but rather it defines placeholders for content, and provides the layout, orientation, flow, structure, and logical organization of the elements on the page. We can also think of templates as documents with "blanks" that will be filled in with real data and user interface controls at request time. One of the benefits of templating is the separation of content from presentation, making the maintenance of the views in our web application much easier. The <ui:insert> tag has a name attribute that is used to specify a dynamic content region that will be inserted by the template client. When Facelets renders a UI composition template, it attempts to substitute any <ui:insert> tags in the Facelets template document with corresponding <ui:define> tags from the Facelets template client document. Conceptually, the Facelets composition template transformation process can be visualized as follows: In this scenario, the browser requests a Facelets template client document in our JSF application. This document contains two <ui:define> tags that specify named content elements and references a Facelets template document using the <ui:composition> tag's template attribute. The Facelets template document contains two <ui:insert> tags that have the same names as the <ui:define> tags in the client document, and three <ui:include> tags for the header, footer, and navigation menu. This is a good example of the excellent support that Facelets provides for the Composite View design pattern. Facelets transforms the template client document by merging any content it defines using <ui:define> tags with the content insertion points specified in the Facelets template document using the <ui:insert> tag. The result of merging the Facelets template client document with the Facelets template document is rendered in the browser as a composite view. While this concept may seem a bit complicated at first, it is actually a powerful feature of the Facelets view defi nition framework that can greatly simplify user interface templating in a web application. In fact, the Facelets composition template document can itself be a template client by referencing another composition template. In this way, a complex hierarchy of templates can be used to construct a flexible, multi-layered presentation tier for a JSF application. Without the Facelets templating system, we would have to copy and paste view elements such as headers, footers, and menus from one page to the next to achieve a consistent look and feel across our web application. Facelets templating enables us to define our look and feel in one document and to reuse it across multiple pages. Therefore, if we decide to change the look and feel, we only have to update one document and the change is immediately propagated to all the views of the JSF application. Let's look at some examples of how to use the Facelets templating feature. A simple Facelets template The following is an example of a simple Facelets template. It simply renders a message within an HTML <h2> element. Facelets will replace the "unnamed" <ui:insert> tag (without the name attribute) in the template document with the content of the <ui:composition> tag from the template client document. template01.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Facelets template example</title><link rel="stylesheet" type="text/css" href="/css/style.css" /></head><body><h2><ui:insert /></h2></body></html> A simple Facelets template client Let's look at a simple example of Facelets templating. The following page is a Facelets template client document. (Remember: you can identify a Facelets template client by looking for the existence of the template attribute on the <ui:composition> tag.) The <ui:composition> tag simply contains the text Hello World. templateClient01.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ui:composition example</title></head><body><ui:composition template="/WEB-INF/templates/template01.jsf">Hello World</ui:composition><ui:debug /></body></html> The following screenshot displays the result of the Facelets UI composition template transformation when the browser requests templateClient01.jsf. Another simple Facelets template client The following Facelets template client example demonstrates how a template can be reused across multiple pages in the JSF application: templateClient01a.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ui:composition example</title></head><body><ui:composition template="/WEB-INF/templates/template01.jsf">How are you today?</ui:composition><ui:debug /></body></html> The following screenshot displays the result of the Facelets UI composition template transformation when the browser requests templateClient01a.jsf: A more complex Facelets template The Facelets template in the previous example is quite simple and does not demonstrate some of the more advanced capabilities of Facelets templating. In particular, the template in the previous example only has a single <ui:insert> tag, with no name attribute specified. The behavior of the unnamed <ui:insert> tag is to include any content in the referencing template client page. In more complex templates, multiple <ui:insert> tags can be used to enable template client documents to defi ne several custom content elements that will be inserted throughout the template. The following Facelets template document declares three named <ui:insert> elements. Notice carefully where these tags are located. template02.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><ui:insert name="title" /></title><link rel="stylesheet" type="text/css" href="/css/style.css" /></head><body><ui:include src="/WEB-INF/includes/header.jsf" /><h2><ui:insert name="header" /></h2><ui:insert name="content" /><ui:include src="/WEB-INF/includes/footer.jsf" /></body></html> In the following example, the template client document defines three content elements named title, header, and content using the <ui:define> tag. Their position in the client document is not important because the template document determines where this content will be positioned. templateClient02.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ui:composition example</title></head><body><ui:composition template="/WEB-INF/templates/template02.jsf"><ui:define name="title">Facelet template example</ui:define><ui:define name="header">Hello World</ui:define><ui:define name="content">Page content goes here.</ui:define></ui:composition><ui:debug /></body></html> The following screenshot displays the result of a more complex Facelets UI composition template transformation when the browser requests the page named templateClient02.jsf. The next example demonstrates reusing a more advanced Facelets UI composition template. At this stage, we should have a good understanding of the basic concepts of Facelets templating and reuse. templateClient02a.jsf<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ui:composition example</title></head><body>Facelets Components[ 78 ]<ui:composition template="/WEB-INF/templates/template02.jsf"><ui:define name="title">Facelet template example</ui:define><ui:define name="header">Thanks for visiting!</ui:define><ui:define name="content">We hope you enjoyed our site.</ui:define></ui:composition><ui:debug /></body></html> The next screenshot displays the result of the Facelets UI composition transformation when the browser requests templateClient02a.jsf. We can follow this pattern to make a number of JSF pages reuse the template in this manner to achieve a consistent look and feel across our web application. Decorating the user interface The Facelets framework supports the definition of smaller, reusable view elements that can be combined at runtime using the Facelets UI tag library. Some of these tags, such as the <ui:composition> and <ui:component> tags, trim their surrounding content. This behavior is desirable when including content from one complete XHTML document within another complete XHTML document. There are cases, however, when we do not want Facelets to trim the content outside the Facelets tag, such as when we are decorating content on one page with additional JSF or HTML markup defi ned in another page. For example, suppose there is a section of content in our XHTML document that we want to wrap or "decorate" with an HTML <div> element defined in another Facelets page. In this scenario, we want all the content on the page to be displayed, and we are simply surrounding part of the content with additional markup defined in another Facelets template. Facelets provides the <ui:decoration> tag for this purpose. Decorating content on a Facelets page The following example demonstrates how to decorate content on a Facelets page with markup from another Facelets page using the <ui:decoration> tag. The <ui:decoration> tag has a template attribute and behaves like the <ui:composition> tag. Facelets templating typically uses the <ui:composition>. It references a Facelets template document that contains markup to be included in the current document. The main difference between the <ui:composition> tag and the <ui:decoration> tag is that Facelets trims the content outside the <ui:composition> tag but does not trim the content outside the <ui:decoration> tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ui:decorate example</title><link rel="stylesheet" type="text/css" href="css/style.css" /></head><body>Text before will stay.<ui:decorate template="/WEB-INF/templates/box.jsf"><span class="header">Information Box</span><p>This is the first line of information.</p><p>This is the second line of information.</p><p>This is the third line of information.</p></ui:decorate>Text after will stay.<ui:debug /></body></html> Creating a Facelets decoration Let's examine the Facelets decoration template referenced by the previous example. The following source code demonstrates how to create a Facelets template to provide the decoration that will surround the content on another page. As we are using a <ui:composition> tag, only the content inside this tag will be used. In this example, we declare an HTML <div> element with the "box" CSS style class that contains a single Facelets <ui:insert> tag. When Facelets renders the above Facelets page, it encounters the <ui:decorate> tag that references the box.jsf page. The <ui:decorate> tag will be merged together with the associated decoration template and then rendered in the view. In this scenario, Facelets will insert the child content of the <ui:decorate> tag into the Facelets decoration template where the <ui:insert> tag is declared. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Box</title></head><body><ui:composition><div class="box"><ui:insert /></div></ui:composition></body></html> The result is that our content is surrounded or "decorated" by the <div> element. Any text before or after the <ui:decoration> is still rendered on the page, as shown in the next screenshot: The included decoration is rendered as is, and is not nested inside a UI component as demonstrated in the following Facelets debug page:
Read more
  • 0
  • 0
  • 4033

article-image-moodle-19-math-quizzes-part-1
Packt
30 Nov 2009
5 min read
Save for later

Moodle 1.9 Math Quizzes: Part 1

Packt
30 Nov 2009
5 min read
As good as the Moodle quiz module is at recognizing the correctness of our students' answers, we quickly run into problems when we need Moodle to recognize, for example, that 3a+2b is exactly the same as 2b+3a . To accomplish this, we're going to need a Computer Algebra System (CAS). The Maxima system (more on this later) has been successfully integrated into Moodle, thanks to the work carried out by Chris Sangwin and Alex Billingsley at the University of Birmingham in the UK. In this article, we will also learn how to perform these tasks: Install and integrate STACK into Moodle Create questions that can be automatically marked using STACK Let's start by adding numeric questions into the course question bank. Creating quizzes Creating a quiz in Moodle is a two-stage process. First, we add our questions to the question bank (each course has its own question bank). Once we've added questions to the question bank, we can add a quiz activity to the course and then choose questions to add to it from the question bank. What are the advantages of having a two-stage process? I worked in much the same way creating quizzes before I started with Moodle. My bookshelf of math books was my question bank, and I would take questions from there to add into my quizzes. Here are just a few of the advantages: If there is a particular point you want to reinforce, then it's easy to include the same question in different quizzes throughout your course. It's easy to share your questions with other Moodle courses. For example, questions on the Pythagorean Theorem are relevant to pure math, mechanics, engineering, and physics. Questions can be exported from and imported into the question bank. This means converting questions over to Moodle is a job that can be shared between colleagues. Here's a basic Pythagorean Theorem question I converted over to Moodle: Question types However, I don't want to convert just this single question over to Moodle; I also want to have questions similar to this one but with different numbers. I want those numbers chosen randomly by Moodle, so I don't have to keep thinking up different numbers each time I set the quiz. The question type I need is Calculated, which we'll learn about in the next section. Calculated question type Let's learn how to add a calculated question to the course question bank now: Return to your course's front page, and click on Questions in the course Administration block: The course Question bank is displayed. From the Create new question drop-down menu, choose Calculated: Give the question a name. Make sure it's a name that you (and, potentially, your colleagues) can recognize when it's in the question bank. Don't call it '1', 'i', or 'a)' because you don't know where it will appear in the quiz. Now, supply the question text: Notice that I have used placeholders in the text, {a} and {b}. We will be configuring Moodle to replace those with numbers shortly. Scroll down to the Answer box. We need to enter the correct calculation into the Correct Answer Formula edit box (don't include a '=' in your answer): The students need to give the correct answer (exactly), but don't worry about the Tolerance setting: leave it set to 0.01. Set the Grade to 100%. I want the students to give their answers to three significant figures, and to that end I needed to click on the Correct answer shows drop-down menu, set that to 3, and change the Format to significant figures: Scroll down to the bottom of the page, and click on the Next Page button. You are now taken to the Choose dataset properties page. The numbers for the variables {a} and {b} will be chosen from a dataset. I want to use my own datasets for each variable. Select will use a new shared dataset for both drop-downs: Click on the Next Page button. You are taken to the Edit the datasets page. Now, we can specify the range of values for {a} and {b}: We need to add numbers to this dataset. I want to add 20 possible pairs of numbers for {a} and {b}. Scroll down to the Add box, select 20 items from the item(s) drop-down menu and click on the Add button: Twenty pairs of numbers are now added to the dataset. Moodle will choose pairs of numbers in this dataset when the student is presented with the question. If you want to alter any of the numbers Moodle has automatically generated for us, you can do so in the second-half of the page. Scroll down to the very bottom of the page, and click on the Save changes button. Our new calculated question is now added to the question bank: To recap, we have seen that creating a calculated question is a two-step process. First, we need to specify the question text. The question text contains variables that Moodle will then replace with random values when the quiz is taken. Then, we need to specify datasets for each of the variables, from which Moodle will choose the values when the quiz is taken. We can have Moodle choose the numbers for us, or we can select our own.
Read more
  • 0
  • 0
  • 3658

article-image-skin-customization-jboss-richfaces-33
Packt
30 Nov 2009
5 min read
Save for later

Skin Customization in JBoss RichFaces 3.3

Packt
30 Nov 2009
5 min read
Skinnability Every RichFaces component gives the support for skinnability and it means that just by changing the skin, we change the look for all of the components. That's very good for giving our application a consistent look and not repeating the same CSS values for each component every time. RichFaces still uses CSS, but it also enhances it in order to make it simpler to manage and maintain. Customize skin parameters A skin file contains the basic settings (such as font, colors, and so on) that we'll use for all the components—just by changing those settings, we can customize the basic look and feel for the RichFaces framework. As you might know, RichFaces comes with some built-in skins (and other external plug 'n' skin ones)—you can start with those skins in order to create your own custom skin. The built-in skins are: Plain emeraldTown blueSky wine japanCherry ruby classic deepMarine The plug 'n' skin ones are: laguna darkX glassX The plug 'n' skin skins are packaged in external jar files (that you can download from the same location as that of the RichFaces framework) that must be added into the project in order to be able to use them. Remember that the skin used by the application can be set as context-param in the web.xml file: <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>emeraldTown</param-value></context-param> This is an example with the emeralTown skin set: If we change the skin to japanCherry, we have the following screenshot: That's without changing a single line of CSS or XHTML! Edit a basic skin Now let's start creating our own basic skin. In order to do that, we are going to reuse one of the built-in skin files and change it. You can find the skin files in the richfaces-impl-3.x.x.jar file inside the META-INF/skins directory. Let's open the file and then open, for example, the emeraldTown.skin.properties file that looks like this (yes, the skin file is a .properties file!): #ColorsheaderBackgroundColor=#005000headerGradientColor=#70BA70headerTextColor=#FFFFFFheaderWeightFont=boldgeneralBackgroundColor=#f1f1f1generalTextColor=#000000generalSizeFont=18pxgeneralFamilyFont=Arial, Verdana, sans-serifcontrolTextColor=#000000controlBackgroundColor=#ffffffadditionalBackgroundColor=#E2F6E2shadowBackgroundColor=#000000shadowOpacity=1panelBorderColor=#C0C0C0subBorderColor=#fffffftabBackgroundColor=#ADCDADtabDisabledTextColor=#67AA67trimColor=#BBECBBtipBackgroundColor=#FAE6B0tipBorderColor=#E5973EselectControlColor=#FF9409generalLinkColor=#43BD43hoverLinkColor=#FF9409visitedLinkColor=#43BD43# FontsheaderSizeFont=18pxheaderFamilyFont=Arial, Verdana, sans-seriftabSizeFont=11tabFamilyFont=Arial, Verdana, sans-serifbuttonSizeFont=18buttonFamilyFont=Arial, Verdana, sans-seriftableBackgroundColor=#FFFFFFtableFooterBackgroundColor=#cccccctableSubfooterBackgroundColor=#f1f1f1tableBorderColor=#C0C0C0tableBorderWidth=2px#Calendar colorscalendarWeekBackgroundColor=#f5f5f5calendarHolidaysBackgroundColor=#FFEBDAcalendarHolidaysTextColor=#FF7800calendarCurrentBackgroundColor=#FF7800calendarCurrentTextColor=#FFEBDAcalendarSpecBackgroundColor=#E2F6E2calendarSpecTextColor=#000000warningColor=#FFE6E6warningBackgroundColor=#FF0000editorBackgroundColor=#F1F1F1editBackgroundColor=#FEFFDA#GradientsgradientType=plain In order to test it, let's open our application project, create a file called mySkin.skin.properties inside the directory /resources/WEB-INF/, and add the above text. Then, let's open the build.xml file and edit it, and add the following code into the war target: <copy tofile="${war.dir}/WEB-INF/classes/mySkin.skin.properties"file="${basedir}/resources/WEB-INF/mySkin.skin.properties"overwrite="true"/> Also, as our application supports multiple skins, let's open the components.xml file and add support to it: <property name="defaultSkin">mySkin</property><property name="availableSkins"> <value>mySkin</value> <value>laguna</value> <value>darkX</value> <value>glassX</value> <value>blueSky</value> <value>classic</value> <value>ruby</value> <value>wine</value> <value>deepMarine</value> <value>emeraldTown</value> <value>japanCherry</value></property> If you just want to select the new skin as the fixed skin, you would just edit the web.xml file and select the new skin by inserting the name into the context parameter (as explained before). Just to make an (bad looking, but understandable) example, let's change some parameters in the skin file: #ColorsheaderBackgroundColor=#005000headerGradientColor=#70BA70headerTextColor=#FFFFFFheaderWeightFont=boldgeneralBackgroundColor=#f1f1f1generalTextColor=#000000generalSizeFont=18pxgeneralFamilyFont=Arial, Verdana, sans-serifcontrolTextColor=#000000controlBackgroundColor=#ffffffadditionalBackgroundColor=#E2F6E2shadowBackgroundColor=#000000shadowOpacity=1panelBorderColor=#C0C0C0subBorderColor=#fffffftabBackgroundColor=#ADCDADtabDisabledTextColor=#67AA67trimColor=#BBECBBtipBackgroundColor=#FAE6B0tipBorderColor=#E5973EselectControlColor=#FF9409generalLinkColor=#43BD43hoverLinkColor=#FF9409visitedLinkColor=#43BD43# FontsheaderSizeFont=18pxheaderFamilyFont=Arial, Verdana, sans-seriftabSizeFont=11tabFamilyFont=Arial, Verdana, sans-serifbuttonSizeFont=18buttonFamilyFont=Arial, Verdana, sans-seriftableBackgroundColor=#FFFFFFtableFooterBackgroundColor=#cccccctableSubfooterBackgroundColor=#f1f1f1tableBorderColor=#C0C0C0tableBorderWidth=2px#Calendar colorscalendarWeekBackgroundColor=#f5f5f5calendarHolidaysBackgroundColor=#FFEBDAcalendarHolidaysTextColor=#FF7800calendarCurrentBackgroundColor=#FF7800calendarCurrentTextColor=#FFEBDAcalendarSpecBackgroundColor=#E2F6E2calendarSpecTextColor=#000000warningColor=#FFE6E6warningBackgroundColor=#FF0000editorBackgroundColor=#F1F1F1editBackgroundColor=#FEFFDA#GradientsgradientType=plain Here is the screenshot of what happened with the new skin: How do I know which parameters to change? The official RichFaces Developer Guide contains, for every component, a table with the correspondences between the skin parameters and the CSS properties they are connected to.
Read more
  • 0
  • 0
  • 3920

article-image-polygon-modeling-handgun-using-blender-3d-249-part-2
Packt
30 Nov 2009
4 min read
Save for later

Polygon Modeling of a Handgun using Blender 3D 2.49: Part 2

Packt
30 Nov 2009
4 min read
Modeling the hand wrap Set the view to front again, and select the vertices pointed in the following image. This time we will need two extrusions. Select the vertices in the top-left corner of the model, and move them down to align them to the image. Then, select the other three vertices shown in the following image and extrude them once: As the extruded geometry doesn't fit the guides of our reference image, we will have to select and move the lower vertices and place them as shown in the following image. They don't have to be exactly in the same position, but they should be placed in such a way that the shape of the model looks like our reference image. Remember that you can also select the vertices with the brush select tool. Press the B key twice, and then you will be able to paint the selection. Right after you place the vertices in their new positions, make another extrusion. By the end of the extrusion, try to place the lower vertices aligned with the right side of the guidelines. Just by looking at the image, you'll notice that one side of the model won't be aligned. So, select the vertices on the left or right (any one that isn't aligned with the image) and move it until it gets aligned. By now, the work will be a repetition of extrusions until we have our model created. Select the vertices pointed in the next images, and extrude them until you get the final shape. At this point in the project, you should be familiar with the technique. It's important to remember that for those operations, most of the alignment of the objects with the reference image is done by eye. At the end of each extrusion, use the S key to set the size of the new geometry until it fits with the reference image. If you prefer, the transform ation can be executed in face select mode to speed up the selection of the faces used in the extrusion. Here, we'll use the Skin Faces/Edge-Loops option again to connect the two selected faces. Sometimes, the faces created with this option will be generated with a Set Smooth option selected. This may cause the faces to look odd and have a different set of shading from the other faces. To make it look exactly the same as other faces of the model, select the created faces and click on the Set Solid button. If you don't know where this button is located, you will find it in the Editing panel. After the Skin Faces/Edge-Loops option is applied, the shade of the object will look a bit strange. This is because the smooth option of Blender is being used. Use the Set Solid option to make the faces appear in flat shade mode. A big part of the modeling is complete, but there are a few parts of the weapon missing. Our next task is to create additional parts of the gun, such as a detail for the hand wrap and the energy tank. For this project, we will create different objects for those parts to make our modeling easier. As you can see in the following image, we have created a big part of the gun with a well-organized topology and a fairly clean mesh, which is represented by a minimum number of faces and vertices, made only by quad faces. This type of mesh can be easily edited later by using subdivisions and new extrudes, which is a good reason to keep it as clean as possible.
Read more
  • 0
  • 0
  • 2191

article-image-moodle-19-math-quizzes-part-2
Packt
30 Nov 2009
4 min read
Save for later

Moodle 1.9 Math Quizzes: Part 2

Packt
30 Nov 2009
4 min read
Adding a math quiz Once we've added a question or two to the question bank, we can add a quiz to our course. I want a simple quiz where each student is allowed one attempt with no help along the way. Let's see how to achieve this now: Return to your course's front page, choose a topic, click on the Add an activity drop-down menu, and select Quiz from the list. Give the quiz a name (this will appear on the course's front page) and, if you wish, you can specify a short introduction: Scroll down to the Attempts box. Set Attempts allowed to 1 and Adaptive mode to No: Scroll down to the bottom of the page, and click the Save and display button. A split screen page is displayed with the course question bank on the right and the (currently empty) quiz on the left: To add questions from the question bank to the quiz, simply select them and click on the Add to quiz button: The questions are now added to the quiz. You'll now see them listed on the left-hand side of the page: To preview the quiz, click on the Preview tab at the top of the page: That's it! The quiz is now configured. Recall that I set Adaptive mode to No. Adaptive mode adds a Submit button to each question, allowing students (with some suitable feedback from me) to learn from their mistakes as they work through the quiz. Try experimenting with this setting. See how your students behave with the Submit button. For example, don't let them think that they can guess a multiple choice answer until they eventually get it right. Remind them that they'll be penalized for each wrong answer. Encouraging students as they attempt the quiz You've seen that there are a lot of settings I've simply ignored as I've configured this quiz. Return to your course's front page, and click on Questions from the course administration block to open the course Question bank. Click on the edit icon next to the numerical question we configured earlier in this article. (Have you spotted that you can tell what type of question it is from the icon on the far-right? Hover the mouse pointer over the icon.): Remember how I mentioned that I'd started filling out feedback? I'm going to finish doing that now in this question by giving some General feedback: When you are happy with your feedback, remember to scroll to the bottom of the page and click on the Save changes button. Now, return to your course's front page, turn editing on, and click on the update icon next to the quiz we added in the previous section: On the quiz configuration page, scroll down to the Attempts section and set Adaptive mode to Yes: Scroll to the bottom of the page, and click on the Save changes button. Preview the quiz now, and notice that under each question there is a Submit button. Experiment with entering both correct and incorrect responses. Click on the Submit button, and see how Moodle reacts by giving the student our feedback. Remember: if you are planning to use Adaptive mode, then it's worth reminding your students that they will be penalized if they get an answer wrong! Reporting quiz results What's great about a Moodle quiz is the detailed reporting Moodle provides for us. Here is an example of the report page for my quiz once a student has attempted it. (In fact, this is a colleague of mine helping me to check that my feedback is understandable!): Such reporting not only allows us to see what our students have been up to, but I also find it an invaluable tool for determining the success of my teaching. Once someone has attempted your quiz, you can no longer modify it (add or remove questions). You will need to delete the attempts to unlock the quiz.
Read more
  • 0
  • 0
  • 1883

article-image-report-components-nav-2009-part-2
Packt
30 Nov 2009
6 min read
Save for later

Report components in NAV 2009: Part 2

Packt
30 Nov 2009
6 min read
Data item Sections Earlier in our discussion on reports, we referred to the primary components of a report. The Triggers and Properties we have reviewed so far are the data processing components. Next in the report processing sequence are Sections. In Classic RD reports, Sections are the output layout and formatting components. In RTC reports, Sections have a much more limited, but still critically important, role. In the process of creating the initial report design, you may be entering data either completely manually as we've done in our example work, or you may use the Classic Report Wizard. If you use the Wizard, you will end up with Sections defined suitable for Classic Client Report processing. Those Sections may be only rough draft equivalents of what you may want your final report to look like, but they are a suitable starting place for the Classic RD layout work, if that were the tool you were going to use. If you are creating your report completely manually, that is by not using the Wizard, you may also find it appropriate to define Sections to the point that the Classic Client could print a basic, readable report. In our case, we are focusing our production report development effort on the RoleTailored Client, so we will invest minimal effort on Classic Client compatible report layouts. We might do just enough to allow test report runs for data examination purposes and logic flow debugging. However, creating basic Section layouts provides us with another benefit relative to our VS RD layout work, especially if we can create them using the Report Wizard, because all the fields to be used by VS RD must be specified in the Sections. Creating RTC reports via the Classic Report Wizard Let's look at the RTC report development flow again. The preceding image is very similar to the one we studied earlier in this articles, but this flowchart only shows the steps that are pertinent to VS RD. In Step 6 of this flow, there is an option to Create Layout Suggestion in the Visual Studio Report Designer as shown in the following screenshot: When you choose Create Layout Suggestion, the C/SIDE Report Designer will invoke a process that transforms the layout in Sections to a layout in the Visual Studio Report Designer. If a VS RD layout previously existed, the newly created layout will overwrite it. Therefore, this option will normally be used only once, in the initial stages of report design. Let's experiment by using the Report Wizard to create a simple report listing the gifts received by ICAN. We will access the Report Wizard in the Object Designer. Click on Reports | New, then fill in the Wizard screen as shown in the following image. Then click on OK and choose fields to display in the report as shown in the following screenshot. Click on Next, then choose the sorting order (that is index or key) that starts with Donor ID. Click on Next again and choose to Group the data by Donor ID. Click on Next again and choose to create totals for the Estimated Value field. One more, click on Next and choose the List Style for the report, then click on Finish. At this point, you will have generated a Classic Client report using the Report Wizard. If you View | Sections, you should see a C/SIDE report layout that looks much like the following screenshot. Let's save our newly generated report so that, if we need to, we can come back to this point as a checkpoint. Click on File | Save As and assign the report to ID 50002 with the Name of Gifts by Donor. Now click on Tools | Create Layout Suggestion. The process of transforming the Classic Report Layout to a Visual Studio Report Designer Layout will take a few seconds. When the report layout transformation process completes, you should see a screen that looks very similar to the following screenshot. The primary data layout portion of the same VS RD screen is shown in the next image. Compare this to the Classic RD data layout we just looked at a couple of steps ago. You will see some similarities and some considerable differences. Without doing anything else, let's save the VS RD layout we just created for the RoleTailored Client, then run both versions of the report to see the differences in the generated results. To save the VS RD layout, start by simply exiting the VS Report Designer. Once the VS RD screen closes, you will see the following question. Respond by clicking Yes. Then, when you exit the Classic Report Designer, you will see this question. Respond by clicking Yes. You will then be presented with the following message. Again, click on Yes. If there were an error in the RDLC created within the VS RD (such as an incorrect variable name used), an error message similar to the following would display. Since, hopefully, we didn't get such an error message, we can proceed to test both the Classic Client and the RoleTailored Client versions of our generated report. We can test the Classic Client (or C/SIDE RD) version of Report 50002 from the same Object Designer screen where we did our initial design work. Highlight the line for Report 50002 and click on the Run button. You should see the following screen: If we were running this as users, we might want to make a selection of specific Donors here on which to report. As we are just testing, simply click on Preview to see our report onscreen. The report will then appear, looking like the following: As you can see, with minimum development effort (and a minimum of technical knowledge), we have designed and created a report listing Gifts by Donor with subtotals by Donor. The report has proper page and column headings. Not only that, but the report was initiated withs a Request Form allowing application of filters. Close the Classic Client report; now let's run the RTC version. Just like we could do with Pages, we will run our Report test from the Windows Run option. Click on Run and enter the command to run Report 50002, as shown in the next screenshot. Click on OK. If the RoleTailored Client is not active, after a short pause, it will be activated. Then the Request Page will appear. Compare the look and contents of this Request Page with the one we saw previously for the Classic Client. As before, click on Preview and view the report. Of course, this time we're looking at the RTC version. This method of automatic transformation is very useful for getting an initial base for a new report or, obviously, for the complete generation process for a simple report where the requirements for layout are not too restrictive.
Read more
  • 0
  • 0
  • 2556
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-creating-text-logo-blender
Packt
30 Nov 2009
3 min read
Save for later

Creating a Text Logo in Blender

Packt
30 Nov 2009
3 min read
Here is the final image we will be creating: Let us begin! We are going to begin with the default settings in Blender, as you can see below. Creating the Background To create the background we are going to be adding a plane and then making a series of holes in it. This will then act as the basis for our entire background when we replicate the plane with two array modifiers and a mirror modifier. Go ahead and: Add a plane from top view by hitting spacebar > Add > Mesh > Plane Subdivide that plane by hitting W > Subdivide Multi > 3 divisions This will give us a grid that we can punch a few holes in with relative ease. Next, go ahead and select the vertices shown below: Then: Press x > Delete Faces to delete the selected faces Next select the inside edges of the upper-left hole by clicking on one of the edges with alt > RMB You may then hit e > esc to extrude and cancel the transform that extruding activates. Next you can hit cntrl + shift + s > 1 for the To Sphere command, this will modify the extruded vertices into a perfect circle. Check out the result below: From here we can duplicate this circle and the surrounding faces into place of all the other holes such that we have a mesh that will repeat without any gaps. Think of it as a tilable texture but in mesh form! As you will surely notice, on the bottom left and bottom right you will only duplicate have of the circle. After duplicating each piece and moving it into place it will be necessary to remove all the duplicate vertices: Select everything with a Press w > Remove Doubles Moving on, before we can replicate our pattern we need to move it such that the bottom, left corner is at the center point of our grid. If you used the default size for the plane then you can simply select everything and hold down cntrl while moving it to lock it to the grid. Now, for our final background we want the holes in our mesh to have some depth, to do this all we need to do is select each of the inner circles and extrude them down along the Z-axis as you can see in the image below: Now is where things begin to get really fun! We are going to now add two array modifiers to replicate our pattern. The first array will repeat the pattern along the X-axis to the right, and the second array will replicate the pattern down along the Y-axis. We will then you a use mirror modifier along the X and Y axis to duplicate the whole pattern across the axis’. First go to the Editing Buttons and click on Add Modifier > Array Increase the count to 10 Click Merge Add a second Array and change the count to 3 Click Merge Change the X Offset to 0 and the Y Offset to 1.0 This will leave you with 1/4 of our final pattern. To complete it: Add a Mirror Modifier Click Y in addition to the default X, this will mirror it both up and across the central axis. Add a Subsurf modifier to smooth out the mesh Select everything with a and then press w > Set Smooth Setting the mesh to smooth will likely cause some normal issues (black spots) in which case you need to hit cntrl + n > Recalculate Normals while everything is selected.
Read more
  • 0
  • 0
  • 3785

article-image-user-interface-design-icefaces-18-part-2
Packt
30 Nov 2009
11 min read
Save for later

User Interface Design in ICEfaces 1.8: Part 2

Packt
30 Nov 2009
11 min read
Facelets templating To implement the layout design, we use the Facelets templating that is officially a part of the JSF specification since release 2.0. This article will only have a look at certain parts of the Facelets technology. So, we will not discuss how to configure a web project to use Facelets. You can study the source code examples of this article, or have a look at the developer documentation (https://facelets.dev.java.net/nonav/docs/dev/docbook.html) and the articles section of the Facelets wiki (http://wiki.java.net/bin/view/Projects/FaceletsArticles)for further details. The page template First of all, we define a page template that follows our mockup design. For this, we reuse the HelloWorld(Facelets) application. You can import the WAR file now if you did not create a Facelets project. For importing a WAR file, use the menu File | Import | Web | WAR file. In the dialog box, click on the Browse button and select the corresponding WAR file. Click on the Finish button to start the import. The run configuration is done. However, you do not have to configure the Jetty server again. Instead, it can be simply selected as your target. We start coding with a new XHTML file in the WebContent folder. Use the menu File | New | Other | Web | HTML Page and click on the Next button. Use page-template.xhtml for File name in the next dialog. Click on the Next button again and choose New ICEfaces Facelets.xhtml File (.xhtml). Click on the Finish button to create the file. The ICEfaces plugin creates this code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title> <ui:insert name="title"> Default title </ui:insert> </title> </head> <body> <div id="header"> <ui:include src="/header.xhtml"> <ui:param name="param_name" value="param_value"/> </ui:include> </div> <div id="content"> <ice:form> </ice:form> </div> </body> </html> The structure of the page is almost pure HTML. This is an advantage when using Facelets. The handling of pages is easier and can even be done with a standard HTML editor. The generated code is not what we need. If you try to run this, you will get an error because the header.xhtml file is missing in the project. So, we delete the code between the <body> tags and add the basic structure for the templating. The changed code looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title> <ui:insert name="title"> Default title </ui:insert> </title> </head> <body> <table align="center" cellpadding="0" cellspacing="0"> <tr><td><!-- header --></td></tr> <tr><td><!-- main navigation --></td></tr> <tr><td><!-- content --></td></tr> <tr><td><!-- footer --></td></tr> </table> </body> </html> We change the <body> part to a table structure. You may wonder why we use a <table> for the layout, and even the align attribute, when there is a <div> tag and CSS. The answer is pragmatism. We do not follow the doctrine because we want to get a clean code and keep things simple. If you have a look at the insufficient CSS support of the Internet Explorer family and the necessary waste of time to get things running, it makes no sense to do so. The CSS support in Internet Explorer is a good example of the violation of user expectations. We define four rows in the table to follow our layout design. You may have recognized that the <title> tag still has its <ui:insert> definition. This is the Facelets tag we use to tell the templating where we want to insert our page-specific code. To separate the different insert areas from each other, the <ui:insert> has a name attribute. We substitute the comments with the <ui:insert> definitions, so that the templating can do the replacements: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title> <ui:insert name="title"> Default title </ui:insert> </title> </head> <body> <table align="center" cellpadding="0" cellspacing="0"> <tr><td><ui:insert name="header"/></td></tr> <tr><td><ui:insert name="mainNavigation"/></td></tr> <tr><td><ui:insert name="content"/></td></tr> <tr><td><ui:insert name="footer"/></td></tr> </table> </body> </html> The <ui:insert> tag allows us to set defaults that are used if we do not define something for replacement. Everything defined between <ui:insert> and </ui:insert> will then be shown instead. We will use this to define a standard behavior of a page that can be overwritten, if necessary. Additionally, this allows us to give hints in the rendering output if something that should be defined in a page is missing. Here is the code showing both aspects: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <ice:outputStyle href="/xmlhttp/css/royale/royale.css" /> <title> <ui:insert name="title"> Please, define a title. </ui:insert> </title> </head> <body> <table align="center" cellpadding="0" cellspacing="0"> <tr><td> <ui:insert name="header"> <ice:graphicImage url="/logo.png" /> </ui:insert> </td></tr> <tr><td> <ui:insert name="mainNavigation"> <ice:form> <ice:menuBar noIcons="true"> <ice:menuItem value="Menu 1"/> <ice:menuItem value="Menu 2"/> <ice:menuItem value="Menu 3"/> </ice:menuBar> </ice:form> </ui:insert> </td></tr> <tr><td> <ui:insert name="content"> Please, define some content. </ui:insert> </td></tr> <tr><td> <ui:insert name="footer"> <ice:outputText value="&#169; 2009 by The ICEcubes." /> </ui:insert> </td></tr> </table> </body> </html> The header, the main navigation, and the footer now have defaults. For the page title and the page content, there are messages that ask for an explicit definition. The header has a reference to an image. Add any image you like to the WebContent and adapt the url attribute of the <ice:graphicImage> tag, if necessary. The example project for this article will show the ICEcube logo. It is the logo that is shown in the mockup above. The <ice:menuBar> tag has to be surrounded by a <ice:form> tag, so that the JSF actions of the menu entries can be processed. Additionally, we need a reference to one of the ICEfaces default skins in the <head> tag to get a correct menu presentation. We take the Royale skin here. If you do not know what the Royale skin looks like, you can have a look at the ICEfaces Component Showcase (http://component-showcase.icefaces.org) and select it in the combo box on the top left. After your selection, all components present themselves in this skin definition. Using the template A productive page template has a lot more to define and is also different in its structure. References to your own CSS, JavaScript, or FavIcon files are missing here. The page template would be unmaintainable soon if we were to manage the pull-down menu this way. However, we will primarily look at the basics here. So, we keep the page template for now. Next, we adapt the existing ICEfacesPage1.xhtml to use the page template for its rendering. Here is the original code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title> <ui:insert name="title"> Default title </ui:insert> </title> </head> <body> <div id="header"> <!-- <ui:include src="/header.xhtml" > <ui:param name="param_name" value="param_value" /> </ui:include> --> </div> <div id="content"> <ice:form> <ice:outputText value="Hello World!"/> <!-- drop ICEfaces components here --> </ice:form> </div> </body> </html> We keep the Hello World! output and use the new page template to give some decoration to it. First of all, we need a reference to the page template so that the templating knows that it has to manage the page. As the page template defines the page structure, we no longer need a <head> tag definition. You may recognize <ui:insert> in the <title> tag. This is indeed the code we normally use in a page template. Facelets has rendered the content in between because it did not find a replacement tag. Theoretically, you are free to define such statements in any location of your code. However, this is not recommended. Facelets has a look at the complete code base and matches pairs of corresponding name attribute definitions between <ui:insert name="..."> and <ui:define name="..."> tags. Here is the adapted code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <body> <ui:composition template="/page-template.xhtml"> <div id="content"> <ice:form> <ice:outputText value="Hello World!"/> </ice:form> </div> </ui:composition> </body> </html> This code creates the following output: We can see our friendly reminders for the missing title and the missing content. The header, the main navigation, and the footer are rendered as expected. The structure of the template seems to be valid, although we recognize that a CSS fle is necessary to define some space between the rows of our layout table. However, something is wrong. Any idea what it is? If you have a look at the hello-world.xhtml again, you can find our Hello World! output; but this cannot be found in the rendering result. As we use the page template, we have to tell the templating where something has to be rendered in the page. However, we did not do this for our Hello World! output. The following code defines the missing <ui:define> tag and skips the <div> and <ice:form> tags that are not really necessary here: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <body> <ui:composition template="/page-template.xhtml"> <ui:define name="title"> Hello World on Facelets </ui:define> <ui:define name="content"> <ice:outputText value="Hello World!"/> </ui:define> </ui:composition> </body> </html>
Read more
  • 0
  • 0
  • 2540

article-image-drag-and-drop-yui-part-2
Packt
30 Nov 2009
12 min read
Save for later

Drag-and-Drop with the YUI: Part-2

Packt
30 Nov 2009
12 min read
Scripting DragDrop There are two ways that we could go about achieving our objective. We could take the easy way and treat each draggable object as an independent module, with its own independent properties and event handlers. This would make the code simpler, but would mean that we would require a good deal more of it. If there are just one or two objects on your page which can be dragged and dropped then this way is fine. However, when you begin to have more than just a couple of objects that can be moved, the amount of code required to handle these objects efficiently increases dramatically. The second way may be a little more complex and therefore will require a greater degree of understanding. However, this way allows for sharing properties and event handlers across similar drag-and-drop objects. This reduces the overall footprint of your application and saves us an incredible amount of typing. Creating Individual Drag Objects We can look at both methods, so you can see just how much work the second way saves us. We'll start with the easy method. Add the following <script> tag directly before the closing </body> tag: <script type="text/javascript">//create the namespace object for this exampleYAHOO.namespace("yuibook.dd");//define the setDDs functionYAHOO.yuibook.dd.setDDs = function() {//detect the useragentvar ua = YAHOO.env.ua;if (ua.ie != 0) {ua.data = "ie";}//define variablesvar basketTotal = 0;var basketTot = 0;var Dom = YAHOO.util.Dom;//create the 3 DragDropProxy objectsvar dd1 = new YAHOO.util.DDProxy("prod1");dd1.isTarget = false;dd1.scroll = false;var dd2 = new YAHOO.util.DDProxy("prod2");dd2.isTarget = false;dd2.scroll = false;var dd3 = new YAHOO.util.DDProxy("prod3");dd3.isTarget = false;dd3.scroll = false;var basket = new YAHOO.util.DDTarget("basket");//define function to call when dd1 starts being draggeddd1.startDrag = function() {//set cursor position to top-left of proxydd1.setDelta(0,0);}//define function to call when dd1 stops being dragdeddd1.endDrag = function() {}//define function to call when dd1 enters basketdd1.onDragEnter = function(e, id) {//has dd1 been dragged into basket?if (id == "basket") {//add 1 to the total number of itemsbasketTotal += 1;var tot = YAHOO.util.Dom.get("basketTotal")tot.innerHTML = basketTotal;//create new p element to hold product summaryvar p = document.createElement("p");Dom.addClass(p, "prod");p.id = "prod" + basketTotal;//add icon for product 1 to basketvar ico = document.createElement("img");ico.setAttribute("src", "images/prod1_ico.jpg");ico.id = "imageico" + basketTotal;Dom.addClass(ico, "icon");//add product 1 summary to basketp.appendChild(ico);Dom.get("basketBody").appendChild(p);//create new p element for product 1 titlevar p2 = document.createElement("p");var info = Dom.get("prod1info");//is the browser IE?if (ua.data == "ie") {var infos = info.innerHTML.split("<BR>");} else {var infos = info.innerHTML.split("<br>");}//set product 1 titlevar title = document.createTextNode(infos[0]);Dom.addClass(p2, "prodTitle");p2.id = "prodTitle" + basketTotal;//add title to basketp2.appendChild(title);Dom.insertAfter(p2, Dom.get(ico));//create p element for product 1 pricevar p3 = document.createElement("p");var price = document.createTextNode(infos[1]);Dom.addClass(p3, "prodPrice");p3.id = "prodPrice" + basketTotal;//add product 1 price to basketp3.appendChild(price);Dom.insertAfter(p3, Dom.get(p2));//update total basket priceprice = Dom.get(p3).innerHTML;var rawPrice = price.slice(1,6);var cost = parseFloat(rawPrice);basketTot += cost;var newBasketTot = Dom.get("basketCost");newBasketTot.innerHTML = basketTot;}}//define function to call when dd2 starts being draggeddd2.startDrag = function() {dd2.setDelta(0,0);}//define function to call when dd2 stops being draggeddd2.endDrag = function() {}//define function to call when dd2 enters basketdd2.onDragEnter = function(e, id) {if (id == "basket") {//add 1 to the total number of itemsbasketTotal += 1;var tot = YAHOO.util.Dom.get("basketTotal")tot.innerHTML = basketTotal;//create new p element to hold product summaryvar p = document.createElement("p");Dom.addClass(p, "prod");p.id = "prod" + basketTotal;//add icon for product 2 to basketvar ico = document.createElement("img");ico.setAttribute("src", "images/prod2_ico.jpg");ico.id = "imageico" + basketTotal;Dom.addClass(ico, "icon");//add product 2 summary to basketp.appendChild(ico);Dom.get("basketBody").appendChild(p);//create new p element for product 2 titlevar p2 = document.createElement("p");var info = Dom.get("prod2info");//is the browser IE?if (ua.data == "ie") {var infos = info.innerHTML.split("<BR>");} else {var infos = info.innerHTML.split("<br>");}//set product 2 titlevar title = document.createTextNode(infos[0]);Dom.addClass(p2, "prodTitle");p2.id = "prodTitle" + basketTotal;//add title to basketp2.appendChild(title);Dom.insertAfter(p2, Dom.get(ico));//create p element for product 2 pricevar p3 = document.createElement("p");var price = document.createTextNode(infos[1]);Dom.addClass(p3, "prodPrice");p3.id = "prodPrice" + basketTotal;//add product 2 price to basketp3.appendChild(price);Dom.insertAfter(p3, Dom.get(p2));//update total basket priceprice = Dom.get(p3).innerHTML;var rawPrice = price.slice(1,6);var cost = parseFloat(rawPrice);basketTot += cost;var newBasketTot = Dom.get("basketCost");newBasketTot.innerHTML = basketTot;}}//define function to call when dd3 starts being draggeddd3.startDrag = function() {dd3.setDelta(0,0);}//define function to call when dd3 stops being draggeddd3.endDrag = function() {}//define function for when dd3 enters basketdd3.onDragEnter = function(e, id) {if (id == "basket") {//add 1 to the total number of itemsbasketTotal += 1;var tot = YAHOO.util.Dom.get("basketTotal")tot.innerHTML = basketTotal;//create new p element to hold product summaryvar p = document.createElement("p");Dom.addClass(p, "prod");p.id = "prod" + basketTotal;//add icon for product 3 to basketvar ico = document.createElement("img");ico.setAttribute("src", "images/prod3_ico.jpg");ico.id = "imageico" + basketTotal;Dom.addClass(ico, "icon");//add product 3 summary to basketp.appendChild(ico);Dom.get("basketBody").appendChild(p);//create new p element for product 3 titlevar p2 = document.createElement("p");var info = Dom.get("prod3info");//is the browser IE?if (ua.data == "ie") {var infos = info.innerHTML.split("<BR>");} else {var infos = info.innerHTML.split("<br>");}//set product 3 titlevar title = document.createTextNode(infos[0]);Dom.addClass(p2, "prodTitle");p2.id = "prodTitle" + basketTotal;//add title to basketp2.appendChild(title);Dom.insertAfter(p2, Dom.get(ico));//create p element for product 3 pricevar p3 = document.createElement("p");var price = document.createTextNode(infos[1]);Dom.addClass(p3, "prodPrice");p3.id = "prodPrice" + basketTotal;//add product 3 price to basketp3.appendChild(price);Dom.insertAfter(p3, Dom.get(p2));//update total basket priceprice = Dom.get(p3).innerHTML;var rawPrice = price.slice(1,6);var cost = parseFloat(rawPrice);basketTot += cost;var newBasketTot = Dom.get("basketCost");newBasketTot.innerHTML = basketTot;}}}//execute setDDs when DOM is readyYAHOO.util.Event.onDOMReady(YAHOO.yuibook.dd.setDDs);</script> All of the code here sits within the setDDs() function, which is called using the Event utility's onDOMReady() method. The first section of code within the setDDs() function uses the .env.ua() method of the YAHOO global object to determine the user-agent string of the browsing environment. We can use this as a quick and easy way of detecting the browser being used to view the page. The ie property exists within the ua object even if IE is not in use, but if it isn't in use, the property is set to 0. Therefore, if the ie property does not equal to 0 it means that IE is the browser currently being used. In this case, the ie property will hold an integer representing the version of IE in use. When IE is being used, we set the data property of our ua variable to the string ie. We then create a series of variables for use in the script. The last variable is created purely for convenience. We'll be making heavy use of the DOM utility during this example, so defining that first part of the DOM call as a short variable helps make things easier on us. Next we create all three of the individual DDProxy objects. Remember, in this implementation, each object has to have its own properties and event handlers defined for it. We also define the basket as a DDTarget so that we can make use of the .onDragEnter() method. Because we want each product to interact only with our shopping basket and not the other products on the page, we have to set the .isTarget property to false. As well as being able to specifically create drop targets using the YAHOO.util.DDTarget class, any drag object is by default also a drop target. Additionally, we can switch off the .scroll property, which causes the viewport to scroll indefinitely when the dragged object exceeds the window boundary. Using DragDrop Events Three event handlers are required for this example: startDrag, endDrag, and onDragEnter. The startDrag event fires as soon as the left mouse button has been held down for the required length of time on a drag object, or the pointer moves the specified number of pixels. The .setDelta() method used in the startDrag event handler allows us to control where the pointer is relative to the drag object, or in this case, the proxy element. By specifying 0,0 as arguments for this method, we are instructing the pointer to appear at the top-left corner of the proxy element. This is needed so that the element is placed back where it began instead of where the pointer was relative to the drag object when the drag began. The endDrag event fires when a mouseup event is detected on the object being dragged. The anonymous function here has a very special purpose, even though it is just an empty function.What it does is ensure that the item being dragged is returned to its original position once it has been dropped instead of remaining where it was dropped. This is important because if we didn't keep the listing pictures in their proper locations, the page would soon be littered with abandoned drag objects. The onDragEnter event fires when the moving object is dragged over a legal target. Since the shopping basket is the only valid target on the page, this will fire whenever a product object is dragged over the basket. This function is where the bulk of our code lies. Two arguments are specified for this function. The first is the event object, which is automatically passed to our handler. The second argument is the id of the element that triggered the event, which in this example will be the basket. We first use our YAHOO.util.Dom shortcut to get the <span> element displaying the number of items in the basket, then use the innerHTML property to alter this value in accordance with the basketTotal variable. We create a new paragraph element and give it a class of prod. This new element will act as a container for a short summary of the item placed in the basket. We can go ahead and create the different items that will make up this short description of the product that has been purchased. A new <img> element is created and stored in the ico variable. Its src attribute is set to the icon representing the product. We then give it a class name so that we can style it and an id attribute so that we can identify it. Once created and configured, we can append the <img> to the new <p> element, and then append the <p> element to the body of the basket. Now let's work on extracting some of the listing description to display in the basket. We create another new <p> element and give it a class of prodTitle. We then need to do more detection to determine which product was dropped, getting the full listing text of the product in the title variable once we have. Each part of the listing text is separated by a <br> element, so we can create an array of each different bit of information contained in the listing text using the .split() method. This is the part of the script where we use the information gathered from the ua property earlier on. IE for some reason capitalizes all HTML elements in the DOM. This means that IE sees <BR> tags, while other browsers see <br>, and is the reason we need the if statement to determine the browser in use. The first item in the infos array is the name of the product, so we can use this as the title for the product summary and create a new textNode based on it. This title element is then inserted into the DOM directly after the icon element using the DOM utility's .insertAfter() method, which takes the element to insert and the element it should be inserted after as arguments. For good measure, let's add the price of the product to the product summary. A final element is created to hold a new textNode comprised of the second item in the infos array, which happens to be the price of the product. The class for the new <p> element is set and it is then inserted as a sibling of the previous element that was created. At the bottom of our basket is a price indicator showing the total cost of all items in the basket; we can easily update this using the same method as we updated the basket contents total earlier on. We recycle the price variable, updating it with the HTML element from the basket. As the price is currently a text string rather than a number, we have to convert it. Before we can do this however, we need to remove the currency symbol from the front of it, which we can do with the .slice() method. Then we can use the standard JavaScript parseFloat math function to convert the remaining string into a true floating-point number. We can then update the current cost by adding the cost of the dropped product to it. Finally, we set the innerHTML property of the basketCost span element to the new total. As each drag object is completely independent, the rest of our script is made up of identical event handlers tied to the other drag objects (products 2 and 3). This is what bloats our code to three times the size it actually needs to be, and imagine how much typing would need to be done if there were 30 products on the page
Read more
  • 0
  • 0
  • 1295

article-image-extending-tabs-jquery-ui-17
Packt
30 Nov 2009
4 min read
Save for later

Extending Tabs in jQuery UI 1.7

Packt
30 Nov 2009
4 min read
  The tab widget defines a series of useful options that allow you to add callback functions to perform different actions when certain events exposed by the widget are detected. The following table lists the configuration options that are able to accept executable functions on an event: Property Usage add Execute a function when a new tab is added. disable Execute a function when a tab is disabled. enable Execute a function when a tab is enabled. load Execute a function when a tab's remote data has loaded. remove Execute a function when a tab is removed. select Execute a function when a tab is selected. show Execute a function when the content section of a tab is shown.   Each component of the library has callback options (such as those in the previous table), which are tuned to look for key moments in any visitor interaction. Any function we use with these callbacks are usually executed before the change happens. Therefore, you can return false from your callback and prevent the action from occurring. In our next example, we will look at how easy it is to react to a particular tab being selected using the standard non-bind technique. Change the final <script> element in tabs7.html so that it appears as follows: <script type="text/javascript"> $(function(){ function handleSelect(event, tab) { $("<p>").text("The tab at index " + tab.index +  " was selected").addClass("status-message ui-corner-all") .appendTo($(".ui-tabs-nav","#myTabs")).fadeOut(5000); } var tabOpts = { select:handleSelect }; $("#myTabs").tabs(tabOpts); });</script> Save this file as tabs8.html. We also need a little CSS to complete this example, in the <head> of the page we just created add the following <link> element: <link rel="stylesheet" type="text/css" href="css/tabSelect.css"> Then in a new page in your text editor add the following code: .status-message { position:absolute; right:3px; top:4px; margin:0; padding:11px 8px 10px; font-size:11px; background-color:#ffffff; border:1px solid #aaaaaa;} Save this file as tabSelect.css in the css folder. We made use of the select callback in this example, although the principle is the same for any of the other custom events fired by tabs. The name of our callback function is provided as the value of the select property in our configuration object. Two arguments will be passed automatically to the function we define by the widget when it is executed. These are the original event object and a custom object containing useful properties from the tab which is in the function's execution context. To find out which of the tabs was clicked, we can look at the index property of the second object (remember these are zero-based indices). This is added, along with a little explanatory text, to a paragraph element that we create on the fly and append to the widget header. In this example, the callback function was defined outside the configuration object, and was instead referenced by the object. We can also define these callback functions inside our configuration object to make our code more efficient. For example, our function and configuration object from the previous example could have been defined like this: var tabOpts = { select: function(event, tab) { $("<p>").text("The tab at index " + tab.index + " was selected") .addClass("status-message ui-corner-all").appendTo($(".ui-tabs-nav", "#myTabs")).fadeOut(5000); }} Check tabs8inline.html in the code download for further clarification on this way of using event callbacks. Whenever a tab is selected, you should see the paragraph before it fades away. Note that the event is fired before the change occurs. Binding to events Using the event callbacks exposed by each component is the standard way of handling interactions. However, in addition to the callbacks listed in the previous table we can also hook into another set of events fired by each component at different times. We can use the standard jQuery bind() method to bind an event handler to a custom event fired by the tabs widget in the same way that we could bind to a standard DOM event, such as a click. The following table lists the tab widget's custom binding events and their triggers: Event Trigger tabsselect A tab is selected. tabsload A remote tab has loaded. tabsshow A tab is shown. tabsadd A tab has been added to the interface. tabsremove A tab has been removed from the interface. tabsdisable A tab has been disabled. tabsenable A tab has been enabled.
Read more
  • 0
  • 0
  • 2255
article-image-apache-myfaces-trinidad-12-web-application-groundwork-part-1
Packt
30 Nov 2009
8 min read
Save for later

Apache MyFaces Trinidad 1.2 Web Application Groundwork: Part 1

Packt
30 Nov 2009
8 min read
Navigation Navigation deals with all aspects of the user to moving from one part of an application to another. This includes the following means that the application must support, to allow the user moving to a certain functionality that is available through various kinds of links: Support of movement invocation through mouse clicks on tree nodes or keyboard shortcuts on such nodes, for example, menu items such as tr:commandNavigationItem, tr:commandLink, and s:link Support of movement invocation through mouse-clicks on buttons or keyboard shortcuts on such controls, for example, tr:commandButton, s:button, and s:link Support of movement invocation through mouse-clicks on hyper links or keyboard shortcuts on such links, for example, tr:commandLink, and s:link Support of movement invocation through mouse-clicks on icon links or buttons, or keyboard shortcuts on such links or buttons, for example, tr:image, tr:icon, and so on Further support for other variations of similar means of direct manipulation, for example, select boxes or radio buttons that cause a form to change in a way that encompasses moving to another page with more or other fields The following Image shows various means of navigation that all have to be considered (tree links, button clicks, selections and so on): To keep such navigation as simple, and yet as effective as technically possible, we move away from the Struts-inspired JSF way of declaring the navigation by means of XML files, something also kept up by Seam. We take advantage of Trinidad's dialog framework. It allows navigation on the pure Java side so that Seam's pages.xml can concentrate on the general navigation aspects such as exception handling or security/authorization. Following advantages can be observed in such an approach: Navigation declarations are kept simple and manageable thanks to a small pages.xml and yet no *.page.xml files are needed. Navigation occurs only in two areas—the XHTML and the application-specific Seam component controllers. Navigation always works the same way—first the model is set up and made available to the view by the controller, then the controller navigates to the view using the dialog framework. Finally, when the view is left, it is either closed (click on X), cancelled (click on Cancel), or accepted (click on OK) which is followed by post processing such as selecting and passing a value on to another object. You can access all the required sources, tools or plugins, and the sample project setup here. Thus, for instance, the login dialog is a real programmatic Trinidad dialog as it is called the following way: @Begin(join=true)public void doLogin(javax.faces.event.ActionEvent event){FacesContext jsfCtx = FacesContext.getCurrentInstance();// Create the dialog UIViewRootViewHandler viewHandler = jsfCtx.getApplication().getViewHandler();UIViewRoot dialog = viewHandler.createView(jsfCtx, "/login.xhtml");RequestContext trCtx = RequestContext.getCurrentInstance();trCtx.launchDialog(dialog,null, event.getComponent(),false, null);} Whereby the XHTML does not use the standard Trinidad dialog command features, but passes control to above action listener: <tr:form><tr:commandLink id="loginCommandLink" text="Login"actionListener="#{controller.doLogin}"rendered="#{not identity.loggedIn}" blocking="true"/></tr:form> The only occurrences of login.xhtml in pages.xml are in the general declaration of pages.xml and in the general error handling, but no other navigation of login.xhtml needs to be declared: <pages xsi:schemaLocation="http://jboss.com/products/seam/pageshttp://jboss.com/products/seam/pages-2.0.xsd"login-view-id="/login.xhtml">...<exception class="org.jboss.seam.security.NotLoggedInException"><redirect view-id="/login.xhtml"><message>Please log in first</message></redirect></exception> Finally, the dialog is closed, which is again done in a programmatic way for Trinidad dialogs: public void closeDialog(){Identity id = (Identity)Contexts.lookupInStatefulContexts(org.jboss.seam.security.identity");id.login();RequestContext trCtx = RequestContext.getCurrentInstance();trCtx.returnFromDialog(null,null);} This time, we do not need to deal with an event and close it by the simpler JSF action reference: <div class="actionButtons"><tr:commandButton text="Login" action="#{controller.closeDialog}" /></div> To understand the dialog logic behind above processes let us take a look at the general principles of the dialog framework that Trinidad provides. Trinidad's Dialog Framework The Apache MyFaces Trinidad Dialog Framework is an inheritance that stems back from the days of Oracle's ADF and UIX frameworks. It was the main way to navigate across dialogs, moving from page to page, from popup dialog to main browser dialog window, and so on. It offers a declarative way that works by using the conventional pages declarations as known from the pure JSF side, also in combination with Seam's pages.xml. Furthermore, it allows navigation in a purely programmatic manner as can be seen in the preceding examples. Nowadays, the dialog framework provided with Trinidad still counts as an alternative to the usual approach based in declaring pages and referencing them from within the application. Moreover, its uniform approach of dealing with both kinds of navigation, popup windows, and main browser windows remains as yet another attractive characteristic. For both reasons, we want to take advantage of this technique and concentrate on the purely programmatic side. For the declarative, please refer to http://myfaces.apache.org/trinidad/devguide/dialogs.html. Programmatically creating a dialog To create a dialog only the invocation of a method called launchDialog is required. It is a method provided by Trinidad's RequestContext object: public abstract void launchDialog(UIViewRoot dialogRoot,java.util.Map dialogParameters, UIComponent source, boolean useWindow, Map windowProperties); So the developer needs to provide the following parameters: A JSF component tree (the UIViewRoot dialogRoot) Some objects to pass to the dialog, see the upcoming sub section A JSF component from which the dialog is initiated and which receives a Trinidad ReturnEvent when the dialog to be shown is finished (closed) A Boolean flag to set the display type, popup, or main window The size of the pop-up window that is only required if the display type is a pop-up window which is set by putting integer objects into this map with keys width and height for window width and height respectively In above example, we can see that: ViewHandler viewHandler = jsfCtx.getApplication().getViewHandler();UIViewRoot dialog = viewHandler.createView(jsfCtx, "/login.xhtml");RequestContext trCtx = RequestContext.getCurrentInstance();trCtx.launchDialog(dialog,null, event.getComponent(), false, null); The JSF view handler is applied to create the new component tree based on the current JSF Faces context and the specific page to be shown in the dialog, which is the usual way. Next, in the actual call of the launchDialog method, we can see the purely programmatic approach without passing any objects to the dialog to be launched. Furthermore, we can see that because it is inside an action event listener of a commandLink, the dialog activity is linked with that link component. In other words, once the dialog is finished, a ReturnEvent is raised and handled by a respective return event listener on that component. Providing the data flow from dialog to dialog There are two alternatives to pass objects to a dialog and back: Using Trinidad's page flow scope Using Seam's scopes The first way is sort of built-in to Trinidad dialogs because above dialogParameters is a map of parameters that is going to populate a newly created pageFlowScope map solely created for the upcoming dialog. This map also includes all the objects that stem from the currently available pageFlowScope. One could also think of it as a nested scope because once the dialog is finished, this map is not available anymore; therefore, any modifications to this newly nested scope will not be preserved once the dialog is closed. The second way would be consistent with the rest of the web application is if the other parts use such important Seam scopes as conversation. Generally, it is more advisable to prefer one of both and avoid a mixture. In this article we take advantage of page flow scopes as Trinidad is in the foreground. Returning from a dialog Once the dialog is cancelled, or the activity accepted and finished, the application must link to Trinidad's standard closing process which is calling the returnFromDialog method of RequestContext. For example, the closeWindow needs to apply Trinidad's RequestContext: RequestContext trCtx = RequestContext.getCurrentInstance();trCtx.returnFromDialog(null,null); This is a special case because the returnFromDialog method's signature is defined as follows: public abstract void returnFromDialog(Object returnValue, Map<Object,Object> returnParameters); Generally, while invoking the returnFromDialog method, one provides return objects as dialog results, that is, for instance the result of a selection. Therefore, it is perfectly normal to return a single object as returnValue while returnParameters may remain null. In any case, the ReturnEvent object provides two methods to access such dialog results: public Object getReturnValue(): This method yields the object that has been passed as the first parameter of the invocation of returnFromDialog public Map<Object, Object> getReturnParameters(): This method yields the map that has been passed as the second parameter of the invocation of returnFromDialog In the case of our simple closeDialog method, no parameters are passed back as Seam's login procedure does it all for us, and we do not need to pass anything back as it is saved by Seam in its identity object. In the following section, we will see the specific example which is in our web sample application.
Read more
  • 0
  • 0
  • 1901

article-image-tabs-jquery-ui-17
Packt
30 Nov 2009
7 min read
Save for later

Tabs in jQuery UI 1.7

Packt
30 Nov 2009
7 min read
The UI tabs widget is used to toggle visibility across a set of different elements, each element containing content that can be accessed by clicking on its heading which appears as an individual tab. The tabs are structured so that they line up next to each other, whereas the content sections are layered on top of each other, with only the top one visible. Clicking a tab will highlight the tab and bring its associated content panel to the top of the stack. Only one content panel can be open at a time. The following screenshot shows the different components of a set of UI tabs: A basic tab implementation The structure of the underlying HTML elements, on which tabs are based, is rigid and widgets require a certain number of elements for them to work. The tabs must be created from a list element (ordered or unordered) and each list item must contain an <a> element. Each link will need to have a corresponding element with a specified id that it is associated with the link's href attribute. We'll clarify the exact structure of these elements after our first example. In a new file in your text editor, create the following page: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="development-bundle/themes/smoothness/ui.all.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Tabs Example 1</title> </head> <body> <div id="myTabs"> <ul> <li><a href="#a">Tab 1</a></li> <li><a href="#b">Tab 2</a></li> </ul> <div id="a">This is the content panel linked to the first tab,  it is shown by default.</div> <div id="b">This content is linked to the second tab and will be shown when its tab is clicked.</div> </div> <script type="text/javascript" src="development-bundle/jquery-1.3.2.js"></script> <script type="text/javascript" src="development-bundle/ui/ui.core.js"></script> <script type="text/javascript" src="development-bundle/ui/ui.tabs.js"></script> <script type="text/javascript"> $(function(){ $("#myTabs").tabs(); }); </script> </body></html> Save the code as tabs1.html in your jqueryui working folder. Let's review what was used. The following script and CSS resources are needed for the default tab widget instantiation: ui.all.css jquery-1.3.2.js ui.core.js ui.tabs.js A tab widget consists of several standard HTML elements arranged in a specific manner (these can be either hardcoded into the page, or added dynamically, or can be a mixture of both depending on the requirements of your implementation). An outer container element, which the tabs method is called on A list element( <ul> or <ol>) An <a> element for each tab An element for the content of each tab The first two elements within the outer container make the clickable tab headings, which are used to show the content section that is associated with the tab. Each tab should include a list item containing the link. The href attribute of the link should be set as a fragment identifier, prefixed with #. It should match the id attribute of the element that forms the content section, with which it is associated. The content sections of each tab are created by the elements. The id attribute is required and will be targeted by its corresponding element. We've used elements in this example as the content panels for each tab, but other elements, such as elements can also be used. The elements discussed so far, along with their required attributes, are the minimum that are required from the underlying markup.We link to several <script> resources from the library at the bottom of the <body> before its closing tag. Loading scripts last, after stylesheets and page elements is a proven technique for improving performance. After linking first to jQuery, we link to the ui.core.js file that is required by all components (except the effects, which have their own core file). We then link to the component's source file that in this case is ui.tabs.js.After the three required script files from the library, we can turn to our custom < script> element in which we add the code that creates the tabs. We simply use the $(function(){}); shortcut to execute our code when the document is ready. We then call the tabs() widget method on the jQuery object, representing our tabs container element (the <ul> with an id of myTabs).When we run this file in a browser, we should see the tabs as they appeared in the first screenshot of this article(without the annotations of course). Tab CSS framework classes Using Firebug for Firefox (or another generic DOM explorer) we can see that a variety of class names are added to the different underlying HTML elements that the tabs widget is created from, as shown in the following screenshot: Let's review these briefly. To the outer container < div> the following class names are added: Class name Purpose ui-tabs Allows tab-specific structural CSS to be applied. ui-widget Sets generic font styles that are inherited by nested elements. ui-widget-content Provides theme-specific styles. ui-corner-all Applies rounded corners to container. The first element within the container is the < ul> element. This element receives the following class names: Class name Purpose ui-tabs-nav Allows tab-specific structural CSS to be applied. ui-helper-reset Neutralizes browser-specific styles applied to <ul> elements. ui-helper-clearfix Applies the clear-fix as this element has children that are floated. ui-widget-header Provides theme-specific styles. ui-corner-all Applies rounded corners. The individual < li> elements are given the following class names: Class name Purpose ui-state-default Applies theme-specific styles. ui-corner-top Applies rounded corners to the top edges of the elements. ui-tabs-selected This is only applied to the active tab. On page load of the default implementation this will be the first tab. Selecting another tab will remove this class from the currently selected tab and apply it to the new tab. ui-state-active Applies theme-specific styles to the currently selected tab. This class name will be added to the tab that is currently selected, just like the previous class name. The reason there are two class names is that ui-tabs-selected provides the functional CSS, while ui-state-active provides the visual, decorative styles. The < a> elements within each < li> are not given any class names, but they still have both structural and theme-specific styles applied to them by the framework. Finally, the elements that hold each tab's content are given the following class names: Class name Purpose ui-tabs-panel Applies structural CSS to the content panels ui-widget-content Applies theme-specific styles ui-corner-bottom Applied rounded corners to the bottom edges of the content panels All of these classes are added to the underlying elements automatically by the library, we don't need to manually add them when coding the page. As these tables illustrate, the CSS framework supplies the complete set of both structural CSS styles that control how the tabs function and theme-specific styles that control how the tabs appear, but not how they function. We can easily see which selectors we'll need to override if we wish to tweak the appearance of the widget, which is what we'll do in the following section.
Read more
  • 0
  • 0
  • 4260

article-image-apache-myfaces-trinidad-12-web-application-groundwork-part-2
Packt
30 Nov 2009
3 min read
Save for later

Apache MyFaces Trinidad 1.2 Web Application Groundwork: Part 2

Packt
30 Nov 2009
3 min read
Deployment Deployment is very easy because with Seam-gen, we also inherit the deployment mechanism (already run during the project setup, earlier) provided by the Ant build process of Seam-gen. However, a few notes regarding the specific deployment of a Trinidad and Facelet web application in contrast with Seam-gen are discussed in more detail in the upcoming topics. The following screenshot shows the referenced libraries within the Eclipse IDE: Trinidad-specific and Facelet-related changes to the project files First of all, the lib directory lacks the Trinidad JAR files and the Facelet JAR: jsf-facelets-1.1.14.jar trinidad-api-1.2.9.jar trinidad-impl-1.2.9.jar So above JAR files must be added to the lib directory while others, such as the RichFaces JARs, should be removed as we want to achieve a clean setup of a single component library. A mix-up should be avoided to keep away from integration problems. The following screenshot shows the contents of the lib directory inside Eclipse (part I only shows files not referenced by the Eclipse project): Most importantly, we need to update the file deployed-jars.list, as it is looked at by the build process to provide the application server with the required JAR files. So we reduce this list file to a more minimal Trinidad-specific version: antlr-runtime.jar commons-beanutils.jar commons-digester.jar core.jar drools-compiler.jar drools-core.jar janino.jar jboss-el.jar jboss-seam.jar jboss-seam-*.jar jbpm-jpdl.jar jsf-facelets-1.1.14.jar mvel14.jar trinidad-api-1.2.10.jar trinidad-impl-1.2.10.jar The following screenshot shows the contents of the lib directory inside Eclipse (part II only shows files not referenced by the Eclipse project): Next, in the resources directory we must add a provider for Seam's conversation mechanism to support Seam conversations in Trinidad dialogs. Its file name must follow the Trinidad naming convention for this provider type, and it must be located below resources in META-INF/services: File name: org.apache.myfaces.trinidad.PageFlowScopeProvider Contents: It must contain the name and package path of the provider class, for example, trinidad.SeamPageFlowScopeProviderImpl This class is created as an implementation of Trinidad's abstract class PageFlowScopeProvider that can be easily done with Eclipse's comfortable class creation wizard. There are further simplifications: The org.jboss.seam.ui.richfaces package in the resources directory is required for Seam's support of RichFaces, but is obsolete for us and should thus be deleted In the WEB-INF directory, we can carry out the following activities: We can add a folder for Facelet composition components We can simplify the components.xml file by getting rid of persistence declarations such as persistence:managed-persistence-context, persistence:entity-manager-factory, and drools:rule-base declarations (the security we only leave is the one for the identity object) The faces-config must be adapted to suit the Trinidad renderer as described earlier The pages.xml becomes even simpler as we practically avoid it altogether using the dialog framework as described in the navigation section earlier We must modify the web.xml to suit Trinidad's requirements We must add three additional files, namely the trinidad-config.xml, the trinidad-skins.xml, and a taglib.xml to declare the Facelet composition components The *-dev-ds.xml and *-prod-ds.xml files may be emptied of any specific data because no database-backing is used in our test project
Read more
  • 0
  • 0
  • 1423
article-image-linux-e-mail-using-spamassassin
Packt
30 Nov 2009
8 min read
Save for later

Linux E-mail: Using SpamAssassin

Packt
30 Nov 2009
8 min read
Now that SpamAssassin is installed, we need to configure the system to use it. SpamAssassin can be used in many ways. It can be integrated into the MTA for maximum performance; it can run as a daemon or a simple script to avoid complexity; it can use separate settings for each user or use a single set of settings for all users; and it can be used for all accounts or just for the chosen ones. In this article, we will discuss using SpamAssassin in three ways. The first method is with Procmail. This is the simplest method to configure and is suitable for low-volume sites, for example, less than 10,000 e-mails a day. The second method is to use SpamAssassin as a daemon. This is more efficient, and can still be used with Procmail, if desired. The third method is to integrate SpamAssassin with a content filter such as amavisd. This offers performance advantages, but occasionally the content filter does not work with the latest release of SpamAssassin. Problems, if any, are usually resolved quickly. To help you get the most out of SpamAssassin, Packt Publishing has published SpamAssassin: A practical guide to integration and configuration, (ISBN 1-904811-12-4) by Alistair McDonald. Using SpamAssassin with Procmail Before we configure the system to use SpamAssassin, let's consider what SpamAssassin does. SpamAssassin is not an e-mail filter. A filter is something that changes the destination of an e-mail. SpamAssassin adds e-mail headers to an e-mail message to indicate if it is spam or not. Consider an e-mail with headers like this: Return-Path: <user@domain.com>X-Original-To: jdoe@localhostDelivered-To: jdoe@host.domain.comReceived: from localhost (localhost [127.0.0.1])by domain.com (Postfix) with ESMTP id 52A2CF2948for <jdoe@localhost>; Thu, 11 Nov 2004 03:39:42 +0000 (GMT)Received: from pop.ntlworld.com [62.253.162.50]by localhost with POP3 (fetchmail-6.2.5)for jdoe@localhost (single-drop); Thu, 11 Nov 2004 03:39:42 +0000(GMT)Message-ID: <D8F7B41C.4DDAFE7@anotherdomain.com>Date: Wed, 10 Nov 2004 17:54:14 -0800From: "stephen mellors" <gregory@anotherdomain.com>User-Agent: MIME-tools 5.503 (Entity 5.501)X-Accept-Language: en-usMIME-Version: 1.0To: "Jane Doe" <jdoe@domain.com>Subject: nearest pharmacy onlineContent-Type: text/plain;charset="us-ascii"Content-Transfer-Encoding: 7bit SpamAssassin will add header lines. X-Spam-Flag: YESX-Spam-Checker-Version: SpamAssassin 3.1.0-r54722 (2004-10-13) onhost.domain.comX-Spam-Level: *****X-Spam-Status: Yes, score=5.8 required=5.0 tests=BAYES_05,HTML_00_10,HTML_MESSAGE,MPART_ALT_DIFF autolearn=noversion=3.1.0-r54722 SpamAssassin doesn't change the destination of the e-mail, all it does is add headers that enable something else to change the destination of the e-mail. The best indication that an e-mail is spam is the X-Spam-Flag. If this is YES, SpamAssassin considers the mail to be spam and it can be filtered by Procmail. SpamAssassin also assigns a score to each e-mail—the higher the score, the more likely that the e-mail is spam. The threshold that determines if an e-mail is spam can be configured on a system-wide or per-user basis. The default of 5.0 is a sensible default if you are using an unmodified installation of SpamAssassin without any custom rulesets. Global procmailrc file Let's suppose that we want to check all incoming e-mail for spam using SpamAssassin. Commands in the /etc/procmailrc file are run for all users, so executing SpamAssassin here is ideal. The following simple recipe will run SpamAssassin for all users when placed in /etc/procmailrc: :0fw| /usr/bin/spamassassin To place all spam in an individual spam folder, ensure that the global/etc/procmailrc file has a line specifying a default destination. For example: DEFAULT=$HOME/.maildir/ If not, then add a line specifying DEFAULT. To filter spam into a folder, add a recipe similar to the following: * ^X-Spam-Flag: Yes.SPAM/new This assumes that each user has a folder called SPAM already configured. To place all the spam in a single, central folder, use an absolute path to the destination in the recipe: * ^X-Spam-Flag: Yes/var/spool/poss_spam This will place all spam in a single folder, which can be reviewed by the system administrator. As times, regular e-mail may occasionally be wrongly detected as spam, the folder should not be world-readable, which leads to a more generalized statement. SpamAssassin will be run under the system account used by Postfix. This means that the Bayesian database and the auto-whitelists and blacklists will be shared by all users. From a security point of view, it's important that the various databases that SpamAssassin creates are not world-writable. SpamAssassin stores user-specific files in the ~/.spamassassin/ directory. Here is a list of fi les that may be present for a user: //===INSERT TABLE 01=== Some of them may contain confidential data—for example, regular contacts will appear in the auto-whitelist files. Careful use of permissions will ensure that the files are not readable by regular user accounts. Using SpamAssassin on a per-user basis Perhaps some users don't receive spam, or there may be issues with users sharing whitelists and Bayesian databases. SpamAssassin can be run on an individual basis by moving the recipes to the ~/.procmailrc of specific users. This should increase the filtering performance for each user, but increases disk space usage for each user and requires setting up each individual user account by modifying its ~/.procmailrc. A typical user's .procmailrc might look like this: MAILDIR=$HOME/.maildir:0fw| /usr/bin/spamassassin:0* ^X-Spam-Flag: Yes.SPAM/cur As suggested, e-mail may sometimes be wrongly detected as spam. It's worthwhile reviewing spam to ensure that legitimate e-mails have not been wrongly classified. If the user receives a lot of spam, then wading through it all is time consuming, tedious, and error prone. Procmail can filter spam by checking the spam score written in the e-mail headers by SpamAssassin. The low-scoring spam (for example, scoring up to 9) can be placed in one folder called Probable_Spam, while higher scoring e-mails (which are more likely to be spam) can be placed a folder called Certain_Spam. To do this, we use the X-Spam-Level header, which SpamAssassin creates. This is simply the number of asterisks, related to the X-Spam-Level value. By moving e-mail with more than a certain number of asterisks to the Certain_Spam folder, the remaining spam is "Probable Spam". E-mail that is marked with X-Spam-Flag: NO, is obviously not spam. The following .procmailrc file will filter high scoring spam separately from low scoring spam and non spam: MAILDIR=$HOME/.maildir:0fw| /usr/bin/spamassassin:0* ^X-Spam-Level: **************.Certain_Spam/cur:0* ^X-Spam-FLAG: YES.Probable_Spam/cur Using SpamAssassin as a daemon with Postfix A daemon is a background process; one that waits for work, processes it, and then waits for more work. Using this approach actually improves performance (as long as there is sufficient memory) because responsiveness is improved—the program is always ready and waiting and does not have to be loaded each time spam tagging is required. To use SpamAssassin as a daemon, a user account should be added—it's dangerous to run any service as root. As root, enter the following commands to make a user and a group called spam: # groupadd spam# useradd -m -d /home/spam -g spam -s /bin/false spam# chmod 0700 /home/spam To configure Postfix to run SpamAssassin, use SpamAssassin as a daemon. The Postfix master.cf file must be changed. Edit the file and locate the line that begins with 'smtp inet'. Amend the line to add -o content_filter=spamd to the end. smtp inet n - n - - smtpd -o content_filter=spamd Add the following lines to the end of the file: spamd unix - n n - - pipeflags=R user=spam argv=/usr/bin/spamc-e /usr/sbin/sendmail -oi -f ${sender} ${recipient} If the text is spread across several lines, any continuing line must begin with spaces as shown. The changes to the file define a filter called spamd that runs the spamc client for each message and also specifies that the filter should be run whenever an e-mail is received via SMTP. On this line, spamd is the name of the filter and matches the name used in the content_filter line. The user= portion specifies the user context that should be used to run the command. The argv= portion describes the program that should be run. The other flags are used by Procmail and their presence is important. Using SpamAssassin with amavisd-new amavisd-new is an interface between MTAs and content checkers. Despite its name, amavisd-new is a well-established open source package that is well maintained. Content checkers scan e-mail for viruses and/or spam. amavisd-new is slightly different. Just like like spamd, it is written in Perl and runs as a daemon, but instead of accessing SpamAssassin via the spamc or spamassassin clients, it loads SpamAssassin into memory and accesses the SpamAssassin functions directly. It is therefore closely coupled to SpamAssassin and may need to be upgraded at the same time as SpamAssassin. Unlike other Perl-based applications and utilities, amavisd-new is not available from CPAN. However, it is available in source form and RPM form for many distributions of Linux, and is also available for debian-based repositories. Details of versions available are listed on http://www.ijs.si/software/amavisd/#download. We recommend that if the version of SpamAssassin that your distributor offers is up-to-date, then you should use their package of both SpamAssassin and amavisd.
Read more
  • 0
  • 0
  • 2551

article-image-polygon-modeling-handgun-using-blender-3d-249-part-1
Packt
30 Nov 2009
3 min read
Save for later

Polygon Modeling of a Handgun using Blender 3D 2.49: Part 1

Packt
30 Nov 2009
3 min read
With the base model created, we will be able to analyze the shape of our model and evaluate the next steps of the project. We can even decide to make changes to the project because new ideas may appear when we see the object in 3D rather than in 2D. Starting with a background image The first step to start the modeling is to add the reference image as the background of the Blender 3D view. To do that, we can go to the View menu in the 3D view and choose Background Image. The background image in Blender appears only when we are at an orthogonal or Camera view. The background image is a simple black and white drawing of the weapon, but it will be a great reference for modeling. Before we go any further, it's important to point out a few things about the Background Image menu. We can make some adjustments to the image if it doesn't fit our Blender view: Use: With this button turned on, we will use the image as a background. If you want to hide the image, just turn it off and the image will disappear. Blend: The blend slider will control the transparency of the image. If you feel that the image is actually blocking your view of the whole model, making it a bit transparent may help. Size: As the name says, we can control the scale of the image. X and Y offset: With this option, we will be able to move the image in the X or Y axis to place it in a specific location. After clicking on the Use button, just hit the load button and choose the image to be used as a reference. Since you don't have the image used in this example, visit the Packt web site and download the project files from Support. If you've never used a reference image in Blender, it is important to note that the reference images appear only in 3D view when we are using the orthographic view or the camera view mode. It works only in the top, right, left, front, and other orthographic views. If you hit 5 and change the view to perspective, the image will disappear. By using the middle mouse button or the scroll to rotate the view, the image disappears. However, it's still there and we can see the image again by changing the view to an orthogonal or camera view. Make the image more transparent by using the Blend control. It will help in focusing on the model instead of the image. A value of 0.25 will be enough to help in the modeling without causing confusion.
Read more
  • 0
  • 0
  • 3319
Modal Close icon
Modal Close icon