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-unittest-python
Packt
21 Jan 2010
11 min read
Save for later

Unittest in Python

Packt
21 Jan 2010
11 min read
So let's get on with it! Basic unittest Before we start talking about new concepts and features, let's take a look at how to use unittest to express the ideas that we've already learned about. That way, we'll have something solid to ground our new understanding into. Time for action – testing PID with unittest We'll visit the PID class (or at least the tests for the PID class). We'll write the tests so that they operate within the unittest framework. We'll be implementing the tests using the unittest framework. Create a new file called test_pid.py in the same directory as pid.py. Notice that this is a .py file: unittest tests are pure python source code, rather than being plain text with source code embedded in it. That means the tests will be less useful from a documentary point of view, but grants other benefits in exchange. Insert the following code into your newly-created test_pid.py (and please note that a few lines are long enough to get wrapped on the article's page): from unittest import TestCase, mainfrom mocker import Mockerimport pidclass test_pid_constructor(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mocker.replay() controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12) mocker.restore() mocker.verify() self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 0.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 1.0) self.assertAlmostEqual(controller.previous_error, -12.0) self.assertAlmostEqual(controller.integrated_error, 0) def test_with_when(self): controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=1, initial=12, when=43) self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 1.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 43.0) self.assertAlmostEqual(controller.previous_error, -11.0) self.assertAlmostEqual(controller.integrated_error, 0)class test_calculate_response(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mock_time() mocker.result(2.0) mock_time() mocker.result(3.0) mock_time() mocker.result(4.0) mock_time() mocker.result(5.0) mocker.replay() controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12) self.assertEqual(controller.calculate_response(6), -3) self.assertEqual(controller.calculate_response(3), -4.5) self.assertEqual(controller.calculate_response(-1.5), -0.75) self.assertEqual(controller.calculate_response(‑2.25), ‑1.125) mocker.restore() mocker.verify() def test_with_when(self): controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12, when=1) self.assertEqual(controller.calculate_response(6, 2), -3) self.assertEqual(controller.calculate_response(3, 3), -4.5) self.assertEqual(controller.calculate_response(‑1.5, 4), ‑0.75) self.assertEqual(controller.calculate_response(‑2.25, 5), ‑1.125)if __name__ == '__main__': main() Run the tests by typing: $ python test_pid.py What just happened? Let's go through the code section and see what each part does. After that, we'll talk about what it all means when put together. from unittest import TestCase, mainfrom mocker import Mockerimport pidclass test_pid_constructor(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mocker.replay() controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12) mocker.restore() mocker.verify() self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 0.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 1.0) self.assertAlmostEqual(controller.previous_error, -12.0) self.assertAlmostEqual(controller.integrated_error, 0) After a little bit of setup code, we have a test that the PID controller works correctly when not given a when parameter. Mocker is used to replace time.time with a mock that always returns a predictable value, and then we use several assertions to confirm that the attributes of the controller have been initialized to the expected values. def test_with_when(self): controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=1, initial=12, when=43) self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 1.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 43.0) self.assertAlmostEqual(controller.previous_error, -11.0) self.assertAlmostEqual(controller.integrated_error, 0) This test confirms that the PID constructor works correctly when the when parameter is supplied. Unlike the previous test, there's no need to use Mocker, because the outcome of the test is not supposed to be dependant on anything except the parameter values—the current time is irrelevant. class test_calculate_response(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mock_time() mocker.result(2.0) mock_time() mocker.result(3.0) mock_time() mocker.result(4.0) mock_time() mocker.result(5.0) mocker.replay() controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12) self.assertEqual(controller.calculate_response(6), -3) self.assertEqual(controller.calculate_response(3), -4.5) self.assertEqual(controller.calculate_response(-1.5), -0.75) sel+f.assertEqual(controller.calculate_response(‑2.25), ‑1.125) mocker.restore() mocker.verify() The tests in this class describe the intended behavior of the calculate_response method. This first test checks the behavior when the optional when parameter is not supplied, and mocks time.time to make that behavior predictable. def test_with_when(self): controller = pid.PID(P=0.5, I=0.5, D=0.5, setpoint=0, initial=12, when=1) self.assertEqual(controller.calculate_response(6, 2), -3) self.assertEqual(controller.calculate_response(3, 3), -4.5) self.assertEqual(controller.calculate_response(‑1.5, 4), ‑0.75) self.assertEqual(controller.calculate_response(‑2.25, 5), ‑1.125) In this test, the when parameter is supplied, so there is no need to mock time.time. We just have to check that the result is what we expected. The actual tests that we performed are the same ones that were written in the doctest. So far, all that we see is a different way of expressing them. The first thing to notice is that the test file is divided up into classes that inherit from unittest.TestCase, each of which contains one or more test methods. The name of each test method begins with the word test, which is how unittest recognizes that they are tests. Each test method embodies a single test of a single unit. This gives us a convenient way to structure our tests, grouping together related tests into the same class, so that they're easier to find. Putting each test into its own method means that each test executes in an isolated namespace, which makes it somewhat easier to keep unittest‑style tests from interfering with each other, relative to doctest‑style tests. It also means that unittest knows how many unit tests are in your test file, instead of simply knowing how many expressions there are (you may have noticed that doctest counts each >>> line as a separate test). Finally, putting each test in its own method means that each test has a name, which can be a valuable feature. Tests in unittest don't directly care about anything that isn't part of a call to one of the assert methods of TestCase. That means that when we're using Mocker, we don't have to be bothered about the mock objects that get returned from demonstration expressions, unless we want to use them. It also means that we need to remember to write an assert describing every aspect of the test that we want to have checked. We'll go over the various assertion methods of TestCase shortly. Tests aren't of much use, if you can't execute them. For the moment, the way we'll be doing that is by calling unittest.main when our test file is executed as a program by the Python interpreter. That's about the simplest way to run unittest code, but it's cumbersome when you have lots of tests spread across lots of files. if __name__ == '__main__': might look strange to you, but its meaning is fairly straight forward. When Python loads any module, it stores that module's name in a variable called __name__ within the module (unless the module is the one passed to the interpreter on the command line). That module always gets the string '__main__' bound to its __name__ variable. So, if __name__ == '__main__': means—if this module was executed directly from the command line. Assertions Assertions are the mechanism that we use to tell unittest what the important outcomes of the test are. By using appropriate assertions, we can tell unittest exactly what to expect from each test. assertTrue When we call self.assertTrue(expression), we're telling unittest that the expression must be true in order for the test to be a success. This is a very flexible assertion, since you can check for nearly anything by writing the appropriate boolean expression. It's also one of the last assertions you should consider using, because it doesn't tell unittest anything about the kind of comparison you're making, which means that unittest can't tell you as clearly what's gone wrong if the test fails. For an example of this, consider the following test code which contains two tests that are guaranteed to fail: from unittest import TestCase, mainclass two_failing_tests(TestCase): def test_assertTrue(self): self.assertTrue(1 == 1 + 1) def test_assertEqual(self): self.assertEqual(1, 1 + 1)if __name__ == '__main__': main() It might seem like the two tests are interchangeable, since both test the same thing. Certainly they'll both fail (or in the unlikely event that one equals two, they'll both pass), so why prefer one over the other? Take a look at what happens when we run the tests (and also notice that the tests were not executed in the same order as they were written; tests are totally independent of each other, so that's okay, right?): Do you see the difference? The assertTrue test was able to correctly determine that the test should fail, but it didn't know enough to report any useful information about why it failed. The assertEqual test, on the other hand, knew first of all that it was checking that two expressions were equal, and second it knew how to present the results, so that they would be most useful: by evaluating each of the expressions that it was comparing and placing a != symbol between the results. It tells us both what expectation failed, and what the relevant expressions evaluate to. assertFalse The assertFalse method will succeed when the assertTrue method would fail, and vice versa. It has the same limits in terms of producing useful output that assertTrue has, and the same flexibility in terms of being able to test nearly any condition. assertEqual As mentioned in the assertTrue discussion, the assertEqual assertion checks that its two parameters are in fact equal, and reports a failure if they are not, along with the actual values of the parameters. assertNotEqual The assertNotEqual assertion fails whenever the assertEqual assertion would have succeeded, and vice versa. When it reports a failure, its output indicates that the values of the two expressions are equal, and provides you with those values. assertAlmostEqual As we've seen before, comparing floating point numbers can be troublesome. In particular, checking that two floating point numbers are equal is problematic, because things that you might expect to be equal—things that, mathematically, are equal—may still end up differing down among the least significant bits. Floating point numbers only compare equal when every bit is the same. To address that problem, unittest provides assertAlmostEqual, which checks that two floating point values are almost the same; a small amount of difference between them is tolerated. Lets look at this problem in action. If you take the square root of 7, and then square it, the result should be 7. Here's a pair of tests that check that fact: from unittest import TestCase, mainclass floating_point_problems(TestCase): def test_assertEqual(self): self.assertEqual((7.0 ** 0.5) ** 2.0, 7.0) def test_assertAlmostEqual(self): self.assertAlmostEqual((7.0 ** 0.5) ** 2.0, 7.0) if __name__ == '__main__': main() The test_assertEqual method checks that , which is true in reality. In the more specialized number system available to computers, though, taking the square root of 7 and then squaring it doesn't quite get us back to 7, so this test will fail. More on that in a moment. Test test_assertAlmostEqual method checks that , which even the computer will agree is true, so this test should pass. Running those tests produces the following, although the specific number that you get back instead of 7 may vary depending on the details of the computer the tests are being run on: Unfortunately, floating point numbers are not precise, because the majority of numbers on the real number line can not be represented with a finite, non-repeating sequence of digits, much less a mere 64 bits. Consequently, what you get back from evaluating the mathematical expression is not quite 7. It's close enough for government work though—or practically any other sort of work as well—so we don't want our test to quibble over that tiny difference. Because of that, we should use assertAlmostEqual and assertNotAlmostEqual when we're comparing floating point numbers for equality. This problem doesn't generally carry over into other comparison operators. Checking that one floating point number is less than the other, for example, is very unlikely to produce the wrong result due to insignificant errors. It's only in cases of equality that this problem bites us.
Read more
  • 0
  • 0
  • 3050

Packt
20 Jan 2010
8 min read
Save for later

SOA Management—OSB (aka ALSB) Management

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

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

Shipping and Tax Calculations with PHP 5 Ecommerce

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

article-image-developing-applications-jboss-and-hibernate-part-2
Packt
19 Jan 2010
6 min read
Save for later

Developing Applications with JBoss and Hibernate: Part 2

Packt
19 Jan 2010
6 min read
Adding a web client to your project There are several ways to test our Hibernate application. The simplest of all is adding a web application, which is packaged in an enterprise application along with the Hibernate application. Create a new dynamic web project named HibernateWeb. The first step, before adding servlets and JSPs is linking the HibernateProject libraries to your web application, otherwise, you will not be able to reference the Hibernate POJOs. Right-click on your project and select Properties. Reach the Java Build Path option and select the tab Projects. From there add HibernateProject. Let's move on. This project will contain a main servlet that acts as a controller, and a few JPSs for the client view. We will start by adding com.packtpub.hibernateWeb.HibernateServlet to our project. In the following snippet, you can see the core section of the servlet. Here, we will not detail the Controller logic, which is straightforward if you have some rudiments of the MVC pattern; rather we want to highlight the most interesting part of it, which is how to query and persist Hibernate objects. public class HibernateServlet extends HttpServlet {private SessionFactory getSessionFactory() {return (SessionFactory)getServletContext().getAttribute("sessionFactory");}public void init() { [1]if (getSessionFactory() != null) {return;}InitialContext ctx;try {ctx = new InitialContext();factory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");getServletContext().setAttribute("sessionFactory", factory);}catch (NamingException e) {e.printStackTrace();}}private String saveEmployee(HttpServletRequest request) {Session hsession=null;String name=request.getParameter("name");String salary=request.getParameter("salary");String departmentId=request.getParameter("departmentId");try {hsession = getSessionFactory().openSession();hsession.beginTransaction();Query query = hsession.createQuery("from Department d whered.departmentId = :departmentId"); [2]query.setInteger("departmentId", new Integer(departmentId));Department dep = (Department) query.uniqueResult();Employee emp = new Employee();emp.setDepartment(dep);emp.setEmployeeName(name);emp.setEmployeeSalary(Integer.parseInt(salary));hsession.save(emp); [3]hsession.getTransaction().commit();}catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();hsession.getTransaction().rollback();}finally {if (hsession.isOpen())hsession.close();}return employeeList(request);}private String employeeList(HttpServletRequest request) {Session hsession=null;Department dep;try {hsession = getSessionFactory().openSession();Query query = hsession.createQuery("select p from Employee pjoin fetch p.department c"); [4]List <Employee>list = query.list();request.setAttribute("employee", list);}catch (Exception e) {e.printStackTrace();}finally {if (hsession.isOpen())hsession.close();}return "/listEmployees.jsp";}private String saveDepartment(HttpServletRequest request) {String depName=request.getParameter("depName");Session hsession=null;Department dep;try {hsession = getSessionFactory().openSession();hsession.beginTransaction();dep = new Department();dep.setDepartmentName(depName);hsession.save(dep); [5]hsession.getTransaction().commit();}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();hsession.getTransaction().rollback();}finally {if (hsession.isOpen())hsession.close();}return employeeList(request);}} As you can see from the preceding code, we recover the SessionFactory from the JNDI tree in the init() [1] method of the servlet. Instances of SessionFactory are thread-safe and typically shared throughout an application, so we store it in the ServletContext and share it among all servlet instances. The SessionFactory is subsequently used to start a Hibernate session, which is not thread-safe and should only be used for a single transaction or unit of work in an application. In order to store our Employee, in the saveEmployee method, we first retrieve the corresponding Department from our schema [2], and finally the Employee is saved [3] and the transaction is committed. The list of employees is fetched by the employeeList method. Notice we are using a join fetch statement to retrieve all the employees [4], which will be routed to the listEmployees.jsp view. Why? The answer is that with the default fetch mode (Lazy), once the Hibernate session is closed, the client will not be able to navigate through the department field of the Employee. The common solution to this issue is switching to the EAGER fetch mode that reads the related fields (in our case department) in memory, as soon as we query the Employee table. You have more than one option to achieve this. One possible solution, if you don't want to change the default fetch mode for the Employee table, is to build an ad hoc query that forces Hibernate to read also the fields in relation with the Employee table. "select p from Employee p join fetch p.department c" If you prefer to use the XML class files to configure the fetch mode, you can also change the lazy="true" attribute in the employee-department relationship. The last method, saveDepartment [5] takes care to persist a new Department in the corresponding table. We complete our excursus on the web tier with the listEmployees.jsp that is used to display a tabular view of the employees: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><script language="JavaScript">function doSubmit(url) {document.module.action = url;document.module.submit();}</script><body><table border="1"><tr><th>Name</th><th>Salary</th> <TH>department</th></tr><c:forEach items="${employee}" var="emp"><tr><td> <c:out value="${emp.employeeName}"/> </td><td> <c:out value="${emp.employeeSalary}"/></td><td> <c:out value="${emp.department.departmentName}"/></td></tr></c:forEach></table><form name="module" method="POST"><input type="button" value ="New Employee"onClick="doSubmit('actionServlet?op=newEmployee')"><input type="button" value ="New Department"onClick="doSubmit('actionServlet?op=newDepartment')"></form></body></html> This page uses JSP 2.0 Expression Language (EL) to iterate through the list of employees, as highlighted in the last code snippet. We have also hightlighted the taglib directive, at the beginning of the page. This directive will be used to resolve the JSTL core set of libraries that ships with JBoss AS in the server/xxx/deploy/jbossweb.sar/jstl.jar library. (Eclipse does not contain references to this library when you create a web project; you have to add jstl.jar to your build path, otherwise Eclipse will mark it as an error. However, that's only a visual annoyance because the JBoss Web container has got everything it needs to run JSTL.) The complete web application is available on the Packtpub website (http://www.packtpub.com) and includes two additional JSPs for entering the employee (newEmployee.jsp) and department (newDepartment.jsp) data, plus one placeholder index.jsp that merely forwards to the Hibernate servlet.
Read more
  • 0
  • 0
  • 1903

article-image-installing-openvpn-windows-and-mac
Packt
19 Jan 2010
5 min read
Save for later

Installing OpenVPN on Windows and Mac

Packt
19 Jan 2010
5 min read
Obtaining the software There are only a few prerequisites that have to be met if you want to install OpenVPN on Windows, if you are running versions later than Windows 2000. Mac OS X is required on Apple platforms. Installation of OpenVPN can be done in one of the following ways: For Microsoft Windows operating systems, you have to download the binary .exe file from http://openvpn.net/index.php/open-source/downloads.html or the package containing a graphical user interface from http://openvpn.se/. Those who dare to use the release candidate of version 2.1, or a forthcoming version 2.1 will find that the Windows GUI is already integrated (since OpenVPN 2.1rc13 from October 2008). On Macintosh systems running Mac OS X, there is a graphical installation wizard and management tool called Tunnelblick. Note that OpenVPN versions that are not tagged as stable should never be used in the production environment. There may be security issues and bugs that cause the code to crash or open your complete network to intruders. The stable versions have been tested for stability and security flaws, and will not be published as stable until they meet the developer team's requirements. Installing OpenVPN on Windows If you want to install OpenVPN on Windows, you have to make a choice before downloading. You can install the original OpenVPN software from a link such as http://www.openvpn.net/release/openvpn-2.0.9-install.exe (this is still my preferred suggestion) or install the OpenVPN GUI from http://openvpn.se/files/install_packages/openvpn-2.0.9-gui-1.0.3-install.exe. This package contains the OpenVPN software plus a GUI to bring up or close down tunnels. Especially, if you set up an OpenVPN client—be it a laptop or desktop PC for a home worker, which is only connecting temporarily to your VPN—the Windows user will want to have an easy-to-use, clickable interface. However, if you do not want the users to interact with the VPN tunnels, then the original OpenVPN software will do, and, as mentioned, beginning with release candidate 13 of version 2.1, the GUI is integrated. OpenVPN can be made to run as a service on the Windows PC, which means it is started automatically on startup. It can be configured to enable the tunnel automatically or forced by a click of a mouse. The installation is pretty straightforward and should not pose any problem to the experienced Windows user. The following sections show you a guided installation process. If you are prompted that the driver has not passed Windows Logo testing, click on Install. Downloading and starting installation Download the newest version of the OpenVPN GUI from http://openvpn.se/ to your local drive. Log in as the administrator or a privileged user, and double-click on the downloaded file to start the Setup Wizard. If you are using a desktop firewall, you will be prompted to allow OpenVPN to be installed and connected to the Internet later. The OpenVPN GUI installation wizard, probably the most convenient way to install OpenVPN on Windows, is started. Click on Next to proceed and agree to the terms of the license agreement (I Agree). Even though OpenVPN and the OpenVPN GUI are freely available under the open source General Public License (GPL), you still have to accept a license agreement. You should read the license to make sure that your planned use of OpenVPN conforms to it. Click on I Agree to proceed. Selecting the components and location The next dialog window offers a choice on the top of OpenVPN components that you may want to install. The standard selection of components change makes sense to is suitable for most cases. In this dialog, you have several options to choose from. Even if you normally don't need to make changes here, the following table gives you an overview of the entries and when you should install which feature. The Client Install is a system that only connects to another OpenVPN system, whereas the Server Install is an OpenVPN system that allows incoming connections. As you can see, the only differences are the RSA management and the option to run OpenVPN as a service. Both can be configured using different methods later, such as the configuration file, the Windows system management, or software like xca that we will use to generate and administer certificates. Press Next to continue installation and choose the path that you want to install OpenVPN to. This normally defaults to C:Program FilesOpenVPN, and there are usually very few reasons to change that. Click on Install to confirm. Finishing installation While OpenVPN is installing, you can read its output in the installation window and follow the creation of folders, files, and shortcuts and the installation of drivers (TAP) for networking. Recent Windows systems will warn you about the TUN/TAP driver that is about to be installed. As Microsoft can't validate the origin of the driver, its security subsystem warns you with the following dialog (Windows Server 2008): Click on Install this driver software anyway and see the OpenVPN installer complete the installation. If you've made it so far, you have successfully installed OpenVPN on your Windows system. If you want to read the Readme file, then activate the checkbox Show Readme before you click on Finish.
Read more
  • 0
  • 0
  • 13224

article-image-developing-applications-jboss-and-hibernate-part-1
Packt
19 Jan 2010
4 min read
Save for later

Developing Applications with JBoss and Hibernate: Part 1

Packt
19 Jan 2010
4 min read
Introducing Hibernate Hibernate provides a bridge between the database and the application by persisting application objects in the database, rather than requiring the developer to write and maintain lots of code to store and retrieve objects. The main configuration file, hibernate.cfg.xml, specifies how Hibernate obtains database connections, either from a JNDI DataSource or from a JDBC connection pool. Additionally, the configuration file defines the persistent classes, which are backed by mapping definition files. This is a sample hibernate.cfg.xml configuration file that is used to handle connections to a MySQL database, mapping the com.sample.MySample class. <hibernate-configuration><session-factory><property name="connection.username">user</property><property name="connection.password">password</property><property name="connection.url"> jdbc:mysql://localhost/database</property><property name="connection.driver_class"> com.mysql.jdbc.Driver</property><property name="dialect"> org.hibernate.dialect.MySQLDialect</property><mapping resource="com/sample/MyClass.hbm.xml"/></session-factory></hibernate-configuration> From our point of view, it is important to know that Hibernate applications can coexist in both the managed environment and the non-managed environment. An application server is a typical example of a managed environment that provides services to hosting applications, such as connection pooling and transaction. On the other hand, a non-managed application refers to standalone applications, such as Swing Java clients that typically lack any built-in service. In this article, we will focus on managed environment applications, installed on JBoss Application Server. You will not need to download any library to your JBoss installation. As a matter of fact, JBoss persistence layer is designed around Hibernate API, so it already contains all the core libraries. Creating a Hibernate application You can choose different strategies for building a Hibernate application. For example, you could start building Java classes and map files from scratch, and then let Hibernate generate the database schema accordingly. You can also start from a database schema and reverse engineer it into Java classes and Hibernate mapping files. We will choose the latter option, which is also the fastest. Here's an overview of our application. In this example, we will design an employee agenda divided into departments. The persistence model will be developed with Hibernate, using the reverse engineering facet of JBoss tools. We will then need an interface for recording our employees and departments, and to query them as well. The web interface will be developed using a simple Model-View-Controller (MVC) pattern and basic JSP 2.0 and servlet features. The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice. Setting up the database schema The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice. CREATE schema hibernate;GRANT ALL PRIVILEGES ON hibernate.* TO 'jboss'@'localhost' WITH GRANTOPTION;CREATE TABLE `hibernate`.`department` (`department_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,`department_name` VARCHAR(45) NOT NULL,PRIMARY KEY (`department_id`))ENGINE = InnoDB;CREATE TABLE `hibernate`.`employee` (`employee_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,`employee_name` VARCHAR(45) NOT NULL,`employee_salary` INTEGER UNSIGNED NOT NULL,`employee_department_id` INTEGER UNSIGNED NOT NULL,PRIMARY KEY (`employee_id`),CONSTRAINT `FK_employee_1` FOREIGN KEY `FK_employee_1` (`employee_department_id`)REFERENCES `department` (`department_id`)ON DELETE CASCADEON UPDATE CASCADE)ENGINE = InnoDB; With the first Data Definition Language (DDL) command, we have created a schema named Hibernate that will be used to store our tables. Then, we have assigned the necessary privileges on the Hibernate schema to the user jboss. Finally, we created a table named department that contains the list of company units, and another table named employee that contains the list of workers. The employee table references the department with a foreign key constraint.
Read more
  • 0
  • 0
  • 3246
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-working-cxf-tool
Packt
18 Jan 2010
9 min read
Save for later

Working with CXF Tool

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

article-image-setting-tools-build-applications-using-jbpm-part-1
Packt
18 Jan 2010
15 min read
Save for later

Setting Up Tools to Build Applications Using jBPM: Part 1

Packt
18 Jan 2010
15 min read
Background about the jBPM project In this section, we will talk about where the jBPM framework is located inside the JBoss projects. As we know, JBoss jBPM was created and maintained for JBoss. JBoss is in charge of developing middleware "enterprise" software in Java. It is middleware because it is a type of software to make or run software, and "enterprise", as it is focused on big scenarios. This enterprise does not necessarily mean Java EE. It is also interesting to know that JBoss was bought from a company called Red Hat (famous for the Linux distribution with the same name, and also in charge of the Fedora community distribution). In order to get the right first impression about the framework, you will need to know a little about other products that JBoss has developed and where this framework is located and focused inside the company projects. At this moment, the only entry point that we have is the JBoss community page, http://www.jboss.org/. This page contains the information about all the middleware projects that JBoss is developing (all open source). If we click on the Projects link in the top menu, we are going to be redirected to a page that shows us the following image: This image shows us one important major central block for the JBoss Application Server, which contains a lot of projects intended to run inside this application server. The most representative modules are: JBoss Web: The web container based on Tomcat Web Server JBoss EJB3: EJB3 container that is standard EJB3 compliance for Java EE 5 Hibernate: The world-renowned Object Relational Mapping (ORM) framework Seam: The new web framework to build rich Internet applications JBoss Messaging: The default JMS provider that enables high performance, scalable, clustered messaging for Java On top of that, we can see two frameworks for Web Interface design (RichFaces/Ajax4jsf and Gravel) based on the components, which can be used in any web application that you code. And then, on top of it all, we can see three important blocks—Portal, Integration, and Telecom. As you can imagine, we are focused on the Integration block that contains three projects inside it. As you can see, this Integration block is also outside the JBoss Application Server boundaries. Therefore, we might suppose that these three products will run without any dependency from JBoss or any other application server. Now we are going to talk about these three frameworks, which have different focuses inside the integration field. JBoss Drools Drools is, of late, focused on business knowledge, and because it was born as an inference engine, it will be in charge of using all that business knowledge in order to take business actions based on this knowledge for a specific situation. You can find out more information about this framework (now redefined as Business Logic integration Platform) at http://www.drools.org. JBoss ESB It is a product focused on supplying an Enterprise Service Bus (ESB), which allows us to use different connectors to communicate with heterogeneous systems that were created in different languages. These use different protocols for communication. You can find out more information about this project at http://www.jboss.org/jbossesb/. JBoss jBPM jBPM has a process-centric philosophy. This involves all the APIs and tools that are related to the processes and how to manage them. The framework perspective is always centered on the business process that we describe. Also, the services available inside the framework are only for manipulating the processes. All the other things that we want or need for integration with our processes will be delegated to third-party frameworks or tools. Now, if we enter into the official page of jBPM (http://www.jbpm.org), we are going to see all the official information and updates about the framework. It is important to notice the home page, which shows us the following image: This is the first image that developers see when they get interested in jBPM. This image shows us the component distribution inside the jBPM framework project. Understanding these building blocks (components) will help us to understand the code of the framework and each part's functionality. Most of the time, this image is not clearly understood, so let's analyze it! Supported languages One of the important things that the image shows is the multi-language support for modeling processes in different scenarios. We can see that three languages are currently supported/proposed by the framework with the possibility to plug in new languages that we need, in order to represent our business processes with extra technology requirements. These supported languages are selected according to our business scenario and the technology that this scenario requires. The most general and commonly used language is jBPM Process Definition Language (jPDL). This language can be used in  situations where we are defining the project architecture and the technology that the project will use. In most of the cases, jPDL will be the correct choice, because it brings the flexibility to model any kind of situation, the extensibility to expand our process language with new words to add extra functionality to the base implementation, and no technology pluggability limitation, thereby allowing us to interact with any kind of external services and systems. That is why jPDL can be used in almost all situations. If you don't have any technology restriction in your requirements, this language is recommended. jBPM also implements the Business Process Execution Language (BPEL), which is broadly used to orchestrate Web Services classes between different systems. To support business scenarios where all the interactions are between web services, I recommend that you make use of this language, only if you are restricted to using a standard like BPEL, in order to model your business process. PageFlow is the last one shown in the image. This language will be used when you use the JBoss Seam framework and want to describe how your web pages are synchronized to fulfill some requirements. These kind of flows are commonly used to describe navigation flow possibilities that a user will have in a website. Web applications will benefit enormously from this, because the flow of the web application will be decoupled from the web application code, letting us introduce changes without modifying the web pages themselves. At last, the language pluggability feature is represented with the ellipse (...). This will be required in situations wherein the available languages are not enough to represent our business scenarios. This could happen when a new standard like BPEL or  BPMN arises, or if our company has its own language to represent business processes. In these kind of situations, we will need to implement our custom language on top of the process' virtual machine. This is not an easy task and it is important for you to know that it is not a trivial thing to implement an entire language. So, here we will be focused on learning jPDL in depth, to understand all of its features and how to extend it in order to fulfill our requirements. Remember that jPDL is a generic language that allows us to express almost every situation. In other words, the only situation where jPDL doesn't fit is where the process definition syntax doesn't allow us to represent our business process or where the syntax needs to follow a standard format like BPMN or BPEL. Also, it is important to notice that all these languages are separate from the Process Virtual Machine (PVM), the block on the bottom-left of the image, which will execute our defined process. PVM is like the core of the framework and understands all the languages that are defined. This virtual machine will know how to execute them and how to behave for each activity in different business scenarios. When we begin to understand the jPDL language in depth, we will see how PVM behaves for each activity described in our process definitions. Other modules Besides the PVM and all the languages, we can also see some other modules that implement extra functionality, which will help us with different requirements. The following list contains a brief description of each module: Graphical Process Designer (GPD) module: It is the graphical process designer module implemented as an Eclipse plugin. Identity module: This module is a proof of concept, out-of-the-box working module used to integrate business roles for our processes. This module is focused on letting us represent people/users inside the process definition and execution. This module shows us a simple structure for users and groups that can be used inside our processes. For real scenarios, this module will help us to understand how we will map our users' structures with the jBPM framework. Task ManaGeMenT (TaskMGMT) module: This module's functionality involves dealing with all the integration that the people/employees/business roles have with the processes. This module will help us to manage all the necessary data to create application clients, which the business roles will use in their everyday work. Enterprise module: This module brings us extra functionality for enterprise environments. Now that we know how the components are distributed inside the framework, we can jump to the jPDL section of jBPM's official web page. Here we will find the third image that all the developers will see when they get started with jBPM. Let's analyze this image to understand why and how the framework can be used in different platforms. This image tries to give us an example of how jBPM could be deployed on a web server or an application server. Please, keep in mind that this is not the only way that jBPM could be deployed on, or embedded in, an application, because jBPM can also be used in a standalone application. In addition, this image shows us some of the BPM stages that are implemented. For example, we can see how the designed processes will be formalized in the jPDL XML syntax in Graphical Process Designer (GPD)— here called the Eclipse jPDL Editor. On the other side of the image, we can see the execution stage implemented inside a container that could be an Enterprise Container (such as JBoss Application Server) or just a web server (such as Tomcat or Jetty). This distinction is made with the extensions of the deployed files (war, for Web Archives, and ear, for Enterprise Archives). In this container, it is important to note the jpdl-jbpm.jar archive that contains the PVM and the language definition, which lets us understand the process defined in jPDL. Also, we have the jbpm-identity.jar as a result of the Identity Module that we have seen in the other image. Besides, we have the hibernate.jar dependency. This fact is very important to note, because our processes will be persisted with Hibernate and we need to know how to adapt this to our needs. The last thing that we need to see is the Firefox/Internet Explorer logo on top of the image, which tries to show us how our clients (users), all the people who interact and make activities in our processes will talk (communicate) with the framework. Once again, HTTP interaction is not the only way to interact with the processes, we can implement any kind of interactions (such as JMS for enterprise messaging, Web Services to communicate with heterogeneous systems, mails for some kind of flexibility, SMS, and so on). Here we get a first impression about the framework, now we are ready to go ahead and install all the tools that we need, in order to start building applications. Tools and software For common tools such as Java Development Kit, IDE installation, database installation, and so on, only the key points will be discussed. In jBPM tooling, a detailed explanation will follow the download and installation process. We will be going into the structure detail and specification in depth; about how and why we are doing this installation. If you are an experienced developer, you can skip this section and go directly to the jBPM installation section. In order to go to the jBPM installation section straightaway, you will need to have the following software installed correctly: Java Development Kit 1.5 or higher (This is the first thing that Java developers learn. If you don't know how to install it, please take a look at the following link: http://java.sun.com/javase/6/webnotes/install/index.html.) Maven 2.0.9 or higher A Hibernate supported database, here we will use MySQL You will need to have downloaded the Java Connector for your selected database JBoss 5.0.1.GA installed (If you are thinking about creating Enterprise Applications, you will need JBoss AS installed. If you only want to create web applications with Tomcat or Jetty installed, this will be fine.) Eclipse IDE 3.4 Ganymede (Eclipse IDE 3.4 Ganymede is the suggested version. You can try it with other versions, but this is the one tested in the article.) An SVN client, here we will use Tortoise SVN (Available for Windows only, you can also use a subversion plugin for Eclipse or for your favorite IDE.) If you have all this software up and running, you can jump to the next section. If not, here we will see a brief introduction of each one of them with some reasons that explain why we need each of these tools. Maven—why do I need it? Maven is an Apache project that helps us to build, maintain, and manage our Java Application projects. One of the main ideas behind Maven is to solve all the dependency problems between our applications and all the framework libraries that we use. If you read the What is Maven? page (http://maven.apache.org/what-is-maven.html), you will find the key point behind this project. The important things that we will use here and in your diary work will be: A standard structure for all your projects Centralized project and dependencies description Standard structure for all your projects Maven proposes a set of standard structures to build our Java projects. The project descriptor that we need to write/create depends on the Java project type that we want to build. The main idea behind it is to minimize the configuration files to build our applications. A standard is proposed to build each type of application. You can see all the suggested standard structure on the official Maven page: http://maven.apache.org/guides/introduction/introduction-to-thestandard-directory-layout.html. Centralized project and dependencies description When we are using Maven, our way of building applications and managing the dependencies needed by these applications changes a lot. In Maven, the concept of Project Object Model (POM) is introduced. This POM will define our project structure, dependencies, and outcome(s) in XML syntax. This means that we will have just one file where we will define the type of project we are building, the first order dependencies that the project will have, and the kind of outcome(s) that we are expecting after we build our project. Take a look at the following pom.xml file: <?xml version="1.0" encoding="UTF-8"?><project xsi_schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.jbpm.examples</groupId> <artifactId>chapter02.homeworkSolution</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>chapter02.homeworkSolution</name> <url>http://maven.apache.org</url> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build><dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency></dependencies></project> We are basically defining all the mentioned characteristics of our project. All this information is deduced from the packaging attribute, which in this case is: <packaging>jar</packaging> The standard structure of directories will be used in order to know where the source code is located and where the compiled outcome will be placed. Maven installation Getting maven installed is a very simple task. You should download the Maven binaries from the official page(http://maven.apache.org). This will be a .zip file, or a .tar.gz file, which you will only need to uncompress in the programs directory. You will also add the bin directory to the system Path variable. With that, you will be able to call the mvn command from the console. To test whether Maven is working properly, you can open the Windows console and type mvn. You should get something like this: This output shows us that Maven is correctly installed. However, as it is installed in C:Documents and Settingssalaboy21 (the installation directory) where there is no project descriptor, the build failed. I strongly recommend that you read and understand the Getting Started section in the official Maven documentation at http://maven.apache.org/guides/getting-started/index.html.
Read more
  • 0
  • 0
  • 8371

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

Showcasing Personnel with Faculty/Staff Directory using Plone 3

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

article-image-overview-tomcat-6-servlet-container-part-1
Packt
18 Jan 2010
11 min read
Save for later

An Overview of Tomcat 6 Servlet Container: Part 1

Packt
18 Jan 2010
11 min read
In practice, it is highly unlikely that you will interface an EJB container from WebSphere and a JMS implementation from WebLogic, with the Tomcat servlet container from the Apache foundation, but it is at least theoretically possible. Note that the term 'interface', as it is used here, also encompasses abstract classes. The specification's API might provide a template implementation whose operations are defined in terms of some basic set of primitives that are kept abstract for the service provider to implement. A service provider is required to make available concrete implementations of these interfaces and abstract classes. For example, the HttpSession interface is implemented by Tomcat in the form of org.apache.catalina.session.StandardSession. Let's examine the image of the Tomcat container: The objective of this article is to cover the primary request processing components that are present in this image. Advanced topics, such as clustering and security, are shown as shaded in this image and are not covered. In this image, the '+' symbol after the Service, Host, Context, and Wrapper instances indicate that there can be one or more of these elements. For instance, a Service may have a single Engine, but an Engine can contain one or more Hosts. In addition, the whirling circle represents a pool of request processor threads. Here, we will fly over the architecture of Tomcat from a 10,000-foot perspective taking in the sights as we go. Component taxonomy Tomcat's architecture follows the construction of a Matrushka doll from Russia. In other words, it is all about containment where one entity contains another, and that entity in turn contains yet another. In Tomcat, a 'container' is a generic term that refers to any component that can contain another, such as a Server, Service, Engine, Host, or Context. Of these, the Server and Service components are special containers, designated as Top Level Elements as they represent aspects of the running Tomcat instance. All the other Tomcat components are subordinate to these top level elements. The Engine, Host, and Context components are officially termed Containers, and refer to components that process incoming requests and generate an appropriate outgoing response. Nested Components can be thought of as sub-elements that can be nested inside either Top Level Elements or other Containers to configure how they function. Examples of nested components include the Valve, which represents a reusable unit of work; the Pipeline, which represents a chain of Valves strung together; and a Realm which helps set up container-managed security for a particular container. Other nested components include the Loader which is used to enforce the specification's guidelines for servlet class loading; the Manager that supports session management for each web application; the Resources component that represents the web application's static resources and a mechanism to access these resources; and the Listener that allows you to insert custom processing at important points in a container's life cycle, such as when a component is being started or stopped. Not all nested components can be nested within every container. A final major component, which falls into its own category, is the Connector. It represents the connection end point that an external client (such as a web browser) can use to connect to the Tomcat container. Before we go on to examine these components, let's take a quick look at how they are organized structurally. Note that this diagram only shows the key properties of each container. When Tomcat is started, the Java Virtual Machine (JVM) instance in which it runs will contain a singleton Server top level element, which represents the entire Tomcat server. A Server will usually contain just one Service object, which is a structural element that combines one or more Connectors (for example, an HTTP and an HTTPS connector) that funnel incoming requests through to a single Catalina servlet Engine. The Engine represents the core request processing code within Tomcat and supports the definition of multiple Virtual Hosts within it. A virtual host allows a single running Tomcat engine to make it seem to the outside world that there are multiple separate domains (for example, www.my-site.com and www.your-site.com) being hosted on a single machine. Each virtual host can, in turn, support multiple web applications known as Contexts that are deployed to it. A context is represented using the web application format specified by the servlet specification, either as a single compressed WAR (Web Application Archive) file or as an uncompressed directory. In addition, a context is configured using a web.xml file, as defined by the servlet specification. A context can, in turn, contain multiple servlets that are deployed into it, each of which is wrapped in a Wrapper component. The Server, Service, Connector, Engine, Host, and Context elements that will be present in a particular running Tomcat instance are configured using the server.xml configuration file. Architectural benefits This architecture has a couple of useful features. It not only makes it easy to manage component life cycles (each component manages the life cycle notifications for its children), but also to dynamically assemble a running Tomcat server instance that is based on the information that has been read from configuration files at startup. In particular, the server.xml file is parsed at startup, and its contents are used to instantiate and configure the defined elements, which are then assembled into a running Tomcat instance. The server.xml file is read only once, and edits to it will not be picked up until Tomcat is restarted. This architecture also eases the configuration burden by allowing child containers to inherit the configuration of their parent containers. For instance, a Realm defines a data store that can be used for authentication and authorization of users who are attempting to access protected resources within a web application. For ease of configuration, a realm that is defined for an engine applies to all its children hosts and contexts. At the same time, a particular child, such as a given context, may override its inherited realm by specifying its own realm to be used in place of its parent's realm. Top Level Components The Server and Service container components exist largely as structural conveniences. A Server represents the running instance of Tomcat and contains one or more Service children, each of which represents a collection of request processing components. Server A Server represents the entire Tomcat instance and is a singleton within a Java Virtual Machine, and is responsible for managing the life cycle of its contained services. The following image depicts the key aspects of the Server component. As shown, a Server instance is configured using the server.xml configuration file. The root element of this file is <Server> and represents the Tomcat instance. Its default implementation is provided using org.apache.catalina.core.StandardServer, but you can specify your own custom implementation through the className attribute of the <Server> element. A key aspect of the Server is that it opens a server socket on port 8005 (the default) to listen a shutdown command (by default, this command is the text string SHUTDOWN). When this shutdown command is received, the server gracefully shuts itself down. For security reasons, the connection requesting the shutdown must be initiated from the same machine that is running this instance of Tomcat. A Server also provides an implementation of the Java Naming and Directory Interface (JNDI) service, allowing you to register arbitrary objects (such as data sources) or environment variables, by name. At runtime, individual components (such as servlets) can retrieve this information by looking up the desired object name in the server's JNDI bindings. While a JNDI implementation is not integral to the functioning of a servlet container, it is part of the Java EE specification and is a service that servlets have a right to expect from their application servers or servlet containers. Implementing this service makes for easy portability of web applications across containers. While there is always just one server instance within a JVM, it is entirely possible to have multiple server instances running on a single physical machine, each encased in its own JVM. Doing so insulates web applications that are running on one VM from errors in applications that are running on others, and simplifies maintenance by allowing a JVM to be restarted independently of the others. This is one of the mechanisms used in a shared hosting environment (the other is virtual hosting, which we will see shortly) where you need isolation from other web applications that are running on the same physical server. Service While the Server represents the Tomcat instance itself, a Service represents the set of request processing components within Tomcat. A Server can contain more than one Service, where each service associates a group of Connector components with a single Engine. Requests from clients are received on a connector, which in turn funnels them through into the engine, which is the key request processing component within Tomcat. The image shows connectors for HTTP, HTTPS, and the Apache JServ Protocol (AJP). There is very little reason to modify this element, and the default Service instance is usually sufficient. A hint as to when you might need more than one Service instance can be found in the above image. As shown, a service aggregates connectors, each of which monitors a given IP address and port, and responds in a given protocol. An example use case for having multiple services, therefore, is when you want to partition your services (and their contained engines, hosts, and web applications) by IP address and/or port number. For instance, you might configure your firewall to expose the connectors for one service to an external audience, while restricting your other service to hosting intranet applications that are visible only to internal users. This would ensure that an external user could never access your Intranet application, as that access would be blocked by the firewall. The Service, therefore, is nothing more than a grouping construct. It does not currently add any other value to the proceedings. Connectors A Connector is a service endpoint on which a client connects to the Tomcat container. It serves to insulate the engine from the various communication protocols that are used by clients, such as HTTP, HTTPS, or the Apache JServ Protocol (AJP). Tomcat can be configured to work in two modes—Standalone or in Conjunction with a separate web server. In standalone mode, Tomcat is configured with HTTP and HTTPS connectors, which make it act like a full-fledged web server by serving up static content when requested, as well as by delegating to the Catalina engine for dynamic content. Out of the box, Tomcat provides three possible implementations of the HTTP/1.1 and HTTPS connectors for this mode of operation. The most common are the standard connectors, known as Coyote which are implemented using standard Java I/O mechanisms. You may also make use of a couple of newer implementations, one which uses the non-blocking NIO features of Java 1.4, and the other which takes advantage of native code that is optimized for a particular operating system through the Apache Portable Runtime (APR). Note that both the Connector and the Engine run in the same JVM. In fact, they run within the same Server instance. In conjunction mode, Tomcat plays a supporting role to a web server, such as Apache httpd or Microsoft's IIS. The client here is the web server, communicating with Tomcat either through an Apache module or an ISAPI DLL. When this module determines that a request must be routed to Tomcat for processing, it will communicate this request to Tomcat using AJP, a binary protocol that is designed to be more efficient than the text based HTTP when communicating between a web server and Tomcat. On the Tomcat side, an AJP connector accepts this communication and translates it into a form that the Catalina engine can process. In this mode, Tomcat is running in its own JVM as a separate process from the web server. In either mode, the primary attributes of a Connector are the IP address and port on which it will listen for incoming requests, and the protocol that it supports. Another key attribute is the maximum number of request processing threads that can be created to concurrently handle incoming requests. Once all these threads are busy, any incoming request will be ignored until a thread becomes available. By default, a connector listens on all the IP addresses for the given physical machine (its address attribute defaults to 0.0.0.0). However, a connector can be configured to listen on just one of the IP addresses for a machine. This will constrain it to accept connections from only that specified IP address. Any request that is received by any one of a service's connectors is passed on to the service's single engine. This engine, known as Catalina, is responsible for the processing of the request, and the generation of the response. The engine returns the response to the connector, which then transmits it back to the client using the appropriate communication protocol.
Read more
  • 0
  • 0
  • 12989
article-image-movable-type-5-introduction
Packt
18 Jan 2010
4 min read
Save for later

Movable Type 5: An Introduction

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

article-image-securely-encrypt-removable-media-ubuntu
Packt
18 Jan 2010
3 min read
Save for later

Securely Encrypt Removable Media with Ubuntu

Packt
18 Jan 2010
3 min read
The other day my Dad mentioned that "any true geek always carries a USB drive with him". I proved my geek-hood by producing the 2G titanium thumb drive from around my neck. I then did him one further by telling him that the drive was encrypted with AES 256 bit encryption. I don't know whether or not he was impressed, but I sure proved that I am a true geek. It was this experience that prompted me to share my instructions on how to securely encrypt any removable drive. Following the steps outlined in this tutorial will wipe all data from the device / partition that you present to the encryption utility. You cannot encrypt an existing system using this method and retain the data. Please ensure that you have backups of your data, or that your data is otherwise expendable. Step 1: The first step in this tutorial is installing the cryptsetup utility. This tool is part of the cryptsetup package, which is available in the default repositories. You can search for this using your favorite package management utility or install from the terminal using the command: sudo aptitude install cryptsetup Step 2: Once you have the required utility installed, we'll need to prepare the device for use. This step will alter the partition table on the device, potentially causing loss of data. Again, refer to the warning above. Identify the Device We need to know the /dev/ entry that the device is assigned in order to successfully partition and encrypt it. There are two methods outlined below which can aid you in determining the device name. In many cases the device may be listed as /dev/sdb1, /dev/sdc1, etc. The first method of identifying the device is using the fdisk utility. Simply listing all available partitions may help you determine the device. Hint: you can use the size of the device to help determine its device entry if needed. [cedwards@daphne ~]$ sudo fdisk -lDisk /dev/sda: 80.0 GB, 80026361856 bytes255 heads, 63 sectors/track, 9729 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesDisk identifier: 0x000602ca Device Boot Start End Blocks Id System/dev/sda1 * 1 13 104422 83 Linux/dev/sda2 14 46 265072+ 82 Linux swap / Solaris/dev/sda3 47 1003 7687102+ 83 Linux/dev/sda4 1004 9729 70091595 83 LinuxDisk /dev/sdb: 1021 MB, 1021313024 bytes10 heads, 45 sectors/track, 4432 cylindersUnits = cylinders of 450 * 512 = 230400 bytesDisk identifier: 0x00000000 Device Boot Start End Blocks Id System/dev/sdb1 1 4432 997177+ 83 Linux In this example I have determined that my 1G USB drive is detected as /dev/sdb1. This will be the device entry that I will use moving forward. A second method that you can use to determine the device is the dmesg utility. The dmesg utility outputs kernel-level messages to the console. One little "trick" is to unplug and replug your removable disk, and then run dmesg. You should see output similar to: dmesg...usb-storage: device found at 7usb-storage: waiting for device to settle before scanningscsi 8:0:0:0: Direct-Access Kingston DataTraveler 2.0 1.00 PQ: 0 ANSI: 2sd 8:0:0:0: Attached scsi generic sg1 type 0usb-storage: device scan completesd 8:0:0:0: [sdb] 1994752 512-byte logical blocks: (1.02 GB/974 MiB)sd 8:0:0:0: [sdb] Write Protect is offsd 8:0:0:0: [sdb] Mode Sense: 23 00 00 00sd 8:0:0:0: [sdb] Assuming drive cache: write throughsd 8:0:0:0: [sdb] Assuming drive cache: write through sdb: sdb1sd 8:0:0:0: [sdb] Assuming drive cache: write throughsd 8:0:0:0: [sdb] Attached SCSI removable diskEXT4-fs (dm-0): mounted filesystem with ordered data mode Again, we can see from this information that the USB device was detected and assigned at sdb1.
Read more
  • 0
  • 0
  • 3736

article-image-install-gnome-shell-ubuntu-910-karmic-koala
Packt
18 Jan 2010
3 min read
Save for later

Install GNOME-Shell on Ubuntu 9.10 "Karmic Koala"

Packt
18 Jan 2010
3 min read
Remember, these are development builds and preview snapshots, and are still in the early stages. While it appears to be functional (so far) your mileage may vary. Installing GNOME-Shell With the release of Ubuntu 9.10, a GNOME-Shell preview is included in the repositories. This makes it very easy to install (and remove) as needed. The downside is that it is just a snapshot so you are not running the latest-greatest builds. For this reason I've included instructions on installing the package as well as compiling the latest builds. I should also note that GNOME Shell requires reasonable 3D support. This means that it will likely *not* work within a virtual machine. In particular, problems have been reported trying to run GNOME Shell with 3D support in VirtualBox. Package Installation If you'd prefer to install the package and just take a sneak-peek at the snapshot, simply run the command below in your terminal: sudo aptitude install gnome-shell Manual Compilation Manually compiling GNOME Shell will allow you to use the latest and greatest builds, but it can also require more work. The notes below are based on a successful build I did in late 2009, but your mileage may vary. If you run into problems please note the following: Installing GNOME Shell does not affect your current installation, so if the build breaks you should still have a clean environment. You can find more details as well as known issues here: GnomeShell There is one package that you'll need to compile GNOME Shell called jhbuild. This package, however, has been removed from the Ubuntu 9.10 repositories for being outdated. I did find that I could use the package from the 9.04 repository and haven’t noticed any problems in doing so. To install jhbuild from the 9.04 repository use the instructions below: Visit http://packages.ubuntu.com/jaunty/all/jhbuild/download Select a mirror close to you Download / Install the .deb package. I don’t believe there are any additional dependencies needed for this package. After that package is installed you’ll want to download a GNOME Shell Build Setup script which makes this entire process much, much simpler. cd ~ wget http://git.gnome.org/cgit/gnome-shell/plain/tools/build/gnome-shell-build-setup.sh This script will handle finding and installing dependencies as well as compiling the builds, etc. To launch this script, run the command: gnome-shell-build-setup.sh You'll need to ensure that any suggested packages are installed before continuing. You may need to re-run this script multiple times until it has no more warnings. Lastly, you can begin the build process. This process took about twenty minutes on my C2D 2.0Ghz Dell laptop. My build was completely automated, but considering this is building newer and newer builds, your mileage may vary. To begin the build process on your machine, run the command: jhbuild build Ready To Launch Congratulations! You've now got GNOME-Shell installed and ready to launch. I've outlined the steps below. Please take note of the method, depending on how you installed. Also, please note that before you launch GNOME-Shell you must DISABLE Compiz. If you have Compiz running, navigate to System > Preferences > Appearances and disable it under the Desktop Effects tab. Package Installation Launch gnome-shell --replace Manual Compilation It will as follows: ~/gnome-shell/source/gnome-shell/src/gnome-shell --replace
Read more
  • 0
  • 0
  • 12276
article-image-setting-tools-build-applications-using-jbpm-part-2
Packt
18 Jan 2010
13 min read
Save for later

Setting Up Tools to Build Applications Using jBPM: Part 2

Packt
18 Jan 2010
13 min read
jBPM structure It is an important task to understand the jBPM framework structure. We will find out how the framework sources are divided. Also, this section is very important for those programmers who want to be active community developers, fixing issues and adding new functionalities. As we have already discussed, jBPM was built and managed with Maven. For this reason, we will find a file called pom.xml inside our working copy of the official JBoss SVN repository that represents the project as a whole. If we run Maven goals to this project, all the framework will be built. As we have seen in the previous section, all the project modules were built. Look at the previous screenshot that informs us that, by default, the modules Core, Identity, Enterprise, Examples, and Simulation are built when we run the clean install goals to the main project. With the install goal too, the generated jar files are copied to our local Maven repository, so we can use it in our applications by only referencing the local Maven repository. So, the idea here is to see in detail what exactly these modules include. If you open the modules directory that is located inside your working copy, you will see the following sub-directories: In the next few sections, we will talk about the most important modules that developers need to know in order to feel comfortable with the framework. Take this as a quick, deep introduction to becoming a JBoss jBPM community member. Core module The most important module of the jBPM framework is the core module. This module contains all the framework functionality. Here we will find the base classes that we will use in our applications. If you open this directory, you will find the pom.xml file that describes this project. The important thing to notice from this file is that it gives us the Maven ArtifactID name and the GroupID. We will use this information to build our applications, because in our applications, we will need to specify the jBPM dependency in order to use the framework classes. The following image will show us only the first section of the pom.xml file located inside the modules/core/directory. This file will describe the project name, the group id that it belongs to, and also the relationship with its parent (the main project). If you open this file, you will notice that all the dependencies that this project (jar archive) needs, in order to be built, will be described in the next section. This is also interesting when you want to know exactly which libraries the framework will need to have in the classpath in order to run. You need to remember that Maven will take care of all the transitory dependencies, meaning that in this project file, only the first order dependencies will be described. So, for example, in the dependencies section of the pom.xml file, we will see the Hibernate dependency, but you won't see all the artifacts needed to build and run Hibernate—Maven will take care of all these second order dependencies. If we build only the Core module project by running the clean install goal (mvn clean install -Dmaven.test.skip), we will get three new JAR archives in the target directory. These archives will be: jbpm-jpdl-3.2.6.SP1.jar : The core functionality of the framework—you will need this JAR in all your applications that use jBPM directly. Remember, if you are using Maven, you will need to add this artifact dependency to your project and not this archive. jbpm-jpdl-3.2.6.SP1-config.jar : Some XML configurations that the framework needs. This confi guration will be used if you need your process to persist in some relational database. jbpm-jpdl-3.2.6.SP1-sources.jar : This JAR will contain all the sources that were used to build the main jar file. This can be helpful to debug our application and see how the core classes interact with each other when our processes are in the execution stage. You will also find a few directories that were used as temporary directories to build these three JAR files. DB module This module is in charge of building the different database schemes to run jBPM needed by the different vendors that support Hibernate. If you build this module in the target directory of the project (generated with the clean install of maven goals). Distribution module This is only a module created with specific goals to build and create the binary installer, which can be downloaded from jBPM's official page. If you want to get a modified installer of this framework, you will need to build this module. But it is rarely used by development teams. Enterprise module This module will contain extra features for high-availability environments, including a command service to interact with the framework's APIs, an enterprise messages solution for asynchronous execution, and enterprise-ready timers. If we build this module, we will get three JAR fies. The main one will be jbpm-enterprise-3.2.6.SP1.jar, the source code and the configuration files that these classes will need. Example module This is a very interesting module, because it contains some basic examples about how the framework could be used. If you open this module, you will find different packages with JUnit tests that show us how to use the framework APIs to achieve some common situations. These tests are used only for a learning purpose and try to introduce the most common classes that all developers will use. Feel free to play with these tests, modify them, and try to understand what is going on there. Identity module This module contains a proof of concept model to use out of the box when we start creating applications that handle human interactions. The basic idea here is to have a simple model to represent how the process users are structured in our company. As you can imagine, depending on the company structure, we need to be able to adapt this model to our business needs. This is just a basic implementation that you will probably replace for your own customized implementation. Simulation module This module includes some use cases for simulating our process executions. The idea here is to know how to obtain reports that help us to improve our process executions, measuring times, and costs for each execution. User Guide module This module will let you build the official documentation from scratch. It is not built when the main project is built, just to save us time. You can build all the documentation in three formats—HTML file separated, one single and long HTML file, or PDF. Knowing this structure will help us to decide where to make changes and where to look for a specific functionality inside the framework sources. Try to go deep inside the src directory for each project to see how the sources are distributed for each project in more detail. Building real world applications In this section, we are going to build two example applications—both similar in content and functionalities, but built with different methodologies. The first one will be created using the Eclipse Plugin provided by the jBPM framework. This approach will give us a quick structure that lets us create our first application using jBPM. On the other hand, in the second application that we will build, we will use Maven to describe and manage our project, simulating a more realistic situation where complex applications could be built by mixing different frameworks. Eclipse Plugin Project/GPD Introduction In this section, we will build an example application that uses jBPM using the Eclipse plugin, which provides us with the jBPM framework. The idea here is to look at how these kinds of projects are created and what the structure proposed by the plugin. The outcome of this section will be a Process Archive (PAR) file generated by the GPD plugin, which contains a process definition and all the technical details needed to run in an execution environment. To achieve this, I have set up my workspace in the directory projects inside the software directory. And by having the jBPM plugin installed, you will be able to create new jBPM projects. You can do this by going to File | New | Other and choosing the New type of project called Process Project. Then you must click on the Next button to assign a new name to this project. I chose FirstProcess for the project name (I know, a very original one!) and click on Next again. The first time that you create some of these projects, Eclipse will ask you to choose the jBPM Runtime that you want. This means that you can have different runtimes (different versions of jBPM to use with this plugin) installed. To configure the correct runtime, you will need to locate the directory that the installer creates—it's called jbpm-3.2.6.SP1—then assign a name to this runtime. A common practice here is to put the name with the correct version, this will help us to identify the runtime with which we are configuring our process projects. Then you should click on the Finish button at the bottom of the window. This will generate our first process project called FirstProcess. If you have problems creating a new jBPM project, this can be noticed because you'll have a red cross placed in your project name in the Project Explorer window. You could see the current problems in the Problems window (Windows | Show View | Problems). If the problem is that a JAR file called activation.jar is missing, you should do a workaround to fix this situation. To fix this, you should go to your jBPM installation directory—in this case, software/programs/jbpm-3.2.6.SP1 on my desktop, and then go to src/resources/gpd and open a file called version.info.xml and remove the line that makes the reference to the file called activation.jar. Then you should restart the IDE and the problem will disappear. If you create the process project and the sample process definition is not created (under src/main/jpdl), you could use the project created inside this article's code directory called FirstProcess. GPD Project structure Once you have created the project, we could take a look at the current structure proposed by the plugin. This image show us the structure proposed by the GPD plugin. Four source directories will be used to contain different types of resources that our project will use the first one src/main/java will contain all the Java sources that our process uses in order to execute custom Java logic. Here we will put all the classes that will be used to achieve custom behaviors at runtime. When you create a process project, a sample process and some classes are generated. If you take a look inside this directory, you will find a class called MessageActionHandler.java. This class represents a technical detail that the process definition will use in order to execute custom code when the process is being executed. The src/main/config directory will contain all the resources that will be needed to configure the framework. In the src/main/jpdl directory, you will find all the defined processes. When you create a sample process with your project, a process called simple is created. And in src/test/ java, you will find all the tests created to ensure that our processes behave in the right way when they get executed. When the sample process is created, a test for this process is also created. It will give us a quick preview of the APIs that we will use to run our processes. For the sample process, a test called SimpleProcessTest is created. This test creates a process execution and runs it to test whether the process will behave in the way in which it is supposed to work. Be careful if you modify the process diagram, because this test will fail. Feel free to play with the diagram and with this test to see what happens. Here we will see a quick introduction about what this test does. SimpleProcessTest This test is automatically created when you create a jBPM process project with a sample process. If you open this class located in the src/test/java directory of the project, you will notice that the behavior of the test is described with comments in the code. Here we will try to see step by step what the test performs and how the test uses the jBPM APIs to interact with the process defined using the Graphical Process Editor. This test class, like every JUnit tests class will extend the class TestCase (for JUNIT 3.x). It then defines each test inside methods that start with the prefix test*. In this case, the test is called testSimpleProcess(). Feel free to add your own test in other methods that use the prefix test* in the name of the method. If we see the testSimpleProcess() method, we will see that the first line of code will create an object called processDefinition of the ProcessDefinition type using the processdefinition.xml file. ProcessDefinition processDefinition = ProcessDefinition.parseXmlResource("simple/processdefinition.xml"); At this point, we will have our process definition represented as an object. In other words, the same structure that was represented in the XML file, is now represented in the Java Object. Using the APIs provided by JUnit, we will check that the ProcessDefinition object is correctly created. assertNotNull("Definition should not be null", processDefinition); Then we need to create a process execution that will run based on the process definition object. In the jBPM language, this concept of execution is represented with the word instance. So, we must create a new ProcessInstance object that will represent one execution of our defined process. ProcessInstance instance = new ProcessInstance(processDefinition); Then the only thing we need to do is interact with the process and tell the process instance to jump from one node to the next using the concept of a signal, which represents an external event. It tells the process that it needs to continue the execution to the next node. instance.signal(); If you take a look at all the assert methods used in the code, they only confirm that the process is in the node in which it is supposed to be. Another thing that this test checks is that the Actions attached to the process change the value of a process variable. Try to figure out what is happening with that variable and where the process definition changes this variable's value. The following assert can give you a small clue about it: assertEquals("Message variable contains message", instance.getContextInstance(). getVariable("message"), "Going to the first state!"); To run this test, you just need to right click on the source of this class and go to Run As, and then choose JUnit Test. You should check whether the test succeeded in the JUnit panel (a green light will be shown if all goes well). Graphical Process Editor In this section, we will analyze the most used GPD windows, giving a brief introduction to all the functionality that this plugin provides us. We already see the project structure and the wizard to create new jBPM projects. The most frequently used window that GPD proposes to us is the Graphical Process Editor, which lets us draw our processes in a very intuitive way. This editor contains four tabs that gives us different functionalities for different users/roles.
Read more
  • 0
  • 0
  • 2006

article-image-navigating-pages-xaml-browser-applications
Packt
18 Jan 2010
4 min read
Save for later

Navigating Pages in XAML Browser Applications

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