Bula de Remédio

maio 25, 2013

Usando o Mac OS

Arquivado em: Uncategorized — jadsonjs @ 3:26 am

Atalhos do Teclados:

Copiar: ⌘ + C

Colar: ⌘ + V

Mover para cá ( recortar )  : Option + ⌘ + V

Mover Item para o Lixo: Command + Delete

Comandos:

Configurar uma variável de ambiente : PATH=$PATH:/Users/… /../…/seu_diretorio

Executando um arquivo shell script:  sh nome_do_arquivo.sh

 

Image

Conditional Execution: A Pattern for the Implementation of Fine-Grained Variabilities in Software Product Lines

Arquivado em: Padrões de Projeto — jadsonjs @ 2:28 am

Jadson Santos1,2, Gleydson Lima1,2, Uirá Kulesza1 Demóstenes Sena1, Felipe Pinto1, Jalerson Lima1 Alexandre Vianna1, David Pereira2, Victor Fernandes2

1 Department of Informatics and Applied Mathematics (DIMAP) – Federal University of Rio Grande do Norte (UFRN) – Natal – RN – Brazil

2Informatic Superintendence (SINFO) – Federal University of Rio Grande do Norte (UFRN) – Natal – RN – Brazil

jadson@info.ufrn.br, gleydson@info.ufrn.br, uira@dimap.ufrn.br, demostenes.sena@ifrn.edu.br, felipe.pinto@ifrn.edu.br, jalerson.lima@ifrn.edu.br, strapacao@gmail.com, david@info.ufrn.br, victorhcf@gmail.com

Abstract. This paper presents the Conditional Execution design pattern that aims to help the implementation of fine-grained variabilities in the context of software product lines of information systems. The pattern has been used successfully in three product lines of web information systems developed by Informatic Superintendence (SINFO) at Federal University of Rio Grande do Norte.

1. Intention

The Conditional Execution design pattern contributes to the implementation of fine-grained variabilities in the context of software product lines (SPL) [Clements and Northrop 2001] [Czarnecki and Eisenecker 2000] [Weiss 1999] of information systems. It provides support to the modularization of a certain variability located in one or more modules to values assigned to configurations parameters, allowing its activation (or deactivation) dynamically in the system.

2. Example

In order to illustrate the need for the usage of the pattern, we present examples from a Library Management module of a software product line of an academic information system. We use the punishment functionality for users who return late borrowed books. This functionality defines a variability that determines the kinds of punishment, which can be: (i) a payment in cash or (ii) a suspension for a period of time without to make new loans.

During the execution of the system, which represents a product (instance) of the SPL, the decision for execution of such punishment variability can happen several times, for example, during the execution of a new loan, returning a book or printing a bill for payment. The variability code is also spread among the system layers, from the calculation of the amounts of punishment in the business layer to the user visualization of loan functionalities in GUI layer. In some cases, the system manager can provide a

“period of forgiving” during which the users do not receive punishment, even if they return the material overdue. All variabilities related to the punishment feature must be deactivated from the system and then being re-activated immediately after the system manager request.

Listing 1 shows the code of the ReturnLoanProcessor class from business layer containing the functionality “return of a book loan” without the punishment variability. We want to create a variation point inside the core conditional statement that verifies if the return of the book is delayed. It is noticed that the code that creates a suspension is intertwined with business code that verifies the permission of the operator (library employee who performs the loan), updating the data to commit the loan and sending e-mail information to the user about the book return.

ReturnLoanProcessorWithOutVariability

Listing 1: Example of fine-grained variability in business layer

Software product lines of medium and large scale with a large number of features, tend to have fine-grained variabilities [Kästner, Apel and Kuhlemann 2008] that are intertwined with the implementations of other common and variable features.

It is necessary to implement the variability of execution the punishment feature in the example in Listing 1 in a way that, depending on the type of punishment that is currently active, the code that implements such variability is executed, creating the correct punishment for the user, instead always create a suspension.

The decision for the execution of the variability need be codified to allow its dynamic change, reflecting if the punishment variability is currently active or not. In addition, it is also need the introduction of the variability implementation inside of classes of the business layer. In Listing 1, for example, the punishment variability must be implemented using another conditional statement (“if”) that determines its execution.

Finally, another requirement is that the proposed solution to implement the punishment variability can be used in other modules of the system, eventually implemented using other technologies. Listing 2 shows, for example, a Java Server Faces (JSF) web page from the same system, which implements a menu with the user options related to the functionalities of the book loan. The item “Print Bill for Pay Library Fines” should be visible to users only if the variability of fine is enabled.

server_menu

Listing 2: Example of fine-grained variability in view layer.

Object-oriented (OO) solutions such as design patterns [Gamma et al 1995] can contribute to the modularization of SPL variabilities in information systems by providing flexible structures to implement optional and alternatives features, which may be activated depending on the desired behavior in the product. For example, the State or Strategy [Gamma et al 1995] design patterns can be used to implement alternative variabilities, such as the example shown in Listing 1, which involves choosing one among a set of algorithms or possible states.

Although the adoption of traditional design patterns can help the modularization of SPL variabilities in information systems, the decision to instantiate or execute such variability may depend on many other parameters configured from the SPL domain. These parameters can be available during the process of derivation of the product (configuration parameters of the product) or only during its execution.

There are other modularization techniques that can be used in the implementation of fine-grained variability of information systems, such as aspect- oriented programming and conditional compilation. Each one of them faces difficulties when used in this context. Aspect-oriented programming (AOP) enables the modularization of such variabilities. However, the implementation of fine-grained variabilities is usually strongly coupled with the business code where it is located. Because of that, the use of aspects requires to expose all parameters used by the variability, which demands the codification of complex pointcuts [Kästner, Apel and Kuhlemann 2008]. Furthermore, in the context of the development of information

systems in the industry, it is not common to find software engineers who have advanced knowledge for using such technique.

The Conditional Compilation is another technique that can be used for implementing fine-grained variabilities. This technique works by defining a set of pre- processor directives in the source code, which indicate the inclusion of a fragment of code on the product of a SPL. However, this technique provides a series of limitations compared to other existing ones: (i) it is possible to define only boolean parameters when specifying the variability, and (ii) all the variabilities need to be addressed and solved during the compilation of the system, there is no support for the definition of variabilities, whose execution can be decided during the system execution.

3. Context

Nowadays there is a great demand in the industry for the customization of information software systems already developed for a given institution, in order to adapt those systems to be used in environments from other institutions. One of the motivations for such scenario is to increase productivity and quality of development of new information systems through the reuse of design and code of previously developed systems.

In this context, software engineering approaches to the development of software product lines (SPL) emerge as a promising proposal. A SPL can be seen as a family of systems that maintains: (i) a set of common features for all members of the family, known as similarities; and (ii) a set of variable features that changes based on specific needs of a SPL family member (product), called variabilities. A feature represents a functionality or property of SPLs that is used to capture their similarities and distinguish their variabilities.

The development process of SPLs involves not only the identification and modeling of their similarities and variabilities, but also the definition of a flexible architecture and the choice of adequate implementation techniques to modularize the SPL variabilities.

.

4. Problem

The Conditional Execution pattern proposes to address the following question: How to implement fine-grained variabilities in information system product lines in order to allow dynamic product configuration, without causing major changes impacts on architecture designed, keeping the performance expected by the system and being flexible enough to be implemented by all its modules and/or layers?

The following forces emerge from this problem:

(1) Dynamic Configuration: The variability choice should be performed dynamically, thus giving more flexibility to the SPL customization.

(2) Low Impact: The implementation of the variability should not require substantial changes on the SPL structure .

(3) Fine Granularity and Crosscutting: The variability can appear in any layer or piece of code, being fine-grained and/or crosscutting.

(4) Performance: The solution should run with low overhead for the system.

5. Solution

The pattern proposes to map each identified variability to a configuration parameter, which allows defining if the variation will be performed at runtime according to the parameter value.

The parameters are stored in a persistent repository, which allows easily reading and updating their values. A component is concerned in retrieving the parameter values in a transparent and efficient way, so it can instantiate the variability code to be executed based on these values.

The proposed solution is a combination of conditional statements “ifs” with configuration parameters of the system. Thus, it can decide which variability will be present in a particular product by adding or removing variabilities at runtime without keeping this decision hardcoded.

6. Structure

The Conditional Execution pattern consists of four main participants, which are illustrated in Figure 1:

Structure Diagram

Figure 1: Conditional Execution pattern structure.

6.1 Target Classes

It represents the system components where variabilities happen. The execution of the variability code depends on the configuration of the system parameters values. In the context of web information systems, Target Classes may be in any layer of the application, includying dynamic HTML content pages.

6.2 Variability Implementation

The code that modularizes the variability is located within the Target Classes. It usually consists on: (i) a direct implementation of variability code inside a Target Class; or (ii) a call to a component that implements the variability. The execution of this snippet is decided by the Execution Manager.

6.3 Execution Manager

The Execution Manager is the central element of the pattern. It determines if certain SPL variability will be executed or not based on configuration parameters from the system. The main tasks of this element are: (i) to get the parameters values from the repository as efficiently and transparently as possible; and (ii) to determine the execution of the variabilities associated with the retrieved parameters on Target Classes. Execution Manager contains the decision logic to determine if the variability is performed, removing this responsibility from the Target Classes. It provides access to configuration parameters, allowing the runtime adaptation of the variability. Finally, the Execution Manager must also provide mechanisms to optimize and minimize access to the repository, and it must maintain the parameters values synchronized with the values stored in the repository.

6.4 Parameters Repository

The Parameters Repository is responsible to store the parameters values used during the conditional execution. It allows storing and updating the parameters values during the application execution. It is fundamental that the retrieving of the parameter values is not costly for the system performance. Database systems or local files are examples of technologies that can be used as a parameter repository.

7. Dynamic

The following scenario defines the behavior of the Conditional Execution pattern during the runtime execution of variabilities.

Scenario 1: Variability Execution

An instance of the Target Class calls the Execution Manager to determine if the variability will be performed. The Execution Manager retrieves the parameter value by calling the Parameters Repository. After that, the Execution Manager indicates to the Target Class if the Variability Implementation must be executed or not. Figure 2 shows a sequence diagram that illustrates this scenario.

Dinâmica do Padrão Execucao Condicional

Figure 2: Dynamic of the Conditional Execution pattern.

8. Consequences

The Conditional Execution pattern brings the following benefits:

  • Simplicity. It simplifies the implementation and customization of fine-grained variabilities by allowing the extraction or introduction of SPL variabilities in existing legacy information systems.
  • Load-time or runtime customization. Variabilities can be configured at load or execution time. Changes in the system business rules, for example, that demands the addition or removal of variabilities may be performed by the software engineers without the need to recompile the system, such as using techniques like Conditional Compilation.
  • Preventing compilations issues. All variabilities code are present in the SPL products, the pattern eliminates the possibility of generating compilation errors during the product derivation process compared to the Conditional Compilation technique [Kästner and Apel 2009].
  • Reducing code complexity. It avoids the implementation of aspects with complex pointcuts that need exposing several parameters. It allows introducing variability code based on parameter values that can be easily implementing in any mainstream programming languages.On the other hand, Conditional Execution pattern has the following drawbacks:

• Poor variability modularization. When compared to other techniques such as aspect-oriented programming, the Conditional Execution pattern does not provide an adequate modularization, because it does not promote the separated and localized implementation of fine-grained variability. However, the usage and adaptation of virtual separation of concerns (VSoC) tools [Kästner, Apel and Kuhlemann 2008] can help to overcome this deficiency.

• Late detection of variability correct configuration. Because the Conditional Execution pattern is an implementation technique that enables the runtime decision for the execution of SPL variabilities, the effective test to verify the correct configuration of the system with their respective variabilities can be done just at load time and/or during the system execution.

• Exposure of full product line code. The code of all variabilities is always present in every SPL product, requiring only changes in parameters values for activating each of these variabilities. This may not be suitable for some business models, in which the product price depends on the amount and kind of variabilities enabled.

9. Known Uses

In recent years, the Conditional Execution design pattern has been used to implement different types of fine-grained variabilities in the information systems of the Informatics Superintendence (SINFO) at the Federal University of Rio Grande do Norte (UFRN) [SINFO / UFRN 2012 ] [GIS / SINFO 2012], such as:

• SIPAC – Sistema Integrado de Patrimônio, Gestão e Contratos: It provides fundamental operations for the management of the units responsible for finance, property and UFRN contracts, therefore, acting through activities “middle” of this institution. The SIPAC fully integrates administrative area since the request (material, service, supply of funds, daily tickets, lodging, informational material, maintenance of infrastructure) until internal distributed budget controls.

Among the several features of SIPAC using this pattern, we can cite:

o Lock Materials Purchase: It indicates whether the system will block the request of materials if the available balance is exceeded.

o Editing the Contract Occurrences: If the system possesses the operation to change/delete occurrences of contracts.

o Indication Request Period for Scholarships: The period in which the operation of request for financial aid for students is enabled.

• SIGRH – Sistema Integrado de Gestão e Recursos Humanos: It automates the human resources procedures, such as marking / changing vacation, retire calculations, functional assessment, sizing workforce, frequency control, trainings, online services and applications and functional registers, personal department reports, among others. Most operations have some level of

interaction with the nationwide system SIAPE (Sistema Integrado de Administração de Recursos Humanos), while others are only local services.

Among the several features of SIGRH using this pattern we can cite:

o The Training Server: It sets minimum grades and work hours that an employee must reaches to pass in a training course.

o Chief/Vice-Chief Lock Vacations: It sets whether the chief and the vice-chief of a unit can enjoy the vacations in the same period.

o Validation of the Employee Vacations: It defines if the validation rules at the moment of creating a vacation will be applied or not when the manager of the Personal Department creates the vacations for an employee.

• SIGAA – Sistema de Gestão de Atividades Acadêmicas: It automates the procedures in academic area through the modules: undergraduate, postgraduate (stricto sensu and lato sensu), elementary school, high school and technical school; submission and projects control and scholarship research, submission and extension actions control, submission and control of projects education (monitoring and innovations), library management system, reporting of academic professors productions, teaching activities and virtual distance learning environment called “Virtual Class”. It also provides specific portals for: rectory, teachers, students, tutors distance learning, coordination (stricto sensu, lato sensu and undergraduate), and evaluation committees (institutional and faculty).

Among the several features of SIGAA using this pattern we can cite:

o The Online Enroll: It sets whether students complete enrollment by the system or in person way only.

o Calculation of Academic Performance Indices: It calculates the indices that assess the academic performance of students in accordance with the strategies that are configured by the pattern.

o Method Evaluation of students: If students will be evaluated by grade, aptitude or concept.

o Punishment for the Delay in the Library: If users suffer fine or suspension for delaying loans of books in the library.

The mechanism of user authentication is another feature that uses the pattern, it is present in all three systems mentioned above, which can use a database or network authentication with LDAP.

Since one of the characteristics of the pattern is its simplicity of implementation, it can be applied easily in information systems. An example of these systems can be the

ERPs systems (software integrated enterprise resource planning). These softwares have features for presenting a large amount of variability because they are designed to be deployed in as many customers as possible and each of these customers have a business processes whose variability must be answered.

10. Implementation

This section presents an example of how the Conditional Execution pattern can be implemented. This example is the same shown in Section 2 about the punishment variability for the overdue materials (books, journals, proceedings, among others) from Library Management module. During the discussion of the example is highlighted how the forces involved with the pattern were implemented.

 Step 1: Identifying the Target Classes

Inside the SPL SIGAA, there are two variabilities related to the user punishment functionality: (a) cash fines for each day of delay in return of the material, and (b) suspend the user for a certain amount of days, during which the user cannot do new loans.

The using of the punishments functionality is related mainly with two scenarios of implementation in Library Management module: (i) the execution of a new loan when the system must not allow punished users get a new loans and (ii) at the moment of material return when the system must verify if it has been returned late and then it generates a punishment for the user. These two actions are performed in SPL SIGAA respectively by business classes LoanProcessor and ReturnLoanProcessor, which are characterized as Target Classes of the patterns. Both classes are part of the business layer of the SPL SIGAA which is organized following the tier architectural pattern [Buschmann et al 1996].

Inside the functionality user punishment, there is another action that involves print bill for pay library fines. This action should be only enabled if the variability “fine” is properly configured. Inside the SPL SIGAA, the places where this variability happens, which are characterized as Targets Classes are: (i) the Managed Bean PrintBillPayLibraryFinesMBean, and (ii) the following JSP pages: student_menu.jsp, professor_menu.jsp and server_menu.jsp.

Step 2: Mapping each identified variability to configurations parameters

After identification of Targets Classes, you need to create the parameters corresponding to punishment variability. For this case, there are two punishment variabilities. Thus, two parameters were defined:

• SYSTEM_WORKS_WITH_SUSPENSION

• SYSTEM_WORKS_WITH_FINE

The parameters are declared in a Java interface called LibraryParameters, which is shown in Listing 3. This interface is used by Targets Classes and Execution Manager to reference the parameters via Java source code. Each parameter has an identifier. These identifiers are created sequentially, so they are unique for the entire SPL.

InterfaceLibratyParameters

Listing 3: Interface with parameters declarations.

After that, we need to persist parameters in the Parameters Repository. In the specific case of SPL SIGAA is used the technology of the database to persist parameters. It facilitates create, access and change parameter values. Thus, the creation of parameters is inserting them into the database. Listing 4 shows the creation of the SYSTEM_WORKS_WITH_FINE parameter in the database. Besides the identifier and the parameter value, other information such as a brief description and identification of the module of the SPL SIGAA that the parameter belongs are persisted, to facilitate its use through the system.

INSERT INTO comum.parameter (name, description, value, id_subsystem, id_system, identifier)

VALUES (‘SYSTEM_WORKS_WITH_FINE’,

‘Define if the system will use fine like punishment’, ‘true’, 14000, 2, ’2_14000_8′);

Listing 4: Parameters creation in repository

The extra information above referred is not essential to the operation of the pattern. It is not the purpose of the pattern to define of persistence techniques that have to be used, other techniques can be tried to implement the Parameters Repository.

The product derivation can be done by changing the parameter value in the database, as shown in Listing 5. An interesting strategy is creating an use case for system parameters management in order to pass the responsibility to choose which variability will be presented in a particular product for some system manager.

UPDATE comum.parameter set value = ‘false’ where identifier = ’2_14000_8′;

Listing 5: Making product derivation using Conditional Execution pattern.

Thus, simply changing a value in the database determines the pattern characteristic of dynamic configuration.

Step 3: Implementing the Execution Manager

The Execution Manager is the main component in the implementation of this pattern. It contains a logical decision whether a particular variability will be performed or not.

Listing 6 shows a possible implementation of the Execution Manager. In this implementation a method checks if a given parameter variability happens retrieving the parameter from repository and returning its boolean value. If the parameter value is true, the variability is present in the product line and must be executed, if the value is false, the variability must be not executed.

Excution Manager simple

Listing 6: The Execution Manager

Normally, due to the use of this pattern, there is a considerable amount of access to the configuration parameters that can affect the system performance. The large number of data accesses to the Parameters Repository is because the system during its execution has to check in all places where variability may happen (variations points) if the variability is present in that particular product or not. Even if changes in a specific variability present in a product are rare, this checking is always necessary.

For this reason, it is recommended to adopt a strategy to minimize the number of accesses to the Parameters Repository. This strategy can be implemented in various ways. It is not the objective of the pattern to define a specific implementation strategy to achieve this aim.

How in this example of implementation we used a database system, to minimize the impact on system performance it was implemented a cache strategy. This implementation maintains information about the last time that the value of each parameter was synchronized with the value of the repository. When timeout is reached, the Execution Manager reloads the parameter value. This strategy is implemented by the method getParameter in Listing 6.

If you followed this strategy of cache, the Execution Manager should also keep an operation that forces a reload of a parameter or set of parameters whenever requested. This is useful when the value of a parameter is changed and this change should be immediately reflected in the behavior of the system.

The caching strategy used by Execution Manager ensures low impact on system performance, reducing queries to the repository, one of the forces that the proposed pattern undertakes to deliver.

This third step of the pattern implementation needs to be done once. This implementation can usually stay in the SPL architecture and it be used by all variability.

Step 4: Defining the Variability Implementation

The next step is to implement the specific code for each system variability. This code will be called by the Execution Manager if the variability happens in the product. Listing 7 shows a simplified code snippet of fine variability implementation in SIGAA SPL.

Fine Varability Implementation

Listing 7: Fine variability implementation.

Step 5: Calling Conditional Execution from Targets Classes

A conditional execution is implemented to generate the punishment for the material delay return depending on which of variability is currently enabled. Listing 8 shows the business class code ReturnLoanProcessor that is responsible to implement such functionality with the introduction of variability. To have a clear perception of this pattern, we can compare the code in Listing 8 with the code shown in Listing 1, which is presented in the same business class without using the Conditional Execution pattern.

ReturnLoanProcessorWithVariability

Listing 8: Example of Conditional Execution in business layer

We can see in the code in Listing 8 that the implementation was carried out with a low impact, since no change was needed in the core of SPL. Besides, the call to Execution Manager is a simple implementation of the method invocation and it can be perfectly included at the point where the dynamic derivation should occur.

Another variability related to the delay of the loan is SIGAA SPL variability “Print Bill for Pay Library Fines”. This functionality should be performed only if the variability “fine” is active in the system. In this case, a link is shown to the user allowing the printing of payment bill. This is also a typical example of conditional execution of fine-grained variability that can be implemented using the pattern. Listing 9 shows a snippet of a webpage of LPS SIGAA, which includes a link to print the bill only if the variability “fine” is active. Moreover, it is also presented the code snippet of class PrintBillPayLibraryFinesMBean that is responsible for accessing the Execution Manager to verify the occurrence of variability in the product.

11. Variants

server_menu_with_variability 2

PrintBilletPayLibraryFinesMBean

Listing 9: Example of Conditional Execution in view layer.

The Conditional Execution pattern can be used in a way that it performs more complex decisions than just boolean decisions that verify if a variability will be present or not in a product. This section describes two variant implementations of the pattern that are being using by SINFO/UFRN.

To illustrate the first approach, consider the functionality that checks the timeout between loans in the Library System modulo of SPL SIGAA. For this functionality there is an integer value that defines the minimum time, in hours, that a user can make a new loan of the same material. Besides, it makes possible to determine a minimum time between different loans for each product, this verification can be disabled in some products. Listing 10 shows the code of the Target Class where occurs this verification.

Loan Processor

Listing 10: Conditional Execution of Integer Variability

Instead of using a boolean parameter to determine if the variability should occur, it was created only one parameter of type integer. If this parameter value is greater than zero, the Execution Manager enables the execution of verification. At the same time, the parameter value is also used to calculate if the minimum time between loans was obeyed, throwing an exception if the business rule is not followed. Listing 11 shows an alternative implementation of the Execution Manager that verifies if a variation of type integer occurs, besides the method that returns this integer value to be used by the variability.

Excution Manager integer

Listing 11: Execution Manager for Integer Variabilities.

To this alternative implementation was added the information “type” to the parameter, beyond the information previously shown in Listing 4. This information allows determine how the variability should be treated. We call the variabilities that use an integer type parameter of “Integer Variabilities”. We emphasize that this was a solution adopted and it is not the goal of the pattern determines how these implementation details must be performed.

The second approach is based on removing of the dependency that the Targets Classes have with the Variability Implementation. In this approach, the Execution Manager doesn’ t just determine whether a V ariability Implementation will be

performance in a Target Class, but it instantiates and returns to the Target Class the Variability Implementation to be executed.

The solution adopted for this second approach makes use of the Strategy design pattern [Gamma et al 1995]. Some strategies are defined. The names of the classes that implement these strategies are mapping for parameters. If the variability is presented in the product, the Execution Manager instantiates the concrete strategies contained in those parameters.

For this approach was created a new type of parameter called “Strategy Parameter”. This kind of parameter doesn’t contain a boolean or integer value, but a class name that implements the strategy. The variabilities that use this kind of parameter we call of “Strategy Variabilities”. Figure 3 outlines the structure for this second approach. The functionality used is the same of Listings 1 and 8, the punishment of users for Library Management module of SPL SIGAA.

Class Diagram Strategy Conditional Execution

Figure 3: Example of Strategy Variability implementation using Conditional Execution pattern.

In this approach the method getVariabilityStrategies of Execution Manager receives a map of parameters. The map keys are boolean parameters which determine whether the variabilities happen and the map values are strategy parameters containing concrete strategies to be instantiated. Listing 12 contains the code for a possible implementation of the method getVariabilityStrategies.

Excution Manager strategy

Listing 12: Example of Execution Manager for Strategy Variability

If the variability contained in the map key occur, the Execution Manager instantiates the strategy contained in the map value, returning to the Target Class a list of strategies that should be executed in the product and performing the product derivation at runtime.

Listing 13 shows the implementation of the same variability shown in Listing 8, but now using the approach of strategy variability modularizing to treat the functionalities “fine” and “suspension”.

ReturnLoanProcessorWithVariabilityStrategy

Listing 13: Target Class using Conditional Execution for a Strategy Variability.

In this context, to add a new variability to SPL is necessary to create a new strategy punishment that “extends” the class UserPenaltyStrategy. It must insert the new parameters to the variability in Parameters Repository and add them to the map passed as a parameter to the method getVariabilityStrategies of the Execution Manager. Thus, a new strategy is instantiated by the Execution Manager and returned to be performed without the need to add a new conditional statement in the Target Class always that a new variation is added to the product line.

Listing 14 shows an example of information about three kinds of parameters that can be used to implement this pattern.

-- boolean parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type )

VALUES (’2_14000_8′, ‘ SYSTEM_WORKS_WITH_FINE’, ‘true’, 2, 14000, 1);

-- integer parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type)

VALUES (’2_14000_10′, ‘MINIMUM_TIME_BETWEEN_LOANS’, ’24′, 2, 14000, 2);

-- strategy parameter --

INSERT INTO comum.parameter (identifier, name, value, id_system, id_subsystem, type)

VALUES (’2_14000_20′, ‘ CLASS_NAME_SUSPENTION_STRATEGY’,

‘br.ufrn.sigaa.circulacao.negocio.SuspensionDefaultStrategy’, 2, 14000, 3);

Listing 14: Example of three kinds of parameters used by the suggested implementation of the pattern.

Other variants to the pattern implementation can be created, it depends if will appear other variabilities which behave differently from those ones described in this paper.

Acknowledgements

We are grateful to Professor Dr. Eduardo Guerra for his valuable suggestions during the shepherding process that contributed to a broader understanding of the proposed pattern. We also thank all the suggestions given by the participants of the Writers’ Workshop of SugarLoafPLop’2012.

References

Buschmann, F., Meunier, R., Rohnert, H., Sommerlad, P., Stal, M. (1996): Pattern- Oriented Software Architecture, A System of Patterns, vol. 1. Wiley.

Clements, P., Northrop, L. (2001): “Software Product Lines: Practices and Patterns”, Addison-Wesley Professional, 2001.

Czarnecki, K., Eisenecker, U. (2000): “Generative Programming: Methods, Tools, and Applications”, Addison-Wesley, 2000.

Gamma, E., Helm, Richard., Johnson, R., Vlissides, J. (1995). “Design Patterns: Elements of Reusable Object-Oriented Software”, Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.

Kästner, C., Apel, S., Kuhlemann, M. (2008). “Granularity in software product lines”. In Proceedings of the 30th international conference on Software engineering (ICSE ’08). ACM, New York, NY, USA, 311-320.

Kästner, C., Apel, S. Virtual Separation of Concerns – A Second Chance for Preprocessors. Journal of Object Technology. Vol. 8. No 6. 2009

SIG/SINFO – Management Integrated Institutional System of Informatic Superintendence at UFRN: Available at: http://www.info.ufrn.br/wikisistemas, Oct 2012.

SINFO/UFRN – Informatics Superintendence at UFRN (2012). A vailable at: http://www.info.ufrn.br, Oct 2012.

Weiss, D., Lai, C.. (1999): “Software Product-Line Engineering: A Family-Based Software Development Process”, Addison-Wesley Professional, 1999.

janeiro 27, 2012

Acessando Banco do Brasil a partir do Chrome no Linux

Arquivado em: Uncategorized — jadsonjs @ 3:54 pm

Essa aqui é para quem está com dificuldades de acessar o site do Banco do Brasil a partir do Linux utilizando o navegador Chrome.

  1. Primeiramente será preciso instalar a Máquina Virtual do Java na sua máquina, como já demostrado neste post: http://jadsonjs.wordpress.com/2009/02/02/instalando-java-no-ubuntu-linux/
  2. Depois será preciso copia o arquivo libnpjp2.so do diretório lib dentro do diretório de instalação da JRE, para o diretório plugins do Chrome.

O comando abaixo realiza essa tarefa, devendo apenas trocar os caminhos mostrados para os locais de instalação do java e chrome no seu computador :

sudo ln -s /usr/local/java/jdk1.6.0_23/jre/lib/i386/libnpjp2.so /opt/google/chrome/plugins

cria um link simbólico (atalho) do arquivo libnpjp2.so para o diretório plugins do chrome.

 

Reinicie o Chrome e digite o texto seguinte na barra de endereço do navegador:  chrome://plugins

Pronto !  O plugin Java(TM) Plug-in 1.X,X_XX deve ser mostrado. E será possível acessar o site do Banco de Brasil por ele.

abril 2, 2011

Desabilitando rede EDGE Samsung Galaxy 5 com android 2.2

Arquivado em: Configuração/Instalação — jadsonjs @ 7:01 pm

Atualizei o meu Samsung Galxy 5 para o android 2.2 – atualização ofical disponibilizada pela samsug no final de março de 2011.

A atualização “resetou” as minhas configurações de redes sem fio.Resultado, a rede de dados EDGE foi ativada novamente, e como eu não tenho plano de dados, isso me custou muitos R$ dos meus créditos antes que eu descobrisse como desativá-la.

O caminho normal é Menu -> Configurações -> Conexões sem fio e rede > Redes Moveis > Desativar conexão de dados. Mas essa opção apareceu desabilitada para mim assim que a atualização do Android foi concluída :( .

Assim procurando na internet achei um atalho que me salvou da falência:

Segurar o botão de desligar até aparecer um menu na tela. A primeira opção é “Redes Móveis”.  Onde pode-se ativa-la desativa-la.

Obs.: Só desliga a rede de dados móvel (2G/3G), não a rede WiFi.

A desativação também ajuda a poupar bateria. :)

Apanhado de siglas utilizados nessa área de comunicações móveis:

GPS -> Global Position System. Sistema de posicionamento global  via satélite.

GSM -> Global System for Mobile Communications. Rede de comunicação móvel digital. É visto como um sistema de telefone celular de segunda geração, o famoso 2G.

GPRS -> Troca de dados por pacote para sistemas GSM. Também chamado de 2.5G.

EDGE -> Rede de dados para GSM. Aumenta a velocidade das redes GPRS.

UMTS -> A nova tecnologia para comunicação móvel, são as badaladas redes 3G.

HSDPA -> Aumenta a velocidade das redes UMTS. Chamado comercialmente de 3.5G ou 3G+.

março 7, 2011

Enums em Java: utilização e persistência

Arquivado em: Código e Algoritmos — jadsonjs @ 6:52 pm

Este artigo mostra as vantagens na utilização de constantes enumeradas em Java em vez de simples constantes inteiras.  Descreve também como fazer um mapeamento simples para persistir e recuperar o valor inteiro da constante enumerada no banco.

Palavras Chaves:  Enums, Java, Hibernate, @Enumerated, ORDINAL

Enums em Java: utilização e persistência

 

fevereiro 2, 2009

Ubuntu: Como configurar um teclado padrão americano p/ aceitar acentos pt_BR

Arquivado em: Configuração/Instalação — jadsonjs @ 8:08 pm

Para voce que tem um computador com teclado americano como eu mas gostaria de usar acentos e “ç”.

Muito fácil no Ubuntu 8.10:

Sistema -> Preferencias -> Teclado.

Na aba “Disposições”, clique em um botão com um “+” para adicionar uma nova disposição.

Abrirá um nova Janela,

* Onde tem paíz coloque: “Estados Unidos”

* E onde tem variante coloque: “EUA Internacional (com teclas acentuavéis)”

Pronto, remova a desposição que existia, selecione a que foi criada como “padrão”. E clique em “Aplicar (Todo o sistema)”

OBS.: Para digitar o “ç” digite o acento agundo + “c” . (é como se você quisesse acentuar o “c”)

Para digitar qualquer acento sozinho. Precione a tecla do acento + “barra de espaço”

Instalando Java no Ubuntu (Linux)

Arquivado em: Configuração/Instalação — jadsonjs @ 7:25 pm

O Java pode ser instalado de varias maneiras. Atravez do gerenciador de pacotes Synaptic, atraves de comando apt-get

sudo apt-get install sun-java6-jre
sudo apt-get install sun-java5-jdk

ou manualmente, que e como eu prefiro.

Os passos mostrados aqui sao para a instalacao manual do Java no seu Ubuntu.

Entre no site da sun e baixa a ultima versao do Java:   http://java.sun.com/javase/downloads/index.jsp

La basicamente voce vai encontrar duas “versoes”  do Java. O JRE (+- 20 MB) e JSDK (+- 80MB). Para quem quer apenas executar aplicacoes Java, a JRE eh suficiente. O JSDK ou qualquer outra coisa que o site contenha geralmente eh para quem esta interresado em desenvolver alguma aplicacao em Java.

Baixe o arquivo binario. “.bin” em um diretorio de sua preferencia – aqui eu vou usar o /usr/local/java

Se esse diretorio nao existir voce pode cria-lo:

$ sudo mkdir /usr/local/java

De permissao de execucao para o arquivo e o execute:

$ cd /usr/local/java
$ sudo chmod +x jdk-1_6_0_11-linux-i586.bin
$ sudo ./ jdk-1_6_0_11-linux-i586.bin

Para finalizar a instalacao, so eh preciso agora criar um variavel de ambiente “apontando” para o diretorio onde o Java foi instalado para que o sistema operacional seja capaz de acha-lo.

Abra o arquivo /etc/bashrc:


$ sudo gedit /etc/bash.bashrc

Acrescente as seguintes linhas ao final do arquivo:

JAVA_HOME=/usr/local/java/jdk1.6.0_11
export PATH=:$JAVA_HOME/bin:$PATH

Proto aplicacoes Java ja podem ser executadas na sua maquina.

OBS.: Caso possua mais de uma versao do Java na sua maquina (algumas versao do linux vem com uma implementacao do Java livre sem ser a implementacao da propria SUN), use o seguinte comando para escolhe a que voce acabou de instalar.

sudo update-alternatives – - config java

O sistema irá prover algumas opções, digite o número correspondente a opcao que monstra o diretorio onde voce acabou de instalar o Java, nesse caso o /usr/local/java

 

  • Uma coisa importante que ninguem fala. A instalacao seja do JRE ou do JSDK nao instala o plugin do Java, que eh necessario para rodar applets Java dentro do seu navegador da internet – muito usado em sites de bancos, geralmente aqueles techados virtuais de seguranca.

Para instalar o pluing basta copiar ou criar um link simbolido  do arquivo .so que vem dentro do diretorio plugin do jre -para quem instalou o jsdk como eu o diretorio da jre vai esta dentro do diretorio do jsdk – para o diretorio plugins do firefox (no meu caso eu estava usando o firefox)

O comando abaixo cria esse link simbolico. É só trocar o caminho para o caminho onde está instalado o Java e o Firefox no seu sistema.

sudo ln -s /usr/local/java/jdk1.6.0_11/jre/plugin/i386/ns7/libjavaplugin_oji.so        /usr/lib/mozilla/plugins/

Para o Firefox 3.6 o plugin acima não funciona. Deve usar o plugin libnpjp2.so:

sudo ln -s /usr/local/java/jdk1.6.0_18/jre/lib/i386/libnpjp2.so /home/jadson/Programas/firefox/plugins/

Para o Firefox 4.0 o diretório plugin não existe. Então antes deve-se criá-lo.

mkdir /home/jadson/Programas/firefox/plugins/


  • Outra dica muito importante é para conseguir executar aplicações Java gráficas. Por exemplo, se você tentar executar o Eclipse pelo terminal vai funcionar, mas de der dois cliques para executar o Eclipse graficamente, ele não consiguirá encontrar a JVM apesar dela ter acabado de ter sido instalada. Será mostrado a seguinte mensagem:
A Java Runtime Environment (JRE) or Java Development Kit (JDK)
must be available in order to run Eclipse. No Java virtual machine
was found after searching the following locations:
/home/username/eclipse/jre/bin/java
'java' in your current PATH

Para resolver esse problema crie um link simbólico do diretório “java” da JRE para o diretório /usr/bin. Para minha instalação ficou:

sudo ln -s /usr/local/java/jdk1.6.0_11/jre/bin/java         /usr/bin/java

Pronto, agoro acredito que tudo que seja relacionado a Java você consiga executar no Ubuntu ou qualquer outro Linux. Tando no terminal, quanto no modo gráfico ou no seu navegador da Web.


novembro 23, 2008

Criando arquivos JAR, WAR e EAR

Arquivado em: Configuração/Instalação — jadsonjs @ 8:23 pm

Esses três arquivos são os arquivos mais utilizados para distribuição de aplicações Java. Existem várias maneiras de se gerar esses arquivos, algumas IDEs Java como o NetBeans já faz tudo automático para você. Mas eu gosto de criar projetos básicos e gerar “na mão” os arquivos para ficar menos dependente da IDE, vai que de repente surge a necessidade de mudar de NetBeans para Eclipse ou vice-versa. Você pode criar seu projeto na estrutura que quiser dentro das IDEs, desde que final gere os arquivos na estrutura definida nesse artigo para a districuiçao das suas aplicacões.

Um arquivo JAR é apenas um arquivo compactado (igual a um arquivo.zip) que contém um diretório de configurações chamado META-INF com um arquivo MANIFEST.MF dentro dele.

|-META-INF

|        | – MANIFEST.MF

|- DIRETORIO_1

|         |- *.class

|- DIRETORIO_N

Segue um script ANT, que deve ficar na raiz do seu projeto, e que gera um arquivo nessa estrutura:


<?xml version="1.0" encoding="UTF-8"?>
<project name="Criando arquivo EAR " basedir="." default="init">

<!-- definindo as propriedades do arquivo JAR -->
<property name="src" value="src"/>
<property name="bin" value="bin"/>
<property name="libs" value="libs"/>
<property name="dist" value="dist"/>
<property name="jar.file" value="${dist}/exemplo.jar" />

<!-- definindo onde estao os JARs dos sistema para a compilacao -->
<path id="classpath.base">
<fileset dir="${libs}">
<include name="*.jar" />
</fileset>
</path>

<target name="init">
<echo>Iniciando build do arquivo JAR com Ant</echo>
</target>

<target name="clean" depends="init">
<delete dir="${bin}"></delete>
</target>

<target name="prepare" depends="init">
<mkdir dir="${bin}" />
</target>

<!-- compilando os .java do diretorio src -->
<target name="compile" depends="init, clean, prepare">
<echo>Compilando as classes do diretorio src</echo>
<javac srcdir="${src}" destdir="${bin}" verbose="false">
<classpath refid="classpath.base" />
</javac>
</target>

<!--cria o JAR  -->
<target name="criar JAR " depends="compile">
<echo>Gerando arquivo JAR  </echo>
<jar jarfile="${jar.file}">
<fileset dir="${bin}">
</fileset>
</jar>
</target>

</project>

Os arquivos WAR seguem a mesma linha de raciocínio, mas tem a estrutura um pouco mais complexa
por causa do diretório WEB-INF, onde estão as “informações” do módulo web. Qualquer arquivo na
estrutura que se segue pode ser “deployado” em um servidor de aplicação web java.

|-META-INF

|        | – MANIFEST.MF

| – WEB-INF

|         | – classes

|         |          |- pacotes.*.class

|         | – lib

|         |          |- *.jar

|         | – web.xml

|

|- DIRETORIO_1

|         |- *.jsp

|- DIRETORIO_N

|- index.jsp

|-index.html

Abaixo um script ANT para gerar um arquivo WAR:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Criacao do arquivo WAR" basedir="." default="deploywar">

    <!-- definicao das propriedades dos arquivos -->
<property name="src" value="src"/>
<property name="bin" value="bin" />
<property name="libs" value="libs" />
<property name="warfile.name" value="dist/exemplo.war"/>
<property name="webappdir" value="web pages" />
<property name="webxml.file" value="${webappdir}/WEB-INF/web.xml"/>
<property name="webinf.dir" value="${webappdir}/WEB-INF" />
<property name="deploy.home" value="/home/.../jboss/server/default/deploy"/>

	<!-- definindo onde estao os JARs dos sistema -->
<path id="classpath.base">
		<fileset dir="${libs}">
			<include name="*.jar" />
		</fileset>
	</path>

	<target name="init">
		<echo>Iniciando build web do projeto</echo>
	</target>

	<target name="clean" depends="init">
		<delete dir="${bin}"/>
	</target>

	<target name="prepare" depends="init">
		<mkdir dir="${bin}" />
	</target>

	<target name="compile" depends="init, clean, prepare">
		<echo>Compilando classes</echo>
		<javac srcdir="${src}" destdir="${bin}" verbose="false">
			<classpath refid="classpath.base" />
		</javac>
	</target>

	<!-- cria um arquivo war -->
	<target name="criaWar" depends="compile">
		<echo>Gerando arquivo WAR</echo>

		<war warfile="${warfile.name}" webxml="${webxml.file}">
			<fileset dir="${webappdir}" >
				<include name="*.html" />
				<include name="*.jsp" />
			</fileset>

			<classes dir="${bin}" />
	<lib dir="${libs}">
				<exclude name="alcuma_jar_desnecessario_ao_modulo_web.jar" />
			</lib>

			<webinf dir="${webinf.dir}">
       			<include name="${webxml.file}" />
     		</webinf>

		</war>

	</target>

	<!-- faz o deploy no JBoss -->
	<target name="deploywar" depends="criaWar">

		<echo>Deploy do JBOSS</echo>
		<copy file="${warfile.name}" todir="${deploy.home}" />
	</target>

</project>

Para finalizar os arquivos EAR. São arquivos que, para variar, possuem um diretório META-INF e

podem possuir vários arquivos JARs e WARs dentro dele. Cada um com a sua própria estrutura

já citadas anteriormente.

Seguem também o script ANT que gera um EAR:

</pre>
<?xml version="1.0" encoding="UTF-8"?>
<project name="Criando arquivo EAR " basedir="." default="init">

 <!-- definicao das propriedades dos arquivos -->
<property name="src" value="src"/>
<property name="webappdir" value="web pages"/>
<property name="bin" value="bin"/>
<property name="libs" value="libs"/>
<property name="dist" value="dist"/>
<property name="deploy.home" value="/home/.../jboss-4.2.0.GA/server/default/deploy"/>

 <!-- definindo as propriedades do modulo web-->
<property name="warfile.name" value="${dist}/exemplo.war" />
<property name="webxml.file" value="${webappdir}/WEB-INF/web.xml" />
<property name="webinf.dir" value="${webappdir}/WEB-INF" />

 <!-- definindo as propriedades do ear-->
<property name="metainf.dir" value="META-INF" />
<property name="session.jar.file" value="${dist}/exemplo.jar" />
<property name="application.ear.file" value="${dist}/exemplo.ear" />

 <!-- definindo onde estao os JARs dos sistema para a compilacao -->
<path id="classpath.base">
 <fileset dir="${libs}">
 <include name="*.jar" />
 </fileset>
 </path>

 <target name="init">
 <echo>Iniciando build do Projeto EAR com Ant</echo>
 </target>

 <target name="clean" depends="init">
 <delete dir="${bin}"></delete>
 </target>

 <target name="prepare" depends="init">
 <mkdir dir="${bin}" />
 </target>

 <!-- compilando os .java do diretorio src -->
 <target name="compile" depends="init, clean, prepare">
 <echo>Compilando as classes do diretorio src</echo>
 <javac srcdir="${src}" destdir="${bin}" verbose="false">
 <classpath refid="classpath.base" />
 </javac>
 </target>

 <!-- cria o arquivo war do ear -->
 <target name="criaWar" depends="compile">
 <echo>Gerando arquivo WAR</echo>

 <war warfile="${warfile.name}" webxml="${webxml.file}">

 <fileset dir="${webappdir}" >
 <include name="*.html" />
 <include name="*.jsp" />
 </fileset>

 <classes dir="${bin}">
 <!-- As classes Java desses diretorios -->
 <!-- nao fazem parte do modulo web -->
 <exclude name="session/**" />
 </classes>
	<lib dir="${libs}">
 <exclude name="jboss-ejb3x.jar" />
 </lib>

 <webinf dir="${webinf.dir}">
 <include name="${webxml.file}" />
 </webinf>

 </war>

 </target>

 <!--cria o JAR com os EJBs -->
 <target name="criar JAR EJB" depends="criaWar">
 <echo>Gerando arquivo JAR com EJB </echo>
 <jar jarfile="${session.jar.file}">
 <fileset dir="${bin}">
 <!-- Os beans do JSF nao estao no modulo EJB-->
 <exclude name="managedbean/**" />
 </fileset>
 </jar>
 </target>

 <!-- cria o arquivo EAR -->
 <target name="criar arquivo EAR" depends="criar JAR EJB">
 <echo>Gerando arquivo EAR </echo>
 <jar jarfile="${application.ear.file}">

 <metainf dir="META-INF">
 <include name="application.xml" />
 </metainf>

 <fileset dir="${dist}" includes="*.ejb3, *.jar, *.war, *.par" />
 </jar>

 <!-- se quiser apagar os arquivos gerados -->
 <!--
 <delete file="${warfile.name}"/>
 <delete file="${session.jar.file}"/>
 -->

 </target>

 <!-- faz o deploy no JBoss -->
 <target name="deploy-ear" depends="criar arquivo EAR, undeploy-ear">
 <echo>Deploy aplicacao no JBOSS</echo>
 <copy file="${application.ear.file}" todir="${deploy.home}" />
 </target>

 <!-- undeploy da aplicacao -->
 <target name="undeploy-ear">
 <echo>UnDeploy aplicacao no JBOSS</echo>
 <delete file="${deploy.home}/exemplo.ear"/>
 </target>

</project>
<pre>

maio 25, 2008

Restringindo acesso e adicionando SLL a sua aplicação

Arquivado em: Configuração/Instalação, Segurança — jadsonjs @ 4:19 pm

Para restringir acesso a sua aplicação no Tomcat/JBoss basta colocar um arquivo chamado context.xml

no diretório WEB-INF da referida aplicação.

contextxml

O exemplo acima mostra as configuração para liberar acesso somente a localhost e à rede privada 10.0.0.0/24.

 

* Para colocar todas as páginas da suas aplicações para usar SSL basta apenas acrescentar o seguinte trecho ao arquivo web.xml (É preciso que o Tomcat/JBoss esteja configurado para usar SSL).

web.xml

 

 

março 2, 2008

Padrões de Projeto parte 6 de 6

Arquivado em: Padrões de Projeto — jadsonjs @ 8:05 pm

         Finalmente, um exemplo simples que mostra a utilização de alguns dos padrões citados no trabalho e as conclusões.

Artigo Padroes de Projeto – Exemplo de Arquitetura e Conclusões

Older Posts »

Tema: Silver is the New Black. Blog no WordPress.com.

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.