Научная статья на тему 'Code generation and transformation for visual queries in UML'

Code generation and transformation for visual queries in UML Текст научной статьи по специальности «Компьютерные и информационные науки»

CC BY
120
47
i Надоели баннеры? Вы всегда можете отключить рекламу.
i Надоели баннеры? Вы всегда можете отключить рекламу.
iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.
i Надоели баннеры? Вы всегда можете отключить рекламу.

Текст научной работы на тему «Code generation and transformation for visual queries in UML»

Поясним, что представляет собой каждый класс на диаграмме:

• ProcessDefinition — класс описания бизнес-процесса (собственно класс диаграммы).

• FlowObject — класс элемента диаграммы (активности, точки слияния\ветвления, события).

• Connector - класс перехода, связывающего два элемента диаграммы.

• Script - класс, представляющий сценарий, запускающийся при выполнении элемента диаграммы (для точек слияния — алгоритм слияния подшивок).

• Role - класс, представляющий роль, которой должен обладать пользователь для работы с определенным элементом диаграммы.

• JoinGatewayThread - класс, представляющий идентификатор нити, которая может достичь данной точки слияния (см. описание самантики).

Подводя итог, можно сказать, что прототип, являясь лишь упрощенной демонстрацией работы будущей системы, может быть основой для простой системы электронного документоборота.

Работа над прототипом следующего уровня — прототипом, имеющим архитектуру клиент-сервер, ведется с осени 2009 года.

Литература

1. Иртегов Д.В. Система моделирования параллельных процессов, предназначенная для описания потоков работ // Проблемы вычислительной математики, математического моделирования и информатики: Сб. науч. тр. - М.: МЗ Пресс, 2006. - С. 232-254.

2. Havey M. Essential Business Process Modeling. - O'Reilly Media, Inc., 2005.

3. Juric Matjaz B. Business Process Execution Language for Web Services. - Packt Publishing, 2006.

4. Dijkman R., Dumas M., Ouyang C. Formal Semantics and Automated Analysis of BPMN Process Models. - Queensland University of Technology, 2007.

5. Hunter J. Java Servlet Programming. - O'Reilly, 1998.

CODE GENERATION AND TRANSFORMATION FOR VISUAL QUERIES IN UML

Wiktor Filipowicz, Polish-Japanese Institute of Information Technology, Warsaw, Poland,

[email protected]

Piotr Habela, Polish-Japanese Institute of Information Technology, Warsaw, Poland, [email protected] Krzysztof Kaczmarski, Warsaw University of Technology, Warsaw, Poland, [email protected] Krzysztof Stencel, Polish-Japanese Institute of Information Technology, Warsaw, Poland,

[email protected]

Introduction

In the VIDE project [1] we aimed at investigating the capability of executable modelling in the spirit of Model Driven Architecture (MDA) [2], following the standardized modelling languages: UML 2.1 [3], with its Actions and Structured Activities seamlessly integrated with OMG OCL 2.0 [4] expressions. This resulted in a textual programming language for precise UML behaviour specification; OCL expressions being its potentially most complex constituents. The visual nature of the high level UML constructs, inherent complexity of the expressions in some applications and the peculiarities of OCL syntax, motivated the search for a visual notation, especially for the expression part of the language. Several attempts and experimenting led us to a conclusion that the most promising solution would be exploiting the well-known concept of Query By Example (QBE) [5, 6] and applying it to UML models.

In this paper we describe a declarative, object-oriented, QBE-based approach to visualizing OCL expressions over a UML model instance, focusing on the underlying code generation and query rewriting issues.

1. Related Work

54

The QBE language was developed in the mid 1970’s at the IBM Research by Moshe Zloof [6]. QBE is available as a commercial IBM product as a part of Query Management Facility (QMF) interface option to DB2. Another well known implementation is the QBE part of the Paradox DBMS [7], and became one of the reasons of its great success. A visual interface similar to the original QBE is provided by Microsoft in its widespread MS-Access DBMS [8]. A simple and straightforward textual version of object QBE in pure Java/.NET is implemented in the db4o [9].

2. Visual Expressions in Object Query by Example

The language design, called Object Query By Example (OQBE) went beyond the UML/OCL metamodel [3, 4], providing instead new, dedicated constructs based on the notion of example of an object (accompanied by link example and attribute example). The actual OCL expression is produced through the transformation of such an expression model. The functionality, syntax and motivations for design decisions for our OQBE have been presented in [10]. Here, we briefly summarize the essential features. OQBE introduces a number of new important solutions specific to the object-oriented data model and to OCL. These features include:

• Support for both object identity and value comparisons,

• Returning complex results of nested structures (tuples in the OCL terminology),

• Dedicated construct for the general quantifier (->forAll iterator operation in OCL),

• Querying class extents or from variables / attributes visible in the scope.

Object examples connected with link examples can represent respective data structure examples. An attribute example may play different roles:

• Predicate - if the attribute itself or the result of operation applied to it (including various kinds of comparison) provides a Boolean.

• Output element - if an attribute example has the output flag attached.

• Sorting criterion - if the sort flag with needed properties is attached.

Before we present a detailed algorithm in the subsequent section, let’s describe the evaluation of an expression declared in OQBE as a sequence of the following steps (disregarding optimizations):

1. Retrieving objects represented by the entry points of a graph.

2. Performing joins according to the navigation through link examples.

3. Performing selections according to the constraints on the examples.

4. Sorting the result.

5. Building the final result by performing the projection into one or more fields indicated by the output flags.

Instead of an attribute name an arbitrary OCL code can be embedded.

Although the readability considerations limit the usage of connections between attribute examples, a simple construct called Comparator was introduced in order to represent comparisons between attribute or object examples. The figure below (based on a simple auction site example) illustrates the expression “return users who placed a bid in auctions whose seller has a lower rating than their own”.

user User : User

cs rating c® rating

* outputs >

piaced&a sells

: Bid : Auction

auction

Fig. 1. Comparator, navigation links and object-typed output example

55

One of the features that make OQBE different from the traditional QBE solutions based on the relational model is the availability of nested structures in expression result construction. In the textual OCL this is realized by nesting subexpressions inside an explicit Tuple constructor. We call its visual counterpart the nested region.

A similar visual construct was introduced for the general quantifier (forAll). From the example graph outside the forAll region that is connected with the examples inside the region, only those instances will be included in the result for whose all navigations through the link passing the region boundary the condition is met.

Fig. 2. Nested result and forAll region examples (“seller with their offer list nested” and “user who

sells books only”)

3. OCL Code Generating Procedure

OQBE can be mapped to a number of query/programming languages. In this project OCL is used and thus OQBE will be mapped to and executed as OCL. Each OQBE query can be mapped to OCL in more than one way. Furthermore, not all OCL constructs can be mapped to OQBE, since it covers only a subset of OCL querying capabilities. Therefore, the reverse mapping (from OCL to OQBE) was not considered in this project. The mapping procedure is quite complex mainly due to the lack of the join operator in OCL. In the following we show a workaround, however the generated queries would be much simpler, if the join were present in OCL.

The mapping is constructed in several steps. An OQBE query is a directed graph with vertices representing examples and edges representing navigation links and comparators between examples.

1. We construct the set S being the minimal set of examples such that all examples are reachable by navigation links from some examples of this set.

2. For each example E from the set S we construct a query selecting database objects described by this example. It has a form:

generator->select(condition)

where the generator is either the extent of the class of the example E (if E is not named) or a variable with the same name as the name of example E. The condition is the filtering predicate for the example E.

3. Next we combine all queries constructed in point 2 into queryn which returns all possible tuples built from the results of queries from the step 2. The number n is the cardinality of S. The stepwise construction of this query is performed as follows:

queryi = generatori->select(conditioni)->collect ( it | Tuple { vi = it} )

56

query2 = queryi->collect(it | generator2 ->select(condition2) ->collect(vTemp | Tuple {v2 = it.v2, v2 = vTemp}))

queryk = queryk_2->collect(it | generator* ->select(conditionk) ->collect(vTemp | Tuple {v2 = it.v2, v2 = it.v2, vk-1 =

it.v*-i, Vk = vTemp}))

queryn = queryn_2->collect(it | generator^, ->select(conditionn) ->collect(vTemp | Tuple {v2 = it.v2, v2 = it.v2, vn-1 =

it.vn-2, vn = vTemp}))

4. Then queryn is enriched with fields corresponding to subsequent examples which can be reached from currently available (already reached examples). The querym always returns tuples with m fields representing m examples. Below we will show how to add the example Em+1. Since it is not a member of S, it must be reachable from S by navigation links. Let us assume that Em+1 is reachable from example Ei by link name linkName. Let us also denote by conditionm+1 the filtering condition for example Em+1. In this step we construct the following query:

querym+1 = querym->collect(it | vi.linkName->

select(conditionm+1)-> collect(vTemp | Tuple {v1 = it.vl, v2 = it.v2, vm = it.vm, vm+1 = vTemp}))

5. We repeat the step 4 until all examples are added to the constructed query.

6. Then we collect the sorting criteria and add them at the end of the query obtained after finishing the steps 4-5. The criteria are added from left to right starting from the least significant criterion. The trail added to the query is the following (the criterionk is most significant, while the criterion1 is least significant):

->sortedBy(criterion1) ->...->sortedBy(criterionk)

7. Finally we add the collect operator to limit the output to only these items which are marked as query outputs. The result will be a tuple if the number of outputs is greater than 1. Let us assume that output^.outputr specify the outputs of the constructed query; each of them is either an example of one of its attributes). The trail added in this step is one of the two:

->collect(output1)

if the number of query outputs is one.

->collect(Tuple{name1=output1, namer=outputr} )

if the number of query outputs is greater than one, where name1,...,namer are the names of items of the output tuple. The name namei is either the name given to the «output» stereotype or the name of the output element (attribute or example), if the «output» stereotype is not named.

4. Rewriting Generated OCL Queries

Queries generated by the algorithm described in the previous section are verbose and unreadable. They are not intended to be further developed textually by a programmer. Even, if it is intended only to be directly executed, it can be a challenge for the query engine. In this section we will list query optimization methods which can be used. The rewriting strategies are presented in [11, 12, 13, 14]. In case of generated OCL queries the following methods are iteratively performed:

1. removal of dead subqueries,

2. removal of unused variables,

3. exploiting associativity of the OCL collect operator: a->collect(b|c)->collect(d) = a->collect(b|c->collect(d))

57

4. flattening of vain collect-Tuple-collect chain:

a->collect(Tuple{v1=v})->collect(v)= a->collect(v)

5. flattening vain collect-select-collect chain: a->collect(v|b->select(e)->collect(v)) = a-> select(e)

6. and a rather technical issue like the alpha-conversion of iterator variable names.

The third, fourth and fifth optimisation methods above were necessary, because of some nonoptimal syntax decisions made during the design of OCL. If OCL were improved to be more programmer-friendly, no one would ever think about those methods. Usually, as the result of optimisation we get a much simpler query, which can be further sped up e.g. by using path or classic field indices. Most of optimisation steps are devoted to removal of subqueries which are introduced by the general algorithm but are redundant in the query at hand. The presence of those subqueries is unavoidable so that we can make the generation algorithm universal and powerful. This must not be regarded as a disadvantage of the generation algorithm, since we have tools which remove unnecessary parts of generated queries.

Conclusions

In this paper we have outlined the concept of the object query by example for UML. Contrary to UML as a whole however, OCL is known to relatively few professionals, and may pose a barrier for a broader adoption for a UML based programming language. Hence our proposal of a visual language that offers yet higher level of abstraction compared to OCL. The prototype has been implemented atop of our experimental ODBMS “ODRA” [15]. The core challenge of this work, outlined in this paper, is the code generation and its further transformation that requires applying optimization methods based on rewriting.

References

1. Falda, G., et al, 2008.b Executable Platform Independent Models for Data Intensive Applications. In Computational Science - ICCS 2008, 8th International Conference, Krakow, Poland, June 23-25, 2008, Proceedings, Part III. Springer, pp. 301-310.

2. Object Management Group: OMG Model Driven Architecture, http://www.omg.om/mda/

3. Object Management Group, 2007: Unified Modeling Language: Superstructure version 2.1.1. formal/2007-02-05.

4. Object Management Group, 2006: Object Constraint Language version 2.0. formal/06-05-01.

5. Elmasri, R., Navathe, S.B. 2004. Fundamentals of Database Systems, Addison Wesley, Fourth Edition.

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

6. Zloof, M., 1975. Query By Example. NCC, AFIPS, 44.

7. Business Wire, 1995a. Paradox 5.0 for Windows Voted Best Buy, Feb 6, 1995

http://finda.rticles.com/p/articles/mi m0EIN/is 1995 Feb 6/ai 16407965

8. Microsoft Microsoft Access Home Page, http://office.microsoft.com/en-us/access

9. Paterson, J., Edlich, S., Horning, H.R., 2006. The Definitive Guide to db4o, Apress, Berkeley, California

10. Habela, P., Charfi, A., Spriestersbach, A., 2008. Visual modelling of behaviour in data-intensive business applications. http://www.vide-ist.eu/publications.html

11. Plodzien, J., 2000. Optimization Methods in Object Query Languages. Ph.D. Thesis. Institute of

Computer Science, Polish Academy of Sciences.

http://www.sbql.pl/phds/PhD%20Jacek%20Plodzien.pdf

12. Plodzien, J., Subieta, K., 2001 a. Applying Low-Level Query Optimization Techniques by Rewriting. In DEXA 2001. pp. 867-876

13. Plodzien, J., Subieta, K. 2001 b. Query Optimization through Removing Dead Subqueries. In ADBIS 2001. pp. 27-40.

14. Subieta, K., et al:, 2008. Stack-Based Approach (SBA) and Stack-Based Query Language (SBQL). http://www.sbql.pl

15. Adamus, R., et al, 2008. Overview of the Project ODRA. In Proceedings of the First International Conference on Object Databases, ICOODB 2008. pp.179-197.

58

УДК 004.9:61

РАЗРАБОТКА ПРОГРАММЫ ЗАГРУЗКИ ДАННЫХ ИЗ РАЗЛИЧНЫХ ФОРМАТОВ ФАЙЛОВ В ОБЪЕКТЫ КОНФИГУРАЦИИ ”1С: ПРЕДПРИЯТИЕ 8”

Алтыникова Екатерина Владимировна, студентка, Кафедра «Автоматизированные системы управления», Южно-Российский государственный технический университет,

Россия, Новочеркасск, [email protected]

Колокольцева Ольга Михайловна, ассистент, Кафедра «Автоматизированные системы управления», Южно-Российский государственный технический университет, Россия,

Новочеркасск, [email protected]

Платформа «1С: Предприятие 8» является широко используемой системой

автоматизации деятельности предприятия и может применяться для решения различных задач управления и учета.

В настоящее время разработано большое количество типовых и специализированных решений на платформе «1С: Предприятие 8», которые могут работать в тесной интеграции с другими решениями, разработанными на этой же платформе, так и с программным обеспечением сторонних производителей.

Большое значение имеет возможность организации загрузки и обмена данными между различными информационными системами. Платформа «1С: Предприятие 8» предоставляет разнообразные инструменты для обмена данными и интеграции прикладных решений.

Именно такая задача стала у компании «1С-АналитИКС». Одним из решений, которое разрабатывает и внедряет компания «1С-АналитИКС», является «Аналит: Учет

медицинских услуг». Компания «1С-АналитИКС» постоянно работает над расширением функциональности своих программных решений в связи с меняющимися требованиями в политике здравоохранения. Важная задача дополнения конфигурации - разработка подсистемы «Учет прикрепленного контингента».

Прикрепленный контингент - это перечень пациентов и их данных, присылаемых страховой компанией. Если пациент больше не обслуживается, присылаются данные о его откреплении (список открепленных пациентов).

Для того чтобы прикрепить контингент, в медицинские учреждения, организации отправляют сведения о контингенте в различных видах в виде: бумажного документа, таблиц Microsoft Excel, файлов формата .dbf,.xml (рис. 1)

Основной задачей, которую должна решать подсистема «Учет прикрепленного контингента», является загрузка данных из различных форматов. При этом данные о прикрепленном контингенте должны сохраняться в информационной базе. Как правило, формат данных в передаваемых файлах может быть произвольным. Например, если данные поступают в виде таблицы Microsoft Excel, то порядок столбцов может быть произвольным в файлах, поступающих от различных организаций. Кроме того, могут быть столбцы, которые необходимо игнорировать.

Рис. 1. Схема загрузки данных

Первым этапом в решении поставленной задачи является анализ структуры поступающих файлов и определение объектов конфигурации, в которые будет производиться загрузка данных. Для этого была проанализирована конфигурация «Аналит: Учет медицинских услуг» и построена объектная модель данных на языке UML (рис. 2).

59

i Надоели баннеры? Вы всегда можете отключить рекламу.