Porovnávané verzie

Kľúč

  • Tento riadok sa pridal
  • Riadok je odstránený.
  • Formátovanie sa zmenilo.

The SmartWeb platform enables effective development of web applications that use the D2000 application server as a data source, meaning that they have application logic programmed in the D2000 application server. Thanks to direct usage of standard web technologies such as HTML, CSS, and JavaScript, the applications' design is not limited by graphics possibilities of D2000. Knowledge of these technologies is thus a necessity for developing applications on the SmartWeb platform.

Introduction to Development of Applications

Requirements for Developing

  • Installed Git
  • Development environment for HTML and JavaScript (e.g. WebStorm)
  • Web browser (at least Internet Explorer 11, Google Chrome is recommended)

Application Bundling

In applications on the SmartWeb platform, it is possible to use JavaScript language constructions up to the ECMAScript 2017 version and React components which use JSX syntax regardless of the final used web browser. This is possible because applications created on the SmartWeb platform go through a process called bundling during which they are deployed into a production version. This process makes adjustments of source codes (transpilation) so that they would be natively interpretable by the lowest supported version of a web browser (translations to the JavaScript of ES 5.0 version). At the same time, the size of source codes is reduced during the bundling process - minification (removing empty characters and commentaries, shortening of names of variables and functions...). It spares transmitted data and thus enables quicker loading of web pages. 

Application Configuration

The smartweb.json file serves for configuration of the SmartWeb application. In this file, it is possible to allow or forbid individual components of the application, to set an authentication method, to restrict access to Event scripts and RPD procedures. A detailed description of the configuration can be found in the chapter Configuration of the SmartWeb Application.

Application Structure

The following figure shows the structure of the SmartWeb application.

On the left, there is a description of files which the programmer creates. Those are mostly files of individual pages (pages directory), a page for a login of a user (login.js) and an HTML template of pages (template.html). JavaScript modules shared among pages are located in the custom directory and for storing other files such as pictures, there is the assets directory.

On the right, there are described files generated or copied by the SmartWeb Bundle Engine. Those are mostly built production versions of pages, files of the SmartWeb framework and the JavaScript engine with downloaded libraries for the bundle engine.

Image Added

External Libraries

Thanks to the usage of SystemJS and JSPM, it is possible to use any JavaScript library from GitHub and npm in the SmartWeb application. Dependencies and possible conflicts will be automatically resolved in versions. 

Development of Applications

SmartWeb applications are standardly composed of more web pages. Pages may be written directly as HTML (suffix .html) files or as JavaScript files (suffix .js) which will be using templates (template.html) mapped on the HTML file (e.g. the index.html page is created by a combination of the file template template.html and the file index.js). The file template.html represents a template of a web page using which it is possible to define repeated parts of final pages. Only mandatory HTML element of the template is the element of the <div> type with id "root". Content of this element will be generated based on a particular JavaScript file which is mapped to a final HTML file. In the template, it is possible to use several placeholder variables in SmartWeb. Those will be automatically replaced by their real value during loading of the page

Platforma SmartWeb umožňuje efektívny vývoj webových aplikácií, ktoré ako zdroj dát používajú aplikačný server D2000 resp. majú aplikačnú logiku naprogramovanú v aplikačnom serveri D2000. Vďaka priamemu využívaniu štandardných webových technológií ako HTML, CSS a JavaScript nie je dizajn aplikácií limitovaný grafickými možnosťami D2000. Znalosť týchto technológií je preto nutnou požiadavkou pre vývoj aplikácií na platforme SmartWeb.

Úvod do vývoja aplikácií

Požiadavky na vývoj

  • Nainštalovaný Git
  • Vývojové prostredie pre HTML a JavaScript (napr. WebStorm)
  • Webový prehliadač (minimálne Internet Explorer 11, odporúčaný Google Chrome)

Bundlovanie aplikácie

Pre aplikácie na platforme SmartWeb je možné používať konštrukcie jazyka JavaScript až do verzie ECMAScript 2017 a React komponenty používajúce JSX syntax bez ohľadu na výsledný používaný webový prehliadač. Toto je možné vďaka tomu, že aplikácie vytvorené na platforme SmartWeb prechádzajú pri nasadení do produkčnej verzie procesom spracovania nazývaným bundlovanie. Tento proces má na starosti úpravu zdrojových kódov (transpilácia) tak, aby boli natívne interpretovateľné najnižšou podporovanou verziou webového prehliadača (prekladá sa do JavaScript-u verzie ES 5.0). Zároveň počas procesu bundlovania dochádza k zmenšovaniu veľkosti zdrojových kódov - minifikácia (odstránenie prázdnych znakov a komentárov, skrátenie názvov premenných a funkcií, ...) kvôli šetreniu prenášaných dát a tým rýchlejšiemu načítaniu webových stránok.

Konfigurácia aplikácie

Na konfiguráciu SmartWeb aplikácie slúži súbor smartweb.json, v ktorom je možné povoľovať resp. zakazovať jednotlivé súčasti aplikácie, nastaviť spôsob autentifikácie, obmedziť prístup k Event skriptom a RPC procedúram. Podrobný popis konfigurácie je možné nájsť na stránke Konfigurácia SmartWeb aplikácie.

Štruktúra aplikácie

Nasledovný obrázok znázorňuje štruktúru SmartWeb aplikácie.

Vľavo sa nachádza popis súborov, ktoré vytvára programátor. Sú to najmä súbory jednotlivých stránok (adresár pages), stránka pre prihlasovanie užívateľa (login.js) a HTML šablóna stránok (template.html). JavaScript moduly zdieľané medzi stránkami sa nachádzajú v adresári custom a pre uloženie ostatných súborov ako napr. obrázky slúži adresár assets.

Vpravo sú popísané súbory generované resp. kopírované SmartWeb Bundle Enginom. Ide hlavne o vybuildované produkčné verzie stránok, súbory SmartWeb frameworku a JavaScriptový engine so stiahnutými knižnicami pre bundle engine.

Image Removed

Externé knižnice

Vďaka využitiu SystemJS a JSPM je možné v SmartWeb aplikácii využiť akúkoľvek JavaScript knižnicu z GitHub-u a npm. Závislosti aj prípadné konflikty vo verziách budú automaticky vyriešené.

Vývoj aplikácií

SmartWeb aplikácie sa štandardne skladajú z viacerých webových stránok. Stránky môžu byť napísané priamo ako HTML (prípona .html) súbory alebo ako JavaScript súbory (prípona .js), ktoré budú pomocou šablóny (template.html) namapované na HTML súbor (napr. stránka index.html vznikne kombináciou súboru šablóny template.html a súboru index.js). Súbor template.html predstavuje šablónu webovej stránky, pomocou ktorej je možné zadefinovať opakované súčasti výsledných stránok. Jediným povinným HTML elementom šablóny je element typu <div> s id "root". Obsah tohto elementu bude generovaný na základe konkrétneho JavaScript súboru, ktorý je mapovaný na výsledný HTML súbor. V šablóne je možné použiť niekoľko placeholder premenných definovaných v SmartWeb-e. Tieto budú pri načítaní stránky automaticky nahradené ich skutočnou hodnotou.

  • {{{smartweb.global.context.path}}}  je url cesta (url path) ku koreňovému adresáru SmartWeb servera, odvodená od názvu deploynutého"war" súboru aplikačným serverom Wildfly. (napr.   is the url path to the root directory of the SmartWeb server derived from the name of the deployed "war" file of the Wildfly application server. (e.g. /smartWeb).
  • {{{smartweb.application.root.path}}} je url cesta (url path) ku koreňovému adresáru web aplikácie, odvodená od toho ako je definovaná v konfiguračnom súbore is the url path to the root directory of the web application derived from how it is defined in the smartweb.json. configuration file (napre.g /smartWeb/admin).
  • {{{smartweb.application.script}}} obsahuje kód SmartWeb aplikácie contains a code of the SmartWeb application 
  • {{{smartweb.library.scripts}}} obsahuje kódy použitých knižníc v SmartWeb aplikácii contains a code of the used libraries in the SmartWeb application

The following code represents an example of the template.html file in which there are defined the basic styles, scripts and an icon of the web page: Nasledovný kód predstavuje príklad súboru template.html, v ktorom sa definujú základné štýly, písma a ikona web stránky:

Blok kódu
languagexml
titletemplate.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SmartWeb Demo</title>

    <link rel='shortcut icon' type='image/x-icon' href='{{{smartweb.application.root.path}}}/custom/img/favicon.ico'/>
    <link href="{{{smartweb.application.root.path}}}/assets/fonts/font-awesome/font-awesome.css" rel="stylesheet">
    <link href="{{{smartweb.application.root.path}}}/assets/fonts/font-open-sans/open-sans.css" rel="stylesheet">
    <style>
        .gray-bg {
            background-color: #f3f3f4;
        }
    </style>
    {{{smartweb.library.scripts}}}
</head>
<body class="fixed-nav top-navigation gray-bg">
    <div id="root"/>
    {{{smartweb.application.script}}}
</body>
</html>

Pre každý adresár pod koreňovým adresárom SmartWeb aplikácie je možné definovať vlastný súbor šablóny (vždy nazvaný It is possible to define own template file (always named template.html) . Ak sa v adresári s JavaScript kódom stránky nenachádza súbor šablóny, tak sa automaticky hľadá v adresárovej štruktúre vyššie, až kým sa šablóna nenájde.for every directory under the root directory of the SmartWeb application. If there is no template file in the directory with the Javascript code of the page, it will be automatically looked for in the directory structure above until the template will be found. 

All pages defined under the /pages directory require an authentication. If the user is not authenticated, they will be automatically redirected to the /login.html page which contains a login form and realizes the authentication. The default page to which the user is redirected after entering the address of the SmartWeb application is Všetky stránky definované pod adresárom /pages vyžadujú autentifikáciu. Ak užívateľ nie je autentifikovaný, je automaticky presmerovaný na stránku /login.html, ktorá obsahuje prihlasovací formulár a realizuje autentifikáciu. Predvolená stránka, na ktorú je užívateľ presmerovaný po zadaní adresy SmartWeb aplikácie, je /pages/index.html. Stránky definované mimo adresára /pages nevyžadujú autentifikáciu.

Ladenie aplikácie

Pretože stránky pri ich nasadení do produkčnej verzie prebiehajú počas bundlovania procesom transpilácie a minifikácie, je ich vo výslednej forme veľmi ťažké ladiť. Na ladenie bol preto vytvorený špeciálny vývojový (ladiaci) režim, kedy je stránka do webového prehliadača zaslaná vo svojej pôvodnej podobe a potrebné úpravy kódu ako transpilácia sa realizujú až následne priamo vo webovom prehliadači. Tento režim (ak je povolený) sa aktivuje klávesovou skratkou CTRL+ALT+D resp. doplnením parametra ?DEV za názov načítavanej stránky. Načítanie stránky v ladiacom režime trvá dlhšie, pretože všetky zdojové kódy sú načítavané v ich pôvodnej podobe bez optimalizácie a navyše sú potom ešte v prehliadači pomocou JavaScriptu transformované pre zabezpečenie kompatibility s webovým prehliadačom.

Info

Zmeny na stránke vidia len prihlásení užívatelia, ktorí k stránke pristupujú cez ladiaci režim. Práca ostatných užívateľov s produkčnou verziou stránky/aplikácie nie je nijak ovplyvnená.

Rebundlovanie aplikácie

Po odladení zmien aplikácie pre ich nasadenie do produkcie nie je potrebné reštartovať webový server. Ak je to v konfigurácii povolené, tak pomocou klávesovej skratky CTRL+ALT+R resp. doplnením parametra ?REBUNDLE za názov stránky sa spustí rebundlovanie aplikácie na serveri. 

Prístupy k vývoju webových aplikácií

Platforma SmartWeb umožňuje vysokú flexibilitu z hľadiska vývoja webových aplikácií. Programátor má na výber, ktoré rozhranie a ktoré súčasti SmartWeb platformy na prístup k D2000 použije.

Vlastné UI (užívateľské rozhranie) a REST API

V tomto prípade má programátor úplnú voľnosť z hľadiska tvorby UI webovej aplikácie. Na komunikáciu s D2000 použije REST API, ktoré umožňuje volať D2000 RPC a SBA procedúry a načítavať dáta z archívov.

Pages defined outside the /pages directory do not need authentication. 

Application Debugging 

It is very difficult to debug pages in their final form because they go through transpilation and minification processes during bundling when they are being deployed into the production version. Therefore, there was a special developing (debugging) mode created in which the page is sent into the web browser in its original form and the necessary code adjustments such as transpilation are realized only afterward directly in the web browser.    This mode (if allowed) is activated by a keyboard shortcut CTRL+ALT+D, more precisely by adding the ?DEV parameter after the name of the loading page. Loading a page in the debugging mode lasts longer because all source codes are read in their original forms without optimization and in addition to that, in a browser using the javaScript, they are transformed for securing compatibility with the web browser.

Info

Changes on the page can be seen only by logged in users who access the page via the debugging mode. Work of other users with the production version of the page/application is not affected in any way.

Application Rebundling

After debugging changes in the application for their deployment into production, it is not necessary to restart the web server. If it is allowed in the configuration, using the keyboard shortcut CTRL+ALT+R, more precisely by adding the parameter ?REBUNDLE after the page name, application rebundling on a server will run. 

Approaches to Web Application Development 

The SmartWeb platform enables high flexibility from the point of view of web application development. A programmer can choose which interface and which parts of the SmartWeb platform will be used to access. 

Own UI (interface) and REST API

In this case, a programmer has complete freedom from the point of view of creating the UI of the web application. For communicating with D2000, they use REST API which enables calling D2000 RPC and SBA procedures and reading data from archives. 

The following code represents an example of a page without the use of the SmartWeb Framework only with the use of D2000 REST API. To prevent an attack such as cross-site request forgery, it is necessary to add the CSRF token into every REST request. Using AJAX request, the RPC procedure Sum is called on the event E.SmartWebTutorial through the REST API. The procedure has three parameters - the first two input parameters are submitted by value and the third returning parameter of the real type will be inserted into the attribute named vysledok. A thorough description of the data serialization is available on the page Serialization of Data between Client and API InterfaceNasledovný kód ukazuje príklad stránky bez použitia SmartWeb Frameworku, len s využitím D2000 REST API. Na zabránenie útoku typu cross-site request forgery, je potrebné do každého REST dotazu doplniť CSRF token. Pomocou AJAX dotazu je cez REST API volaná RPC procedúra Sum na Evente E.SmartWebTutorial. Procedúra má tri parametre - prvé dva, vstupné, sú odovzdané hodnotou a tretí, návratový parameter typu real, bude vložený do atribútu s názvom vysledok. Podrobný popis serializácie dát je dostupný na stránke Serializácia dát medzi klientom a API rozhraniami.

Blok kódu
languagexml
titleexample2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SmartWeb Demo</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
</head>
<body class="">
<div id="root">
    <h1>Stranka bez využitia SmartWeb Frameworku 2</h1>
    <div>
        <input id="inputA" type="text" value="10">
        <span style="background-color: rgb(238, 238, 238);"> + </span>
        <input id="inputB" type="text" value="20">
        <span>
            <button id="button1" type="button"> = </button>
        </span>
        <input id="inputC" type="text" class="form-control" disabled="" value="">
    </div>
</div>
<script language="JavaScript">

    function loadData(valueA, valueB) {
        // VytvoríCretaes resp.or načítareads unikátnyunique CSRF token nafor zabráneniepreventing cross-site request forgery
        var csrfToken = Cookies.get('CSRF-TOKEN');

        $.ajax({
            url: `/smartWeb/api/web/rest/v0/d2/rpc/E.SmartWebTutorial/Sum?CSRF-TOKEN=${csrfToken}`,
            type: 'POST',
            data: JSON.stringify([
                valueA, valueB, {type: 'real', returnAs: 'vysledok'}
            ]),
            async: false,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: false,
            success: function (data, status, jqXHR) {
                $('#inputC').val(data.vysledok.value);
            },
            error: function (jqXHR, status) {
                // error handler
                console.log(jqXHR);
                alert('fail' + status.code);
            }
        });
    }

    $(document).ready(function () {
        $('#button1').on('click', function () {
            var valueA = parseFloat($('#inputA').val());
            var valueB = parseFloat($('#inputB').val());
            loadData(valueA, valueB);
        });
    });
</script>
</body>
</html>

Vlastné Own UI a and (Comet) D2Api

Ďalšou možnosťou pri vývoji webovej aplikácie je použitie rozhrania D2Api, ktoré je implementované pomocou knižnice CometD. Toto rozhranie, na rozdiel od REST rozhrania, umožňuje aj tzv. server push komunikáciu, čo znamená, že zo servera môžu byť na klienta kedykoľvek odoslané dáta bez toho, aby si ich klient vopred vypýtal. Táto forma komunikácie je výhodná najmä v prípade, keď je žiadané na webovej stránke v reálnom čase publikovať zmeny hodnôt v D2000.

React/SmartWeb komponenty a (Comet) D2Api

Tento prípad naplno využíva vlastnosti a možnosti SmartWeb Frameworku. SmartWeb Bundle Engine sa stará závislosti knižníc a správne usporiadanie modulov pred ich volaním, rieši spätnú kompatibilitu JavaScript kódov ich transpiláciou a optimalizuje veľkosť kódu. Volania D2Api sú zabalené v triede DataContainer, ktorá sa stará o automatickú inicializáciu pripojenia cez D2Api. Navyše sú k dispozícii predpripravené React komponenty, podporujúce responzívny dizajn pomocou Bootstrap frameworku.

Another possibility when developing a web application is using the D2Api interface which is implemented with the use of the CometD library. This interface, unlike the REST interface, enables also the so-called server push communication which means that data could be sent to a client from the server anytime without the client asking for them beforehand. This form of communication is advantageous mainly in the case when it is desired to publish value changes in D2000 on the web page in real time.

React/SmartWeb Components and (Comet) D2Api

This case fully takes advantage of the features and possibilities of the SmartWeb Framework. The SmartWeb Bundle Engine takes care of independence of libraries and the right order of modules before calling them and it also takes care of the backward compatibility of JavaScript codes by transpilation and optimizes the size of the code. D2Api callings are packed in the DataContainer class which takes care of automatic initialization of connection through D2Api. Moreover, React Components prepared in advance that support responsive design using Bootstrap framework are at disposal.

The following example renders the objects.html page. The ObjectsPage class is the React component defining the design and behaviour of the page. DataContainer is a special React component that realizes a connection to D2000 and promotes into the page the property this.props.d2 that represents the instance of the D2Api class serving for communicating with D2000. The page uses ValueComponent components prepared in advance for acquiring current values of D2000 objects - in this case, a minute (object Min) and a second (object Nasledovný príklad renderuje stránku objects.html. Trieda ObjectsPage je React komponent definujúci vzhľad a správanie stránky. DataContainer je špeciálny React komponent, ktorý realizuje pripojenie na D2000 a do stránky propaguje property this.props.d2, ktorá predstavuje inštanciu triedy D2Api slúžiacu na komunikáciu s D2000. Stránka využíva predpripravené komponenty ValueComponent na získavanie aktuálnych hodnôt D2000 objektov - v tomto prípade minúta (objekt Min) a sekunda (objekt Sec).

Blok kódu
languagejs
titleobjects.js
import React from 'react'
import {DataContainer, PageHeader, ValueComponent} from '../custom/components'

DataContainer.renderComponent(class ObjectsPage extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div className="container-fluid">
                <PageHeader {...this.props}/>
                <div className="wrapper wrapper-content page-heading">
                    <div className="row">
                        <div className="col-xs-8 text-right">
                            <span>Aktuálna<span>Current minútaminute zfrom D2000:</span>
                        </div>
                        <div className="col-xs-4 text-right">
                            <ValueComponent d2={this.props.d2}
                                            datasource="Min"
                                            numberFormat="0"
                                            missingFormattedValue="?"/>
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-xs-8 text-right">
                            <span>Aktuálna<span>Current sekundasecond zfrom D2000:</span>
                        </div>
                        <div className="col-xs-4 text-right">
                            <ValueComponent d2={this.props.d2}
                                            datasource="Sec"
                                            numberFormat="0"
                                            missingFormattedValue="?"/>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
});

...