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-overview-joomla-virtuemart
Packt
15 Jun 2011
12 min read
Save for later

An overview of Joomla! and VirtueMart

Packt
15 Jun 2011
12 min read
Navigating through the Joomla! and VirtueMart directories You should have a Joomla! and VirtueMart e-commerce site installed somewhere. If not, you should now install one first before reading on. From this point onward, we will assume that you can access a Joomla! VirtueMart site and can freely browse its content, either on your local computer using the file manager of your operating system or in a web server somewhere using an FTP client program. To work on the exercises, you should also be able to edit each of the files. OK. Let's start our study by navigating through the Joomla! directories. If you look at the root of your Joomla! site, you will be amazed how large the Joomla! project is. There are totally close to 5,000 files under some 350 directories! It would be difficult to find your way through this vast structure of files if there are no hints at all. Fortunately, Joomla! has a very good directory structure and will be easy to follow once you know its basic organization. Knowing your way through this vast structure is very important when embarking on any VirtueMart customization project of considerable size. The good news is that usually we only need to know a very small fraction of those 350 directories and 5,000 files. In the Joomla! root, the most important directories we need to know are the administrator, components, modules, and plugins directories (This does not mean that the other directories are not important. We highlight these few directories just because they are the directories we will reference from time-to-time) You will probably recognize that the last three of these shortlisted directories correspond to the three major extension types of Joomla! So within these directories, we will expect to see a series of subdirectories, each of which corresponds to an extension installed in the Joomla! framework. This is exactly the case, except for the plugins where the directories are arranged in terms of their type instead of their source. Let's take a closer look at one of the most important components that comes with Joomla!. Navigate to the components directory and open the subdirectory com_content. The com_content component is the one that manages articles we created in Joomla!. You have probably been using a lot of this component. Within this directory, you will find a number of files and a few subdirectories. We notice there is a file named controller.php and two subdirectories named models and views. We will have more to say on these in a moment. Let's move back to the root directory and take a look at the last important directory mentioned above. This administrator directory mimics the root directory in many respects. We see that most of the subdirectories we found in the root have a corresponding subdirectory within the administrator directory. For example, we find subdirectories named components and modules within the administrator as well. As we know, there are two main sections of a Joomla! website, also known as the frontend and the backend. The root directory and administrator directory are respectively the location where the frontend and backend files are located. While this dividing line is not rigid, we can use this as a guide when we want to locate a frontend or backend file. Since both the root and the administrator directories contain a subdirectory called components, to avoid ambiguity, we will refer to them as the root components and administrator components directory, respectively. Now, let's work our way a little bit down the directory tree to see how VirtueMart fits into this framework. Within the root components directory, you will see a subdirectory called com_virtuemart. Yes, this is the location where you can find all the files used by VirtueMart for the frontend. Under the com_virtuemart directory, among some other files and subdirectories, you will notice a themes subdirectory. You will find each of the VirtueMart themes you have installed there. The themes directory is the major work area. From now on, we will refer to the com_virtuemart directory under the root components directory as the root VirtueMart directory or the frontend VirtueMart directory. Within the administrator components directory, there is also a subdirectory called com_virtuemart where the backend VirtueMart files are located. Under this main directory, there are four subdirectories named as classes, html, languages, and sql. Obviously, these directories will contain, respectively, the class files, HTML files, language files, and SQL (also known as database) files. Actually, the classes and html directories have a deeper meaning than their names suggest, as we shall see in a moment. Structure of the Joomla! URL path Before leaving our high-level exploration of the Joomla! tree structure, let's digress a little bit to study how a Joomla! URL is built up. While the Joomla! directory structure is so complicated, the URL used to access the site is much simpler. Most of the time, the URL just starts with index.php?. (If you have a Search Engine Friendly or SEF system enabled, you should turn it off during the development and testing of your customization, or at least turn it off mentally while we are talking about the URL. You can turn off SEF in the Joomla! Configuration page.) For example, if we want to access the VirtueMart (frontend) home page, we can use the following URL: http://your_joomla_live_site/index.php?option=com_virtuemart Similarly, the URL http://your_joomla_live_site/administrator/index.php?option=com_virtuemart will bring up the VirtueMart backend control panel, if you're already logged in. All other Joomla! URL, in fact, work in the same way, although many times you see some additional parameters as well. (Don't forget to replace your_joomla_live_site in the above URL with your domain name and the Joomla! root directory, in case the site is not installed in the root.) Actually, the index.php script is the main entry into your Joomla! site. All major requests to the frontend start from here (major requests only since there are some other entry points as well, but they don't bother us at this point). Similarly, all major requests to the backend start from the file administrator/index.php. Restricting the entry point to the site makes it very easy to control authorized and unauthorized accesses. For example, if we want to put the site offline, we can simply change a configuration in Joomla! and all components will be offline as well. We don't need to change each page or even each component one-by-one. Understanding the structure of the Joomla! URL is pretty useful during the development and debugging process. Sometimes we may need to work on a partly live site in which the Joomla! site is already working, but the VirtueMart shop is still under construction. In such cases, it is common to unpublish the menu items for the shop so that the shop is still hidden from the public. The fact that the menu item is hidden actually means the shop is less accessible but not inaccessible. If we want to test the VirtueMart shop, we can still type the URL on the browser by ourselves. Using the URL http://your_joomla_live_site/index.php?option=com_virtuemart we can bring up the VirtueMart home page. We will learn some more tricks in testing individual shop pages along the way of our study of VirtueMart themes and templates. One simple application of what we learnt about the URL can be used when customizing Joomla!. When working with VirtueMart projects, we will need to go to the VirtueMart backend from time-to-time to modify the VirtueMart settings. As we all know, after logging in, what we have on the browser window is the control panel page. We will need to point to the components/virtuemart menu before we can open the VirtueMart backend home. This is not a complicated task, but will be very tedious if repeated every time we log back into the site. Can we make Joomla! smarter, to open the VirtueMart home by default when we log on? Yes, we can. The trick actually relates to what we talked about so far. If you want to customize Joomla! to open the VirtueMart backend by default, you can stay with me for the following warm-up exercise. I understand some of you may not want to change the default login page. Exercise 1.1: Making the Joomla! backend default to VirtueMart Open your favorite text editor. Navigate to the Joomla! site root. Open the file administrator/includes/helper.php. At around line 44 (the actual line may vary from version-to-version), change the code $option = 'com_cpanel'; to $option = 'com_virtuemart'; Save the file. Open your browser and log in to your Joomla! site. Alas, you should see the VirtueMart control panel instead of the Joomla! control panel. This simple exercise demonstrated that sometimes a useful change does not need complex coding. What we need is a little knowledge of how things work. I bet you probably understand what we have done above without explanation. After login, Joomla! will automatically go to the default component, hardcoded in the file helper.php. For standard Joomla!, this will be the com_cpanel component. In Exercise 1.1, we have changed this default backend component from com_cpanel to com_virtuemart. Instead of VirtueMart, we can certainly change the default to other components such as community builder or MOSET. Joomla! 1.5 presentation framework Since VirtueMart is a Joomla! component, it cannot exist outside Joomla!. So before diving into the detail of the VirtueMart engine, it pays to take a brief look at how Joomla! actually works. While an understanding of the presentation framework of Joomla! and VirtueMart may be useful for themes and templates development, it is not essential for the actual customization design. Joomla! emerged from version 1.0 and later developed into 1.5. In this upgrade, Joomla! has been basically rewritten from the ground up. A presentation structure called Model-View-Controller or MVC has been adopted in Joomla! 1.5. While a detailed explanation of the MVC structure is out of the scope, a basic understanding of its working will help us understand why and how VirtueMart 1.1 behaves in the way it is right now. Joomla! is a web application. Each page of Joomla! is in fact a text file consisting of HTML code. Depending on the detail parameters of a web request, Joomla! will generate a dynamic HTML page by combining data stored in the database and site configuration data stored in various PHP files. In the early history of dynamic web pages, program code were written in a way that HTML tags are mixed with presentation logic in one place. The spaghetti code, as it is sometimes called, makes maintenance and extension of the coding very difficult. As the basic structure of a dynamic web page is better understood, more and more new coding patterns emerge to make the life of a web developer easier. The MVC presentation framework is one of those patterns that have been proposed to build computer applications. This framework has gradually become the standard pattern for building web applications and has been adopted by many open source web projects. Models In the MVC presentation framework , the job of building a web page is divided into three main tiers. The backend tier is the data that is stored in the database (strictly speaking, there is no prescribed data storage format though a database is a natural way to manage the data). We need to grab data needed to build the web page. This tier of the job is done by the Model, which describes how data is stored and how data can be retrieved from the data server. Views The frontend tier determines what and how data is presented on the browser. This is the job of the View. For a given dataset from a Model, there can be many different ways to present the data. Let's say, we have a set of statistical data, for example. We can present this data as a bar graph or a pie chart. Each of these presentations is called a View of the same Model. Controllers Now statistical data is just a set of numbers. How can we convert them into a bar graph or a pie chart? That is exactly how the Controller comes into place. A Controller is a routine specifying how to convert the Model into various Views. One major advantage of this separation of data (Model) and presentation (View) makes changes to the application much easier. We can change the presentation independent of the underlying data and vice versa. So, in the Joomla! 1.5 world, we will have a set of Models which interface with the database, a set of Views to tell the browser how to present the data, and a set of Controllers that control how to convert the Model into the View. According to the best practice, all Joomla! 1.5 components should follow this same structure. Thus, each Joomla! 1.5 component should have two subdirectories called models and views. Also, the root directory will contain a controller.php which extends the Joomla! controller's capability. This structure is revealed as we look at the contents of a Joomla! component which we had done previously. However, because of historical reasons and others, not all components follow this best practice. VirtueMart is one of those exceptions.
Read more
  • 0
  • 0
  • 2280

article-image-getting-started-opensso
Packt
13 Jun 2011
8 min read
Save for later

Getting Started with OpenSSO

Packt
13 Jun 2011
8 min read
OpenAM Written and tested with OpenAM Snapshot 9—the Single Sign-On (SSO) tool for securing your web applications in a fast and easy way History of OpenSSO Back in early 2000, Sun Microsystems Inc. started the Directory Server Access Management Edition project to develop a product that would solve the web Single Sign-On (SSO) problems. The initial scope was to just provide authentication and authorization as part of the SSO using a proprietary protocol. Over the years it evolved to become a lightweight pure Java application providing a comprehensive set of security features to protect the enterprise resources. After undergoing a lot of changes in terms of product name, features, among other things, it ended up with OpenSSO. As part of Sun Microsystems software business strategy, they have open sourced most of their commercial enterprise software products including Sun Java Enterprise System (JES), Java SDK, and Communication suite of products. OpenSSO is the term coined by the Sun's access management product team as part of their strategy to open source Sun Java System Access Manager, Sun Java System SAML v2 Plugin for Federation Services, and Sun Java System Federation Manager. OpenSSO is an integrated product that includes the features of both Access and Federation manager products. The goal was to amalgamate the access, federation, and web services features. This goal was achieved when Sun released the OpenSSO Enterprise 8.0 that received strong market traction and analysts coverage. Sun's OpenSSO product made it to the leadership quadrant in 2008 in the Access Management category which was published by the Gartner Analyst group. As part of the open source initiative, a lot of code re-factoring and feature alignments occurred that changed the product's outlook. It removed all the native dependencies that were required to build and deploy earlier. OpenSSO became the pure Java web application that enabled the customers and open source community to take advantage of the automatic deployment by just dropping the web archive on any Java servlet container to deploy it. The build and check-in processes were highly simplified which attracted the open source community to contribute to the code and quality of the product. OpenSSO had a very flexible release model wherein new features or bug fixes could easily be implemented in the customer environment by picking up the nightly, express, or enterprise build. OpenSSO Enterprise 8.0 was a major release by Sun that was built from the open source branch. After this release, there were two other express releases. Those were very feature-rich and introduced Secure Token Service (STS) and OAuth functionality. Express build 9 was not released in the binary form by Oracle but the source code has been made available to the open source community. You can download the OpenAM express build, built using the express build 9 branch from the Forgerock site. As part of the acquisition of Sun Microsystems Inc. by Oracle Corporation that happened back in early 2010, the release and support models have been changed for OpenSSO. If you are interested in obtaining a support contract for the enterprise version of the product, you should call up the Oracle support team or the product management team. Oracle continues its support for the OpenSSO enterprise's existing customers. For the OpenSSO open source version (also known as OpenAM) you can approach the Forgerock team to obtain support. OpenSSO vs. OpenAM OpenSSO was the only open source product in the access management segment that had production level quality. Over eight thousands test cases were executed on twelve different Java servlet containers. OpenSSO is supported by a vibrant community that includes engineers, architects, and solution developers. If you have any questions, just send a mail to users@opensso.dev.java.net, and you are likely get the answer to what you want to know. Recently Forgerock (http://www.forgerock.com) undertook an initiative to keep the community and product strong. They periodically fix the bugs in the open source branch. Their version of OpenSSO is called OpenAM, but the code base is the same as OpenSSO. There may be incompatibilities in future if OpenAM code base deviates a lot from the OpenSSO express build 9 code base. Note that the Oracle Open SSO Enterprise 8.0 update releases are based on the OpenSSO Enterprise release 8.0 code base, whereas the open source version OpenAM is continuing its development from the express build 9 code base. OpenSSO—an overview OpenSSO is a freely available feature-rich access management product; it can be downloaded from http://www.forgerock.com/openam.html. It integrates authentication and authorization services, SSO, and open standards-based federation protocols to provide SSO among disparate business domains, entitlement services, and web services security. Overall, customers will be able to build a comprehensive solution for protecting their network resources by preventing unauthorized access to web services, applications, web content, and securing identity data. OpenSSO offers a complete solution for securing both web applications and web services. You can enforce a comprehensive security policy for web applications and services across the enterprise, rather than relying on developers to come up with ad hoc ways to secure services as they develop them. OpenSSO is a pure Java application that makes it easy to deploy on any operating system platform or container as it supports a broad range of operating systems and servlet containers. OpenSSO services All the services provided by the OpenSSO are exposed over HTTP protocol. The clients access them using appropriate interfaces. OpenSSO exposes a rich library of Application Programming Interfaces (APIs) and Service Provider Interfaces (SPIs) using which, customers can achieve the desired functionality. These services developed for OpenSSO generally contain both a server component and a client component. The server component is a simple Java servlet developed to receive XML requests and return XML responses. The opensso.war web application encompasses all the services and associated configuration items that are required to deliver the OpenSSO functionality. The client component is provided as Java API, and in some cases, C API. This allows remote applications and other OpenSSO services to communicate with and consume the particular functionality. Each core service uses its own framework to retrieve customer and service data and to provide it to other OpenSSO services. The OpenSSO framework integrates all of these service frameworks to form a layer that is accessible to all product components and plugins as shown in the following diagram: There are certain core services that are not covered due to the scope of this article. Just to make you aware of the breadth of features provided by the OpenSSO, in the next few sections, some of the prominent features that are not covered will be briefly introduced. Federation services Typically, in the web access management the Single Sign-On happens in the same company, within the same Domain Name Service (DNS) domain. Most of the time this will work for small companies or in B2C type scenarios, whereas in a B2B scenario use of a DNS domain-based SSO will not work as the cookie will not be forwarded to the other DNS domains. Besides, there are privacy and security concerns to perform SSO across multiple businesses using this approach. So how do we solve these kinds of problems where customers want to seamlessly sign on to services even though the services are provided by a third party? Federation is the solution. So, what is federation? Federation is a process that establishes a standards-based method for sharing and managing identity data and establishing a Single Sign-On across security domains and organizations. It allows an organization to offer a variety of external services to trusted business partners, as well as corporate services to internal departments and divisions. Forming trust relationships across security domains allows an organization to integrate applications offered by different departments or divisions within the enterprise, as well as engage in relationships with co-operating business partners that offer complementary services. Towards the federation or solving SSO across multiple domains, multiple industry standards, such as those developed by the Organization for the Advancement of Structured Information Standards (OASIS) and the Liberty Alliance Project), are supported. OpenSSO provides an open and extensible framework for identity federation and associated web services that resolves the problems of identity-enabling web services, web service discovery and invocation, security, and privacy. Federation services are built on the following standards: Liberty Alliance Project Identity Federation Framework (Liberty ID-FF) 1.1 and 1.2 OASIS Security Assertion Markup Language (SAML) 1.0 and 1.1 OASIS Security Assertion Markup Language (SAML) 2.0 WS-Federation (Passive Requestor Profile) SAML 2.0 is becoming the de facto standard for the federation SAML 2.0 is becoming the de facto standard for the federation SSO as many of the vendors and service providers support SAML 2.0 protocol. For instance Google Apps and Salesforce support SAML 2.0 as their choice of protocol for SSO.
Read more
  • 0
  • 0
  • 5781

article-image-how-scribus-different-other-software
Packt
13 Jun 2011
7 min read
Save for later

How Scribus is Different from Other Software

Packt
13 Jun 2011
7 min read
  Scribus 1.3.5: Beginner's Guide You might be fully interested in free software, may be running Linux or any other system except Apple Mac OS or Microsoft Windows, and in this case, you don't have much choice except for Scribus, Scribus, or Scribus. This is mostly because proprietary equivalent software such as Adobe InDesign or Quark Xpress is not available for Linux-based platforms. Desktop publishing software versus text processors If you have already used layout software before, these arguments are not new to you. However, if you come from any other computer-assisted profession, you may be surprised at the way such software is organized. Especially, most of you would have certainly used text processors such as Microsoft Word, OpenOffice.org Writer, and maybe Microsoft Publisher. Once you go deeper into the details, you'll see how Scribus is different. I've heard many people explain that they were trying Scribus, because they thought or heard it was a better piece of software. Text processors are very qualitative when it's time to handle text (and this is an important point) but not when there is a need to customize a document. Just take a look around: you can identify any magazine or any book collection because of their visual identity, which is made possible by the Desktop Publishing set of software. Could you identify as easily the origin of a Microsoft Word or OpenOffice document? I'm not sure, because all of these documents will be very similar. Generally, you won't use a layout program if you need to save time and work very quickly, because it is not intended to save time, but to let you be as free as possible to create a unique document: the one that will make you change the world, or the one that will help you improve the communication of your company and make it more efficient. Scribus will give you everything to be as productive as possible. However, every time you need to choose a color, every time you need to add a shape, or every time you need to change the text settings, every single little task that you will find yourself doing to get the best graphically designed final document will add to the time taken. This is a very important point if you want your layout project to succeed. I have experienced many projects where people really underestimated the time taken to perform these tasks. To help you create your document, remember that a layout program is not based on text handling, but on the page. In Scribus, the page is an object that you'll be able to manipulate. On the page, you'll add shapes or frames that you'll place precisely, one by one, and each of these will have their own properties. Especially in a layout program, images are drastically apart from the text, whereas in a text processor both will be in the same flow. This again results in a different way of considering the elements you will have and may change the way you work. This is for the best, and once you get used to this, once you have the major but quite simple software possibilities integrated, and once you have the print process specificities in your work, you'll be more free than you've ever been to create a unique document. This document will be the result of your own creativity and not only the default settings defined by a product or another. To InDesign and Xpress users If you've already used a layout program, you will certainly have questions such as: Is this software as good as mine? Can I import what I've done with my actual software so that I won't have to do everything again? Will I have many things to learn to be as productive as I actually am? For the first question, Scribus is in some ways very good and has very original features but in some other ways it is less than perfect. The real question is: what do you already use in the software you have and does Scribus have it? I used to be an Xpress teacher and I've often met graphic designers who don't even use styles or master page and Scribus has it. Scribus can use spot color, set bleeds, and many other features required. As an answer to the second question I could simply say "No"—mainly "No". As far as I know, it's always the tricky part in whatever software you use. Scribus will soon be able to import Xpress tags and IDXML, but it is still in development and is actually not usable; if you use Microsoft Publisher, there is really no way. As for the last question, I don't think there are so many things to learn. Scribus has an original user interface but can be inspired by some de facto standards. And mainly, the principles are the same in Scribus and in InDesign or Xpress. Of course, you will use some of your habits, but in two or three days of Scribus testing, everything will be perfect again and you'll feel comfortable with it. Shortcuts will certainly be the most difficult to learn. Xpress users, especially, use them a lot and even InDesign users use them for text handling. Scribus shortcut defaults are much simpler. You can use the Keyboard Shortcuts category of Preferences to change them. Simply select the function for the shortcut you want to change in the Action list, click on the User Defined Key option, click on the Set Key button, and perform the shortcut you'd like to assign. If it is already being used, you won't be able to assign it unless you find where it is assigned and erase it. Applying master pages: In Scribus, unlike in InDesign, the left-hand side master page can be applied to a right-hand side page. Scribus never automates the way master pages are applied, except when creating the document. So, if you're confused by that, don't worry; you'll be able to do what you want even if you have chosen the bad side. Frame conversion and text to outlines: In Scribus, frames are central. Adobe InDesign, in some ways tries to avoid them by using a single tool for text edit and text frame, and at the same time it can import pictures without requiring a frame. But in any case, a frame is made even if automatically. Another good feature with Scribus frames is that they can easily be converted to any other kind of frame. So, if you created a Text Frame and want to put an image into it, you can still do so without deleting and drawing a new frame. This is very important because the default frame shape is set to rectangle and cannot be changed. Importing several pictures In Scribus, it is actually impossible to import several pictures (as it can be done in InDesign) at once. This can be done with Scribus Python scripting. There are already some scripts for this on the Scribus wiki at http://wiki.scribus.net. Check for the script that suits your needs. Summary In this article we saw how Scribus is different from other kinds of software. Further resources on this subject: Scribus: Managing Colors [Article] Scribus: Importing Images [Article] Scribus: Creating a Layout [Article] Working with Colors in Scribus [Article] Scribus: Manipulate and Place Objects in a Layout [Article]
Read more
  • 0
  • 0
  • 10440

article-image-securing-your-jira-4
Packt
10 Jun 2011
13 min read
Save for later

Securing your JIRA 4

Packt
10 Jun 2011
13 min read
JIRA 4 Essentials Track bugs and issues and manage your software development projects with JIRA Before we delve into the deep end of how JIRA handles security, let's first take a look at how user memberships are managed. Users In any information system, for users to access the system, they need to have an account. In JIRA, each user needs to have their own user account for them to access the data. Each user is identified by their username, which cannot be changed after account creation. User Browser JIRA administrators can manage users centrally from the User Browser. Log into JIRA as a JIRA Administrator. Click on Administration from the top menu bar. Select User Browser from the left panel to bring up the User Browser page. From the User Browser, you will be able to see a list of all the users in JIRA. The User Browser also provides you with search capabilities. You will be able to search for users that fit criteria such as username, full name, e-mail address, and group association. By default, the results will be paginated to show twenty users per page, but you can change this setting to show up to one hundred users per page. When dealing with large deployments with hundreds of users, these options will become extremely useful to quickly find the users you need to manage. Other than the ability for you to effectively search for users, the User Browser also serves as the portal for you to add new users to JIRA, and manage user's group/role associations. Adding a user There are two ways for new user accounts to be created in JIRA. The first option is to have centralized management where only the JIRA administrators can create and maintain user accounts. This option is applicable to most private JIRA instances designed to be used by an organization's internal users. The second option is to allow users to sign up for accounts themselves; this is most useful when you are running a public JIRA instance where manually creating user accounts is not feasible because of the volume of work. We will be looking at how to enable public signup options in later sections, for now we will examine how administrators can create user accounts manually. Browse to the User Browser page. Click on the Add User link. This will bring you to the Create New User page. Provide a unique username for the new user. The username cannot be changed once it is set. Specify the password, full name, and e-mail address for the user. Optionally check the Send Password Email option if you have a SMTP server configured for JIRA. If checked, JIRA will send an e-mail to the user with a link for them to reset their password. Click on the Create button to create the new user. Enabling public signup If your JIRA instance is public, for example, as a public support system, creating user accounts individually as explained earlier will become a very demanding job for your administrator. For this type of JIRA setup, you can enable public signup to allow users create accounts themselves. To enable public signup in JIRA: Log into JIRA as a JIRA Administrator. Click on Administration from the top menu bar. Select General Configuration from the left panel to bring up the General Configuration page. Click on the Edit Configuration link at the bottom of the page. Select Public for the Mode field. Click on the Update button to apply the setting. Once you have set JIRA to run in the Public mode, users will be able to sign up and create their own accounts from the login page. As we will see in the later section, Global Permissions, once a user has signed up for a new account, he/she will automatically join groups with JIRA users' global permission. If you have set JIRA to run in Private mode, only the administrator will be able to create new accounts. Enabling CAPTCHA If you are running JIRA in Public mode, you run the risk of having automated spam bots creating user accounts on your system. To counter this, JIRA provides the CAPCHA service where potential users will be required to type in a word represented in an image into a text field. To enable CAPTCHA service: Browse to the General Configuration page. Click on the Edit Configuration link at the bottom of the page. Select On for CAPTCHA on signup. Click on the Update button to apply the setting. Now when someone tries to sign up for an account, JIRA will present them with a CAPTCHA challenge that must be verified before the account is created. Groups Groups are a common way of managing users in any information system. A group often represents a collection of users, usually based on their positions and responsibilities within the organization. In JIRA, groups provide an effective way to apply configuration settings to users, such as permissions and notifications. Groups are global in JIRA, which is something that should not be confused with Project Roles (discussed later). This means if you belong to the jira-administrators group, you will always be in that group regardless of which project you are accessing. We will see in later sections how this is different from project roles and their significance. One important point to keep in mind is that a group association does not cascade in JIRA. For example, just because a user is in the jira-developers group does not mean he/she will have the privileges of the jira-users group. Group Browser JIRA administrators can manage groups centrally from the Group Browser. Log into JIRA as a JIRA Administrator. Click on Administration from the top menu bar. Select Group Browser from the left panel to bring up the Group Browser page. Similar to the User Browser, the Group Browser allows you to search, add, and configure groups within JIRA. JIRA comes with three default groups. These groups are created automatically when you install JIRA. Out of the three groups, jira-administrators and jira-users are of most significance. As we will see later in this chapter, by default, jira-administrators are given the global permission to administer JIRA while jira-users are only given permission to access JIRA. You can, as we will learn, change this default behavior so your custom groups have the same permissions. Adding a group Other than the three groups that come by default with JIRA, you can create your own groups. It is important to note that once you have created a group, you cannot change its name. Make sure you think about the name of the group carefully before you create it. Browse to the Group Browser page. Specify a unique name of the new group in the Add Group section. Click on the Add Group button to create the new group. After a group has been created, it is empty and will have no members. It will also have no configuration settings such as the permissions applied. Editing group membership It is often that people move around within an organization, and JIRA needs to be kept up-to-date with the movement. From the Group Browser, there are two ways to manage group membership. The first option is to manage the membership on per-group level, and the second option is to manage several groups at the same time. Both options are actually very similar, so we will be covering both at the same time. To manage individual groups: Browse to the Group Browser page. Click on the Edit Members link for the group you wish to manage the member for. This will bring you to the Bulk Edit Group Members page. To manage multiple groups: Browse to the Group Browser page. Click on the Bulk Edit Group Member link. This will bring you to the Bulk Edit Group Members page. You will notice that both options will take you the same page. The difference is if you have chosen the individual group option, JIRA will auto select the group to update, and if you have chosen the bulk edit option, no groups will be selected. However, regardless of which option you have chosen, you can still select one or all of the groups to apply your changes to. To update the membership in one or more groups: Browse to the Bulk Edit Group Members page. Select one or more groups to update. Select users from middle box and click on the Leave button to take users out of the groups. Specify users (by typing usernames) in the right-hand box and click on the Join button to add users into the groups. Deleting a group If a group has become redundant, you can remove it from JIRA. Browse to the Group Browser page. Click on the Delete link of the group you wish to remove. This will take you to the Delete Group page. Click on the Delete button to permanently remove the group. Once you have removed the group, it will automatically remove all the users who previously belonged to it. Project roles As we have seen, groups are collections of users and are applied globally. JIRA offers another way of grouping users, which is applied on the project level only. Project role browser Similar to users and groups, project roles are maintained centrally by the JIRA administrator through the Project Role Browser. There is a slight difference however, since project roles are specific to projects, JIRA administrators only define what roles are available in JIRA and their default members. Each project's administrators (discussed in later sections) can further define each role's membership for their own projects, overriding the default assignment. We will first look at what JIRA administrators can control through the Project Role browser and then look at how project administrators can fine-tune the membership assignment later. To access the Project Role Browser: Log into JIRA as a JIRA Administrator. Click on Administration from the top menu bar. Select Project Role Browser from the left panel to bring up the Project Role Browser page. Adding a project role type The list of project roles is managed by the JIRA administrator. As an administrator, you can create new role types which can then be used by project administrators for their projects. To create a new project role: Browse to the Project Role Browser page. Specify a unique name for the new project role in the Add Project Role section. Specify an optional description. Click on the Add Project Role button to create the project role. Once you have added a new project role, it will appear for all the projects. Editing a project role You can update a project role's name and description. Browse to the Project Role Browser page. Click on the Edit link for the project role you wish to update. This will take you to the Edit Project Role page. Specify a new name and description. Click on the Update button to apply the changes. Deleting a project role Existing project roles can be deleted if they are no longer used. Browse to the Project Role Browser page. Click on the Delete link of the project role you wish to remove. This will bring up the Delete Project Role page. Click on the Delete button to remove the project role. Managing default members As new projects are created in JIRA, often those projects share a similar security requirement. It becomes desirable to have default members assigned to the project roles when new projects are created. For example, by default, users in the jira-administrators group will have the Administrators project role. This increases the efficiency of security setup by creating a baseline for new projects, but also offers the flexibility to allow modifications to the default setup to cater for unique requirements. Browse to the Project Role Browser page. Click on the Manage Default Members link for the project role you wish to remove. This will take you to the Edit Default Members for Project Role page. From this page, you will see all the default members assigned to the selected project role. Default members can be logically assigned project roles based on group setup. Users can be useful when you have exceptional cases, such as a lead developer who should have the Developers role in all software development projects. To add a default user/group for the project role: Click on the Edit link for the default member option (either user or group). Use the user picker/group picker function to select the users/groups you wish to assign to the project role. Click on the Add button to assign the role. Once added, any new project created will have the specified users/groups assigned to the project role. It is important to note that after you have set default members, only new projects will have the settings applied. Existing projects will not retrospectively have the default members applied. Default members is an efficient way for JIRA administrators to assign project role members automatically without having to manually manage it for each new project as they come in. After a project has been created, it becomes the responsibility of the project administrator to maintain the project's role membership, which we will be looking at in the next section. Assigning project role members JIRA allows you to assign default members to projects when they are created. This might be sufficient for most projects when they start, but changes will often need to be made due to staff movements throughout the project life cycle. It is possible for the JIRA administrator to continue maintaining each project's membership, but it can easily become an overwhelming task. In most cases, since project roles are specific to each project, it makes sense to delegate this responsibility to the owner of each project. In JIRA, an owner of a project is someone with the Administrators Projects permission. By default, members of the Administrators project role will have this permission. We will see how to manage JIRA's permissions in the later sections. As a project administrator, you will be able to assign members to the various project roles for your project. You can assign roles from the project administration page. Log into JIRA as a user with Administrators project role for one or more projects. (By default, members of the jira-administrators group will have this role). Click on Administration from the top menu bar. Select the project you wish to manage the role members for. This will bring you to the Project Administration page. Click on the View Members link next to Project Roles. This will bring you to the Manage Project Role Membership page. Click on the Edit link for either Users or Groups for the project role you wish to configure. This will take you to the Assign Users/Groups to Project Role page. Use the user/group picker to search and select users/groups to assign to the project role. Click on the Add button. The users and groups assigned to the project role will be for the current project only. You will have to reconfigure the members again for other projects. This way, project role members are maintained separately for each project.
Read more
  • 0
  • 0
  • 14994

article-image-wordpress-3-security-apache-modules
Packt
10 Jun 2011
6 min read
Save for later

WordPress 3 Security: Apache Modules

Packt
10 Jun 2011
6 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) IP deny with mod_access Apache offers a sure-fire way to lock down admin, care of the mod_access module. Similar to cPanel's IP Deny Manager, the greater flexibility of hand-coding empowers us to allow or deny all but specified IP addresses, domains, hosts, and networks. For now, we'll prevent access to the wp-admin directory pages for all IPs except yours. Open an htaccess file in your wp-admin directory via your control panel or the terminal: nano /path/to/WP-root/wp-admin/.htaccess Add these lines, swapping the IP for yours: order deny,allowdeny from allallow from 123.45.67.890 Need access from more IPs? Just add more alongside the first one, single space separated. But. If your IP address is dynamic, which very often it is, you may find this method a little too effective. If you do become locked out, cruise server-side to switch the IP. What is my IP? That old chestnut: whatismyip – http://whatismyip.com IP spoofing A chestnut gone bad, denying alone won't protect against man-in-the-middle attacks, so if you got this farthinking that you could have avoided all the SSL stuff after all, no, you were right to do that. No safeguard is a silver bullet. Deny syntax sure helps though, if you're not on the move.   Password protect directories Password protection is a way to give access to a directory and its sub-tree to a selected few people and may be used, typically: To house private files to which you need access from anywhere By developers fine-tuning a new blog theme For a client zone on a commercial site As an extra layer of protection to, say, wp-login or phpMyAdmin The procedure is to choose a directory, granting access to specified users. These privileged directory users are separate from, and should not be confused with, your server or WordPress users, the control being governed by Apache rather than by Linux or your WordPress database. That's a good thing, adding an independent tier of protection. cPanel's Password Protect Directories There are various ways to secure a directory, so let's start off with the regular control panel option, which in cPanel, is called Password Protect Directories: Browse to the target directory in File Manager, right-clicking and choosing Password Protect (or click through the panel icon if you like). Select the checkbox and give the directory a name to appear on the authentication screen. Save and you are redirected to a confirmation page. Click back to the previous page and add a username and password to access the folder. Save the newly authorized user. Now you can surf to that folder or some file within, are asked for credentials, and can log in. So what did we really just do there? Clicked on some shiny icons, added some details, and cPanel interacted a bit over far too many pages. Let's get geeky, it's worth it.   Authentication with mod_auth When we protect a folder, cPanel uses Apache's mod_auth module to amend or create two hidden files, htaccess and passwd. htaccess lives in the folder to protect and passwd lives safely above the web root in the hush-hush htpasswd directory. Using an example file, we can compare our control panel actions with those using the terminal, interacting directly with mod_auth. Cue screenshots, using cPanel we did this: And mod_auth creates the ruleset in the htaccess file, which we equally could just type: AuthType BasicAuthName "Protect me pretty please"AuthUserFile "/home/USERNAME/.htpasswds/public_html/protectme/passwd"Require valid-user Then we did this: And mod_auth yawns a bit while it adds credentials to a password file: johndoe:L9c7m/hO16slA (John's password is encrypted, server-side, but he logs in using the plaintext hackth!s.) Now then. Two points. First, with the syntax learnt or duplicated, it's quicker to bin the middleman and just use the shell. More importantly, by directly chatting up Apache, we have a better array of security tools. To clarify, let's take this a step at a time. The htaccess file Before we look at the mod_auth syntax that goes in htaccess files, a quick aside ... A quick shout out to htaccess, bless We've met the hidden htaccess file already. It's essentially a convenient and versatile web configuration file that can be added to multiple directories. The directives these files contain can equally be placed in other types of files such as those for our virtual hosts (which is tidier, all those directives from htaccess files being in one place). Uniquely, however, rules added in htaccess can be parsed immediately, or in other words, without the need to restart Apache. Feel the power! One other thing about htaccess: you don't need root access to add or edit these files. Listen up, shared hosting people, this is very convenient because you don't have root access (to hack into your co-sharers directories!) to those configuration files, but you do have access to your own jailed (or chroot-ed) web files. And because htaccess files live with your files, you can tweak them at will. Now back to using htaccess to store that mod_auth syntax ... In this case, for any directory you want to protect, just add or append an htaccess file with your tailored mod_auth directives. Here's a closer look at the mod_auth syntax, beginning with its type: AuthType Basic Pretty basic then and more on that later. For when we navigate to the login page we want some kind of instructional message: AuthName "Protect me pretty please" Now the link to the directory's corresponding password file: AuthUserFile "/home/USERNAME/.htpasswds/public_html/DIRECTORY-TOPROTECT/passwd" And we'll specify to give access only to users recorded in the password file: Require valid-user So far so good. Carry on. The passwd file Often referred to as the htpasswd file, here's the syntax it houses: johndoe:L9c7m/hO16slA johndoe is the authorized, or required user. L9c7m/hO16slA is the encrypted form of hackth!s , his password. We use a handy tool, also called htpasswd, to encrypt that. Add as many usernames and passwords as you like to this file, each on a new line. The file itself can live and be called whatever you like as long as the AuthUserFile directive corresponds. One thing though: the file should be located above your web root.  
Read more
  • 0
  • 0
  • 2013

article-image-article-packt-technology-books-kindle
Packt
10 Jun 2011
1 min read
Save for later

Packt Books are Now Available in Kindle Format on Amazon + Win a Kindle!

Packt
10 Jun 2011
1 min read
If you’re one of the millions of Kindle users out there you’ll be pleased to hear that Packt’s entire catalogue of technology books is now available to purchase in Kindle format from Amazon, and with over 540 titles available you'll be spoilt for choice.   Whether its Moodle or Microsoft you can now download your Packt book from Amazon and refer to it quickly and easily wherever you are, learning has never been easier.   Packt's current best-selling Kindle books include:   And if you don't yet own a Kindle, well now's your opportunity to take full advantage of this milestone with: Packt's Kindle Competition   Simply identify the key pictured at the top and send your answers A, B, C, or D to KindleComp@PacktPub.com, all correct answers will then be entered into a prize draw to win a Kindle                                                  
Read more
  • 0
  • 0
  • 4660
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-adf-proof-concept
Packt
10 Jun 2011
12 min read
Save for later

The ADF Proof of Concept

Packt
10 Jun 2011
12 min read
Oracle ADF Enterprise Application Development—Made Simple Successfully plan, develop, test and deploy enterprise applications with Oracle ADF You can compare the situation at the start of a project to standing in front of a mountain with the task to excavate a tunnel. The mountainsides are almost vertical, and there is no way for you to climb the mountain to figure out how wide it is. You can take two approaches: You can either start blasting and drilling in the full width of the tunnel you need You can start drilling a very small pilot tunnel all through the mountain, and then expand it to full width later It's probably more efficient to build in the full width of the tunnel straight from the beginning, but this approach has some serious disadvantages as well. You don't know how wide the mountain is, so you can't tell how long it will take to build the tunnel. In addition, you don't know what kind of surprises might lurk in the mountain—porous rock, aquifers, or any number of other obstacles to your tunnel building. That's why you should build the pilot tunnel first—so you know the size of the task and have an idea of the obstacles you might meet on the way. The Proof of Concept is that pilot tunnel. The very brief ADF primer Since you have decided to evaluate ADF for your enterprise application, you probably already have a pretty good idea of its architecture and capabilities. Therefore, this section will only give a very brief overview of ADF—there are many whitepapers, tutorials, and demonstrations available at the Oracle Technology Network website. Your starting point for ADF information is http://otn.oracle. com/developer-tools/jdev/overview. Enterprise architecture A modern enterprise application typically consists of a frontend, user-facing part and a backend business service part. Frontend The frontend part is constructed from several layers. In a web-based application, these are normally arranged in the common Model-View-Controller (MVC) pattern as illustrated next: The View layer is interacting with the user, displaying data as well as receiving updates and user actions. The Controller layer is in charge of interpreting user actions and deciding which screens are presented to the user in which order. And the Model layer is representing the backend business services to the View and Controller, hiding the complexity of storing and retrieving data. This architecture implements a clean separation of duties— the page doesn't have to worry about where to go next, because that is the task of the controller. And the controller doesn't have to worry about how to store data in the data service, because that is the task of the model. Other Frontends An enterprise application could also have a desktop application frontend, and might have additional frontends for mobile users or even use existing desktop applications like Microsoft Excel to interact with data. In the ADF technology stack, all of these alternative frontends interact with the same model, making it easy to develop multiple frontend applications against the same data services. Backend The backend part consists of a business service layer that implements the business logic and provide some way of accessing the underlying data services. Business services can be implemented as API code written in Java, PL/SQL or other languages, web services, or using a business service framework such as ADF Business Components. Under the business services layer there will be a data service layer actually storing persistent data. Typically, this is based on relational tables, but it could also be XML files in a file system or data in other systems accessed through an interface. ADF architecture There are many different ways of building applications with Oracle Application Development Framework, but Oracle has chosen a modern SOA-based architecture for Oracle Fusion Applications. This brand new product has been built from the ground up as the successor to Oracle E-Business Suite, Siebel, PeopleSoft, J.D. Edwards and many other applications Oracle has acquired over the last couple of years. If it is good enough for Oracle Fusion Applications, arguably the biggest enterprise application development effort ever undertaken by mankind, it is probably good enough for you, too. Oracle Fusion Applications are using the following parts of the ADF framework: ADF Faces Rich Client (ADFv), a very rich set of user interface components implementing advanced functionality in a web application. ADF Controller (ADFc), implementing the features of a normal JSF controller, but extended with the possibility to define modular, reusable page flows. ADFc also allows you to declare transaction boundaries so one database transaction can span many pages. ADF binding layer (ADFm), standard defining a common backend model that the user interface can communicate with. ADF Business Components (ADFbc), a highly productive, declarative way of defining business services based on relational tables. You can see all of these in the following figure: There are many ways of getting from A to B—this article is about travelling the straight and well-paved road Oracle has built for Fusion Applications. However, other routes might be appropriate in some situations: You could build the user interface as a desktop application using ADF Swing components, you could use ADF for a mobile device, or you could use ADF Desktop Integration to access your data directly from within Microsoft Excel. Your business services could be based on Web Services, EJBs or many other technologies, using the ADF binding layer to connect to the user interface. Entity objects and associations Entity objects (EOs) takes care of object-relational mapping: Making your relational tables available to the application as Java objects. Entity objects are the base that view objects are built on, and all data modifications go through the entity object. You will normally have one entity object for every database table or database view your application uses, and this object is responsible for producing the correct SQL statements to insert, update or delete in the underlying relational tables. The entity objects helps you build scalable and well-performing applications by intelligently caching records on the application server in order to minimize the load the application places on the database. Like entity objects are the middle-tier reflection of database tables and database views, Associations are the reflection of foreign key relationships between tables. An association represents a connection between two entity objects and allows ADF to relate data in one entity object with data in another. JDeveloper is normally able to create these automatically by simply inspecting the database, but in case your database does not contain foreign keys, you can build associations by hand to tell ADF about the relationships in your data. View objects and View Links While you do not really need to make any major decisions when building the entity objects for the Proof of Concept, you do need to consider the consumers of your business services when you start building view objects—for example, what information you would display on a screen. View objects are typically based on entity objects and you will be using them for two purposes: To provide data for your screens To provide data for lists of values (LOVs) The data handling view objects are normally specific for each screen or business service. One screen can use multiple view objects—in general, you need to create one view object for each master-detail level you wish to display on your screen. One view object can pull together data from several entity objects, so if you just need to retrieve a reference value from another table, you do not need to create a separate view object for this. The LOV view objects are used for drop-down lists and other selections in your user interface. They will typically be defined as read-only and because they are reusable, you will define them once and re-use them everywhere you need a drop-down list on a specific data set. View Links are used to define the relationships between the view objects and are typically based on associations (again often based on foreign keys in the database). The following figure shows an example of two ways to display the data from the familiar EMP and DEPT tables. The left-hand illustration shows a situation where you wish to display a department with all the employees of the department in a master-detail screen. In this case, you create two view objects connected by a view link. The right-hand illustration shows a situation where you wish to display all employees, together with the name of the department where they work. In this case, you only need one view object, pulling together data from both the EMP and DEPT tables through the entity objects. Application modules Application modules encapsulate the view object instances and business service methods necessary to perform a unit of work. Each application module has its own transactional context and holds its own database connection. This means that all of the work a user performs using view objects from one application module is part of one database transaction. Application modules can have different granularity, but typically, you will have one application module for each major piece of functionality. If your requirements are specified with use cases, there will often be one application module for each major use case. However, multiple use cases can also be grouped together into one application module – indeed, it is possible to build a small application using just one application modules. Application modules for Oracle Forms If you come from an Oracle Forms background and are developing a replacement for an Oracle Forms application, your application will often have a relatively small number of complex, major Forms, and larger number of simple data maintenance Forms. You will often create one Application Module per major Form, and a few application modules that each provide data for a number of simple Forms. If you wish, you can combine multiple application modules inside one root application module. This is called nesting and allows several application modules to participate in the transaction of the root application module. This also saves database connections because only the root application module needs a connection. The ADF user interface The preferred way to build the user interface in an ADF enterprise application is with JavaServer Faces (JSF). JSF is a component-based framework for building webbased user interfaces that overcome many of the limitations of earlier technologies like JavaServer Pages (JSP). In a JSF application, the user interface does not contain any code, but is instead built from configurable components from a component library. For your application, you will want to use the sophisticated ADF 11g JavaServer Faces (JSF) component library, known as the ADF Faces Rich Client. There are other JSF component libraries—for example, the previous version of the ADF Faces components (version 10g) has been released by Oracle as Open Source and is now part of the Apache MyFaces Trinidad project. But for a modern enterprise application, use ADF Faces Rich Client. ADF Task Flows One of the great improvements in ADF 11g was the addition of ADF Task Flows. It had long been clear to web developers that in a web application, you cannot just let each page decide where to go next—you need the controller from the MVC architecture. Various frameworks and technologies have implemented controllers (both the popular Struts framework and JSF has this), but the controller in ADF Task Flows is the first controller capable of handling large enterprise applications. An ADF web application has one Unbounded Task Flow where you place all the publicly accessible pages and define the navigation between them. This corresponds to other controller architectures. But ADF also has Bounded Task Flows, which are complete, reusable mini-applications that can be called from the unbounded task flow or from another bounded task flow. A bounded task flow has a well-defined entry point, accepts input parameters and can deliver an outcome back to the caller. For example, you might build a customer management task flow to handle customer data. In this way, your application can be built in a modular fashion—the developers in charge of implementing each use case can define their own bounded task flow with a well-defined interface for others to call. The team building the customer management task flow is thus free to add new pages or change the navigation flow without affecting the rest of the application. ADF pages and fragments In your task flows, you can define either pages or page fragments. Pages are complete web pages that you can run on their own, while page fragments are reusable components that you place inside regions on pages. An enterprise application will often have a small number of pages (possibly only one), and a larger number of page fragments that dynamically replace each other inside a region. This design means that the user does not see the whole browser window redraw itself—only parts of the page will change as one fragment is replaced with another. It is this technique that makes an ADF application seem more like a desktop application than a traditional web application. On your pages or page fragments, you add content using layout components, data components and control components: The layout components are containers for other components and control the screen layout. Often, multiple layout components are nested inside each other to achieve the desired layout. The data components are the fields, drop-down lists, radio buttons and so on that the user interacts with to create and modify data. The control components are the buttons and links used to perform actions in an ADF application.
Read more
  • 0
  • 0
  • 5145

article-image-cocoa-and-objective-c-handling-events
Packt
09 Jun 2011
8 min read
Save for later

Cocoa and Objective-C: Handling events

Packt
09 Jun 2011
8 min read
Some recipes in this article require Mac OS X Snow Leopard 10.6. The Trackpad preferences allow you to easily adjust many gestures that will used in the following recipes. To make sure that your trackpad is recognizing gestures, make sure that you have set the correct preferences to enable gesture support under the Trackpad System Preference. Interpreting the pinch gesture The pinch gesture is a gesture normally used for the zooming of a view or for changing the font size of text. In this recipe, we will create a custom view that handles the pinch gesture to resize a custom view. Getting ready In Xcode, create a new Cocoa Application and name it Pinch. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, Add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next, we need to add the code to handle the pinch gesture. Add the following method to the MyView class implementation: - (void)magnifyWithEvent:(NSEvent *)event { NSSize size = [self frame].size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; } Choose Build and Run from Xcode's toolbar to run the application. How it works... In our drawRect: method, we use Cocoa to draw a simple rounded rectangle with a three point wide gray stroke. Next, we implement the magnifyWithEvent: method. Because NSView inherits from NSResponder, we can override the magnifyWithEvent: method from the NSResponder class. When the user starts a pinch gesture, and the magnifyWithEvent: method is called, the NSEvent passed to us in the magnifyWithEvent: method which contains a magnification factor we can use to determine how much to scale our view. First, we get the current size of our view. We add one to the magnification factor and multiply by the frame's width and height to scale the view. Finally, we set the frame's new size. There's more... You will notice when running the sample code that our view resizes with the lower-left corner of our custom view remaining in a constant position. In order to make our view zoom in and out from the center, change the magnifyWithEvent: method's code to the following: NSSize size = [self frame].size; NSSize originalSize = size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; CGFloat deltaX = (originalSize.width - size.width) / 2; CGFloat deltaY = (originalSize.height - size.height) / 2; NSPoint origin = self.frame.origin; origin.x = origin.x + deltaX; origin.y = origin.y + deltaY; [self setFrameOrigin:origin]; Basically, what we have done is moved our custom view's origin by the difference between the original size and the new size. Interpreting the swipe gesture The swipe gesture is detected when three or more fingers move across the trackpad. This gesture is often used to page through a series of images. In this recipe, we will create a custom view that interprets the swipe gesture in four different directions and displays the direction of the swipe in our custom view: Getting ready In Xcode, create a new Cocoa Application and name it Swipe. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, open the MyView.h file and add the direction variable to the class interface: NSString *direction; Open the MyView.m file and add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; if (direction == nil) { direction = @""; } NSAttributedString *string = [[[NSAttributedString alloc] initWithString:direction] autorelease]; NSPoint point = NSMakePoint(([self bounds].size.width / 2) - ([string size].width / 2), ([self bounds].size.height / 2) - ([string size].height / 2)); [string drawAtPoint:point]; Add the following code to handle the swipe gesture: - (void)swipeWithEvent:(NSEvent *)event { if ([event deltaX] > 0) { direction = @"Left"; } else if ([event deltaX] < 0) { direction = @"Right"; } else if ([event deltaY] > 0) { direction = @"Up"; } else if ([event deltaY] < 0){ direction = @"Down"; } [self setNeedsDisplay:YES]; } In Xcode, choose Build and Run from the toolbar to run the application. How it works... As we did in the other recipes in this article, we draw a simple rounded rectangle in the drawRect: method of the view. However, we will also be drawing a string denoting the direction of the swipe in the middle of our view. In order to handle the swipe gesture, we override the swipeWithEvent: method from the NSResponder class which NSView inherits. By inspecting the values of deltaX and deltaY of the NSEvent passed into the swipeWithEvent: method, we can determine the direction of the swipe. We set the direction string with the direction of the swipe so we can draw it in the drawRect: method. Finally, we call setNeedsDisplay:YES to force our view to redraw itself. There's more... You might have noticed that we do not need to override the acceptsFirstResponder: method in our view in order to handle the gesture events. When the mouse is located within our view, we automatically receive the gesture events. All we need to do is implement the methods for the gestures we are interested in. Interpreting the rotate gesture The rotate gesture can be used in any number of ways in a custom view. From rotating the view itself or simulating a rotating dial in a custom control. This recipe will show you how to implement the rotate gesture to rotate a custom view. Using your thumb and index finger, you will be able to rotate the custom view around its center: Getting ready In Xcode, create a new Cocoa Application and name it Rotate. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next we need to add the code to handle the rotate gesture. Add the following method to the MyView class implementation: - (void)rotateWithEvent:(NSEvent *)event { CGFloat currentRotation = [self frameCenterRotation]; [self setFrameCenterRotation:(currentRotation + [event rotation])]; } Choose Build and Run from Xcode's toolbar to test the application. How it works... As we did in the previous recipe, we will create a simple rounded rectangle with a three-point stroke to represent our custom view. Our custom view overrides the rotateWithEvent: method from NSResponder to handle the rotation gesture. The rotation property of the NSEvent passed to us in the rotateWithEvent: contains the change in rotation from the last time the rotateWithEvent: method was called. We simply add this value to our view's frameCenterRotation value to get the new rotation. There's more... The value returned from NSEvent's rotation will be negative when the rotation is clockwise and positive when the rotation is counter-clockwise.
Read more
  • 0
  • 0
  • 4401

article-image-how-build-rss-reader-windows-phone-7
Packt
09 Jun 2011
10 min read
Save for later

How to Build a RSS Reader for Windows Phone 7

Packt
09 Jun 2011
10 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Security in SharePoint 2010 We begin this article with a discussion on security for a very simple reason: security in SharePoint is tricky. In addition to that one very simple reason, authenticating users against SharePoint from within a Windows Phone 7 client application is even trickier. In this article, the example RSS reader that we develop will only use anonymous access to the RSS feeds in SharePoint. Setting up anonymous access is very simple and we'll walk through the steps here. When writing this article, I came across a lot of errors on my testing server, but not my development server. After a couple of days of unsuccessful web searches and reinstalling different components, I discovered the root of my problem was due to the fact that the SharePoint 2010 Prerequisites install a non-final version of ADO. NET Data Services 1.5. Make sure the final version is installed from Microsoft. More information is available at the following URL: http://blogs.msdn.com/b/astoriateam/archive/2010/01/27/data-services-update-for-net-3-5-sp1-available-for-download.aspx There are two places where we need to make changes to our SharePoint site to enable anonymous access: Central Administration Site Permissions Central Administration Classic mode authentication is more or less just classic Windows authentication using NTLM or Kerberos. Although Internet Explorer Mobile in Windows Phone 7 can do the NTLM authentication, as we've been doing up to now to view SharePoint sites in the browser, the version of Silverlight that is included in Windows Phone 7 cannot currently use this authentication mechanism. Carry out the following steps to configure Central Administration for anonymous access: From the Start menu, select All Programs. Find the folder named Microsoft SharePoint 2010 Products in the list of programs and click on it. Click on SharePoint 2010 Central Administration. You need to select the Yes option on the User Account Control dialog that may appear. At this point, the home page for SharePoint 2010 Central Administration should appear as displayed in the following screenshot: (Move the mouse over the image to enlarge.) Next, click on Manage web applications. The page that appears lists out all of the web applications in the SharePoint site. There should be two items listed here, but it is possible there are more. Select the main website by clicking on its name. This main website is usually titled SharePoint – 80. Once selected, the ribbon bar across the top should light up, as all the icons become active. Carry out the following steps to enable anonymous access: Click on the Authentication Providers icon. In the Authentication Providers dialog that appears, select the Default link. The Edit Authentication dialog box will appear. In the third section, down under a heading of Anonymous Access there is a check box listed as Enable anonymous access. Check that box. Scroll all the way to the bottom of the dialog box and select the Save button. SharePoint 2010 will process the request. Then, return to the Authentication Providers dialog box and close it. There is one more section that may need tweaking and if this is a production environment, it should be considered. That section is Anonymous Policy. Click on the icon for it in the ribbon and a dialog box will appear. From here, we can customize the anonymous policy for the site. None – No policy basically leaves the door open for read and write access from anonymous users. This is a good policy to use when anyone who can access the site should also be able to modify the content of the site. This is a good policy for Wiki's. Deny Write – Has no write access allows the anonymous users to read the site, but they cannot write, update, or delete content. This is a good policy to use for sites that we want to specify particular authenticated accounts write access, but allow everyone the ability to read the content. Some Wiki's use this policy and a lot of blogs use this policy. Deny All – Has no access selecting this removes all permissions to the anonymous user. Secure content should always use this policy. Site Permissions Once we have updated the web application to allow anonymous access, we have to give anonymous users access to the site collection. To do this, we close Central Administration and open our SharePoint site. Once on the site, select Site Permissions from the Site Actions menu. This will open the Permissions home page. In the ribbon at the top, there is an icon named Anonymous Access. Click on that button and the Anonymous Access dialog will appear, as shown in the following screenshot: This dialog has three radio buttons to fine tune the access that anonymous users have. The key point to remember here is that although we are really opening up the site for everyone to see, we can break the inherit permissions model on a child page at any time if we need to remove anonymous access. Now that we have opened up our SharePoint site to anonymous users, we can begin to write applications for Windows Phone 7. In a production environment, we may not have the privilege of opening a SharePoint site this wide, but remember that we are only doing it for demonstration purposes here. We have to walk before we can run. Now, let's get started on the RSS reader.   Using WebClient to get data from the web As was stated in the introduction to this article, we are going to build a really simple RSS reader for Windows Phone 7. We are going to keep everything really simple. What that means is that we are going to focus on the pieces of code that actually do something. This is what we are going to do: Create our base project Add a text block to display the WebClient results Create a WebClient Use the WebClient to request the contents of our SharePoint home page Display the raw HTML that is returned in the text block on the page First, a quick word about WebClient. WebClient isn't the most robust method of making requests over a network, but it's really simple and works for simple cases, such as the one we are working with. Creating the base project We can start by creating our base project. This RSS reader will use the Visual Studio Silverlight for Windows Phone Windows Phone Application template. Carry out the following steps to start the project: Open Visual Studio 2010. Select File from the main menu and then select New Project…. In the New Project dialog box that appears, select Silverlight for Windows Phone. Then select Windows Phone Application from the list of templates for Windows Phone. Give the project a name, for example SimpleRSSReader. Give the Solution a name, for example Chapter06. Change the Location as desired and click on the OK button. At this point, Visual Studio will go off and create the solution and project. When it has finished, MainPage.xaml will appear on the screen in split screen mode, as shown in the following screenshot: Displaying WebClient results by adding a text block The first thing we are going to do here is add a text block to the content panel. Add the following code to the Grid that has a name of ContentPanel. <TextBlock x_Name="webClientResults" /> This creates a text block named webClientResults and puts it in ContentPanel. We could spruce this up a bit by providing a font size, or padding, but we are going to keep this really simple and only show the code needed to get things done. Save the progress. Creating a WebClient Open up the code behind by either clicking on it in the top tab bar, double-clicking the file name in Solution Explorer, or press F7 while in the XAML code. In the code behind, create a private member variable, outside the constructor, named client of type WebClient and a private member variable, also outside the constructor, named siteUrl of type string. The siteUrl should have a value that is the URL to your SharePoint home page. private WebClient client = new WebClient();private string siteUrl = "http://ssps2010/"; These are the variables that we'll be using in just a minute. The first is the WebClient that makes the requests on the network. The second is the Url for our SharePoint home page. This is the address that the WebClient will use to request a web page. Requesting the contents of our SharePoint home page Now that we have a WebClient, let us do something with it. Add the following code to the Main Page constructor: client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);client.DownloadStringAsync(new Uri(siteUrl)); The first line adds a new event handler to the DownloadStringCompleted event. This event handler is called client_DownloadStringCompleted and we will write it shortly. The second line is what starts an asynchronous request to our SharePoint home page to get the HTML content. Displaying the raw HTML that is returned Until now, we've created a place in the content panel to display our results. We've created a couple of variables. We've added a new event handler for when the WebClient finishes and we've made the web request for our SharePoint home page. Next, we are going to receive the result from the WebClient. Earlier, when we added a new event handler to the WebClient, we told WebClient that when it finishes downloading the string, it should call our method named client_DownloadStringCompleted. The following is the code for that method: void client_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e) { if(e.Error == null) { webClientResults.Text = e.Result; }} First, we check to see if there is an error. To make this as simple as possible, we are not handling the situation where there is an error. We only care if there are no errors. Always check that errors are null. If there is an exception in the WebClient request, the DownloadStringCompletedEventArgs Error property will contain an object of type Exception. These exceptions can range from network connections being down, which is common for cell phones, to invalid URLs. We then take the result of the web request and put it in the text block we created earlier. Save the progress and press F5 to see the application run on the Windows Phone 7 Emulator. In the preceding screenshot, ApplicationTitle and PageTitle have also been updated. Both of these text blocks are found in the XAML in TitlePanel. We have successfully used WebClient to read data from the web and display it on the screen. It is still in a raw format though, and it isn't much of an RSS reader, especially since this page isn't even RSS. We will get there, but first let's find some RSS in SharePoint.  
Read more
  • 0
  • 0
  • 1683

article-image-getting-started-microsoft-sql-server-2008-r2
Packt
09 Jun 2011
9 min read
Save for later

Getting Started with Microsoft SQL Server 2008 R2

Packt
09 Jun 2011
9 min read
  Microsoft SQL Server 2008 R2 Administration Cookbook Over 70 practical recipes for administering a high-performance SQL Server 2008 R2 system Introduction Microsoft SQL Server 2008 has opened up a new dimension within data platforms and SQL Server 2008 R2 has been developed on the areas of core Database Platform and rich Business Intelligence. On the core database environment, SQL Server 2008 R2 advances the new enhancements as a primary goal of scalability and availability for highly transactional applications on enterprise-wide networks. On Business Intelligence platforms, the new features that are elevated include Master Data Management (MDM), StreamInsight, PowerPivot for Excel 2010, and Report Builder 3.0. The SQL Server 2008 R2 Installation Center includes system configuration checker rules to ensure the deployment and installation completes successfully. Further, the SQL Server setup support files will help to reduce the software footprint for installation of multiple SQL instances. This article begins with SQL Server 2008 R2 version's new features and enhancements, and adding the service pack features using Slipstream technology. Then an explanation towards how best the master data services can help in designing and adopting key solutions, working with data-tier applications to integrate development into deployment, and an explanation of how best the federated servers enhancement can help to design highly scalable applications for data platforms. Adding SQL Server 2008 R2 Service Pack features using Slipstream technology The success of any project relies upon the simpler methods of implementation and a process to reduce the complexity in testing to ensure a successful outcome. This can be applied directly to the process of SQL Server 2008 R2 installation that involves some downtime, such as the reboot of servers. This is where the Slipstream process allows other changes to the databases or database server. This method offers the extension of flexibility to upgrade the process as an easier part, if there are minimal changes to only those required for the upgrade process. The following recipe is prepared to enable you to get to know Slipstream. Slipstream is the process of combining all the latest patch packages into the initial installation. The major advantage of this process is time, and the capability to include all the setup files along with service pack and hotfixes. The single-click deployment of Slipstream helps us to merge the original source media with updates in memory and then install the update files to enable multiple deployments of SQL Server 2008 R2. Getting Ready In order to begin adding features of SQL Server using Slipstream, you need to ensure you have the following in place: .NET Framework 3.5 Service Pack 1: It helps improvements in the area of data platform, such as ADO.NET Entity Framework, ADO.NET data services, and support for new features of SQL Server 2008 version onwards. You can download .NET Framework 3.5 Service Pack 1 from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&displaylang=en. Windows Installer 4.5: It helps the application installation and configuration service for Windows, which works as an embedded chainer to add packages to a multiple package transaction. The major advantage of this feature enables an update to add or change custom action, so that the custom action is called when an update is uninstalled. You can download Windows Installer 4.5 redistributable package from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=5A58B56F-60B6-4412-95B9-54D056D6F9F4. SQL Server setup support files: It installs SQL Server Native Client that contains SQL OLEDB provider and SQL ODBC driver as a native dynamic link library (DLL) supporting applications using native code APIs to SQL Server. How to do it... Slipstream is a built-in ability of the Windows operating system and since the release of SQL Server 2008 Service Pack 1, it is included. The best practice is to use Slipstream Service Pack as an independent process for Service pack installation, Cumulative Update patching, and Hotfix patching. The key step to Slipstream success is to ensure the following steps are succeeded: The prerequisite steps (mentioned in the earlier sections) are completed. In case of multiple language instances of SQL Server, we need to ensure that we download the correct service pack language from http://www.microsoft.com/downloads/en/ that suits the instance. The Service Pack files are independent to each platform to download, such as X86 for 32-bit, X64 for 64-bit, and IA64 for Itanium platform. To perform the Slipstream Service Pack process, you need to complete the following steps: Create two folders on the local server: SQL2K8R2_FullSP and SQL2K8R2SP. Obtain the original SQL Server 2008 R2 setup source media and copy to SQL2K8R2_FullSP folder. Download the Service Pack1 from Microsoft Downloads site to save in SQL2K8R2SP folder, as per the platform architecture: SQLServer2008SP1-KB968369-IA64-ENU.exe SQLServer2008SP1-KB968369-x64-ENU.exe SQLServer2008SP1-KB968369-x86-ENU.exe Extract the package file using Windows Explorer or using a command prompt operation, as shown in the following screenshot: In case the platform consists of multiple SQL instances with different architectures, for instance SQL Server 2008 R2 Enterprise Edition 64-bit as a default instance and SQL Server 2008 R2 Standard Edition as a named instance, then make sure you download the relevant architecture file http://www.microsoft.com/downloads/en/ as stated previously and extract to relevant folders. This is the first checkpoint to proceed further and the key to ensuring the original setup media is updated correctly. Copy the executable and localized resource file from the extracted location to the original source media location using robocopy utility, which is available from Windows Server 2008 onwards: Copy all the files except the module program file that is executed by various programs and applications in Windows operating systems. It is important to ensure the correct architecture files are copied, such X64 and X86 related files. In addition to the initial checkpoint, this additional checkpoint is required in order to ensure the correct path is specified that will be picked up by Slipstream during the setup of SQL Server 2008 R2 and Service Pack installation. The defaultsetup.ini is the key to guide the Slipstream process to install the RTM version and Service Pack files. The file can be located within the SQL2K8R2_FullSP folder as per the architecture. From Windows Explorer, go to the SQL2K8R2_FullSP folder and open the defaultsetp.ini file to add the correct path for the PCUSOURCE parameter. The file can be located from the SQL Server setup folder location for the processor, for instance, the 32-bit platform the file is available from servernamedirectorySQL Server 2008 R2X86 folder. The previous screenshot represents the file existence within the server, to ensure that the matching SQL Server Product ID (license key) is supplied. There is more attached to the process if the file does not exist, there is no harm to the Slipstream process, the file can be created at the original folder defined in the following steps. It is essential that the license key (product ID) and PCUSource information is included as follows: ;SQLSERVER2008 Configuration File [SQLSERVER2008] PID="??" PCUSOURCE=?? Now, the PCUSOURCE value should consist of the full path of Service pack files that are copied during the initial step, the entry should be as follows: add PCUSOURCE="{Full path}PCU". The full path must include the absolute path to the PCU folder, for instance, if the setup files exist in local folder the path must be as follows: <drivename>SQLServer2008R2_FullSP If that folder is shared out, then the full path must be: MyServerSQLServer2008_FullSP1 The final step of this Slipstream process is to execute the setup.exe from SQL2K8R2_FullSP folder. How it works... The Slipstream steps and installation process are a two-fold movement. Slipstream uses the Remote Installation Services (RIS) technology of Windows Server services to allow configuration management to be automated. The RIS process is capable of downloading the required files or images from the specific path to complete the installation process. The SQL Server 2008 R2 setup runs a pre-check before preceding the installation. The System Configuration Check (SCC) application scans the computer where the SQL Server will be installed. The SCC checks for a set of conditions that prevent a successful installation of SQL Server services. Before the setup starts the SQL Server installation wizard, the SCC executes as a background process and retrieves the status of each item. It then compares the result with the required conditions and provides guidance for the removal of blocking issues. The SQL Server Setup validates your computer configuration using a System Configuration Checker (SCC) before the Setup operation completes using a set of check-parameters that will help to resolve the blocking issues. The sample list of check-parameters is as follows: The following are some of the additional checks that SCC performs to determine if the SQL Server editions in an in-place upgrade path are valid: Checks the system databases for features that are not supported in the SQL Server edition to which you are upgrading Checks that neither SQL Server 7.0 nor SQL Server 7.0 OLAP Services is installed on the server SQL Server 2008 or higher versions are not supported on the server that has SQL Server 7.0. Checks all user databases for features that are not supported by the SQL Server edition Checks if the SQL Server service can be restarted Checks that the SQL Server service is not set to Disabled Checks if the selected instance of SQL Server meets the upgrade matrix requirements Checks if SQL Server Analysis Services is being upgraded to a valid edition SCC checks if the edition of the selected instance of SQL Server is supported for 'Allowable Upgrade Paths' There's more... As the prerequisite process of Slipstream is completed, we need to ensure that the installation of SQL Server 2008 R2, Service Pack, and Hotfixes patches are applied with the setup steps. To confirm the workflow process is followed correctly from the folder SQL2K8R2_FullSP, double-click on setup.exe file to continue the installation of RTM version, Service Pack, and required hotfix patches. While continuing the setup at the Installation Rules screen, the SCC rule checks for Update Setup Media Language Compatibility value, which should be passed in order to proceed, as shown in the following screenshot: If you have failed to see the update setup media language rule, then the same information can be obtained once the installation process is completed. The complete steps and final result of setup are logged as a text file under the folder: C:Program FilesMicrosoft SQL Server100Setup BootstrapLog. The log file is saved as Summary_<MachineName>_Date_Time.txt, for example, 'Summary_DBiASSQA_20100708_200214.txt'.
Read more
  • 0
  • 0
  • 7740
article-image-java-refactoring-netbeans
Packt
08 Jun 2011
7 min read
Save for later

Java Refactoring in NetBeans

Packt
08 Jun 2011
7 min read
  NetBeans IDE 7 Cookbook Over 70 highly focused practical recipes to maximize your output with NetBeans         Introduction Be warned that many of the refactoring techniques presented in this article might break some code. NetBeans, and other IDEs for that matter too, make it easier to revert changes but of course be wary of things going wrong. With that in mind, let's dig in. Renaming elements This recipe focuses on how the IDE handles the renaming of all elements of a project, being the project itself, classes, methods, variables, and packages. How to do it... Let's create the code to be renamed: Create a new project, this can be achieved by either clicking File and then New Project or pressing Ctrl+Shift+N. On New Project window, choose Java on the Categories side, and on the Projects side select Java Application. Then click Next. Under Name and Location: name the project as RenameElements and click Finish. With the project created we will need to clear the RenameElements.java class of the main method and insert the following code: package renameelements; import java.io.File; public class RenameElements { private void printFiles(String string) { File file = new File(string); if (file.isFile()) { System.out.println(file.getPath()); } else if (file.isDirectory()) { for(String directory : file.list()) printFiles(string + file.separator + directory); } if (!file.exists()) System.out.println(string + " does not exist."); } } The next step is to rename the package, so place the cursor on top of the package name, renameelements, and press Ctrl+R. A Rename dialog pops-up with the package name. Type util under New Name and click on Refactor. Our class contains several variables we can rename: Place the cursor on the top of the String parameter named string and press Ctrl+R. Type path and press Enter Let's rename the other variables: Rename file into filePath. To rename methods, perform the steps below: Place the cursor on the top of the method declaration, printFiles, right-click it then select Refactor and Rename.... On the Rename Method dialog, under New Name enter recursiveFilePrinting and press Refactor. Then let's rename classes: To rename a class navigate to the Projects window and press Ctrl+R on the RenameElements.java file. On the Rename Class dialog enter FileManipulator and press Enter. And finally renaming an entire project: Navigate to the Project window, right-click on the project name, RenamingElements, and choose Rename.... Under Project Name enter FileSystem and tick Also Rename Project Folder; after that, click on Rename. How it works... Renaming a project works a bit differently from renaming a variable, since in this action NetBeans needs to rename the folder where the project is placed. The Ctrl+R shortcut is not enough in itself so NetBeans shows the Rename Project dialog. This emphasizes to the developer that something deeper is happening. When renaming a project, NetBeans gives the developer the possibility of renaming the folder where the project is contained to the same name of the project. This is a good practice and, more often than not, is followed. Moving elements NetBeans enables the developer to easily move classes around different projects and packages. No more breaking compatibility when moving those classes around, since all are seamlessly handled by the IDE. Getting ready For this recipe we will need a Java project and a Java class so we can exemplify how moving elements really work. The exisiting code, created in the previous recipe, is going to be enough. Also you can try doing this with your own code since moving classes are not such a complicated step that can't be undone. Let's create a project: Create a new project, which can be achieved either by clicking File and then New Project or pressing Ctrl+Shift+N. In the New Project window, choose Java on the Categories side and Java Application on the Projects side, then click Next. Under Name and Location, name the Project as MovingElements and click Finish. Now right-click on the movingelements package, select New... and Java Class.... On the New Java Class dialog enter the class name as Person. Leave all the other fields with their default values and click Finish. How to do it... Place the cursor inside of Person.java and press Ctrl+M. Select a working project from Project field. Select Source Packages in the Location field. Under the To Package field enter: classextraction: How it works... When clicking the Refactor button the class is removed from the current project and placed in the project that was selected from the dialog. The package in that class is then updated to match. Extracting a superclass Extracting superclasses enables NetBeans to add different levels of hierarchy even after the code is written. Usually, requirements changing in the middle of development, and rewriting classes to support inheritance would quite complicated and time-consuming. NetBeans enables the developer to create those superclasses in a few clicks and, by understanding how this mechanism works, even creates superclasses that extend other superclasses. Getting ready We will need to create a Project based on the Getting Ready section of the previous recipe, since it is very similar. The only change from the previous recipe is that this recipe's project name will be SuperClassExtraction. After project creation: Right-click on the superclassextraction package, select New... and Java Class.... On the New Java Class dialog enter the class name as DataAnalyzer. Leave all the other fields with their default values and click Finish. Replace the entire content of the DataAnalyzer.java with the following code: package superclassextraction; import java.util.ArrayList; public class DataAnalyzer { ArrayList<String> data; static final boolean CORRECT = true; static final boolean INCORRECT = false; private void fetchData() { //code } void saveData() { } public boolean parseData() { return CORRECT; } public String analyzeData(ArrayList<String> data, int offset) { //code return ""; } } Now let's extract our superclass. How to do it... Right-click inside of the DataAnalyzer.java class, select Refactor and Extract Superclass.... When the Extract Superclass dialog appears, enter Superclass Name as Analyzer. On Members to Extract, select all members, but leave saveData out. Under the Make Abstract column select analyzeData() and leave parseData(), saveData(), fetchData() out. Then click Refactor. How it works... When the Refactor button is pressed, NetBeans copies the marked methods from DataAnalyzer.java and re-creates them in the superclass. NetBeans deals intelligently with methods marked as abstract. The abstract methods are moved up in the hierarchy and the implementation is left in the concrete class. In our example analyzeData is moved to the abstract class but marked as abstract; the real implementation is then left in DataAnalyzer. NetBeans also supports the moving of fields, in our case the CORRECT and INCORRECT fields. The following is the code in DataAnalyzer.java: public class DataAnalyzer extends Analyzer { public void saveData() { //code } public String analyzeData(ArrayList<String> data, int offset) { //code return ""; } } The following is the code in Analyzer.java: public abstract class Analyzer { static final boolean CORRECT = true; static final boolean INCORRECT = false; ArrayList<String> data; public Analyzer() { } public abstract String analyzeData(ArrayList<String> data, int offset); public void fetchData() { //code } public boolean parseData() { //code return DataAnalyzer.CORRECT; } } There's more... Let's learn how to implement parent class methods. Implementing parent class methods Let's add a method to the parent class: Open Analyzer.java and enter the following code: public void clearData(){ data.clear(); } Save the file. Open DataAnalyzer.java, press Alt+Insert and select Override Method.... In the Generate Override Methods dialog select the clearData() option and click Generate. NetBeans will then override the method and add the implementation to DataAnalyzer.java: @Override public void clearData() { super.clearData(); }  
Read more
  • 0
  • 0
  • 23700

article-image-python-3-designing-tasklist-application
Packt
08 Jun 2011
7 min read
Save for later

Python 3: Designing a Tasklist Application

Packt
08 Jun 2011
7 min read
  Python 3 Web Development Beginner's Guide Use Python to create, theme, and deploy unique web applications         Read more about this book       (For more resources on Python, see here.) Designing a tasklist application   Designing an application should start with a clear idea of what is expected. Not only to determine what is technically required, but almost as important, to define clear boundaries so that we don't lose time on things that are just nice to have. Nice to have features are something to be added if there is time left in the project. Thehighlightedcodesetstherotationofthecircletofalse.Withoutthis,therevolute jointwouldbejustaweld jointintheend. So let's draw up a shortlist of the relevant features of our tasklist application. Some of these may seem obvious, but as we will see, these have a direct impact on some implementation choices that we have to make, such as: The application will be used by multiple users Task lists should be stored indefinitely A task list may contain an unlimited number of tasks but the user interface is designed for optimal performance for up to 25 tasks or so Tasks may be added, deleted, and marked as done Although this list isn't exhaustive, it has some important implications. The fact that the tasklist application will be used by more than one user means that we have to identify and authorize people who want to use it. In other words, we will need some sort of logon screen and a way to check people against some sort of password database. Because we do not want to burden the user with identifying himself/herself each and every time a task list is refreshed or altered, we need some way of implementing the concept of a session. Web applications use the stateless HTTP protocol. This means, from the server's point of view, every request is a single, unrelated event, and no information is retained at the server. This obviously presents us with a problem if we want to perform a set of related actions. The solution is to ask the web browser to send a small piece of information along with every request it makes to the application after the application has identified the user. This might be accomplished in a number of ways. The server may add an extra parameter to all links inside any web page it generates, commonly referred to as a session id, or use the even more general concept of a cookie. Once the server asks the web browser to store a cookie, this cookie is sent with every following request to the same website. The advantage of cookies is that common web application frameworks (like CherryPy) are already equipped to deal with them and implementing sessions with cookies is much simpler than designing the application to alter all hyperlinks it generates to include a proper session ID. The disadvantage might be that people may block their browser from storing cookies because some websites use them to track their clicking behavior. We let the simplicity of implementation prevail and opt for cookies. If users want to block cookies this is not much of a problem as most browsers also have the option to selectively allow cookies from designated websites. The following image illustrates the way CherryPy manages sessions with the help of cookies: It starts when the client (the web browser) sends a request to CherryPy. Upon receiving the request, the first check is to see if the web browser has sent along a cookie with a session ID. If it didn't, a new session idea is generated. Also, if there was a cookie with a session ID, if this ID is no longer valid (because it has expired, for example, or is a remnant from a very old interaction and doesn't exist in the current cache of session IDs) CherryPy also generates a new session ID. At this point, no persistent information is stored if this is a new session, but if it's an existing session there might be persistent data available. If there is, CherryPy creates a Session object and initializes it with the available persistent data. If not, it creates an empty Session object. This object is available as a global variable cherrypy.session. The next step for CherryPy is to pass control to the function that will handle the request. This handler has access to the Session object and may change it, for example, by storing additional information for later reuse. (Note that the Session object acts like a dictionary so you can simply associate values with keys with cherrypy.session['key']=value. The only restriction to the keys and values is that they must be serializable if the persistent storage is on disk). Then before returning the results generated by the handler, CherryPy checks if the Session object has changed. If (and only if) it has, are the contents of the Session object saved to a more permanent storage. Finally, the response is returned accompanied by a cookie with the session ID. Time for action – creating a logon screen Our first task is to create a small application that does little more than present the user with a logon screen. It will be the starting point of our tasklist application and many others as well. The code for this example is available from the Packt website. If you have not downloaded it yet, this might be a good time to do so. Enter the following pieces of code and save it in a file called logonapp.py import cherrypy import logon class Root(object): logon = logon.Logon(path="/logon", authenticated="/", not_authenticated="/goaway") @cherrypy.expose def index(self): username=logon.checkauth('/logon') return ''' <html><body> <p>Hello user <b>%s</b></p> </body></html>'''%username @cherrypy.expose def goaway(self): return ''' <html> <body><h1>Not authenticated, please go away.</h1> </body></html>''' @cherrypy.expose def somepage(self): username=logon.checkauth('/logon',returntopage=True) return '''<html> <body><h1>This is some page.</h1> </body> </html>''' if __name__ == "__main__": import os.path current_dir = os.path.dirname(os.path.abspath(__file__)) cherrypy.quickstart(Root(),config={ '/': {'tools.sessions.on': True } } ) If you now run logonapp.py, a very simple application is available on port 8080. It presents the user with a logon screen when the top level page http://localhost:8080/ is accessed. An example is shown in the following illustration: If a correct username/password combination is entered, a welcome message is shown. If an unknown username or wrong password is entered, the user is redirected to http://localhost:8080/goaway. The somepage() method (highlighted) returns a page with (presumably) some useful content. If the user is not yet authenticated, the logon screen is shown and upon entering the correct credentials, the user is directed back to http://localhost:8080/somepage. The complete tree of web pages within the logon sample application and the possible paths the user may pick through is shown next: Logon + session ID vs. HTTP basic authentication You may wonder why we choose not to reuse CherryPy's bundled auth_basic tool that offers basic authentication (for more information on this tool, see http://www.cherrypy.org/wiki/BuiltinTools#tools.auth_ basic). If all we wanted was to check whether a user is allowed access to a single page, this would be a good choice. The basic authentication is sufficient to authenticate a user, but has no concept of a session. This means we lack a way to store data that needs to be accessible when we process subsequent requests by the same user. The sessions tool we use here does provide this additional functionality.
Read more
  • 0
  • 0
  • 11288

article-image-moodle-20-multimedia-working-2d-and-3d-maps
Packt
08 Jun 2011
12 min read
Save for later

Moodle 2.0 Multimedia: Working with 2D and 3D Maps

Packt
08 Jun 2011
12 min read
  Moodle 2.0 Multimedia Cookbook Add images, videos, music, and much more to make your Moodle course interactive and fun         Read more about this book       (For more resources on Moodle 2.0, see here.) Introduction Whenever you think of a map, you may either think of the traditional planisphere or the terrestrial globe. There are several types of maps apart from those previously mentioned. We can work with maps of the moon, Mars, constellations, and even the universe! Thus, we are not only going to focus on our planet, but we are going to travel even further! The topic of this article is going to deal with Traveling Around the World and Watching the Universe. After reading this article, you can focus on your next holiday! We explain how to work with different types of maps. We are going to be as creative as possible. We should try to work with maps in an unconventional way. That is to say, the idea is to use a map for a Geography class, but we can use maps as a resource for any type of activity. Thus, we can work with the Geography teacher and he/she could work on another geographical feature of the place that we are working with. Therefore, in that way, we are adding more information to the place we are exploring. Maps are very attractive and they may become quite appealing to our students as long as we find a way to develop a rich activity using them. We should encourage the use of maps and the available resources that we have on the Web so that they can insert them in their homework by themselves as well. Thus, we can develop the activities in such a way that we can either provide the map or ask them to design a map. We can also work with maps in the case of Literature. We can ask students to draw a map of a place that has never existed in the real world, though it did in a story. Thus, another bit of homework that could prove helpful would be for students to design and carry out the map of such a place using the tools that we are going to explore in the following recipes. An example of this could be to draw the map of the country Ruritania and locate the cities of Zenda and Strealsau. These places do not exist in the real world, but they exist in the book The Prisoner of Zenda by Anthony Hope. So, many things can be done with maps. Creating maps with sceneries In this activity, we are going to create a map with sceneries. Therefore, we could either browse our files for pictures from our trips or holidays, or we can search for sceneries on the Web. After selecting the pictures, we create a new folder in Windows Explorer, for example C:Images_Traveling. In this folder, we save all the pictures so as to organize our work. We will use the following well-known website: http://earth.google.com/ to design a map using the pictures we have saved in the folder that we have just created. Let's get ready! Getting ready In this activity, we will work with the previously mentioned website. Therefore, we need to open the web browser and enter it. Click on Download Google Earth 6. Read the Google Maps/Earth Terms of Service and if you agree, click on Agree and Download. The icon of Google Earth will appear on your desktop, as shown in the following screenshot: How to do it... We have already carried out the first steps for this activity. Now, we have to design the maps with the pictures that we want to add. There are also some pictures that are available in the maps; you can also work with them, though the aim of this activity is to upload images in the map. Follow these steps in order to create a folder and find images for the activity: Click on the icon on your desktop and open Google Earth. Bring the Earth closer with the icons on the right. Locate a remote city in the southern hemisphere, as shown in the following screenshot: In the Fly to block, write "Mar del Plata", or any other remote city. Then press Enter or click on the magnifying glass next to the block. You will travel virtually to the desired city. Bring the map forward and locate the place where the picture to be uploaded was taken. Click on Add | Photo. Complete the Name block. Click on Browse. Search for the picture that you want to upload and click on it. Complete the other blocks: Description | View | Photo. Click on OK. The picture will appear, as shown in the following screenshot: You can repeat the same process as many times as the number of pictures you want to upload. After uploading all the pictures, click on File | Save | Save Image, as shown in the following screenshot: Complete the File name block and click on Save. How it works... After uploading the desired pictures to the map, we can create an activity. We could start this course with a little social interaction. We ask our students to think about what element they shouldn't forget if they happen to go to this place. They may not know this city, for sure, unless they live nearby. This is the most interesting part of inserting a remote city that they may want to know more about it! Therefore, a Chat is a good idea to have where all the students will be invited in order to discuss the city. We upload the map that we have created with the images to our activity within the Moodle course. Choose the weekly outline section where you want to insert this activity and follow these steps: Click on Add an activity | Chat. Complete the Name of this chat room and Introduction text blocks. Click on the Insert/edit image icon | Find or upload an image | Browse and look for the image that we have just saved. Click on Upload this file. Complete the Image description block and click on Insert. Click on Save and return to course. The activity looks as shown in the following screenshot: Drawing regions within a map In this activity, we are going to use an interactive website in which we choose a map to work with. It is a very simple one, but we could enhance it by adding interesting ingredients to the recipe. We will use a software for drawing a region on the map, and highlight a region for our students to work with. As it was pointed out before, we are not going to focus on geographical features, though you can add this ingredient yourself when designing the activity. Getting ready We open our default web browser and work with the following website: http://www.fusioncharts.com/maps/Default.asp. We click on Map Gallery and choose a map to work with. In this case, we choose a map of the world and highlight five regions, one for each continent. You can modify it and work with different regions within a continent or a country too. How to do it... We look for the desired map. We can find different types of maps to work with. Everything depends on what type of activity we have in mind. In this case, as the topic of this article has to do with traveling, we circle five regions and ask our students to choose where they would like to go. First of all, we have to find the map and save it as an image so that we can draw the regions and upload it to our Moodle course. Therefore, follow these steps: Click on click here | World Map with countries on the aforementioned site. Another pop-up window appears, displaying a map of the world with the countries. There appears a Map Configuration block where you can customize some features, as shown in the next screenshot. Click on Save Map as Image, as shown in the following screenshot: Another pop-up window will appear. Click on Save. Complete the File name block. Click on Save. Click on Open. A pop-up window displaying the map will appear. Click on File | Copy. Paste the map in Paint or Inkscape. Click on Edit | Paste from and browse for the name of the file. Select the file and click on Open. Use the resources available to draw the regions that you want students to work with, as shown in the following screenshot: Click on File | Save as and write a name for the file. Click on Save. How it works... We have already drawn the regions that we want our students to work with. We have chosen one country from every continent; you can choose another or design it in a different way. We can add a writing activity in which students choose where they would like to travel using the previous map. Select the weekly outline section where you want to add the activity and follow these steps: Click on Add an activity | Upload a single file within Assignments. Complete the Assignment name and Description blocks. Click on the Insert/edit image icon | Find or upload an image | Browse. When you find the image that you want to upload, click on Open | Upload this file. Complete the Image description block. Click on Insert. Click on Save and return to course. The activity is ready! When students click on the activity, it looks as shown in the following screenshot: Labeling a map with pins In this recipe, we will learn how to insert a map in our Moodle course labeled with pins, because we pin all the cities that we are going to work with. Therefore, we insert the map as a resource. After that, we design activities for our students to use the interactive map that we have just added. It is another way to use a resource, making our Moodle course more appealing to the eyes of our students. Getting ready We are going to work with Google Earth, as we did in the first recipe, so we have already installed it. We should think of the cities to insert in our course because we need to pin them all! How to do it... Click on the Google Earth icon that you have on your desktop. This is a way to enrich our traveling course by enhancing its appearance. So, these are the steps that you have to follow: Complete the Fly to block with the place that you want to pin. Click on the yellow pin, as shown in the following screenshot: A pop-up window will appear. Complete the Name block by writing the name of the city. Check the Latitude and Longitude, so that you place the pin correctly. You may complete the Description block. You can change the appearance of the pin by clicking on the pin itself. Another pop-up window will appear showing different sorts of icons, as shown in the following screenshot: You can choose the desired icon by clicking on it | OK. The icon that you have selected will appear in the map. Pin as many cities as you are going to work with and repeat steps 1-7. After pinning all the cities, save the file. Click on File | Save | Save Place as. Complete the File name block (remember to save the file in the folder which was created for this course) | Save. You have already saved the pinned map. How it works... We have to insert the map in our Moodle course. In this case, we are going to Add a resource, because we are introducing all the activities that are to come. So, choose the weekly outline section where you want to save the resource. These are the steps that you have to follow: Click on Add a resource | File. Complete the Name and Description blocks. Click on Add | Browse. Click on the file that you are going to upload | Open | Upload this file | Save and return to course. Although we have added a file, students can work with the map interactively! There's more We can embed the map in an HTML block in our Moodle course. Click on the downwards arrow next to Add... in Add a block, as shown in the following screenshot: Choose HTML and a new block will appear in our Moodle course. Embedding a map in an HTML block Open Google Earth and follow these steps in order to embed the map in the block that we have already added: Click on the View in Google Maps icon, as shown in the following screenshot: Another window appears. Click on Link | Customize and preview embedded map, as shown in the following screenshot: Click on Custom and adjust the Width and Height. In the Preview section, click on the minus sign and adjust the map to fit the window. Copy the HTML code to embed in our Moodle course. Go back to the Moodle course and click on the configuration icon to embed the map. Complete the Block title. In the Content block, click on the HTML icon, paste the HTML code which was copied, and click on Update. Click on Save changes. The map will look as shown in the following screenshot:
Read more
  • 0
  • 0
  • 2904
article-image-getting-started-sage
Packt
08 Jun 2011
7 min read
Save for later

Getting started with Sage

Packt
08 Jun 2011
7 min read
Sage Beginner's Guide Remember that you don't actually have to install Sage to start using it. You can start learning Sage by utilizing one of the free public notebook servers that can be found at http://www.sagenb.org/. However, if you find that Sage suits your needs, you will want to install a copy on your own computer. This will guarantee that Sage is always available to you, and it will reduce the load on the public servers so that others can experiment with Sage. In addition, your data will be more secure, and you can utilize more computing power to solve larger problems. Before you begin At the moment, Sage is fully supported on certain versions of the following platforms: some Linux distributions (Fedora, openSUSE, Red Hat, and Ubuntu), Mac OS X, OpenSolaris, and Solaris. Sage is tested on all of these platforms before each release, and binaries are always available for these platforms. The latest list of supported platforms is available at http://wiki.sagemath.org/SupportedPlatforms. The page also contains information about platforms that Sage will probably run on, and the status of efforts to port Sage to various platforms. When downloading Sage, the website attempts to detect which operating system you are using, and directs you to the appropriate download page. If it sends you to the wrong download page, use the "Download" menu at the top of the page to choose the correct platform. If you get stuck at any point, the official Sage installation guide is available at http://www.sagemath.org/doc/installation/. Installing a binary version of Sage on Windows Installing Sage on Windows is slightly more involved than installing a typical Windows program. Sage is a collection of over 90 different tools. Many of these tools are developed within a UNIX-like environment, and some have not been successfully ported to Windows. Porting programs from UNIX-like environments to Windows requires the installation of Cygwin (http://www.cygwin.com/), which provides many of the tools that are standard on a Linux system. Rather than attempting to port all of the necessary tools to Cygwin on Windows, the developers of Sage have chosen to distribute Sage as a virtual machine that can run on Windows with the use of the free VMWare Player. A port to Cygwin is in progress, and more information can be found at http://trac.sagemath.org/sage_trac/wiki/CygwinPort. Downloading VMware Player The VMWare Player can be found at http://www.vmware.com/products/player/. Clicking the Download link will direct you to a registration form. Fill out and submit the form. You will receive a confirmation email that contains a link that must be clicked to complete the registration process and take you to the download page. Choose Start Download Manager, which downloads and runs a small application that performs the actual download and saves the file to a location of your choice. Installing VMWare Player After downloading VMWare Player, double-click the saved file to start the installation wizard. Follow the instructions in the wizard to install the Player. You will have to reboot the computer when instructed. Downloading and extracting Sage Download Sage by following the Download link from http://www.sagemath.org. The site should automatically detect that you are using Windows, and direct you to the right download page. Choose the closest mirror and download the compressed virtual machine. Be aware that the file is nearly 1GB in size. Once the download is complete, right-click the compressed file and choose Extract all from the pop-up menu. Launching the virtual machine Launch VMware Player and accept the license terms. When the Player has started, click Open a Virtual Machine and select the Sage virtual machine, which is called sage-vmware.vmx. Click Play virtual machine to run Sage. If you have run Sage before, it should appear in the list of virtual machines on the left side of the dialog box, and you can double-click to run it. When the virtual machine launches, you may receive one or more warnings about various devices (such as Bluetooth adapters) that the virtual machine cannot connect to. Don't worry about this, since Sage doesn't need these devices. Start Sage Once the virtual machine is running, you will see three icons. Double-clicking the Sage Notebook icon starts the Sage notebook interface, while the Sage icon starts the commandline interface. The first time you run Sage, you will have to wait while it regenerates files. When it finishes, you are ready to go. You may get the warning "External network not set up" when launching the notebook interface. This does not cause any problems. When you are done using Sage, choose Shut Down… from the System menu at the top of the window, and a dialog will appear. Click the Shut Down button to close the virtual machine.   Installing a binary version of Sage on OS X On Mac OS X, you have the option of installing a pre-built binary application, or downloading the source code and compiling Sage yourself. One advantage of the pre-built binary is that it is very easy to install, because it contains everything you need to run Sage. Another advantage of the binary is that building Sage from source requires a lot of computational resources, and may take a long time on older machines. However, there are a number of disadvantages to prebuilt binaries. The binary download is quite large, and the installed files take up a lot of disk space. Many of the tools in the binary may be duplicates of tools you already have on your system. Pre-built binaries cannot be tuned to take advantage of the hardware features of a particular platform, so building Sage from source is preferred if you are looking for the best performance on CPU-intensive tasks. You will have to choose which method is right for you. Downloading Sage Download Sage by following the Download link from http://www.sagemath.org. The site should automatically detect that you are using OS X, and direct you to the right download page. Choose a mirror site close to you. Select your architecture (Intel for new Macs, or PowerPC for older G4 and G5 macs). Then, click the link for the correct .dmg file for you version of Mac OS X. If you aren't sure, click the Apple menu on the far left side of the menu bar and choose About This Mac. Installing Sage Once the download is complete, double-click the .dmg file to mount the disk image. Drag the Sage folder from the disk image to the desired location on your hard drive (such as the Apps folder). If the copy procedure fails, you will need to do it from the command line. Open the Terminal application and enter the following commands. Be sure to change the name sage-4.5-OSX-64bit-10.6-i386-Darwin.dmg to the name of the file you just downloaded: $ cd /Applications $ cp -R -P /Volumes/sage-4.5-OSX-64bit-10.6-i386-Darwin.dmg /sage . After the copy process is complete, right-click on the icon for the disk image, and choose Eject. Starting Sage Use the Finder to visit the Sage folder that you just created. Double-click on the icon called Sage. It should open with the Terminal application. If it doesn't start, right-click on the icon, go to the Open With submenu and choose Terminal.app. The Sage command line will now be running in a Terminal window. The first time you run Sage, you will have to wait while it regenerates files. When it finishes, you are ready to go. There are three ways to exit Sage: type exit or quit at the Sage command prompt, or press Ctrl-D in the Terminal window. You can then quit the Terminal application.  
Read more
  • 0
  • 0
  • 6210

article-image-learn-computer-vision-applications-open-cv
Packt
07 Jun 2011
16 min read
Save for later

Learn computer vision applications in Open CV

Packt
07 Jun 2011
16 min read
  OpenCV 2 Computer Vision Application Programming Cookbook Over 50 recipes to master this library of programming functions for real-time computer vision         Read more about this book       OpenCV (Open Source Computer Vision) is an open source library containing more than 500 optimized algorithms for image and video analysis. Since its introduction in 1999, it has been largely adopted as the primary development tool by the community of researchers and developers in computer vision. OpenCV was originally developed at Intel by a team led by Gary Bradski as an initiative to advance research in vision and promote the development of rich, vision-based CPU-intensive applications. In this article by Robert Laganière, author of OpenCV 2 Computer Vision Application Programming Cookbook, we will cover: Calibrating a camera Computing the fundamental matrix of an image pair Matching images using random sample consensus Computing a homography between two images (For more resources related to the article, see here.) Introduction Images are generally produced using a digital camera that captures a scene by projecting light onto an image sensor going through its lens. The fact that an image is formed through the projection of a 3D scene onto a 2D plane imposes the existence of important relations between a scene and its image, and between different images of the same scene. Projective geometry is the tool that is used to describe and characterize, in mathematical terms, the process of image formation. In this article, you will learn some of the fundamental projective relations that exist in multi-view imagery and how these can be used in computer vision programming. But before we start the recipes, let's explore the basic concepts related to scene projection and image formation. Image formation Fundamentally, the process used to produce images has not changed since the beginning of photography. The light coming from an observed scene is captured by a camera through a frontal aperture and the captured light rays hit an image plane (or image sensor) located on the back of the camera. Additionally, a lens is used to concentrate the rays coming from the different scene elements. This process is illustrated by the following figure: Here, do is the distance from the lens to the observed object, di is the distance from the lens to the image plane, and f is the focal length of the lens. These quantities are related by the so-called thin lens equation: In computer vision, this camera model can be simplified in a number of ways. First, we can neglect the effect of the lens by considering a camera with an infinitesimal aperture since, in theory, this does not change the image. Only the central ray is therefore considered. Second, since most of the time we have do>>di, we can assume that the image plane is located at the focal distance. Finally, we can notice from the geometry of the system, that the image on the plane is inverted. We can obtain an identical but upright image by simply positioning the image plane in front of the lens. Obviously, this is not physically feasible, but from a mathematical point of view, this is completely equivalent. This simplified model is often referred to as the pin-hole camera model and it is represented as follows: From this model, and using the law of similar triangles, we can easily derive the basic projective equation: The size (hi) of the image of an object (of height ho) is therefore inversely proportional to its distance (do) from the camera which is naturally true. This relation allows the position of the image of a 3D scene point to be predicted onto the image plane of a camera. Calibrating a camera From the introduction of this article, we learned that the essential parameters of a camera under the pin-hole model are its focal length and the size of the image plane (which defines the field of view of the camera). Also, since we are dealing with digital images, the number of pixels on the image plane is another important characteristic of a camera. Finally, in order to be able to compute the position of an image's scene point in pixel coordinates, we need one additional piece of information. Considering the line coming from the focal point that is orthogonal to the image plane, we need to know at which pixel position this line pierces the image plane. This point is called the principal point. It could be logical to assume that this principal point is at the center of the image plane, but in practice, this one might be off by few pixels depending at which precision the camera has been manufactured. Camera calibration is the process by which the different camera parameters are obtained. One can obviously use the specifications provided by the camera manufacturer, but for some tasks, such as 3D reconstruction, these specifications are not accurate enough. Camera calibration will proceed by showing known patterns to the camera and analyzing the obtained images. An optimization process will then determine the optimal parameter values that explain the observations. This is a complex process but made easy by the availability of OpenCV calibration functions. How to do it... To calibrate a camera, the idea is show to this camera a set of scene points for which their 3D position is known. You must then determine where on the image these points project. Obviously, for accurate results, we need to observe several of these points. One way to achieve this would be to take one picture of a scene with many known 3D points. A more convenient way would be to take several images from different viewpoints of a set of some 3D points. This approach is simpler but requires computing the position of each camera view, in addition to the computation of the internal camera parameters which fortunately is feasible. OpenCV proposes to use a chessboard pattern to generate the set of 3D scene points required for calibration. This pattern creates points at the corners of each square, and since this pattern is flat, we can freely assume that the board is located at Z=0 with the X and Y axes well aligned with the grid. In this case, the calibration process simply consists of showing the chessboard pattern to the camera from different viewpoints. Here is one example of a calibration pattern image: The nice thing is that OpenCV has a function that automatically detects the corners of this chessboard pattern. You simply provide an image and the size of the chessboard used (number of vertical and horizontal inner corner points). The function will return the position of these chessboard corners on the image. If the function fails to find the pattern, then it simply returns false: // output vectors of image pointsstd::vector<cv::Point2f> imageCorners;// number of corners on the chessboardcv::Size boardSize(6,4);// Get the chessboard cornersbool found = cv::findChessboardCorners(image, boardSize, imageCorners); Note that this function accepts additional parameters if one needs to tune the algorithm, which are not discussed here. There is also a function that draws the detected corners on the chessboard image with lines connecting them in sequence: //Draw the cornerscv::drawChessboardCorners(image, boardSize, imageCorners, found); // corners have been found The image obtained is seen here: The lines connecting the points shows the order in which the points are listed in the vector of detected points. Now to calibrate the camera, we need to input a set of such image points together with the coordinate of the corresponding 3D points. Let's encapsulate the calibration process in a CameraCalibrator class: class CameraCalibrator { // input points: // the points in world coordinates std::vector<std::vector<cv::Point3f>> objectPoints; // the point positions in pixels std::vector<std::vector<cv::Point2f>> imagePoints; // output Matrices cv::Mat cameraMatrix; cv::Mat distCoeffs; // flag to specify how calibration is done int flag; // used in image undistortion cv::Mat map1,map2; bool mustInitUndistort; public: CameraCalibrator() : flag(0), mustInitUndistort(true) {}; As mentioned previously, the 3D coordinates of the points on the chessboard pattern can be easily determined if we conveniently place the reference frame on the board. The method that accomplishes this takes a vector of the chessboard image filename as input: // Open chessboard images and extract corner pointsint CameraCalibrator::addChessboardPoints( const std::vector<std::string>& filelist, cv::Size & boardSize) { // the points on the chessboard std::vector<cv::Point2f> imageCorners; std::vector<cv::Point3f> objectCorners; // 3D Scene Points: // Initialize the chessboard corners // in the chessboard reference frame // The corners are at 3D location (X,Y,Z)= (i,j,0) for (int i=0; i<boardSize.height; i++) { for (int j=0; j<boardSize.width; j++) { objectCorners.push_back(cv::Point3f(i, j, 0.0f)); } } // 2D Image points: cv::Mat image; // to contain chessboard image int successes = 0; // for all viewpoints for (int i=0; i<filelist.size(); i++) { // Open the image image = cv::imread(filelist[i],0); // Get the chessboard corners bool found = cv::findChessboardCorners( image, boardSize, imageCorners); // Get subpixel accuracy on the corners cv::cornerSubPix(image, imageCorners, cv::Size(5,5), cv::Size(-1,-1), cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 30, // max number of iterations 0.1)); // min accuracy //If we have a good board, add it to our data if (imageCorners.size() == boardSize.area()) { // Add image and scene points from one view addPoints(imageCorners, objectCorners); successes++; } } return successes;} The first loop inputs the 3D coordinates of the chessboard, which are specified in an arbitrary square size unit here. The corresponding image points are the ones provided by the cv::findChessboardCorners function. This is done for all available viewpoints. Moreover, in order to obtain a more accurate image point location, the function cv::cornerSubPix can be used and as the name suggests, the image points will then be localized at sub-pixel accuracy. The termination criterion that is specified by the cv::TermCriteria object defines a maximum number of iterations and a minimum accuracy in sub-pixel coordinates. The first of these two conditions that is reached will stop the corner refinement process. When a set of chessboard corners has been successfully detected, these points are added to our vector of image and scene points: // Add scene points and corresponding image pointsvoid CameraCalibrator::addPoints(const std::vector<cv::Point2f>&imageCorners, const std::vector<cv::Point3f>& objectCorners) { // 2D image points from one view imagePoints.push_back(imageCorners); // corresponding 3D scene points objectPoints.push_back(objectCorners);} The vectors contains std::vector instances. Indeed, each vector element being a vector of points from one view. Once a sufficient number of chessboard images have been processed (and consequently a large number of 3D scene point/2D image point correspondences are available), we can initiate the computation of the calibration parameters: // Calibrate the camera// returns the re-projection errordouble CameraCalibrator::calibrate(cv::Size &imageSize){ // undistorter must be reinitialized mustInitUndistort= true; //Output rotations and translations std::vector<cv::Mat> rvecs, tvecs; // start calibration return calibrateCamera(objectPoints, // the 3D points imagePoints, // the image points imageSize, // image size cameraMatrix,// output camera matrix distCoeffs, // output distortion matrix rvecs, tvecs,// Rs, Ts flag); // set options} In practice, 10 to 20 chessboard images are sufficient, but these must be taken from different viewpoints at different depths. The two important outputs of this function are the camera matrix and the distortion parameters. The camera matrix will be described in the next section. For now, let's consider the distortion parameters. So far, we have mentioned that with the pin-hole camera model, we can neglect the effect of the lens. But this is only possible if the lens used to capture an image does not introduce too important optical distortions. Unfortunately, this is often the case with lenses of lower quality or with lenses having a very short focal length. You may have already noticed that in the image we used for our example, the chessboard pattern shown is clearly distorted. The edges of the rectangular board being curved in the image. It can also be noticed that this distortion becomes more important as we move far from the center of the image. This is a typical distortion observed with fish-eye lens and it is called radial distortion. The lenses that are used in common digital cameras do not exhibit such a high degree of distortion, but in the case of the lens used here, these distortions cannot certainly be ignored. It is possible to compensate for these deformations by introducing an appropriate model. The idea is to represent the distortions induced by a lens by a set of mathematical equations. Once established, these equations can then be reverted in order to undo the distortions visible on the image. Fortunately, the exact parameters of the transformation that will correct the distortions can be obtained together with the other camera parameter during the calibration phase. Once this is done, any image from the newly calibrated camera can be undistorted: // remove distortion in an image (after calibration)cv::Mat CameraCalibrator::remap(const cv::Mat &image) { cv::Mat undistorted; if (mustInitUndistort) { // called once per calibration cv::initUndistortRectifyMap( cameraMatrix, // computed camera matrix distCoeffs, // computed distortion matrix cv::Mat(), // optional rectification (none) cv::Mat(), // camera matrix to generate undistorted image.size(), // size of undistorted CV_32FC1, // type of output map map1, map2); // the x and y mapping functions mustInitUndistort= false; } // Apply mapping functions cv::remap(image, undistorted, map1, map2, cv::INTER_LINEAR); // interpolation type return undistorted;} Which results in the following image: As you can see, once the image is undistorted, we obtain a regular perspective image. How it works... In order to explain the result of the calibration, we need to go back to the figure in the introduction which describes the pin-hole camera model. More specifically, we want to demonstrate the relation between a point in 3D at position (X,Y,Z) and its image (x,y) on a camera specified in pixel coordinates. Let's redraw this figure by adding a reference frame that we position at the center of the projection as seen here: Note that the Y-axis is pointing downward to get a coordinate system compatible with the usual convention that places the image origin at the upper-left corner. We learned previously that the point (X,Y,Z) will be projected onto the image plane at (fX/Z,fY/Z). Now, if we want to translate this coordinate into pixels, we need to divide the 2D image position by, respectively, the pixel width (px) and height (py). We notice that by dividing the focal length f given in world units (most often meters or millimeters) by px, then we obtain the focal length expressed in (horizontal) pixels. Let's then define this term as fx. Similarly, fy =f/py is defined as the focal length expressed in vertical pixel unit. The complete projective equation is therefore: Recall that (u0,v0) is the principal point that is added to the result in order to move the origin to the upper-left corner of the image. These equations can be rewritten in matrix form through the introduction of homogeneous coordinates in which 2D points are represented by 3-vectors, and 3D points represented by 4-vectors (the extra coordinate is simply an arbitrary scale factor that need to be removed when a 2D coordinate needs to be extracted from a homogeneous 3-vector). Here is the projective equation rewritten: The second matrix is a simple projection matrix. The first matrix includes all of the camera parameters which are called the intrinsic parameters of the camera. This 3x3 matrix is one of the output matrices returned by the cv::calibrateCamera function. There is also a function called cv::calibrationMatrixValues that returns the value of the intrinsic parameters given a calibration matrix. More generally, when the reference frame is not at the projection center of the camera, we will need to add a rotation (a 3x3 matrix) and a translation vector (3x1 matrix). These two matrices describe the rigid transformation that must be applied to the 3D points in order to bring them back to the camera reference frame. Therefore, we can rewrite the projection equation in its most general form: Remember that in our calibration example, the reference frame was placed on the chessboard. Therefore, there is a rigid transformation (rotation and translation) that must be computed for each view. These are in the output parameter list of the cv::calibrateCamera function. The rotation and translation components are often called the extrinsic parameters of the calibration and they are different for each view. The intrinsic parameters remain constant for a given camera/lens system. The intrinsic parameters of our test camera obtained from a calibration based on 20 chessboard images are fx=167, fy=178, u0=156, v0=119. These results are obtained by cv::calibrateCamera through an optimization process aimed at finding the intrinsic and extrinsic parameters that will minimize the difference between the predicted image point position, as computed from the projection of the 3D scene points, and the actual image point position, as observed on the image. The sum of this difference for all points specified during the calibration is called the re-projection error. To correct the distortion, OpenCV uses a polynomial function that is applied to the image point in order to move them at their undistorted position. By default, 5 coefficients are used; a model made of 8 coefficients is also available. Once these coefficients are obtained, it is possible to compute 2 mapping functions (one for the x coordinate and one for the y) that will give the new undistorted position of an image point on a distorted image. This is computed by the function cv::initUndistortRectifyMap and the function cv::remap remaps all of the points of an input image to a new image. Note that because of the non-linear transformation, some pixels of the input image now fall outside the boundary of the output image. You can expand the size of the output image to compensate for this loss of pixels, but you will now obtain output pixels that have no values in the input image (they will then be displayed as black pixels). There's more... When a good estimate of the camera intrinsic parameters are known, it could be advantageous to input them to the cv::calibrateCamera function. They will then be used as initial values in the optimization process. To do so, you just need to add the flag CV_CALIB_USE_INTRINSIC_GUESS and input these values in the calibration matrix parameter. It is also possible to impose a fixed value for the principal point (CV_CALIB_ FIX_PRINCIPAL_POINT), which can often be assumed to be the central pixel. You can also impose a fixed ratio for the focal lengths fx and fy (CV_CALIB_FIX_RATIO) in which case you assume pixels of square shape.
Read more
  • 0
  • 1
  • 7175
Modal Close icon
Modal Close icon