Generic Interface

The OTRS Generic Interface consists of a multiple layer framework that lets OTRS communicate with other systems via a web service. This communication could be bi-directional:

Слои интерфейса Generic Interface

Generic Interface is build based on a layer model, to be flexible and easy to customize.

A layer is a set of files, which control how the Generic Interface performs different parts of a web service. Using the right configuration, one can build different web services for different External Systems without creating new modules.

Примечание

If the Remote System does not support the current bundled modules of the Generic Interface, special modules need to be developed for that specific web service.

Перечень модулей предоставляемых Generic Interface поставляется вместе с OTRS и будет обновлен или увеличен с течением времени.

Рисунок: Слои графического интерфейса

Транспортная Сеть

This layer is responsible for the correct communication with the Remote System. It receives requests and generates responses when acting as provider, and generates requests and receives responses when acting as requester.

Provider communication is handled by a new web server handle called "nph-genericinterface.pl".

Requester communication could be initiated during an event triggered by a Generic Interface module or any other OTRS module. This event is catched by the event handler and depending on the configuration the event will be processed directly by the requester object or delegated to the Scheduler (a separated deamon designed to process tasks asynchronously).

Отображение Данных

This layer is responsible for translating data structures between OTRS and the Remote System (data internal and data external layers). Usually Remote Systems have different data structures than OTRS (including different values and names for those values), and here resides the importance of the layer to change the received information into something that OTRS can understand and on the opposite way send the information to each Remote System using their data dictionaries.

Example: "Priority" (OTRS) might be called "Prio" in a remote system and it could be that value "1 Low" (OTRS) should be mapped to "Information" on the remote system.

Контроллер

Controllers are collections of similar Operations or Invokers. For example, a Ticket controller might contain several standard ticket operations. Custom controllers can be implemented, for example a "TicketExternalCompany" controller which may contain similar functions as the standard Ticket controller, but with a different data interface, or function names (to adapt to the Remote System function names) or complete different code.

One application for Generic Interface could be to synchronize information with one Remote System that only can talk with another Remote System of the same kind. In this case new controllers needs to be developed and the Operations and Invokers has to emulate the Remote System behavior in such way that the interface that OTRS exposes is similar to the Remote System's interface.

Операция (OTRS как поставщик услуг)

An Operation is a single action that can be performed within OTRS. All operations have the same programming interface, they receive the data into one specific parameter, and return a data structure with a success status, potential error message and returning data.

Normally operations uses the already mapped data (internal) to call core modules and perform actions in OTRS like: Create a Ticket, Update a User, Invalidate a Queue, Send a Notification, etc. An operation has full access to the OTRS API to perform the action.

Invoker - запрашивающая сторона (OTRS как запрашивающая сторона, клинет)

An Invoker is an action that OTRS performs against a Remote System. Invokers use the OTRS Core modules to process and collect the needed information to create the request. When the information is ready it has to be mapped to the Remote System format in order to be sent to the Remote System, that will process the information execute the action and send the response back, to either process the success or handle errors.

Поток связи Generic Interface

The Generic Interface has a defined flow to perform actions as a provider and as a requester.

These flows are described below:

OTRS как Поставщик

Удаленный Запрос:
  1. HTTP-запрос

    • OTRS receives HTTP request and passes it through the layers.

    • The provider module is in charge to execute and control these actions.

  2. Транспортная Сеть

    • The network transport module decodes the data payload and separates the operation name from the rest of the data.

    • Название операции и данные операции будут возвращены поставщику.

  3. Внешние данные

    • Данные отправленные из удаленной системы (Это не слой базирующийся на модуле).

  4. Mapping

    • Данные преобразуются из формата Внешней Системы во внутренний формат данных OTRS так, как это указано в конфигурации отображения для этой операции (Mapping для входящих данных запроса).

    • Преобразованные данные возвращаются обратно поставщику.

  5. Внутренние Данные

    • Data as transformed and prepared to be passed to the operation (This is not a module based layer).

  6. Операция

    • Принимает и проверяет данные.

    • Осуществляет контроль доступа пользователей.

    • Выполняет действие.

OTRS Ответ:
  1. Операция

    • Возвращает результирующие данные поставщику.

  2. Внутренние Данные

    • Данные возвращаемые из операции.

  3. Mapping

    • The data is transformed back to the Remote system format as specified in the mapping configuration (Mapping for outgoing response data).

    • Преобразованные данные возвращаются обратно поставщику.

  4. Внешние данные

    • Data as transformed and prepared to be passed to Network Transport as response.

  5. Транспортная Сеть

    • Получает данные уже в формате Удаленной Системы.

    • Создает правильный ответ для этого типа транспортной сети.

  6. HTTP ответ

    • Ответ отправляется обратно клиенту веб-сервиса.

    • В случае ошибки, сообщение об ошибке отправляется удаденной системе (например SOAP-ошибка, HTTP-ошибка и т.д.).

OTRS как запрашиваемая сторона

OTRS Запрос:
  1. Обработчки Event Trigger

    • В зависимости от настройки веб-сервис определяет будет ли запрос синхронным или асинхронным.

      • Синхронный

        • A direct call to the Requester is made in order to create a new request and to pass it through the layers.

      • Асинхронный

        • Create a new Generic Interface (Requester) task for the OTRS Scheduler (by delegating the request execution to the Scheduler, the user experience could be highly improved, otherwise all the time needed to prepare the request and the remote execution will be added to the OTRS Events that trigger those requests).

        • In its next cycle the Scheduler process reads the new task and creates a call to the Requester that will create a new request and then passes it through the layers.

  2. Запрашивающая сторона

    • Получает данные от событий.

    • Проверяет полученные данные (при необходимости).

    • Вызвать модули ядра для дополнения данных (при необходимости).

    • Возвращает структуру данных запроса или отправляет сигнал "Остановка связи" для Запрашивающей Стороны (requester), чтобы корректно отменить запрос.

  3. Внутренние Данные

    • Данные передаются от запрашивающей стороны (Это не слой, основанный на модуле).

  4. Mapping

    • The data is transformed to the Remote system format as specified in the mapping configuration (Mapping for outgoing response data).

    • Уже преобразованные данные возвращаются Запрашивающей Стороне.

  5. Внешние данные

    • Данные преобразованы и подготовлены для отправки удаленной системе.

  6. Транспортная Сеть

    • Receives the remote operation name and the data already transformed to the Remote System format from the requester.

    • Создает действительный запрос для транспортной сети.

    • Отправляет запрос удаленной системе и ожидает ответ от нее

Удаленный Ответ
  1. Транспортная сеть

    • Receives the response and decodes the data payload.

    • Возвращает данные запрашивающей стороне.

  2. Внешние данные

    • Данные полученные от Удаленной Системы

  3. Mapping

    • The data is transformed from the External System format to the OTRS internal format as specified in the mapping configuration for this operation (Mapping for incoming response data).

    • Уже преобразованные данные возвращаются Запрашивающей Стороне.

  4. Внутренние Данные

    • Data as transformed and ready to be passed back to the requester.

  5. Запрашивающая сторона

    • Получает возвращаемые данные.

    • Handles the data as needed specifically by each Invoker (included error handling if any).

    • Return the Invoker result and data to the Requester.

  6. Обработчик или Планировщик Действий

    • Receives the data from the Requester, in the case of the Scheduler this data might contain information to Re-Schedule the task immediately or in the future.

Веб-сервисы

A Web Service is a communication method between two systems, in our case OTRS and a Remote System.

The heart of the Web Service is its configuration, where it is defined what actions the web service can perform internally (Operation), what actions the OTRS request can perform Remote System (Invokers), how data is converted from one system to the other (Mapping), and over which protocol the communication will take place (Transport)

The Generic Interface is the framework that makes it possible to create Web Services for OTRS in a pre-defined way, using already made building blocks that are independent from each other and interchangeable.

Графический интерфейс веб-сервиса

The web service graphical user interface (GUI) is a tool that allows to construct complex web service configurations in a user friendly and convenient interface. It allows to:

  • Создание и Удалинеи веб-сервисов

  • Импортировать и Экспортировать настройки (в формате YAML) для существующих веб-сервисов.

  • Просматривать, Возвращаться и Экспортировать устаревшие конфигурационные параметры для существующих веб-сервисов на странице истории конфигурации.

  • Отслеживать все сообщения журнала для каждого из веб-сервисов на странице Отладчика.

Обзор Веб-интерфейса

The "Web Services" link in the main screen of Admin Interface (in the System Administration box) leads to the web services overview screen, where you are able to manage your web service configurations. You can add new web services or change the configuration of the existing ones from this screen.

Every web service configuration screen has in the upper part of the screen a "bread crumbs" style navigation path. This navigation path is useful to know exactly in which part of the web service configuration we are, and also enables the user to jump back to any part of the configuration process at any time (this action will not save any changes).

Примечание

To create a new web service, press the button "Add web service", and provide the required information.

Рисунок: Обзор Веб-сервисов

Добавить Веб Сервис

The only required field in this part is the web service "Name" that needs to be unique in the system and can not be left empty. Other fields are also necessary for the configuration like the "Debug Threshold" and "Validity" but these fields are already populated with the default value for each list.

The default value for "Debug Threshold" is "debug". When configured in this manner all communication logs are registered in the database. Each subsequent Debug Threshold value is more restrictive and discards communication logs of lower order than the one set in the system.

Отладка уровней (от нижних к верхним)

  • Отладка

  • Информация

  • Уведомление

  • Ошибка

Также есть возможность определить протокол транспортной сети для "OTRS как Поставщика" и "OTRS как Запрашиваемую Сторону".

Нажмите кнопку "Сохнанить", чтобы зарегистрировать новый веб-сервис в базе данных или кнопку "Отменить" чтобы отменить эту операцию.

If you already have a web service configuration file in YAML format you can click on the "Import web service" button on the left side of the screen. For more information on importing web services please check the next section "Web Service Change".

Примечание

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

Рисунок: Добавление нового веб-сервиса

Изменения веб-сервиса:

On this screen you have a complete set of functions to handle every part of a web service. On the left side in the action column you can find some buttons that allows you to perform all possible actions on a web service:

  • Клонирование веб-сервиса.

  • Экспортировать веб-сервис.

  • Импортировать веб-сервис.

  • История конфигурации.

  • Удалить веб-сервис.

  • Отладчик.

Примечание

Переход к "История конфигурации" и "Отладчик" приведет к открытию различных страниц.

Клонирование веб-сервиса:

To clone a web service, you need to click on the "Clone web service" button. A dialog will be shown where you can use the default name or set a new name for the (cloned) web service.

Примечание

Remember that the name of the web service must be unique within the system.

Нажмите кнопку "Клонировать" чтобы создать копию веб-сервиса или кнопку "Отменитьl", чтобы закрыть диалоговое окно.

Рисунок: Клонирование веб-сервиса.

Экспорт веб-сервиса

The "Export web service" button gives you the opportunity to dump the configuration of the current web service into a YAML file, to download it and to store it on your file system. This can be specially useful if you want to migrate the web service from one server to another, for example from a testing environment to a production system.

Предупреждение

All stored passwords in the web service configuration will be exported in plain text format.

Сразу же после нажатия кнопки "Экспорт веб-сервиса" появится диалоговое окно сохранения, на подобе того, которое появляется когда вы нажимаете в браузере ссылку сохранить.

Примечание

Each browser on each operating system has its own save dialog screen and style. Depending on the browser and its configuration it is possible that no dialog is shown and the file is saved to a default directory on your file system. Please check your browser documentation for more specific instructions if needed.

Рисунок: Экспорт веб-сервиса.

Импорт веб-сервиса:

A valid web service configuration YAML file is required to use the import web service feature. Click on the "Import web service" button, browse for the configuration file or provide the complete path in the input box.

Нажмите кнопку "Импорт" чтобы создать новый веб-сервис с файла или кнопку "Отменить" чтобы закрыть диалоговое окно.

Примечание

The web service name will be taken from the configuration file name (e.g. if the file name is MyWebservice.yml the resulting web service will be named MyWebservice). If a web service is registered in the system with the same name as the web service that you want to import, the system will lead you to the web service change screen to let you change the name of the imported web service.

Рисунок: Импорт веб-сервиса.

История веб-сервиса

Every change to the web service configuration creates a new entry in the web service history (as a journal). The web service history screen displays a list of all configuration versions for a web service. Each row (version) in the "Configuration History List" represents a single revision in the web service history.

Click on one of the rows to show the whole configuration as it was on that particular date / time. The configuration will be shown in the "History details" section of this screen. Here you are also able to export the selected web service configuration version or to restore that version into the current web service configuration.

"Экспортировать настройки веб-сервиса" ведет себя точно так же как "Экспортировать веб-сервис". Для более подробной информации обратитесь к этому разделу.

If changes to the current web service configuration do not work as expected and it is not easy to revert the changes manually, you can click on the "Revert web service configuration" button. This will open a dialog to ask you if you are sure to revert the web service configuration. Click "Revert web service configuration" in this dialog to replace the current configuration with the selected version, or click "Cancel" to close the dialog.

Предупреждение

Remember that any passwords stored in the web service configuration will be exported in plain text format.

Please be careful when you restore a configuration because this the process is irreversible.

Рисунок: История веб-сервиса

Удаление веб-сервиса

Иногда возникает необходимость удалить веб-сервис полностью. Для этого можно нажать кнопку "Удалить веб-сервис", появится диалоговое окно с вопросом о подтверждении операции.

Click on "Delete" to confirm the removal of the web service or on "Cancel" to close the dialog.

Предупреждение

Deleting a web service can't be undone, please be careful when deleting a web service.

Рисунок: Удаление веб-сервиса

Отладчик веб-сервиса:

Отладчик хранит журнал веб-сервиса. На странице отладчика можно следить за всеми связями веб-сервера, когда он работает в роли поставщика и получателя.

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

Можно сузить список используя фильтр в правой части страницы. Фильтрацию можно производить по:

  • Тип связи (поставщик или запрашиваемая сторона)

  • Дата: до и / или после определенной даты

  • Удаленный IP-адрес

  • Сочетание всех.

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

Примечание

В зависимости от критериев поиска установленых в фильтре, новый поиск может вернуть пустой список.

On the left part of the screen under the action column you can select "Go back to the web service" or clear the debugger log by pushing the "Clear" button. This will open a dialog that ask you to confirm erasing of the log. Click "Clear" in the dialog button to perform the action or click on "Cancel" to close this dialog.

В разделе "Подробности Запроса" можно просматривать подробную информацию о комуникации. Здесь можно следить за полным потоком и проверять всевозможные ошибки или подтвержать успешные ответы.

Рисунок: Отладчик веб-сервиса.

Изменение настроек веб-службы

Returning to the web service change screen, now we are going to review the right side of it. Here we have the possibility to modify all the general data for a web service such as name, description, debug threshold, etc. Also there are two more sections below that allows us to modify specific parameters for communication types "OTRS as Provider" and "OTRS as Requester".

The web service configuration needs to be saved on each level. This means that if a setting is changed, links to other, deeper parts of the configuration will be disabled forcing you to save the current configuration level. After saving the disabled links will be re-enabled again allowing you to continue with the configuration.

On the "OTRS as provider" section it is possible to set or configure the network transport protocol. Only network transport back-ends that are registered are shown on the list. To configure the network transport click on the "Configure" button. It is also possible to add new operations in this box. To do this select one of the available operations from the "Add Operation" list. This will lead you to the operation configuration screen. After saving the new operation it will be listed in the table above.

"OTRS как запрашивающая сторона" очень похож на предыдущий, но вместо "операций" здесь можно добавить invokers

Click the "Save" button to save and continue configuring the web service, "Save and finish" to save and return to the web service overview screen, or "Cancel" to discard current configuration level changes and return to web service overview screen.

Рисунок: Изменения веб-службы.

Примечание

Like the other Generic Interface configuration screens such as Network Transport, Operation, Invoker and Mapping, the initial configuration (add) screen will only present two options: "Save" and "Cancel". If the configuration is re-visited, a new option "Save and Finish" will appear. The behavior of this feature is defined below.

"Save" will store the current configuration level in the database and it will return to the previous screen to review your changes or to configure deeper settings.

"Save and Finish" сохнанит текущий уровень настроек в базе данных и вернется к предыдущей странице в иерархии конфигурации.

"Отменить" будет отменять любые изменения конфигурации и возвращать их к текущему уровню конфигурации, после чего возвращаться на к предыдущему экрану в иерархии настроек.

Транспортаня сеть Веб-сервиса

In future the list of available network transports will be increased. Currently only the "HTTP::SOAP" transport is available. Each transport has different configuration options to setup and they might use different frontend modules to configure it, but mostly they should look similar to the "HTTP::SOAP" transport configuration module.

It is quite simple to configure the "HTTP::SOAP" protocol as provider. There are only two settings: "Namespace" and "Maximum message length". These fields are required. The first one is a URI to give SOAP methods a context, reducing ambiguities, and the second one is a field where you can specify the maximum size (in bytes) for SOAP messages that OTRS will process.

Рисунок: Транспортаня сеть Веб-сервиса.

Операции веб-сервиса

The actions that can be performed when you are using OTRS as a provider are called "Operations". Each operation belongs to a controller. Controllers are collections of operations or invokers, normally operations from the same controller need similar settings and share the same configuration dialog. But each operation can have independent configuration dialogues if needed.

Name, Description, Backend, and Mappings are fields that normally appear on every operation, other special fields can appear in non default configuration dialogues to fulfill specific needs of the operation.

Normally there are two mapping configuration sections on each operation, one for the incoming data and another one for the outgoing data. You can choose different mapping types (backends) for each mapping direction, since their configuration is independent from each other and also independent from the operation backend. The normal and most common practice is that the operation uses the same mapping type in both cases (with inverted configuration). The complete mapping configuration is done in a separate screen which depends on the mapping type.

The operation backend is pre-populated and is not editable. You will see this parameter when you choose the operation on the web service edit screen. The field is only informative.

In the left part of the screen on the action column you have the options: "Go back to web service" (discarding all changes since the last save) and "Delete". If you click on the last one, a dialog will open and ask you if you like to remove the operation. Click on "Delete" button to confirm the removal of the operation and it configuration or "Cancel" to close the delete dialog.

Рисунок: Операции веб-сервиса

Web Service Requester Network Transport

The network transport configuration for the requester is similar to the configuration for the provider. For the Requester "HTTP::SOAP" network transport there are more fields to be set.

Apart from the "Endpoint" (URI of the Remote System web service interface to accept requests) and "Namespace" which are required fields, you can also specify:

  • Кодировка (такая как utf-8, latin1, iso-8859-1, cp1250, и т.д.) для SOAP-сообщений.

  • SOAPAction Header: you can use this to send an empty or filled SOAPAction header. Set to "No" and the SOAPAction header on the SOAP message will be an empty string, or set to "Yes" to send the soap action in Namespace#Action format and define the separator (typically "/" for .Net web services and "#" for the rest).

  • Аутентификация: установить механизм аутентификации, установлено в "-" чтобы не использовать любую проверку подлинности или выбрать ее из списка, после чего появится поле с подробной информацией.

Примечание

Currently only the "BasicAuth" (HTTP) authentication mechanism is implemented. You can decide whether or not to use it depending on the Remote System configuration. If used, you must provide the User Name and the Password to access the remote system.

Предупреждение

If you supply a password for authentication and after you export the web service to a YAML file this password will be revealed and will be written into a plain text string inside the YAML file. Be aware of it and take precautions if needed.

Figure: Web service requester network transport.

Вызов веб-сервиса:

The actions that can be performed when you are using OTRS as a requester are called "Invokers". Each invoker belongs to a controller (controllers are collections of operations or invokers). Usually invokers from the same controller need similar settings and share the same configuration dialogues. Each invoker can have independent configuration dialogues if needed.

Name, Description, Backend, and Mappings are fields that normally appear on every invoker. Additionally the list of event triggers and other special fields can appear on non default configuration dialogues to fulfill special needs of the invoker.

Normally there are two mapping configuration sections for each invoker, one for the incoming data and another one for the outgoing data. You can choose different mapping types (backends) for each mapping direction, since their configuration is independent from each other and also independent from the invoker backend. The normal and most common practice is that the invoker uses the same mapping type in both cases, with inverted configuration. The complete mapping configuration is done in a separate screen, which depends on the mapping type.

The invoker backend is pre-populated and can not be edited. You will see this parameter when you choose the invoker on the web service edit screen. The field is only informative.

Event triggers are events within OTRS such as "TicketCreate", "ArticleSend", etc. These can act as triggers to execute the invoker. Each invoker needs to have at least one event trigger registered, or the invoker will be useless, because it will never be called. The asynchronous property of the event triggers define if the OTRS process will handle the invoker or if it will be delegated to the Scheduler.

Примечание

The OTRS Scheduler is a separate process that executes tasks in the background. Using this the OTRS process itself will not be affected if the Remote System takes a long time to respond, if it is not available or if there are network problems. If you don't use the scheduler using web services can make OTRS slow or non-responsive. Therefore it is highly recommend to use asynchronous event triggers as often as possible.

To add an Event trigger, first select the event family from the first list, then the event name from the second list, then set the asynchronous property (if unchecked means that the event trigger will not be asynchronous) and finally click on the plus button. A new event trigger will be created and it will be listed on the invoker "Event Triggers" list.

To delete an Event trigger, simply locate the event trigger to be deleted in the "Event Triggers" list and click on the trash icon at the end of the row. This will open a dialog that asks you if you are sure to delete the event trigger. Click "Delete" to remove the event trigger from the list, or "Cancel" to close the dialog.

In the left part of the screen on the action column you have the options: "Go back to web service" (discarding all changes since the last save) and "Delete". If you click on the last one, a dialog will emerge and ask you if you like to remove the invoker. Click on the "Delete" button to confirm the removal of the invoker and its configuration or "Cancel" to close the delete dialog.

Figure: Web service invoker.

Web Service Mapping

There are cases where you need to transform the data from one format to another (map or change data structure), because normally a web service is used to interact with a Remote System, that is highly probable that is not another OTRS system and / or could not understand the OTRS data structures and values. In these cases some or all values have to be changed, and sometimes even the names of the values (keys) or even the complete structure, in order to match with the expected data on the other end. To accomplish this task the Generic Interface Mapping Layer exists.

Each Remote System has it own data structures and it is possible to create new mapping modules for each case (e.g. there is a customized mapping module for SAP Solution Manager shipped with OTRS), but it is not always necessary. The module Mapping::Simple should cover most of the mapping needs.

Примечание

When Mapping::Simple does not cover all mapping needs for a web service, a new mapping module should be created. To learn more about how to create new mapping modules please consult the OTRS Development Manual.

Этот модуль дает возможность установить значение для отображения по умолчанию для каждого ключа или значения для всех передаваемых данных.

At the beginning of the screen you will see a general section where you can set the default rules that will apply for all the unmapped keys and values. There are three options available, these options are listed below:

  • Не изменять: не касается ключей и значений в любом случае.

  • Ignore (drop key/value pair): when this is applied to the key it deletes the key and value, because when a key is deleted then in consequence its associated value is deleted too. When this is applied to the value, only the value is deleted, keeping the key, that now will be associated to an empty value.

  • MapTo (use provided key or value as default): all keys and / or values without a defined map rule, will use this as default, when you select this option a new text field will appear to set this default.

Clicking on the "+" button for new key map, will display a new box for a single mapping configuration. You can add as many key mappings as needed. Just click on the "+" button again and a new mapping box will appear below the existing one. From this mapping boxes you can define a map for a single key, with the next options:

  • Точное значение(я): строка со старым значением будет заменена новой в случае полного совпадения "старого" ключа.

  • Регулярное выражение: строки будут изменены с помощью правила преобразования.

Pressing the new value map "+" button will display a new row for a value map. Here it is also possible to define rules for each value to be mapped with the same options as for the key map (Exact value and Regular expression). You can add as many values to map as needed, and if you want to delete one of them, just click on the "-" button for each mapping value row.

Удаление целого раздела ключей отображения возможно, просто нажмите на кнопку "-", расположеную в верхнем правом углу каждого окна, для которого вы хотите удалить.

If you need to delete a complete mapping configuration: go back to the corresponding operation or invoker screen, look for the mapping direction that you select before and set its value to "-", and save the configuration to apply changes.

Figure: Web service mapping.

Интерфейс командной строки Веб-Сервиса

The Command Line Interface (CLI) is a fast way to work with the web services. It consists of a set of tools that can be use to perform basic operations like:

  • Создать, Обновить, Читать, Просматривать и Удалить веб-сервисы основаные основаные на YAML-файлах.

  • Чтение журнала Отладчика с опциями фильтрации.

Примечание

You don't need to use the CLI to work with web services. Integrated into the Admin interface there is a complete set of screens to interact with every part of the web services. Please read the web service GUI section included in this manual.

Конфигурация Веб-сервиса

Файл "WebserviceConfig.pl" был разработан для того чтобы создать простой, но в то же время быстрый и мощный инструмент для работы с настройками веб-сервиса. Он предоставляет возможность выполнять следующие действия:

  • Add: для создания веб-сервисов с использованием YAML-файлов в качестве источника конфигурации.

  • Update: изменить существующий веб-сервис, конфигурация может быть изменена с использованием других или измененных YAML-файлов.

  • Read: для вывода на экран текущих настроек веб-сервиса.

  • List: чтобы получить полный список всех веб-сервисов, зарегистрированных в системе.

  • Delete: для удаления веб-сервиса из системы. Будьте осторожны при выполнении этой операции, ее невозможно отменить.

Предупреждение

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

Пример: Создание новой конфигурации веб-сервиса:

                shell> OTRS_HOME/bin/otrs.WebserviceConfig.pl -a write -n <webservice_name> -f /path/to/yaml/file
            

Также можно использовать файл 'otrs.WebserviceConfig.pl' со следующими опциями:

  • -a read -i <webservice_id> - Для чтения сохраненной конфигурации.

  • -a write -n <webservice_name> -f /path/to/yaml/file - Для создания нового веб-сервиса.

  • -a write -i <webservice_id> -f /path/to/yaml/file - Для обновления веб-сервиса.

  • -a list - Для просмотра списка доступных веб-сервисов.

  • -a delete -i <webservice_id> - Для удаления веб-сервиса.

Отладчик веб-сервиса:

Another available tool via the command line interface is the "otrs.GenericInterfaceDebugRead.pl" script, which is an interface to search for web service debugger log entries.

Пример: Поиск записей в журнале отладчика:

                shell> bin/otrs.GenericInterfaceDebugRead.pl
            

Дополнительные параметры могут быть использованы для сценария "otrs.GenericInterfaceDebugRead.pl":

  • -c - для фильтрации по Communication ID (md5sum формат).

  • -t - для фильтрации по CommunicationType ('Provider' или 'Requester').

  • -a - для фильтрации по дате (На текущую дату или После нее).

  • -b - для фильтрации по дате (на текущую дату или До нее).

  • -i - для фильтрации по IP-адресу (должен быть правильный IPv4 или IPv6 адрес).

  • -w - для фильтрации по ID веб-сервиса.

  • -d - включить подробные передаваемые данные.

Пример: Поиск записей журнала отладчика со всеми параметрами:

                shell> ./otrs.GenericInterfaceDebugRead.pl -c a7cc4d9f5c70387a9bfbe1351bc88966 -t Provider -a '2011-07-22 00:00:00' -b '2011-07-26 00:00:00' -i 127.0.0.1 -w 123 -d 1
            

Примечание

It is highly recommended to include at least one of the filter options listed above, and even more if the "-d" option is selected, because a lot of information can be retrieved from the data base and displayed on the screen, this could result in slow response times and much more information than what you really needed.

Конфигурация Веб-сервиса

From its design the web services were conceived to be portable from one OTRS system to another, e.g. from a test or development environment to a production system. Therefore it was needed to have an easy way to extract the web service configuration from the database, and import it to another. To accomplish this task the Generic Interface uses YAML files as the web services configuration basis.

Why YAML? YAML is a markup language designed to be human friendly to read and write (it is easier to understand than JSON), it does not have some of the limitations of XML like numeric tags, it is open, standardized, and is complete enough to store the whole web service configuration.

Примечание

Чтобы узнать больше о YAML пожалуйста посетите ссылку http://www.yaml.org/.

Ниже приводится конфигурация веб-сервера на основе файла конфигурации в форматеYAML:

---
Debugger:
  DebugThreshold: debug
Description: This an example of a web service configuration
Provider:
  Operation:
    CloseIncident:
      Description: This is a test operation
      MappingInbound: {}
      MappingOutbound: {}
      RemoteSystemGuid: ''
      Type: Test::Test
    Test:
      Description: This is a test operation
      MappingInbound:
        Config:
          KeyMapDefault:
            MapTo: ''
            MapType: Keep
          KeyMapExact:
            Prio: Priority
          ValueMap:
            Priority:
              ValueMapExact:
                Critical: 5 Very High
                Information: 1 Very Low
                Warning: 3 Normal
          ValueMapDefault:
            MapTo: 3 Normal
            MapType: MapTo
        Type: Simple
      MappingOutbound:
        Config:
          KeyMapDefault:
            MapTo: ''
            MapType: Ignore
          KeyMapExact:
            Priority: Prio
          ValueMap:
            Prio:
              ValueMapExact:
                1 Very Low: Information
                3 Normal: Warning
                5 Very High: Critical
          ValueMapDefault:
            MapTo: ''
            MapType: Ignore
        Type: Simple
      Type: Test::Test
  Transport:
    Config:
      MaxLength: 10000000
      NameSpace: http://www.example.com/actions
    Type: HTTP::SOAP
RemoteSystem: remote.system.description.example.com
Requester:
  Invoker:
    Test:
      Description: This is a test invoker
      Events:
        - Asynchronous: 1
          Event: TicketCreate
        - Asynchronous: 0
          Event: ArticleUpdate
      MappingInbound:
        Type: Simple
      MappingOutbound:
        Type: Simple
      Type: Test::Test
  Transport:
    Config:
      Authentication:
        Password: '*******'
        Type: BasicAuth
        User: otrs
      Encoding: utf-8
      Endpoint: http://www.example.com:8080/endpoint
      NameSpace: http://www.example.com/actions
      SOAPAction: Yes
      SOAPActionSeparator: '#'
    Type: HTTP::SOAP
            
        

Описание Конфигурации

Общий
  • Описание: краткий текст, описывающий веб-сервис.

  • RemoteSystem: краткое описание Удаленной Системы.

  • Debugger: хранилище для хранения настроек отладчика.

  • Provider: хранилище для хранения настроек поставщика.

  • Requester: хранилище для хранения настроек о запрашивающей стороне.

Отладчик
  • DebugThreshold: уровень отладчика

    Возможные значения

    • debug: все журналы хранятся в базе данных.

    • info: информация, уведомления и журнал ошибкок хранятся в базе данных.

    • notice: ошибки уровня уведомление (notice) и ошибка (error) хранятся в базе данных.

    • error: только ошибки уровня error хранятся в базе данных.

Поставщик
  • Operation: хранилище для настроек каждой операции.

  • Transport: хранилище для настроек поставщика транспортой сети.

Операция
  • <OperationName>: Уникальное название операции, хранилище для своих собственных настроек (от 0..n, но без повторений).

<OperationName>

Этот раздел основан на операция с типом "Test::Test" другие операции могут содержать больше или другие настройки.

  • Описание: краткий текст, описывающий операцию.

  • MappingInbound: хранилище для настроек отображаемых данных для данных из входящего запроса.

  • MappingOutbound: хранилище для отображающихся настроек для исходящих данных.

  • Тип бэкэнд операция в формате Controller::Operation.

MappingInbound

Этот раздел основан на отображаемых значениях с типом "Simple". Другие отображаемые значения могут содержать больше или другие настройки.

  • Config: хранилище настроек для этих отображаемых значений.

  • Тип: mapping backend.

Config
  • KeyMapDefault: хранилище для всех не отображаемых значений ключей.

  • ValueMapDefault: хранилище для всех не отображаемых значений настроек.

  • KeyMapExact: хранилище для всех ключей точных отображаемых значений(от 0 .. 1).

  • KeyMapRegEx: хранилище для отображаемых значений всех регулярных выражений.

  • ValueMap: хранилище для всех значений отображений (mapping-a).

KeyMapDefault
  • MapTo: новое значение, которое будет использоваться (применима только если параметр MapType установлен в значение MapTo).

  • MapType: правило для отображения.

    Возможные значения

    • Keep: оставить без изменений.

    • Ignore: понизить.

    • MapTo: заменить на значение MapTo.

ValueMapDefault

Тоже что и KeyMapDefault.

KeyMapExact
  • <oldkey>: <newkey> (от 0 .. n но без повторений).

KeyMapRegEx
  • <oldkey(RegEx)>: <newkey> ( от 0 .. n но без повторений).

ValueMap
  • <newkey>: контейнер для отображаемых значений для этого нового ключа (зависит от новых ключей от KeyMapExact и KeyMapRegEx).

<newkey>
  • ValueMapExact: хранилище для всех точных отображаемых значений (от 0 .. 1).

  • ValueMapRegEx: хранилище для отображаемых значений всех регулярных выражений (от 0 .. 1).

valueMapExact
  • <oldvalue>: <newvalue> ( cardinality 0 .. n без повторений).

ValueMapRegEx
  • <oldvalue(RegEx)>: <newvalue> ( от 0 .. n без повторений).

MappingOutbound

Тоже что и MappingInbound.

Передача

Этот раздел основана на сетевом поставщике HTTP::SOAP, другие поставщики могут содержать больше или другие настройки.

  • Config: хранилище для конкретных параметров конфигурации транспортной сети.

  • Type: the provider network transport backend.

Config
  • MaxLength: максимальная длина в байтах для чтения SOAP-сообщений системой OTRS.

  • NameSpace: URI , который дает контекст для всех операций, принадлежащих этому веб-сервису.

Запрашиваемая сторона
  • Invoker: хранилище для настроек каждой метки.

  • Transport: хранилище для настроек транспортной сети запрашивающей стороны.

Запрашивающая сторона
  • <InvokerName>: Уникальное имя для вызывающей стороны, хранилище для своих собственых настроек (от 0..n, без повторов).

<InvokerName>

Этот раздел основан на типе "Test::Test", другие invoker-ры могут иметь больше или другие настройки.

  • Описание: короткий текст для описания вызывающей стороны

  • События: хранилище настроек не именованного списка действий.

  • MappingInbound: хранилище для настроек отображаемых значений для данных поступающих от ответов.

  • MappingOutbound: хранилище для настроек отображаемых значений для исходящих данных запроса.

  • Тип: invoker backend, в формате Controller::Invoker.

События
  • List Element: (от 0 .. n)

    • Asynchronous: установить если вызов вызывающей стороны будет возложен на Планировщика

      Возможные значения

      • 0: не обрабатывается Планировщиком (Scheduler).

      • 1: Обрабатывается Планировщиком (Scheduler).

    • Event: имя события триггера.

      Возможные Значения (для событий заявки)

      • TicketCreate

      • TicketDelete

      • TicketTitleUpdate

      • TicketUnlockTimeoutUpdate

      • TicketQueueUpdate

      • TicketTypeUpdate

      • TicketServiceUpdate

      • TicketSLAUpdate

      • TicketCustomerUpdate

      • TicketFreeTextUpdate

      • TicketFreeTimeUpdate

      • TicketPendingTimeUpdate

      • TicketLockUpdate

      • TicketArchiveFlagUpdate

      • TicketStateUpdate

      • TicketOwnerUpdate

      • TicketResponsibleUpdate

      • TicketPriorityUpdate

      • HistoryAdd

      • HistoryDelete

      • TicketAccountTime

      • TicketMerge

      • TicketSubscribe

      • TicketUnsubscribe

      • TicketFlagSet

      • TicketFlagDelete

      • TicketSlaveLinkAdd

      • TicketSlaveLinkDelete

      • TicketMasterLinkDelete

      Возможные Значения (для действий над статьями)

      • Действия над статьями

      • ArticleCreate

      • ArticleFreeTextUpdate

      • ArticleUpdate

      • ArticleSend

      • ArticleBounce

      • ArticleAgentNotification

      • ArticleCustomerNotification

      • ArticleAutoResponse

      • ArticleFlagSet

      • ArticleFlagDelete

      • ArticleAgentNotification

      • ArticleCustomerNotification

MappingInbound

То же что и Действие MappingInbound

MappingOutbound

Тоже что и Действие MappingInbound.

Передача

Этот раздел основан на транспортной сети запрашивающей стороны HTTP::SOAP, транспортные сети могут содержать больше или другие настройки.

  • Config: хранилище для конкретных параметров конфигурации транспортной сети.

  • Тип: бэкэнд транспортной сети запрашивающей стороны.

Config
  • Authentication: a container for authentication settings.

  • Encoding: кодирование сообщения SOAP-запроса

  • Endpoint: URI Уаделнного Сервера веб-службы для приема запросов OTRS.

  • NameSpace: URI который предоставлят связь для всех invoker-ов, которые принадлежат этому веб-серверу.

  • SOAPAction: для отправки пустого или заполненого SOAPAction-заголовка в формате SOAP сообщения (in "<NameSpace> <Separator> <Action>" format).

    Возможные значения

    • YES: для отправки заполненого заголовка SOAPAction.

    • No: для отправки пустого обработчика SOAP-действия.

  • SOAPActionSeparator: для установки <Separator> из заполненых SOAPAction заголовков.

    Возможные значения

    • '/': используется для .net веб-сервисов.

    • '#': используется для всех веб-сервисов на базе протокола REST.

Authentication
  • User: имя привилегированого пользователя, который имеет доступ к удаленному веб-сервису.

  • Пароль: пароль для привелигированого пользователя в формате обычного текста.

  • Тип: тип аутентификации.

Коннекторы (Connectors)

A Connector is in essence a set of actions that are either called Operations if OTRS acts as a web service provider or Invokers if OTRS acts as a web service requester. But it can also include special Mappings or Transports.

One Connector can either have only Operations, Only Invokers or both. A connector can even use parts of other connectors like the Mappings or Transports if they are not to specific for the Connector that is trying to implement them.

In other words a Connector is not limited to just the Controller layer but it can be extended to Data Mapping or Network Transport layers if needed.

Due to the modular design of the Generic Interface a Connector can be seen as a plug-in; this means that by adding Connectors the capabilities of the generic interface can be extended using: OTRS Feature add ons, OTRS Custom modules, 3rd Party modules, and so on.

Комплект Коннекторов (Connectors)

В комплекте с этой версией OTRS следующие коннекторы готовы к использованию.

  • Session

  • Заявк

Session Connector

Этот коннектор может создать действительный SessionID, который в дальнейшем может быть использован в любой другой операции.

Поставщики:

  • Операции:

    • SessionCreate

Операции
SessionCreate

Creates a new new valid SessionID to be used in other operations from other connectors like TicketCreate.

Примечание

To use the SessionID in other operations from other connectors it is necessary that the operation implements authentication by SessionID. All the rest of the bundled operations are capable of accepting a valid SessionID as an authentication method.

Возможные Атрибуты:

                            
      <SessionCreate>
         <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <Password>?</Password>
      </SessionCreate>
                            
                        

Коннектор Заявки

This connector supplies the basic functionality to interact with tickets

Поставщики:

  • Операции:

    • TicketCreate

    • TicketUpdate

    • TicketGet

    • TicketSearch

Операции
TicketCreate

Provides an interface to create a ticket in OTRS. A ticket must contain an Article and can contain several attachments, all defined Dynamic Fields can be also set on TicketCreate operation.

Возможные Атрибуты:

                            
      <TicketCreate>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <Ticket>
            <Title>?</Title>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <QueueID>?</QueueID>
            <!--Optional:-->
            <Queue>?</Queue>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <TypeID>?</TypeID>
            <!--Optional:-->
            <Type>?</Type>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ServiceID>?</ServiceID>
            <!--Optional:-->
            <Service>?</Service>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SLAID>?</SLAID>
            <!--Optional:-->
            <SLA>?</SLA>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <StateID>?</StateID>
            <!--Optional:-->
            <State>?</State>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <PriorityID>?</PriorityID>
            <!--Optional:-->
            <Priority>?</Priority>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <OwnerID>?</OwnerID>
            <!--Optional:-->
            <Owner>?</Owner>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ResponsibleID>?</ResponsibleID>
            <!--Optional:-->
            <Responsible>?</Responsible>
            <CustomerUser>?</CustomerUser>
            <!--Optional:-->
            <CustomerID>?</CustomerID>
            <!--Optional:-->
            <PendingTime>
               <Year>?</Year>
               <Month>?</Month>
               <Day>?</Day>
               <Hour>?</Hour>
               <Minute>?</Minute>
            </PendingTime>
         </Ticket>
         <Article>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ArticleTypeID>?</ArticleTypeID>
            <!--Optional:-->
            <ArticleType>?</ArticleType>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SenderTypeID>?</SenderTypeID>
            <!--Optional:-->
            <SenderType>?</SenderType>
            <!--Optional:-->
            <From>?</From>
            <Subject>?</Subject>
            <Body>?</Body>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ContentType>?</ContentType>
            <Charset>?</Charset>
            <MimeType>?</MimeType>
            <!--Optional:-->
            <HistoryType>?</HistoryType>
            <!--Optional:-->
            <HistoryComment>?</HistoryComment>
            <!--Optional:-->
            <AutoResponseType>?</AutoResponseType>
            <!--Optional:-->
            <TimeUnit>?</TimeUnit>
            <!--Optional:-->
            <NoAgentNotify>?</NoAgentNotify>
            <!--Zero or more repetitions:-->
            <ForceNotificationToUserID>?</ForceNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeNotificationToUserID>?</ExcludeNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeMuteNotificationToUserID>?</ExcludeMuteNotificationToUserID>
         </Article>
         <!--Zero or more repetitions:-->
         <DynamicField>
            <Name>?</Name>
            <!--1 or more repetitions:-->
            <Value>?</Value>
         </DynamicField>
         <!--Zero or more repetitions:-->
         <Attachment>
            <Content>cid:61886944659</Content>
            <ContentType>?</ContentType>
            <Filename>?</Filename>
         </Attachment>
      </TicketCreate>
                            
                        

TicketUpdate

TicketUpdate operation adds the capability to modify attributes from an existing ticket or to add a new article, including attachments and all defined dynamic fields for the ticket and the new article.

Примечание

It is not necessary to create a new article to modify a ticket attribute.

Возможные Атрибуты:

                            
      <TicketUpdate>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--You have a CHOICE of the next 2 items at this level-->
         <TicketID>?</TicketID>
         <TicketNumber>?</TicketNumber>
         <!--Optional:-->
         <Ticket>
            <!--Optional:-->
            <Title>?</Title>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <QueueID>?</QueueID>
            <!--Optional:-->
            <Queue>?</Queue>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <TypeID>?</TypeID>
            <!--Optional:-->
            <Type>?</Type>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ServiceID>?</ServiceID>
            <!--Optional:-->
            <Service>?</Service>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SLAID>?</SLAID>
            <!--Optional:-->
            <SLA>?</SLA>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <StateID>?</StateID>
            <!--Optional:-->
            <State>?</State>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <PriorityID>?</PriorityID>
            <!--Optional:-->
            <Priority>?</Priority>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <OwnerID>?</OwnerID>
            <!--Optional:-->
            <Owner>?</Owner>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ResponsibleID>?</ResponsibleID>
            <!--Optional:-->
            <Responsible>?</Responsible>
            <!--Optional:-->
            <CustomerUser>?</CustomerUser>
            <!--Optional:-->
            <CustomerID>?</CustomerID>
            <!--Optional:-->
            <PendingTime>
               <Year>?</Year>
               <Month>?</Month>
               <Day>?</Day>
               <Hour>?</Hour>
               <Minute>?</Minute>
            </PendingTime>
         </Ticket>
         <!--Optional:-->
         <Article>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ArticleTypeID>?</ArticleTypeID>
            <!--Optional:-->
            <ArticleType>?</ArticleType>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SenderTypeID>?</SenderTypeID>
            <!--Optional:-->
            <SenderType>?</SenderType>
            <!--Optional:-->
            <From>?</From>
            <Subject>?</Subject>
            <Body>?</Body>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ContentType>?</ContentType>
            <Charset>?</Charset>
            <MimeType>?</MimeType>
            <!--Optional:-->
            <HistoryType>?</HistoryType>
            <!--Optional:-->
            <HistoryComment>?</HistoryComment>
            <!--Optional:-->
            <AutoResponseType>?</AutoResponseType>
            <!--Optional:-->
            <TimeUnit>?</TimeUnit>
            <!--Optional:-->
            <NoAgentNotify>?</NoAgentNotify>
            <!--Zero or more repetitions:-->
            <ForceNotificationToUserID>?</ForceNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeNotificationToUserID>?</ExcludeNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeMuteNotificationToUserID>?</ExcludeMuteNotificationToUserID>
         </Article>
         <!--Zero or more repetitions:-->
         <DynamicField>
            <Name>?</Name>
            <!--1 or more repetitions:-->
            <Value>?</Value>
         </DynamicField>
         <!--Zero or more repetitions:-->
         <Attachment>
            <Content>cid:166861569966</Content>
            <ContentType>?</ContentType>
            <Filename>?</Filename>
         </Attachment>
      </TicketUpdate>
                            
                        

TicketGet

This operation is used to get all the attributes of a ticket including the dynamic fields, all articles and all of the attachments that belong to the ticket.

Возможные Атрибуты:

                            
      <TicketGet>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--1 or more repetitions:-->
         <TicketID>?</TicketID>
         <!--Optional:-->
         <DynamicFields>?</DynamicFields>
         <!--Optional:-->
         <Extended>?</Extended>
         <!--Optional:-->
         <AllArticles>?</AllArticles>
         <!--Optional:-->
         <ArticleSenderType>?</ArticleSenderType>
         <!--Optional:-->
         <ArticleOrder>?</ArticleOrder>
         <!--Optional:-->
         <ArticleLimit>?</ArticleLimit>
         <!--Optional:-->
         <Attachments>?</Attachments>
      </TicketGet>
                            
                        

TicketSearch

TicketSearch operation returns a list of Ticket IDs that matches a predefined criteria.

Возможные Атрибуты:

                            
      <TicketSearch>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--Optional:-->
         <Limit>?</Limit>
         <!--Zero or more repetitions:-->
         <TicketNumber>?</TicketNumber>
         <!--Zero or more repetitions:-->
         <Title>?</Title>
         <!--Zero or more repetitions:-->
         <Queues>?</Queues>
         <!--Zero or more repetitions:-->
         <QueueIDs>?</QueueIDs>
         <!--Optional:-->
         <UseSubQueues>?</UseSubQueues>
         <!--Zero or more repetitions:-->
         <Types>?</Types>
         <!--Zero or more repetitions:-->
         <TypeIDs>?</TypeIDs>
         <!--Zero or more repetitions:-->
         <States>?</States>
         <!--Zero or more repetitions:-->
         <StateIDs>?</StateIDs>
         <!--Zero or more repetitions:-->
         <StateType>?</StateType>
         <!--Zero or more repetitions:-->
         <StateTypeIDs>?</StateTypeIDs>
         <!--Zero or more repetitions:-->
         <Priorities>?</Priorities>
         <!--Zero or more repetitions:-->
         <PriorityIDs>?</PriorityIDs>
         <!--Zero or more repetitions:-->
         <Services>?</Services>
         <!--Zero or more repetitions:-->
         <ServiceIDs>?</ServiceIDs>
         <!--Zero or more repetitions:-->
         <SLAs>?</SLAs>
         <!--Zero or more repetitions:-->
         <SLAIDs>?</SLAIDs>
         <!--Zero or more repetitions:-->
         <Locks>?</Locks>
         <!--Zero or more repetitions:-->
         <LockIDs>?</LockIDs>
         <!--Zero or more repetitions:-->
         <OwnerIDs>?</OwnerIDs>
         <!--Zero or more repetitions:-->
         <ResponsibleIDs>?</ResponsibleIDs>
         <!--Zero or more repetitions:-->
         <WatchUserIDs>?</WatchUserIDs>
         <!--Zero or more repetitions:-->
         <CustomerID>?</CustomerID>
         <!--Zero or more repetitions:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Zero or more repetitions:-->
         <CreatedUserIDs>?</CreatedUserIDs>
         <!--Zero or more repetitions:-->
         <CreatedTypes>?</CreatedTypes>
         <!--Zero or more repetitions:-->
         <CreatedTypeIDs>?</CreatedTypeIDs>
         <!--Zero or more repetitions:-->
         <CreatedPriorities>?</CreatedPriorities>
         <!--Zero or more repetitions:-->
         <CreatedPriorityIDs>?</CreatedPriorityIDs>
         <!--Zero or more repetitions:-->
         <CreatedStates>?</CreatedStates>
         <!--Zero or more repetitions:-->
         <CreatedStateIDs>?</CreatedStateIDs>
         <!--Zero or more repetitions:-->
         <CreatedQueues>?</CreatedQueues>
         <!--Zero or more repetitions:-->
         <CreatedQueueIDs>?</CreatedQueueIDs>
         <!--Zero or more repetitions:-->
         <DynamicFields>
            <!--You have a MANDATORY CHOICE of the next 6 items at this level-->
            <!--Optional:-->
            <Equals>?</Equals>
            <!--Optional:-->
            <Like>?</Like>
            <!--Optional:-->
            <GreaterThan>?</GreaterThan>
            <!--Optional:-->
            <GreaterThanEquals>?</GreaterThanEquals>
            <!--Optional:-->
            <SmallerThan>?</SmallerThan>
            <!--Optional:-->
            <SmallerThanEquals>?</SmallerThanEquals>
         </DynamicFields>
         <!--Optional:-->
         <Ticketflag>
            <!--Optional:-->
            <Seen>?</Seen>
         </Ticketflag>
         <!--Optional:-->
         <From>?</From>
         <!--Optional:-->
         <To>?</To>
         <!--Optional:-->
         <Cc>?</Cc>
         <!--Optional:-->
         <Subject>?</Subject>
         <!--Optional:-->
         <Body>?</Body>
         <!--Optional:-->
         <FullTextIndex>?</FullTextIndex>
         <!--Optional:-->
         <ContentSearch>?</ContentSearch>
         <!--Optional:-->
         <ConditionInline>?</ConditionInline>
         <!--Optional:-->
         <ArticleCreateTimeOlderMinutes>?</ArticleCreateTimeOlderMinutes>
         <!--Optional:-->
         <ArticleCreateTimeNewerMinutes>?</ArticleCreateTimeNewerMinutes>
         <!--Optional:-->
         <ArticleCreateTimeNewerDate>?</ArticleCreateTimeNewerDate>
         <!--Optional:-->
         <ArticleCreateTimeOlderDate>?</ArticleCreateTimeOlderDate>
         <!--Optional:-->
         <TicketCreateTimeOlderMinutes>?</TicketCreateTimeOlderMinutes>
         <!--Optional:-->
         <ATicketCreateTimeNewerMinutes>?</ATicketCreateTimeNewerMinutes>
         <!--Optional:-->
         <TicketCreateTimeNewerDate>?</TicketCreateTimeNewerDate>
         <!--Optional:-->
         <TicketCreateTimeOlderDate>?</TicketCreateTimeOlderDate>
         <!--Optional:-->
         <TicketChangeTimeOlderMinutes>?</TicketChangeTimeOlderMinutes>
         <!--Optional:-->
         <TicketChangeTimeNewerMinutes>?</TicketChangeTimeNewerMinutes>
         <!--Optional:-->
         <TicketChangeTimeNewerDate>?</TicketChangeTimeNewerDate>
         <!--Optional:-->
         <TicketChangeTimeOlderDate>?</TicketChangeTimeOlderDate>
         <!--Optional:-->
         <TicketCloseTimeOlderMinutes>?</TicketCloseTimeOlderMinutes>
         <!--Optional:-->
         <TicketCloseTimeNewerMinutes>?</TicketCloseTimeNewerMinutes>
         <!--Optional:-->
         <TicketCloseTimeNewerDate>?</TicketCloseTimeNewerDate>
         <!--Optional:-->
         <TicketCloseTimeOlderDate>?</TicketCloseTimeOlderDate>
         <!--Optional:-->
         <TicketPendingTimeOlderMinutes>?</TicketPendingTimeOlderMinutes>
         <!--Optional:-->
         <TicketPendingTimeNewerMinutes>?</TicketPendingTimeNewerMinutes>
         <!--Optional:-->
         <TicketPendingTimeNewerDate>?</TicketPendingTimeNewerDate>
         <!--Optional:-->
         <TicketPendingTimeOlderDate>?</TicketPendingTimeOlderDate>
         <!--Optional:-->
         <TicketEscalationTimeOlderMinutes>?</TicketEscalationTimeOlderMinutes>
         <!--Optional:-->
         <TTicketEscalationTimeNewerMinutes>?</TTicketEscalationTimeNewerMinutes>
         <!--Optional:-->
         <TicketEscalationTimeNewerDate>?</TicketEscalationTimeNewerDate>
         <!--Optional:-->
         <TicketEscalationTimeOlderDate>?</TicketEscalationTimeOlderDate>
         <!--Optional:-->
         <ArchiveFlags>?</ArchiveFlags>
         <!--Zero or more repetitions:-->
         <OrderBy>?</OrderBy>
         <!--Zero or more repetitions:-->
         <SortBy>?</SortBy>
         <!--Zero or more repetitions:-->
         <CustomerUserID>?</CustomerUserID>
      </TicketSearch>
                            
                        

Примеры:

Конфигурация Веб-сервиса

The following is a basic but complete web service configuration file in YAML format to use all the Ticket Connector operations. In order to use it in OTRS you need to copy the content, save it into a file called GenericTicketConnector.yml, and import it into OTRS in the Web Services screen in the Admin panel by clicking in the "Add web service" action from the overview screen and then clicking in the "Import web service" action in the add screen.

                    
---
Debugger:
  DebugThreshold: debug
  TestMode: 0
Description: Ticket Connector Sample
FrameworkVersion: 3.2.x CVS
Provider:
  Operation:
    SessionCreate:
      Description: Creates a Session
      MappingInbound: {}
      MappingOutbound: {}
      Type: Session::SessionCreate
    TicketCreate:
      Description: Creates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketCreate
    TicketUpdate:
      Description: Updates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketUpdate
    TicketGet:
      Description: Retrieve Ticket data
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketGet
    TicketSearch:
      Description: Search for Tickets
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketSearch
  Transport:
    Config:
      MaxLength: 100000000
      NameSpace: http://www.otrs.org/TicketConnector/
    Type: HTTP::SOAP
RemoteSystem: ''
Requester:
  Transport:
    Type: ''
                    
                

Запрашивающая сторона Perl SOAP

The following code is a Perl script that can connect to OTRS via the generic interface. In order to perform the operations provided by the Ticket Connector, it uses two Perl CPAN modules SOAP::Lite and Data::Dumper. Please make sure that your environment is capable to use these modules before you try to run the scipt.

                    
#!/usr/bin/perl -w
# --
# otrs.SOAPRequest.pl - sample to send a SOAP request to OTRS Generic Interface Ticket Connector
# Copyright (C) 2001-2014 OTRS AG, http://otrs.com/
# --
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU AFFERO General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# or see http://www.gnu.org/licenses/agpl.txt.
# --

use strict;
use warnings;

# use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use SOAP::Lite;
use Data::Dumper;

# ---
# Variables to be defined.

# this is the URL for the web service
# the format is
# <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl/Webservice/<WEB_SERVICE_NAME>
# or
# <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl/WebserviceID/<WEB_SERVICE_ID>
my $URL = 'http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector';

# this name space should match the specified name space in the SOAP transport for the web service.
my $NameSpace = 'http://www.otrs.org/TicketConnector/';

# this is operation to execute, it could be TicketCreate, TicketUpdate, TicketGet, TicketSearch
# or SessionCreate. and they must to be defined in the web service.
my $Operation = 'TicketCreate';

# this variable is used to store all the parameters to be included on a request in XML format. Each
# operation has a determined set of mandatory and non mandatory parameters to work correctly. Please
# check the OTRS Admin Manual in order to get a complete list of parameters.
my $XMLData = '
<UserLogin>some user login</UserLogin>
<Password>some password</Password>
<Ticket>
    <Title>some title</Title>
    <CustomerUser>some customer user login</CustomerUser>
    <Queue>some queue</Queue>
    <State>some state</State>
    <Priority>some priority</Priority>
</Ticket>
<Article>
    <Subject>some subject</Subject>
    <Body>some body</Body>
    <ContentType>text/plain; charset=utf8</ContentType>
</Article>
';

# ---

# create a SOAP::Lite data structure from the provided XML data structure.
my $SOAPData = SOAP::Data
    ->type( 'xml' => $XMLData );

my $SOAPObject = SOAP::Lite
    ->uri($NameSpace)
    ->proxy($URL)
    ->$Operation($SOAPData);

# check for a fault in the soap code.
if ( $SOAPObject->fault ) {
    print $SOAPObject->faultcode, " ", $SOAPObject->faultstring, "\n";
}

# otherwise print the results.
else {

    # get the XML response part from the SOAP message.
    my $XMLResponse = $SOAPObject->context()->transport()->proxy()->http_response()->content();

    # deserialize response (convert it into a perl structure).
    my $Deserialized = eval {
        SOAP::Deserializer->deserialize($XMLResponse);
    };

    # remove all the headers and other not needed parts of the SOAP message.
    my $Body = $Deserialized->body();

    # just output relevant data and no the operation name key (like TicketCreateResponse).
    for my $ResponseKey ( keys %{$Body} ) {
        print Dumper( $Body->{$ResponseKey} );
    }
}