BaseX

= XML Database, XPath/XQuery 3.0 Processor

  • Open Source (BSD-licensed), platform independent
  • supp. W3C Update
  • supp. Full Text
  • supp. logging

Components

  1. BaseX XQuery Processor
  2. BaseX Server
  3. BaseX GUI

BaseX XQuery Processor

XQuery 3.0

map operator !
group by, switch
try/catch - handle errors at runtime
function items ~ lambda functions
string Concatenations - 'Hello' || ' ' || 'Universe'
context items
annotations
serialization
functions - eg. math:pi(), fn:analyze-string(), fn:format-dateTime(), count

HTTP

Full Text

W3C XQuery Full Text 1.0 - for information retrieval systems
wildcards, stemming, diactritics

JSON

XML <-> JSON conversion

Updates

XQuery Update Facility 1.0 - inserting, deleting, renaming and replacing nodes.

File

file system operations, such as reading, or writing files and directories.

Java Bindings

Direct access to Java procedures and object manipulation

Map

implementation of maps in XQuery

Execution Plan

Each evaluation procedure can be visualized with individual steps and index accesses

XSLT

Via Saxon

SQL

BaseX Client/Server Architecture

Server: Port 1984, starting: basexserver, stoping: basexserver stop
Client: starting: basexclient, username: admin, password: admin
HTTP Server: default on Jetty Web Server at 8984, starting: basexhttp

Clients in several programming languages.
Transaction Management
User Management - secure auth
Transaction Logging
WebDAV Server
REST Server

BaseX GUI

  • Server Administration
  • realtime XQuery editor
  • interactive visualizations

Basics

addressed by their unique database path
Collection - database with more than one documents

Parts

basex - standalone (embedded)
basexclient, basexserver

Getting started

Download:

  • GUI APP (Mac/Windows version)
  • ZIP Archive - move to your location (eg. /Users/strajk/bin/basex) and add /Users/strajk/bin/basex/bin to system PATH
  • try which basex on terminal

Dependencies

| Java Virtual Machine with Java 1.6

Starting GUI

  • From downloaded installer
  • From downloaded zip
    The GUI can be started as follows (get more information on all Startup Options):
    • Double click on the BaseX.jar file.
    • Run one of the basexgui or basexgui.bat scripts.
    • Execute the following command: java -cp BaseX.jar org.basex.BaseXGUI
    • On Windows: Double click on the BaseX GUI icon.
    • For Maven users: type in mvn exec:java in the main directory of the basex project.
    

GUI
world Find tags and texts containing world
=world Find exact matching text nodes
~world Find text nodes similar to world
@world Find attributes and attribute values
@=world Find exact attribute values
"united world" Find tags and texts containing the phrase "united world"

Creating DB

CREATE DB »name-of-db« »full-path-to-resource-xml-file«       OPEN »name-of-db«
XQUERY //people/person/name
XQUERY doc("»name-of-db«")//country
SHOW DATABASES --> show currently opened databases
INFO --> about currently opened db
LIST --> show databases with info
CREATE BACKUP »name-of-db«, RESTORE »name-of-db« --> ~/BaseXData/»name-of-db«-timestamp.zip

Parsing data into BaseX

Can parse xml, html, json, csv, text

  • Internal - fault-tollerant
  • Java SAXParser
SET INTPARSE true
SET DTD true

Java Templating Engines

separation between the actual view logic and the rendered view

General purpose

Unsorted

What to do with teplates?

template = report design = master page
merge data (dynamic) into template (static) -> final document
data are usually in a form of Container or Collection (eg. HashMap)
data are accessible in teplate through special classes (eg. context or model)

Components

  • Template Engine
  • Content Resource
  • Template Resource

Process

  1. Instantiate an template engine
  2. feed it with data
  3. call a parse()

FreeMarker

  • general purpose (HTML, XML, RTF, …)
  • good for MVC (replaces JSP)
  • support JSP taglibs
  • internationalization - charset, number formating, date formating, language variation of templates
  • replacement of Velocity
  • replacement of XLST

Naming
${...} interpolations
FTL tags - starts with #, refers to directives (as HTML tag

refers t o HTML element

  • predefined # bezobsahove se neuzaviraji
  • user @ bezobsahove se uzaviraji
    Comments <#-- -->
    Anything else static text

variables
doesn't tolerate the referring to missing variables unless you tell them explicitly what to do if the variable is missing.
Scalars: String, Number, Boolean, Date. Containers: Hash, Sequence
Collection

${user}
${user!"Anonymous"} - default value
${cargo.weight!(item.weight * itemCount + 10)}
<#if user??> ${user} is defined </#if>
${user.weight / 2 + 100}

include

<#include "/footer.ftml">

footer_en_US.ftl
footer_en.ftl
footer.ftl

if

<#if someBoolean>It was right</#if>
<#if user == "Strajk">Welcome back, admin!</#if>
<#if offer.icecream.price == 0>Free ice-cream!</#if>

list

<#list animals as being>${being.name} ${being.type}</#list>

expressions

string
arithmentic
boolean arithmetic
array
own
${"green " + "mouse"?upper_case}   <#-- green MOUSE -->

others

<#assign mouse = "Jerry">
${product.id?c} - computer audience, disable locale formating
${married?string("yes", "no")}.

macros (+params)

<#macro greet person="Anonymous" where>
  <h1>Hello ${person}, welcome to ${where}!</h1>
</#macro>
<@greet person="Fred"/>
<#macro wrapper>
  <div class="wrapper">
    <#nested>
  </div>
</#macro>
<@border>Gift to be wrapped</@border>

namespaces

output transformation (eg. escaping HTML)

public class FreemarkerExample extends TemplateExample{

    Configuration config = new Configuration();
    Template freemarkerTemplate;
    OutputStreamWriter output = new OutputStreamWriter(System.out);

    Map<String,String> dataModel = new HashMap<String,String>();

    public FreemarkerExample(String user){
        this.user = user;
        dataModel.put("user", this.user);
    }

    @Override
    public void print() {
        try {
            freemarkerTemplate = new Template("Template", new StringReader("Hello Freemarker, I'm ${user}\n"), config);
            freemarkerTemplate.process(this.dataModel, this.output);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void printFromFile() {
        try {
            freemarkerTemplate = config.getTemplate("templates/freemarker.xml");
            freemarkerTemplate.process(this.dataModel, this.output);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Velocity

public class VelocityExample extends TemplateExample {

    VelocityEngine engine = new VelocityEngine();
    VelocityContext context = new VelocityContext();

    public VelocityExample(String user) {
        this.user = user;
        context.put("user", this.user);
    }

    @Override
    public void print() {
        StringWriter writer = new StringWriter();
        StringReader reader = new StringReader("\nHello Velocity, I'm $user\n");
        try {
            Velocity.evaluate(context, writer, this.user, reader);
            System.out.println( writer.toString() );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void printFromFile() {
        StringWriter writer = new StringWriter();
        try {
            Template template = engine.getTemplate("templates/velocity.vm");
            template.merge( context, writer );
            System.out.println( writer.toString() );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Hello, ${name}!

#foreach($engineName in $engineNames)
  Hello, ${engineName} world!
#end

#if ($engineName = "Velocity")
  Hello, $engineName world!
#else
  Hello, other world!
#end

#include("header.txt")
Hello $engineName world!
#include("footer.txt")

StringTemplate

public class StringTemplateExample extends TemplateExample{

    StringTemplate template = new StringTemplate("Hello StringTemplate, I'm $user$");

    public StringTemplateExample(String user) {
        this.user = user;
        template.setAttribute("user", this.user);
    }

    @Override
    public void print(){
        System.out.println(template);
    }

    @Override
    public void printFromFile(){
        StringTemplateGroup templateGroup = new StringTemplateGroup("xml group", "templates");
        StringTemplate xmlTemplate = templateGroup.getInstanceOf("xml");
        xmlTemplate.setAttribute("user", this.user);

        System.out.println(xmlTemplate.toString());
    }
}
import org.antlr.stringtemplate.*;
import org.antlr.stringtemplate.language.*;

StringTemplateGroup group =  new StringTemplateGroup("»our name«", "»path to teplates foled«]]", DefaultTemplateLexer.class);
StringTemplate homepage = group.getInstanceOf("homepage");
helloAgain.setAttribute("title", "Welcome To StringTemplate");
System.out.println(homepage.toString());
Hello, $name$!
Hello, $user.name$!
Hello, $user.(expression_to_get_property)$
Hello, $users; separator=", "$

$name:bold()$ // Apply template
$users:{s|<li>$s$</li>}; // Anonymous teplate

MVEL2

public class MVELExample extends TemplateExample{

    Map<String,String> map = new HashMap<String,String>();

    public MVELExample(String user) {
        this.user = user;
        map.put("user", user);
    }

    @Override
    public void print() {
        System.out.println((String)TemplateRuntime.eval("Hello MVEL, I'm @{user}\n", map));
    }

    @Override
    public void printFromFile() {
        try {
            System.out.println(TemplateRuntime.eval(new FileInputStream(new File("templates/mvel.xml")), map));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Spring libraries

defines NormalViewResolver, this uses JSP and JSTL views

View resolver
Declared in WebApplicationContext

  • InternalResourceViewResolver
  • ResourceBundleViewResolver

When using JSTL, we need to use JstlView first

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Thymeleaf

JSTL

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
${2+2}

JSP Import

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>
<%@ page session="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

Load XML to DOM

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

// Document doc = db.parse(url.toString());
// Document doc = db.parse("path.xml");

Element rootElem = doc.getDocumentElement();
/
Node: getNodeName(), getNodeValue(), getNodeType(), getParentNode(), getChildNodes(),
Element: .getAttribute(), setAttribute, removeAttribute()
Element: .getElementsByTagName
/

// NodeList nodeList = rootElem.getChildNodes();
// NodeList nodeList = rootElem.getElementsByTagName("tag");

for (int i = 0; i < nodeList.getLength(); i++) {
Element elem = (Element) nodeList.item(i);
String id = elem.getAttribute("id");
// ...
}

serializacetoXML(URI output)

public void serializetoXML(URI output) throws IOException, TransformerConfigurationException, TransformerException {
// Vytvorime instanci tovarni tridy
TransformerFactory factory = TransformerFactory.newInstance();
// Pomoci tovarni tridy ziskame instanci tzv. kopirovaciho transformeru
Transformer transformer = factory.newTransformer();
// Vstupem transformace bude dokument v pameti
DOMSource source = new DOMSource(doc);
// Vystupem transformace bude vystupni soubor
StreamResult result = new StreamResult(output.toString());
// Provedeme transformaci
transformer.transform(source, result);
}

JDO

Relational DB.

Java
JDBC - via SQL to any relational db.
Persistentni objekty - existence pretrva beh aplikace.

Ukladat objekty, ne relace:

  • objekty maji vlastni identitu -> neresime primarni klic (jinak generovan umele)
  • pri zmene db nemusime revidovat vsechny SQL

Nejlepsi reseni -> objektova db (eg. Cache)

Nastroje na persistenci objektu pomoci relacni databaze:

  • J2EE a Entity Beans.
  • Hibernate, TopLink - maji vlastni api, zmena neni jednoduse mozna.
  • JDO - standartni rozhrani persistence

By Sun. Umoznuje ruzne implementace (slouzi jako rozhrani objektove db, provadi maping na relace, uklada data do relacni db)
API je nezavisle na implementaci persistence - muzeme jednoduse meni implementace a typ DB.

--- all in javax.jdo ---
PersistenceManagerFacorty - konfig persistence
PersistenceManager - implementace metod pro persistenci
Transaction - sprava transakci
1 PersistenceManager = 1 Transaction (get via currentTransaction())

Transakce

Posloupnost operaci, probehne bud cela, nebo nic.
-- vsechno v JDO je v transakcich
-> app vzdy v konzistetnim stavu

// Properties properties = new Properties(); // setting db access
properties.setProperty();
…
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(properties);
PersistenceManager pm = pm = pmflgetPersistenceManager();
Transation tx - pm.currentTransaction();
{
    // Write
    tx.begin();
    Person joe = new Person("Joe", "Doe");
    pm.makePersistent(joe);
    tx.commit();

    // or Read
    tx.begin();
    Extent extent = pm.getExtent(Person.class, false);
    for (Iterator i = extent.iterator(); i.hasNext();) {
        Person somebody = (Person) i.next();
        …
    }
    tx.commit();

} finally {
    if (tx.isActive()) {
        tx.rollback(); // zruseni cele transakce
    }
}

States

Meni se v ramci transakce

Transient

Vytvoreny objekt za behu app, nebyl ulozen jako persistent
JDO se o nej vubec nestara

  • kazdy novy objekt
  • persistentni pomoci pm.makeTransient(obj); // zruseni vazby
  • persistentni pomoci pm.deletePersistent(obj) // zruseni + smazani z uloziste

Persistent

Ve sprave JDO.

  • Persistent New (po makePersistent()), zatim neni ulozen, ulozi se po commitu transakce
  • Persistent Clean - ulozen i nacten do objektu v pameti… Odpovidaji si. Tady bude po stavu hollow kdyz ho nacteme.
  • Persistent Dirty - neodpovidaji si. Zmenili jsme ho v pameti. Po commintu transakce se ulozi.
  • Persistent Deleted - je ulozen, bylo provedeno persistentDelete(). Pri commitu bude smazan.
  • Persistent New Deleted - [RARE], makePersistent() -> Persistence New -> deletePersistent() before commit

Hollow

Data v ulozisti. Nejsou nacteny v pameti. // Ale je nejakym zpusobem nactena informace o tom ze tam jsou.

  • Persisteni objekt se Hollow stane po commitu
  • Kazdy objekt nove nacetny z uoziste… jakmile ho zacteme cist tak je z nej Persistent.

###
Kazdy objekt ma indentitu nezavislou na obsahu dat. V relacni db je to vestinou nejaky primarni klic.
V JDO ziskava identitu v okamziku, kdy je ucinen persistentnim. (JDO o nem vi).
Schemata pridelovani identity:

  • Datastore identity - sprava id je na JDO <-- implicitni
  • Application identity - sprava id je na aplikaci (=programatorovi). Pouziti jen vyjimecne. (napr chceme aby iden. osoby bylo RC)
    --- mozno kombinovat

Datastore identity

Implementace JDO musi mit tridu objektu, ktere budou slouzit jako ID
ziskame ho pm.getObjectId();

<class name="Osoba" identity-type="datastore">
    ...
</class>

Application identity

Nase trida musi obsahovat primarni klic (jednoznacna identifikace) - jednoduchy (1 polozka)/slozeny (kombinace vice polozek).
Nelze pouzit String/Long
Musiem definovat atribut primarniho klice (ident) a take jeho tridu (idOsoby)

<class name="Osoba" identity-type="application" objectid-class="IdOsoby">
    <field name="ident" primary-key="true">
    <field name="vek"/>
    ...
</class>

Pozadavky na tridu identifikatoru

  • nestaticke verejne vlastnosti stejneho jmena a typu, jake jsou polozky primarniho klice
  • equals, hashCode() - zavisi na vsechn vlastnostech primarniho klice
  • implicitni konstruktor
  • musi mit konstruktor s argumentem String (on demand identifikator)
  • toString() - kombatibilni s konstruktorem s arg String
  • trida je public, implements Seriazible
  • vsechny nestaticke vlastnosti tridy musi byt Serializable (recomm. String, Date, Number)
  • vsechny nestaticke vlastnosti jsou public

Access to objects in DB

Access via ID

We already know object id, eg. from pm.getObjectId() or from predchozi knowledge (generujeme si idcka sami, eg rodne cislo)
Person somebody = (Person) pm.getObjectById(id, true); // true - kontroluje se pritomnost v ulozisti

Access via extent

Extent = mnozina vsech instanci dane tridy ulozenych v objekotve databazi a muze zahrnovat i tridy odvozene.

Extent people = pm.getExtent(Person.class, true); // true - i odvozene tridy
Iterator itr = osoby.iterator();
try {
    while(itr.hasNext()) {
        somebody = (Person) itr.next();
    }
} finally {
    people.close(itr);
}

Pokud data modifikujeme, musime zacit a ukoncit transakci.

Access data via JDOQL

Query via javax.jdo.Query

String.startsWith(String)
String.endsWith(String)
Collection.isEmpty()
Collection.contains(hodnota)
Map.isEmpty()
Map.contains(hodnota)

Query query = pm.newQUery(Person.class, "age" < 50);
Collection collection = (Collection) query.execute();

Data types

Problem: Java and Relation Db Data types are not compatible, need for mapping

First-Class Object - persistentni object, has own odentity, lze na nej odkazovat… typicky vsechny objekty ulozene v aplikaci.
Second-Class Object - nema vlastni identitu, existuje jako atribut First-class objectu.

Datatypes supported by JDO implementation:

Second-class
boolean, byte, short, int, long, char, float, double
Boolean, Character, Byte, Short, Integer, Long, Float, Double, String, Locale, BigDecimal, BigInteger
Collection, Set, HashSet
java.util.Date
optional [Map, List, ArrayList, HashMap, Hashtable, LinkedList, TreeMap, TreeSet, Vector]

First-class
Every class implements PersisetnceCapable (done by extending translated classes)
Object
Every interface

Kolekce

Dve tridy objektu

  1. Vlastnost typu kolekce (=vlastnik kolekce)
  2. Tridy prvky kolekce (v Jave je mozne pouzit pro kolekci obecny typ Object, pro ulozeni ho ale musime presneji specifikovat)
  3. [MAP] tridy prvku pouzite jako klice (pouziti v meteadatech <map key-type="java.lang.String" value-type="Adresa"/>)

Set neobsahuje duplikaty (nikdy p1.equals(p2)), poradi nehraje roli
List muze obsahovat duplikaty, poradi hraje roli

Pokud je atribut peristentni tridy kolekce ≤ Card > collection of tags ≥, stava se trida vlastnikem kolekce a v jejich metadatech je treba zadat tridu prvku

<class name="Card" identity-type="datastore">
    <field name="name">
        <extension vendor-name="jpox" key="length" value="max 100"/>
    </field>
    <field name="image">
        <extension vendor-name="jpox" key="length" value="max 100"/>
    </field>
    <field name="tags">
        <collection element-type="Tag" embedded-element="true"/> // element-type has to be also persistent // embedded-element - jsou prvky ulozeny jako FCO (true), nebo jako SCO (false)
    </field>
</class>

Object relations

1:N possibilites
Normal mapping - trida A obsahuje atribut kolekci objektu B (skryte vytvari treti tabulku - JOIN TABLE)
Jednostranne inverzni mapovani - kazdy z objektu tridy B obsahuje atribut A, se kterym je v relaci
Oboustranne inverzni mapovani = kombinace prechchozich

Extensions

<class name="Person">
    <field name="name" persistence-modifier="persistent">
        <extension vendor-name="jpox" key="length" value="max 50"/>
    </field>
    ...
</class>
<class name="Employee" persistence-capable-superclass="Osoba">
    <field name="salary" persistence-modifier="persistent"/>
</class>

JDOQL

  1. Import classes used in query
  2. Params declaration - data from outside (from user)
  3. Vars declaration - local variables to handle query
  4. Candidate set - set of object query works with (eg. extent)
    • Class of objects (extent of this and extended classes) query.setClass()
    • precreated extent query.setCandidates(Extent)
    • collection and class of objects query.setCandidates(Collection)
  5. Result set class declaration - one query can return just one type of class
  6. Filter settings - is object part of result or should be ignored?
  7. Order sertings
import java.util.*;
PersistenceManager pm; /* vytvoren drive */
public Collection aktivniAkce()
{
    /* Vytvoříme dotaz, zadáme třídu objektů a filtr */
    Query q = pm.newQuery(Akce.class,
                          "datefrom <= now && dateto >= now");
    /* Import třídy Date */
    q.declareImports("import java.util.Date");
    /* Deklarujeme parametr 'now' */
    q.declareParameters("Date now");
    /* Zjistíme dnešní datum */
    Date dnes = new Date();
    /* Spustíme dotaz */
    Collection result = (Collection) q.execute(dnes);
    return result;
}

Storing data at Gogle App Engine

AppEngineDatastore - NoSQL, schemaless, object, query engine, atomic transactions (no interfering between ops, within entity groups). Implementations of JDO and JPA
Google Cloud SQL - relational SQL, based on MySQL
Google Cloud Storage - for big files

Overview

Entity - properties (named value): string, integer, reference, …
Identified by key: kind, identifier (string/numeric), [ancestor path]. Can be assigned by us or automatically.
Multiple operations in one transactions. (every op. has to suceed, otherwise rollback)

DataStore vs Relational DB

Query performance depends on Result Set (not Date Set) -> load 10 entities from 100 == load 10 entities from 1 000 000. (but because of that, just some ops are supported)
NO join, aggregate, inequality filtering on multiple props, filtering data based on subquery
Hierarchy (~filesystem). Entity can have parent. - permanent. Entity + its descendats = entity group.
Person:GreatGrandpa / Person:Grandpa / Person:Dad / Person:Me

Query

Get by key
Quert by values
Return: keys, entities, projected entities

Writing

Commit phase - entity data is recorded to log
Apply phase - entity data is written & index rows for a entity is written

Google App Engine JDO 2.3

Standard interface for storing objects containing data into a database

  • annotate java objects
  • retrieve objects with queries
  • interacting with a db suing transactions

Setting:

  • JDO and DataNucleus App Engine JARs in war/WEB-INF/lib/
  • jdoconfig.xml in war/WEB-INF/classes/META-INF // tells JDO to use AppEngine
  • build process must perfomr a post-compilation enhancement - associate with JDO impl

@PersistenceCapable - To declare a Java class as capable of being stored and retrieved from the datastore with JDO
@Persistent - fields of class to be stored
@Persistent(serialized = "true") - stored as BLOB (files)
@NotPersistent - fields of class NOT to be stored
(because some default are used - some data types are persistent by default, some are not)
@PrimaryKey, @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) - keys

import com.google.appengine.api.datastore.Key;
import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
public class Employee {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    @Persistent
    private String firstName;
    @Persistent
    private String lastName;
    @Persistent
    private Date hireDate;
    public Employee(String firstName, String lastName, Date hireDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hireDate = hireDate;
    }
    // Accessors for the fields. JDO doesn't use these, but your application does.
    public Key getKey() {
        return key;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getHireDate() {
        return hireDate;
    }
    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }
}

Helps create dynamic webpages based on standart markup languages (HTML, XML, …) – any type of data through OutputStream
1999, Sun Microsystems
Require web server with servlet container (Apache Tomcat, Jetty)
Similar to PHP or ASP.NET Web Forms
Alternative Apache Velocity

High-level abstraction of Java servlets.
JSP translated to executable servlets at runtime, by compiler (embedded in server).
Cached until modified.
Can be used:
• independently
• as view in MVC ( usually M = JavaBeans, V = JSP, C = Java Servlets/framework (Struts, Spring) )

Mix of Java and other languages

Syntax

evaluated inside java servlet class, without semicolon

inner variables, classes, methods definitions

same as expression, but puts all in _jspService() method

to control how the Web container translates and executes the JSP page.
include – directly pasted
taglib – tag library is used, params: prefix and URI
http://java.sun.com/jsp/jstl/core" prefix="c" %>
page
• import – translate into import in servlet
• contentType – optional, if HTML is not used -> text/html
• errorPage -> false (if true object (of type javax.servlet.jsp.JspException) is available // We can define error page to whole WAR
• isErrorPage
• isThreadSafe
• autoFlush – buffer flushed when full (false -> throw exception)
• session
• buffer – buffer size
• language – only possible is Java right now
• extends – DO NOT USE
• info – text for getServletInfo()
• pageEncoding = default ISO-8859-1, change to UTF-8

Implicit objects
out – [JspWriter]
page – servlet itself
pageContext – [PageContext] … usually one HTML page passes multiple JSP
request – [HttpServletRequest]
response – [HttpServletResponse]
session – [HttpSession]
config
application – shared data for all servlets
exception – exceptions not caught by app code

Actions
jsp:include – subroutine, temporalily hands control to other JSP, then return to self

jsp:forward – some as include, but control will NOT be returned back

jsp:param – used in jsp:include, jsp:forward, jsp:params
jsp:getProperty – property of JavaBean

"myerror.jsp" %>
="com.foo.bar" %>

=1;%>
=1; %>

Counting to three:

This number is .

Expression Language
Added in ver. 2.0 (in 2.1 Unified Expression Language, same as in JSF)
Access data and functions in Java objects
${javabean.variable}

Additional tags
Tag libraires, create your own using JSP Tag Extension API
Standart is JSTL (interations, condititons) and Struts Tag LIbrary

JSP 2.0

Displaying parameter values
Hello, ${param.visitor}
Same as: Hello, request.getParameter("visitor")%>

Nested beans
${person.organization.name}

deferred expressions - evaluated az when needed

Compiler-JVM set (called an SDK or JDK)

the lone JVM (called a JRE, Java Runtime Environment)

JSP Life Cycle

Request to JSP Page

Handled by special servlet – checks if JSP was modified since last time

ORM

Object data mode <-> Relational Data Model

Entita (clovek, faktura, objednavka, …)
Trida, ktera nam reprezentuje domenovy objekt
(- odpovida jednomu radku v db)

DTO
Data Transfer Object
Zapozdreni dat a jejich prenos
Pokud potrebujeme neco nekam poslat
Velice podobna jako entita, klidne uplne stejna

  • entita je vzdycky stejne

POJO
Plain Old Java Object
Tridy na ktere nejsou kladeny zadne slozite pozadavky - zadne rozhrani, zadne extendy, zadne konvence
pouze napr muze mit pozadavky na nejake get/set, bezparam konstruktor, …

eg.
Customer (name, address, notes)
Contracts (customer_id, description, …)
U vypisu Customeru nas muzou zajimat jen info o Custoemrech a souhrne infomrace o Contractech (ale ne cele entity)
Vytvorim si CustomerDAO - ktere nektere atributy mit nebude a bude mit nejake navic z Contractu

Pouziva se vice pristupu

  1. Entity EJB
    Entita je objekt, ktery se nachazi v EJB kontejneru a pristup se resil (vzdalene)

  2. JDO
    Java Data Object
    Univerzalni standart pro persistenci, neni omezen na relacni databazi
    Obecnejsi nez JPA
    Ale odstinuje nas od db jeste vic nez ty ostatni

  3. JPA
    Vyuziva koncet POJO Entit
    Inspirovane nastorem Hibernate
    Je ot pouze API, muze byt implementovano ruznymi ORM nastroji TopLink, OpenJPA, Hibernate, …
    Je hodne obecne, muze se menit implementace… Nastroje pak maji nejake veci navic, ale jen extra featury
    JPA je standard

Entity reprezentuji jednotlive domenove objekty (klasicke POJO objekty - attrs, musi mit bezparam constructor, doporucuje se aby byla serializovatelna)

Definice mapovani

  1. Anotace
    Prehlednejsi, je to na jednom miste
    Anotace ma Java od v 5

  2. XML

  1. JavaDoc
    Predtim nez mela Java anotace

XML ma vetsi prioritu nez anotace
Convention over configuration (nemusime nikde rikat do ktere tabulky se bude ukladat, jak se buodu sloupecky jmenovat, …)

Konfigurace v persistence.xml, muze obsahovat vice persistence unit

Persistence unit
Seznam trid, ktere Persistence Unit spravuje
Konfigurace pripojeni (JDNI DataSource, JDBC url, name, pass)
Zpusob rizeni transakci

Konfiguracni parametry
<?xml version="1.0" encoding="UTF-8"?>



org.hibernate.ejb.HibernatePersistence





EntityManager
CRUD operace s entitami, nejdulezitejnsi entita z JPA
Instanci ziskame pomoc EntityManagerFactory (bud primo pres new nebo od containeru pres DI)
Relativne levna operace, ale ne thread-safe.

EntityManagerFactory
Nacita conf z persistence.xml
Ziskame pomoci Persistence.createEntityManagerFactory(--- retezec s nazvem Persistence Unit ---) nebo pomoc DI
Je relativne draha (nacita conf), je thread-safe
Init ORM nastroje

Summary
KOnfigurace v persistence.xml, sklada se z persistence unit (vetsinou jedna, ale napr. dalsi pri testovani, pri vice db,
Kazda entita je asociovana s jednou persistence unit.

Persistence Context se stara instance entity
Persistence Unit se stara o tridy entit
--> pro jednu unit muzeme mit vic contextu, dochazi k tomu pri soubeznych transakcich.
V tabulce mam jednoho Petra, v pameti muzu mit vic instanci Petru ( v jinych kontextech ) -> davat na to pozor

Transakce je spravovana PersistenceContextem, maximalne jedna. Zmeny jsou ulozeny pri commitu.

Na zacatku neexisutje
Vytvorime ppomoci konstruktoru
Obycejna instance v pameti, ORM o ni nevi
em.persist(e) - dostane se do managovaneho stavu, je asoc. s persistence contextem, zmeny jsou automaticky ukladany do db pri provedeni commitu transakce commitu.

Vazby mezi entitami
V ORM ma cenu se bavit o vazbach mezi entitami, v SQL to nejde
Vazba jedostrana, oboustrana (ze zaazniku se dostanu na objednavky, z objednavek na zakazniky)
Kardinalita
(Lazy fetching - mame zakaznika, chceme vytahnout jeho enitity, vytahnou se i vsechny jeho objednavky… pres lazy fetching muzeme nastavit ze objednavky se nastavi az je budeme potrebovat ––– funguje jen po dobu trvani transakce)
Vazby nam vytvari zavislost - muzeem se do nich zamotat
(Produkty obsahuji zavislost na kategoriich, kategorie obsahuji vazby na prodkty)
( -> reseni je lazy fetching - nejde obcas pouzit)
( -> reseni je jednosmerna vazba)

JPQL
Selecty (narozdil od SQL, mame vztahy mezi netitama, nemusime provadet JOIN)
umi ruzne vystupy (entity, atributy, seznam atribitu)

CriteriaAPI
Napr pri dotazovani na db pri vyplnenni formulare od uzivatele

javax.persistence.Query --- createQuery
muzeme si dotazy pripojit rovnou k entitam, potom createNamedQuery
getResultList
getSingleResult
muzou byt parametrizovany (parametry jsou pojmenovane, ne cislovane jako JDBC)

EJB je bitevni tank
Spring je odlehcena varianta, je velmi oblibena, not invasive. Relative simple, do not create other dependencies.
Spring is not formal standard. Big Companies could be afraid.

  • deklarativni rizeni transakci
  • autorizace (via annotations)
  • distribuovane transakce
  • resime ceho chceme dosahnout

Spring JDBC
Apache Commons DB
--- implementace TemplateMethod Patternu
zjednodusuje kod, ale porad nas nechrani v typove kontrole a chybach v SQL

JDO X JPA

DB ------------- Data Access ----------- Service --------------------------- View
sql, jdbc objects data transfer object

Tomcat a Jetty jsou webovy server kontejnery
Jsou pouzity v glassfishu

JDBC
Hibernate

INSERT INTO people (id, name) VALUES (1, "Pepa");
Person p = new Person(1, "Pepa"); em.persist(p); em.getTransaction().commit();
UPDATE people SET name = "Honza" WHERE id = 2;
Person p = em.find(Person.class,2); p.setName("Honza"); em.getTransaction().commit();

Spring

Usnadneni vyvoje enterprise applikaci.

  • DI
  • transakcni zpracovani, remoting business
  • JDBC/ORM
  • centralizovany config
  • usnadneni unit testu

= alternativa k EJB
EJB je zastarale (nebo alespon vychazi ze zastaralych korenu)
EJB je prilis komplexni - 1 komponenta = 4 tridy (component interface, business interface, implenetation, deployment descriptor)
EJB je invazivni -> problemy s unit testy.
EJB pouziva proprietalni technologie.

Dalsi sluzby nad ramec EJB od Springu

  • MVC + intergrace jinych technologii (JSP+JSTL+Tiles, Velocity, FreeMarker, XSLT, JasperReports)
  • integrace jinych MVC (Struts, Tapestry, JSD, WebWork)
  • AOP Aspect Oriented Programing

Testing

Spring provide abstract class for JUnit tests.

Inversion of Control - odpovednost za vytvareni, init a provazadni objektu ven z kodu (do IoC kontejneru)
Dependency Injection je specialni pripad Inversion of Control.

  • Setter injection
  • Construction injection
  • Interface injection

Can be used also as only a libary inside other frameworks (Struts/WebWork) - start Spring via ContextLoaderListener and access it via ServletContext attr

Spring Framework

org.springframework.aop

  • Source-level metadata
  • AOP infrastructure
    org.springframework.beans

org.springframework.context
org.springframework.context.support
org.springframework.expression
org.springframework.instrument
org.springframework.jdbc
org.springframework.jms
org.springframework.orm

  • Hibernate
  • JDO
    org.springframework.oxm
    org.springframework.test
    org.springframework.transaction
    org.springframework.web - Spring Web MVC
    org.springframework.web.portlet
    org.springframework.web.servlet
    org.springframework.web.struts

Spring Web MVC

Designed around DispatcherServlet.

  • dispatches requests to handlers
    • hanlder mapping (via annotations @Controller, @RequestMapping)
    • view resoulution (customizable - url, request type, params, Accept header, ...)
    • locale and theme resolution
    • uploading files

DispatcherServlet

Front Controller design pattern
Central Servlet (inherits from HttpServlet, declared in web.xml)
Has associated parent WebApplicationContext (bound in ServletContext, access via RequestContextUtils) (extension of ApplicationContext) - inherits all beans from it. Integrated with the Spring IoC container (all features of Spring are accessible for us)

  • Dispatches requests to controllers
  • offers other functionality
    For both uses Special beans (can be set, or we can use default - set in DispatcherServlet.properties).

Special bean types

  • HandlerMapping - maps request to handlers, pre and post-processors. eg. via annotations in controllers.
  • HandlerAdapter - for invoking handlers, to shield DispatcherServlet from impl detail (previosly mapped by HandlerMappig)
  • HandlerExceptionResolver - maps exceptions to views
  • ViewResolver - string based view names -> actual View types. (default InternalResourceViewResolver)
  • LocaleResolver
  • ThemeResolver
  • MultipartResolver - processing uploads
  • FlashMapManager - pass attrs between request, eg for flash messages

Lifecycle

  1. Locale resolving
  2. Theme resolving
  3. Multipart resolving, if true -> wrapped in a MultipartHttpServletRequest
  4. Handler searching and executing
  5. If model returned -> render view

Init
Looks for [servlet-name]-servlet.xml in WEB_INF directory, eg. /WEB-INF/golfing-servlet.xml
Create beans from it

web.xml

<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <!-- customize DispatcherServlet instances via init-param elems -->
        <init-param name="contextClass" value="" /> // default: XmlWebApplicationContext
        <init-param name="contextConfigLocation" value="" />
        <init-param name="namespace" value="" /> // default: [servlet-name]-servlet.
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/example/*</url-pattern>
    </servlet-mapping>
</web-app>

Annotations

@Controller - used to handler mapping
@RequestMapping - used to handler mapping, to class or class's method

  • value: strings, {pathVariables}, {symbolicName:[a-z-]+}
  • method: RequestMethod.POST, RequestMethod.GET
  • consumes (Content-Type header): application/json (also negations)
  • produces (Accept request header): application/json
  • params: presence "param", absence "!param", value "param=value"
    @RequestHeader
    @RequestParam
    @PathVariable - useful for REST

Prior to Spring 3.1
Controlled was selected by DefaultAnnotationHandlerMapping
Actual method was narrowed by AnnotationMethodHandlerAdapter

Since Spring 3.1
Controller and method is selected by RequestMappingHandlerMapping (coop with RequestMappingHandlerAdapter)
Not working anymore:

  • select a controller first with SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping and then select method by @RequestMapping
  • rely on method names as a fall-back with disambiguate methods (with same @RequestMapping)
  • have single "default" method in controller without @RequestMapping, when no other mapping was matches (now 404)