Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

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

Managing Discounts, Vouchers, and Referrals with PHP 5 Ecommerce

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

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

Lesson Solutions Using Moodle 1.9: Part 2

Packt
21 Jan 2010
8 min read
Controlling the flow through a lesson If your lesson questions have all true/false or yes/no answers, you will probably set Maximum number of answers/branches to 2. If you use more than two answers per question, consider whether you want to create a jump page for each answer. If you create a unique jump page for every answer on the question pages, and you use three answers per question, how many cards will there be in your flash card deck? The answer is your lesson will have three pages for each flash card, the card itself, plus two jump pages for remedial information. We don't want to spend all day creating a short lesson. But we still want to show remedial information when a student selects the wrong answer. Consider phrasing your questions, answers, and remedial pages so that one remedial page can cover all of the incorrect responses. The illustration shows this kind of flow. Note that we've reduced the number of remedial pages that have to be created. If you must give a different feedback for each answer to a question, consider using a quiz instead of a lesson. While a remedial page in a lesson can consist of anything that you can put on a web page, a feedback can only consist of text. However, quizzes are usually easier to create than lessons. If a quiz with feedback will suffice, you can probably create it faster than the kind of branching lesson shown in the figure. But if your feedback must be feature rich, there's nothing better than Moodle's Lesson module. Use a lesson to create a deck of flash cards Flash cards are a classic teaching strategy. In addition to a learning experience, flash cards also make a good self-assessment tool for students. You can use a lesson, as if it's an online deck of flash cards. One advantage of using an online system is that log files tell you if a student completed the flash card activity, and how well the student did. Keep it moving Students are accustomed to a flash card activity moving quickly. Showing a remedial page after each incorrect response will slow down the activity. Consider using only question feedback, without remedial pages in between cards. In a flash card lesson, every page will be a question page. In a lesson, a question page can have any content that you can put on a normal web page. So, each page in your flash card lesson can consist of a fully-featured web page, with a question at the bottom and some text-only feedback for each answer. When setting the jumps for each answer on the question page (on the card), make sure that a correct answer takes the student to the next page and an incorrect answer keeps them on the same page. Again, this duplicates our physical experience with flash cards. When we get the correct answer, we move on to the next card. When we get the wrong answer, we try again until we've got it right. Lesson settings that help create a flash card experience For a flash card lesson, you will probably set Practice lesson to Yes so that the grade for this lesson will not show up in the Gradebook. As stated above, setting Maximum grade to 0 will prevent this activity from showing up in the Gradebook. However, it will also prevent a student from seeing his/her score on the activity. If you want the student to see how well he/she did on the lesson, set Practice lesson to Yes and use a maximum grade that makes sense such as one point per correct answer. Allow student review enables a student to go backwards in a lesson and retry questions that he/she got wrong. In a flash card activity, this is usually set to No. Instead, we usually set Action after correct answer to Show an unanswered Page. That means after a student answers a flash card question incorrectly, Moodle might display that card again during the same session. If the student answers the question correctly, that card is not shown again during the same session. This is how most of us are accustomed to using physical flash cards. Number of pages (cards) to show determines how many pages are shown. You usually want a flash card session to be short. If the lesson contains more than this number, the lesson ends after reaching the number set here. If the lesson contains fewer than this number, the lesson ends after every card has been shown. For a flash card lesson, set this to less than the total number of cards. You can use the Slide Show setting to display the lesson in a separate window, and make that window the size of a flash card. This can help create the effect of a deck of cards. When the student uses a physical deck of flash cards, he/she can see approximately how far into the deck he/she is. The Progress bar setting can help to create this effect with your online deck of flash cards Use an ungraded lesson to step through instructions Briefly, precorrection is anticipating mistakes that students might make, and providing instruction to help them avoid those mistakes. Consider, you give a complex assignment to students . You know that even if you supply them with written instructions, they are likely to make mistakes, even when following the instructions. You might also give the students a video demo, and a Frequently Made Mistakes document. You could even host a chat before the assignment to answer any questions they have about how to complete it. If you focus these items on the parts of the assignment that are most likely to cause trouble, they become examples of precorrection. You can use a lesson to give students precorrection for difficult instructions. Place directions that should be read in a specific order on a series of lesson pages. See to it that the students step through those pages. This has several advantages over placing all of the instructions on one page. They are as follows: Moodle will log the students' view of the lesson pages so that you can confirm they have read the instructions. While the length of a lesson page is unlimited, the tendency when creating them is to keep them short. This encourages you to break up the directions into smaller chunks, which are easier for students to understand. You can insert a question page after each step, to confirm the user's understanding of the step. Question feedback and remedial pages can correct the students' understanding, before they move to the next step. If you use this technique, the lesson should probably be a Practice lesson so that the students' grade doesn't affect their final grade for the course. A workaround Less ons are designed to primarily be a teaching tool, and only secondarily an assessment tool. However, if you decide that you prefer to use a lesson for assessment, you can work around this limitation. This workaround enables you to determine if a student answered incorrectly on an initial question or on a remedial question. A low score on remedial questions should prompt action on the teacher's part such as contacting the student and offering additional help. You have seen how a lesson usually consists of an instructional page followed by a question page, and that when a student answers a question incorrectly the lesson can display a remedial page. After the remedial page, you can present another question on the same topic. Now, imagine a lesson that covers three items. Each item has its own instructional page followed by a question page, and a remedial page followed by another question page. So, not counting the entry and exit pages, there would be: Three topic pages Three question pages Three remedial topic pages Three remedial question pages If you were looking at the Gradebook for this lesson, and a student's grade indicated that he/she got two questions wrong, you could determine whether it was because he/she gave: One incorrect response on two of the items Two incorrect responses for the same item If the student answered incorrectly on both the first and the remedial questions for the same item, it could indicate the student is having trouble with that item. But the Gradebook won't tell you that. You will need to drill down from the Gradebook into the lesson to see that student's score for each question. From the Gradebook, you would select the category in which the lesson is placed. In this example, the activities are not categorized: After selecting the category (or just Uncategorised), a table of grades for each student/activity is displayed, which is as shown in the following screenshot: You may see that Student2 did not score well on the lesson. So, select the student's score to drill down into the lesson. Select the Reports tab, then the Overview subtab, and then the grade that you want to investigate: Finally , you may think that you're going to see a detailed report telling you which questions this student got right or wrong, so you would then be able to determine which concepts or facts he/she had trouble with, and help the student with those items. But instead, you see the following screenshot:
Read more
  • 0
  • 0
  • 1429

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
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-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

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-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-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-navigating-pages-xaml-browser-applications
Packt
18 Jan 2010
4 min read
Save for later

Navigating Pages in XAML Browser Applications

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

article-image-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-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-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-advantages-and-history-openvpn
Packt
18 Jan 2010
6 min read
Save for later

Advantages and History of OpenVPN

Packt
18 Jan 2010
6 min read
Advantages of OpenVPN With the advent of OpenVPN a new generation of VPN entered the scene. While other VPN solutions often use proprietary or non-standard mechanisms, OpenVPN has a modular concept, both for underlying security and for networking. OpenVPN uses the secure, stable, and lauded SSL/TLS mechanisms and combines them in its own reliability layer. It does not suffer from the complexity that characterizes other VPN implementations like the market leader IPsec. At the same time, it offers possibilities that go beyond every other VPN implementation's scope. Layer 2 and Layer 3 VPN: OpenVPN offers two basic modes, which run either as Layer 2 or Layer 3 VPN. Thus, OpenVPN tunnels on Layer 2 can also transport Ethernet frames, IPX packets, and Windows Network Browsing packets (NETBIOS), all of which are problems in most other VPN solutions. Protecting field workers with the internal firewall: A field worker connected to the central branch of their company with a VPN tunnel can change the network setup on their laptop so that all of their network traffic is sent through the tunnel. Once OpenVPN has established a tunnel, the central firewall in the company's central branch can protect the laptop, even though it is not a local machine. Only one network port must be opened to the local (customers') network by the field worker. The employee is protected by the central firewall whenever he is connected to the VPN. Even better, the administrator of the central VPN server can force the client to use the central firewall by imposing configuration options on the clients. OpenVPN connections can be tunneled through almost every firewall and proxy: If you have Internet access and can access HTTPS web sites, then OpenVPN tunnels should work. Setups where OpenVPN tunnels are banned are very rare. OpenVPN has full proxy support including authentication. Server and client mode, UDP and TCP support: OpenVPN can be configured to run as a TCP or UDP service and as a server or client. As a server, OpenVPN simply waits until a client requests a connection, whereas a client establishes a connection according to its configuration. A server on the Internet can be completely shut down from any other machine except the ones in its virtual private network, which extends the security level of such systems enormously. Only one port in the firewall must be opened to allow incoming connections: Since OpenVPN 2.0, the special server mode allows multiple incoming connections on the same TCP or UDP port, while still using different configurations for every single connection. No problems with NAT: Both OpenVPN server and clients can be within a network using only private IP addresses. Every firewall can be used to send the tunnel traffic to the other tunnel endpoint. Virtual interfaces allow flexible very specific networking and almost every imaginable firewall rule: All restrictions, mechanisms like forwarding, and concepts like NAT (Network Address Translation) or package mangling (changing the metadata of network datagrams, like some firewalls do) can be used with and within OpenVPN tunnels. Any IP Protocol is possible. Yes, you can tunnel VPNs, like IPsec, inside an OpenVPN tunnel. High flexibility with extensive scripting possibilities: OpenVPN offers numerous points during connection setup to start individual scripts. These scripts can be used for a great variety of purposes from authentication to failover and more. Transparent, high-performance support for dynamic IPs: By using OpenVPN, there is no longer a need to use expensive, static IPs on either side of the tunnel. Both tunnel endpoints can have cheap DSL access with dynamic IPs. The users will rarely notice a change of IP on either side, Windows Terminal Server and Secure Shell (SSH) sessions will only seem to hang for few seconds, but they will not terminate and will carry on with the action requested after a short pause. All traffic can be compressed through the LZO library and OpenVPN continuously checks if the compression has been successful. So-called adaptive compression merely 'zips' the uncompressed data to avoid unnecessary overhead. Simple installation on any platform: Both installation and use are incredibly simple. Especially, if you have tried to set up IPsec connections with different implementations, you will find OpenVPN appealing. Modular Design: The modular design with a high degree of simplicity both in security and networking is outstanding. No other VPN solution can offer the same options at this level of security. Support for mobile and embedded: More and more mobile devices are supported. Packages for Windows Mobile and Nokia's Maemo platform, and embedded operating systems like OpenWrt/FreeWrt have all been provided for recently, and there are many others in development. Very active community: OpenVPN has acquired a huge amount of fans in the last few years. There are installations with high volume users with high availability. History of OpenVPN According to an interview on http://linuxsecurity.com published in 2003, James Yonan was traveling in Central Asia in the days prior to September 11, 2001 and connecting to his office over Asian or Russian Internet Providers. The fact that these connections were established over servers in countries with very dubious security made him more and more aware of and concerned about security issues. His research revealed that there were two main streams in VPN technology, one promoting security, and the other usability. None of the solutions available at that time offered an ideal blend of both objectives. IPsec and all of its implementations were difficult to set up, but offered acceptable security. However, its complex structure made it vulnerable to attacks, bugs, and security flaws. Therefore, the networking approach Yonan found in some of the usability camp's solutions seemed to make more sense to him, leading him to a modular networking model using the TUN/TAP virtual networking devices that are provided by the Linux kernel. After some study of the open source VPN field, my conclusion was that the 'usability first' camp had the right ideas about networking and inter-network tunneling, and the SSH, SSL/TLS, and IPSec camps had the appropriate level of seriousness toward the deep crypto issues. This was the basic conceptual starting point for my work on OpenVPN. James Yonan in a LinuxSecurity.com interview on November 10, 2003. (http://www.linuxsecurity.com/content/view/117363/49/) Choosing the TUN/TAP devices as a networking model immediately offered a flexibility that other VPN solutions could not offer. While other SSL/TLS-based VPN solutions needed a browser to establish connections, OpenVPN would prepare almost real (but still virtual) network devices, on which almost all networking activities can be carried out. Yonan then chose the name OpenVPN with respect to the libraries and programs of the OpenSSL project and because of the clear message that this is open source and free software.
Read more
  • 0
  • 0
  • 8732
Modal Close icon
Modal Close icon