Sie sind auf Seite 1von 108

Magnolia International Ltd.

Magnolia CMS Technical Guide

Authors: Antti Hietala, Philipp Brfuss


Date:

27.07.2010

Version: 1.0

Copyright Magnolia International Ltd. 2010.


All rights reserved. No part of this document may be reproduced in any form without prior permission in writing
from Magnolia International Ltd.

Magnolia International Ltd.

Table of contents
Introduction to Magnolia CMS architecture............................................................................................ 6
AdminCentral............................................................................................................................................. 7
Authoring ................................................................................................................................................... 9
Instances ................................................................................................................................................. 12
Public instances serving different content ............................................................................................. 13
Intranet and extranet ............................................................................................................................. 14
Planned redundancy and high availability ............................................................................................. 14
Instance configuration examples ........................................................................................................... 15
Content delivery ...................................................................................................................................... 16
Subscribers............................................................................................................................................ 16
Content storage and structure............................................................................................................... 17
Repository ............................................................................................................................................. 17
Workspaces........................................................................................................................................... 17
Magnolia CMS workspaces ............................................................................................................... 19
Hierarchical content store...................................................................................................................... 20
JCR standard API for content repositories ............................................................................................ 21
Persistent storage ................................................................................................................................. 22
Clustering ................................................................................................................................................ 24
Jackrabbit clustering.............................................................................................................................. 24
Modules.................................................................................................................................................... 26
Pluggable and independent................................................................................................................... 26
Configuration ......................................................................................................................................... 27
JAR structure......................................................................................................................................... 28
Module class ......................................................................................................................................... 29
Dependencies ....................................................................................................................................... 29
Module life-cycle.................................................................................................................................... 30
Bootstrap files........................................................................................................................................ 30
Version handling.................................................................................................................................... 31
Community driven module development ............................................................................................... 32
Magnolia webapp .................................................................................................................................... 33
Directory structure ................................................................................................................................. 33
Adding the Magnolia main filter to the webapp ..................................................................................... 34
Adding the Magnolia context listener .................................................................................................... 35
Request processing and filters.............................................................................................................. 36
Magnolia CMS filter chain ..................................................................................................................... 36

Magnolia International Ltd.

Templating ............................................................................................................................................... 39
Pages and paragraphs .......................................................................................................................... 39
Templating mechanism ......................................................................................................................... 40
Component relations ............................................................................................................................. 41
Templating languages ........................................................................................................................... 42
Tag library.............................................................................................................................................. 43
Example of CMS tags in use ................................................................................................................. 45
Templating support objects ................................................................................................................... 46
Dialogs ..................................................................................................................................................... 47
Tabs and controls .................................................................................................................................. 47
Dialog configuration............................................................................................................................... 48
Create a dialog definition ................................................................................................................... 49
Map the dialog to a paragraph ........................................................................................................... 50
Add the paragraph on a page ............................................................................................................ 50
Best-practice Standard Templating Kit................................................................................................. 51
Contents ................................................................................................................................................ 51
Benefits ................................................................................................................................................. 51
STK components ................................................................................................................................... 52
Site definition ......................................................................................................................................... 52
Areas ..................................................................................................................................................... 54
Template inclusion ................................................................................................................................ 56
Customization........................................................................................................................................ 57
Template prototype ............................................................................................................................ 58
Static HTML prototype ....................................................................................................................... 61
Design with CSS ................................................................................................................................... 64
Layout and grid...................................................................................................................................... 64
HTML structure .................................................................................................................................. 66
Body IDs and classes ............................................................................................................................ 67
CSS configuration .............................................................................................................................. 67
Learn more ............................................................................................................................................ 69
Rendering engine.................................................................................................................................... 70
Steps involved in rendering content ...................................................................................................... 71
Renderers.............................................................................................................................................. 72
Rendering order .................................................................................................................................... 72
Magnolia CMS API................................................................................................................................... 73
Magnolia Context / Aggregation State................................................................................................... 73
Content API ........................................................................................................................................... 74
Components and modules .................................................................................................................... 74
Templating............................................................................................................................................. 74

Magnolia International Ltd.

Configuration mechanisms.................................................................................................................... 76
Properties .............................................................................................................................................. 76
Multiple configurations in the same Web application archive (WAR) .................................................... 77
Components .......................................................................................................................................... 77
Content2Bean ....................................................................................................................................... 78
Where is Content2Bean used? .......................................................................................................... 79
Extending configuration ..................................................................................................................... 80
Observation ........................................................................................................................................... 80
Integration options.................................................................................................................................. 81
Custom filter. ......................................................................................................................................... 81
Custom servlet....................................................................................................................................... 82
Forwarding a request ............................................................................................................................ 83
Custom renderer ................................................................................................................................... 83
Spring (Blossom) module ...................................................................................................................... 83
Direct calls to rendering engine ............................................................................................................. 84
Web services, AJAX and snippets ........................................................................................................ 84
Reading content directly ........................................................................................................................ 84
Internationalization and localization ..................................................................................................... 85
System................................................................................................................................................... 85
Dialogs ............................................................................................................................................... 86
Template scripts................................................................................................................................. 87
Content .................................................................................................................................................. 87
One hierarchy or many ...................................................................................................................... 88
Storing localized content.................................................................................................................... 88
Delivering localized content ............................................................................................................... 89
Authoring ............................................................................................................................................... 90
Unicode ................................................................................................................................................. 92
Security .................................................................................................................................................... 93
Users ..................................................................................................................................................... 93
Groups................................................................................................................................................... 94
Roles ..................................................................................................................................................... 94
ACLs...................................................................................................................................................... 94
Custom login forms................................................................................................................................ 96
Data module............................................................................................................................................. 97
Types..................................................................................................................................................... 98
Dialogs................................................................................................................................................... 99
Content ................................................................................................................................................ 100

Magnolia International Ltd.

Cache ..................................................................................................................................................... 101


Cache filter .......................................................................................................................................... 101
Policy configuration ............................................................................................................................. 101
Caching while developing.................................................................................................................... 102
How caching works ............................................................................................................................. 102
Ehcache back end ............................................................................................................................... 103
Advanced cache strategies ................................................................................................................. 103
Workflow ................................................................................................................................................ 104
Engine ................................................................................................................................................. 105
Participants.......................................................................................................................................... 105
Workitems in inbox .............................................................................................................................. 106
Integration with external processes ..................................................................................................... 106
Resources.............................................................................................................................................. 108

Magnolia International Ltd.

1. Introduction to Magnolia CMS architecture


Magnolia CMS is an open-source Web Content Management System that focuses on providing an intuitive user
experience in an enterprise-scale system. Its combination of ease-of-use and a flexible, standards-based Java
architecture has attracted enterprise customers such as ING, JBoss.org, Johnson & Johnson, Lloyds TSB, Sony,
Seat, Unilever and The US Department of Defense. Magnolia CMS is used by governments and Fortune 500
enterprises, and in more than 100 countries.
Architectural features that make Magnolia CMS suitable for versatile enterprise use are:
Java platform. Magnolia CMS is built on top of the Java Enterprise Edition platform. Java EE reduces
the cost and complexity of developing multi-tier enterprise services. Java EE applications can be rapidly
deployed and easily enhanced as the enterprise responds to competitive pressures. Java provides
further benefits to enterprises such as standardization, availability of trained talent, and a solid
marketplace for competing offers to drive innovation. Magnolia CMS is implemented as a Java EE web
application. A typical web application consists of modules that can be other web applications, Enterprise
JavaBeans (EJB) or application clients. In Magnolia CMS, nearly everything is a module. Even the
AdminCentral, a content editor's view into the CMS, is a module. A Java EE application is a set of
modules with some added glue that binds them together into a complete integrated application.
JCR standard. JCR stands for Content Repository API for Java. It is a specification for a Java platform
API for accessing content repositories in a uniform manner. Repositories are used to store the content
data and related meta data such as versioning information.
Clustering by having multiple public instances. Magnolia CMS is distributed as two web-applications,
one acting as the authoring instance and the other as the public environment. This has several benefits.
It allows for better security by having one application inside your firewall and one outside. You can
increase the number of public instances to guarantee high availability. Separate public instances can
serve geographically targeted content or multiple languages.

Magnolia International Ltd.

2. AdminCentral
AdminCentral is a Magnolia CMS user interface for performing site management and configuration tasks. This is
where administrators and editors work. AdminCentral provides a navigation menu for common tasks on the left
and displays web pages and configuration on the right.

Some of the key menu items are:


Website. Here you create and manage web sites. A site hierarchy is displayed as a tree that consists of
pages.
Documents. Built-in document management system (DMS) for storing documents, images and other
binary resources that you want to use on the web pages. Full-text indexed and searchable.
Forums. Built-in discussion forums for use on a website. You can manage user permissions with
Magnolia CMS's built-in security module.
Inbox. Incoming messages such as workflow notifications.
Data. Create and manage custom data types such as contacts, client references and customer cases.
You could for example create a custom data type "Client", populate it with recently won clients, and
showcase them on your website. Here you can also aggregate RSS feeds from external sources.
Templating Kit. Best-practice templating framework that speeds up site creation and reduces project
risk. Ships with common use case examples such as articles, news, forms, public user registration and
more, yet allows you to create completely custom sites. See Templating Kit below for more.

Magnolia International Ltd.

Security. Manage users, groups, roles and permissions. Public user registration is also managed here.
Configuration. Everything in Magnolia CMS can be configured via AdminCentral: cache, menus,
dialogs, workflows, modules...all of it.
Tools. Maintenance tools for logging, importing and exporting, querying, mail and backup.
Packager. A special tool to help with site migration. You can package an entire website or part of it and
move it to a different Magnolia CMS instance.
Magnolia Store. Store for downloading custom modules that extend Magnolia CMS.

Magnolia International Ltd.

3. Authoring
Authoring is the process of writing web content and managing it as part of the website. This includes allowing
non-technical users to contribute content in an easy and intuitive manner.
Content is authored in the browser. The user interface for content authors supports in-place editing. This is a
mode of working where the edited page looks and behaves just like the live page. New paragraphs are displayed
next to existing paragraphs in accurate context. Authors can immediately see what effect adding a new piece of
content has on the page and move the content around if needed.
When you double-click a page in the site tree in AdminCentral, the page is opened for editing.

Magnolia International Ltd.

Each page is made up of pre-defined content areas that can be controlled with templates. Editable content items
within these areas are called paragraphs. Paragraph is the smallest block of content that end users can edit,
delete and move as a unit. Think of paragraph as content that "belongs together". At its simplest, a paragraph
consists of a heading and some text. However, it can contain almost anything: a related image, links to other
articles in the same category, teased content from a sub page and much more. Editable paragraphs are identified
with green toolbars.

10

Magnolia International Ltd.

Clicking the Edit button in the green toolbar opens a dialog. A dialog is an HTML form with fields for editing
paragraph content and metadata. The data you enter into the fields is stored in the repository and ultimately
rendered as a paragraph on the page.

11

Magnolia International Ltd.

4. Instances
Magnolia CMS is distributed as two web-applications, one acting as the authoring instance and the other as the
public environment. This allows for better security, having one application inside your firewall and one outside. It
also enables clustering configurations.

Author instance is where all authors work. It typically resides in a secure location such as behind a corporate
firewall, inaccessible from the Internet. The author instance publishes content to public instances.
Public instance receives the public content and exposes it to visitors on the Web. It resides in a public, reachable
location. You can have more than one public instances, serving the same or different content.
Each instance functions as an independent application but technically they are the same. An author instance can
be configured to function as a public instance and vice versa. The differences are small adaptations in
configuration and security. Security for the public instances is usually managed separately.

12

Magnolia International Ltd.

4.1. Public instances serving different content


You can manage multiple sites from the same author instance. Each public instance can serve content targeted
for a specific geographical area, for example.

Magnolia CMS's multi-site feature provides granularity for content control on multi-language and multidomain installations. Administrators have the option to direct content authors to the public site through a specific
domain. Authors edit only the part of the content structure that resides at the specified domain. To ensure a
consistent browsing experience, URLs are adapted to always reflect the domain. You can also configure multiple
domains to access the same instance.

13

Magnolia International Ltd.

4.2. Intranet and extranet


Magnolia CMS allows for flexibility in placing secure and sensitive application instances. The diagram below
illustrates a possible placement strategy where an extranet publishing instance resides outside the firewall but an
intranet instance is inside. More advanced configurations can be built to place intranet and extranet instances
inside a firewall, for example.

4.3. Planned redundancy and high availability


A distributed instance setup allows you to responding to high availability requirements and sudden increases in
traffic. Each of the following problem scenarios can be addressed by adding a new public instance to serve the
same content, helping existing instances deal with the load.
Public instance failure. Imagine you have two public Magnolia CMS instances and due to hardware
failure one of them is out of operation for a few days. Start a new public instance to replace the broken
one.
Sudden high load on your site, also known as Slashdot effect. Spin off new public instances until the
traffic subsides.
Public instance blackout. All public instances are corrupted, broken or compromised. No instances exist
to serve content.

14

Magnolia International Ltd.

4.4. Instance configuration examples


Magnolia CMS configurations range from a minimal one-machine setup to a standard three-instance production
setup and beyond.
Minimal. Author and Public instances exist on the same server. This is the default configuration when
you install Magnolia CMS on your computer to try it.
Reduced. Author and Public instances exist on separate servers. The two Public instances are on the
same server or one of the Public instances resides on the same server as the Author instance.
Standard. Public instances exist on separate servers. This configuration enables load balancing.
Incoming requests can be directed to one server or another depending on availability.

15

Magnolia International Ltd.

5. Content delivery
Content is published from the author instance to the public instances via activation. Content authors create new
content on the author instance and then activate it. Activation can trigger an optional editorial workflow in which
an editor reviews the changes and approves them for publication. On approval, the new content is transmitted to
the public instance.

5.1. Subscribers
Public instances that receive the activated content are known as subscribers. Any number of subscribers can
subscribe to a single author instance. Subscribers are key to building high-availability, load-balanced
environments since they can be configured to receive targeted content. A subscriber configuration defines the
address of the subscriber and the type of content it should receive.
Example: The image below shows the configuration for subscriber "nbasuperstars-com". The subscriber resides
at URL http://www.nbasuperstars.com:8080/magnoliaPublic. This is the location of the public
instance on the Internet. The subscriber is active which means it will receive content when activation is
executed. Not all content is published to this subscriber, however. It subscribes only to content residing at
path /sports on the author instance. This is an example of mapping a public instance to a subsection of the
content hierarchy.

Subscribers can subscribe to any content item: websites, subsections of websites, configuration settings, custom
data types and data nodes, forums, comments, documents, images and so on.

16

Magnolia International Ltd.

6. Content storage and structure


Magnolia CMS stores all content (web pages, images, documents, configuration, data) in a content repository.
The repository implementation we have chosen, Apache Jackrabbit, adheres to the Java Content Repository
standard (JCR).

6.1. Repository
A content repository is a high-level information management system that is a superset of traditional data
repositories. It implements content services such as:
Granular content access and access control
Hierarchical, structured and unstructured content
Node types, property types (text, number, date, binary)
Queries (XPath, SQL)
Import and export
Referential integrity
Versioning
Observation
Locking
Clustering
Multiple persistence models
A content repository can store text and binary data (images, documents). You don't need to worry about how the
data is stored. The repository provides a standardized way to store and retrieve it whether it resides in a
traditional database or in a file system.

6.2. Workspaces
Magnolia CMS has one repository, magnolia, which in turn contains several workspaces. There is a workspace
for storing website content, another for user accounts, third for configuration and so on.
Each workspace contains a single rooted tree of items. An item is either a node or a property. Each node may
have child nodes and child properties. Properties cannot have children; they are the leaves of the tree. All of the
actual content in the repository is stored within the values of the properties.

17

Magnolia International Ltd.

Here's what the object hierarchy in a repository looks like:


1. Repository contains workspaces
2. Workspace contains nodes
3. Each workspace has a single root node.
4. Node contains properties
5. Properties store values (data)

The changes you make to nodes and properties are transient in the workspace. Only when the system performs a
workspace save operation are the changes persisted into permanent storage such as a database.

18

Magnolia International Ltd.

6.2.1. Magnolia CMS workspaces


In its default configuration Magnolia CMS has the following workspaces:
website. Websites, pages and paragraphs. This is where most of your site content is stored.
config. Configuration settings for everything.
data. Custom data types and data items.
dms. Documents and images, typically binary data.
templates. Page and paragraph templates in the Standard Templating Kit (STK)
resources. JavaScript and CSS style sheet files used by the STK and themes.
userroles. Roles and access control lists (ACL) for granting permissions to users.
usergroups. Groups of users.
users. System, administrative and public user accounts.
and a few others...

19

Magnolia International Ltd.

Workspaces are mapped to repositories in WEB-INF/config/default/repositories.xml.


<RepositoryMapping>
<Map name="website" repositoryName="magnolia" workspaceName="website" />
<Map name="config" repositoryName="magnolia" workspaceName="config" />
<Map name="users" repositoryName="magnolia" workspaceName="users" />
...
</RepositoryMapping>
The ability to map a workspace to a named repository provides interesting possibilities. While Magnolia CMS
keeps all workspaces in one repository by default, you don't have to. You could map a workspace to a different
repository in order to:
Provide a workspace with its own persistence manager. You could store users in one database and
website content in another.
Use a different persistence mechanism according to how often the data is requested and how quickly it
needs to be available. For example, it might make sense to store search indexes on a fast disk but
archived web content on a slower disk.
Store shared content such as user-generated comments in a clustered storage. This allows various
Magnolia CMS instances to access the same comments. See Jackrabbit clustering for an illustrated
example.
Integrate your system with an external repository. As long as the external repository adheres to the JCR
standard, Magnolia CMS can access content in it.

6.3. Hierarchical content store


A content repository is designed to store, search and retrieve hierarchical data. Data consists of a tree of
nodes with associated properties. Data is stored in the properties. They may store simple values such as
numbers and strings or binary data (images, documents) of arbitrary length. Nodes may optionally have one or
more types associated with them, which in turn dictates the type of their properties, the number and type of their
child nodes, and certain behavioral characteristics.

20

Magnolia International Ltd.

Example: A, B, C and D are nodes. The boxes represent properties with Boolean, numerical, string and binary
values.

6.4. JCR standard API for content repositories


Java Content Repository (JCR) is a standard interface for accessing content repositories. JCR version 1.0 was
specified in Java Specification Request 170 (JSR-170). Version 2.0 in JSR-283 is also final. JCR specifies a
hierarchical content store with support for structured and unstructured content.
Magnolia CMS was the first open-source content management system built specifically to leverage JCR. The
standard decouples the responsibilities of content storage from content management and provides a common API
that enables standardized content reuse across the enterprise and between applications. Magnolia CMS uses the
open-source Jackrabbit reference implementation.

21

Magnolia International Ltd.

Application developers benefit from standardization as they don't need to learn several vendor-specific APIs.
Learning one standard API allows them to work with any compliant repository and write code against
it. Businesses enjoy the freedom of choice. Open standards like JCR are the best medicine against vendor lockin; any CMS that supports the JCR standard becomes a viable alternative. Costs associated with switching
vendors are smaller when your content is already the correct format.

6.5. Persistent storage


A persistence manager (PM) is an internal Jackrabbit component that handles the persistent storage of content
nodes and properties. Each workspace of a Jackrabbit content repository can use a separate persistence
manager to store content for that workspace. The persistence manager sits at the bottom layer of the Jackrabbit
system architecture. Reliability, integrity and performance of the PM are crucial to the overall stability and
performance of the repository.
Important! In order to avoid integrity issues and to benefit from services such as observation, clustering and
indexing, you should always access the content through the JCR API. Changing the data directly (bypassing
the API) causes serious issues. This may sound restrictive but the API is actually quite versatile. You can even
access the content repository from external applications using the API.

22

Magnolia International Ltd.

The choice of persistence managers includes:


Database: Magnolia CMS uses a database as persistence manager by default. This is the most
common option. We ship WAR files and operating system specific bundles with the Derby database.
Derby is an embedded database that allows us to package a fully operational Magnolia CMS example
into a single download, including configuration details and demonstration websites. It requires minimal
installation effort from users. However, for production environments we recommend an enterprise-scale
database such as MySQL, PostgreSQL, Oracle or MS SQL Server. All of them work with JCR. Database
connections are based on JDBC, involve zero deployment, and run fast.
File system: This kind of data store is typically not meant to run in production environments, except in
read-only cases, but it can be very fast.
In-memory: This is a great persistence manager for testing and for small workspaces. All content is kept
in memory and lost as soon as the repository is closed. Even faster than a file system. Again, not for
production use.
Magnolia CMS Enterprise Edition allows you to switch between persistence managers without losing any content.

23

Magnolia International Ltd.

7. Clustering
Magnolia CMS can be configured to run in a clustered environment to provide high availability and load balancing:
High-availability clusters are also known as fail-over clusters. Their purpose is to ensure that content is
served at all times. They operate by having redundant instances which are used to provide service when
a public instance fails. The most common size for a high-availability cluster is two public instances, the
standard Magnolia CMS setup. In such a setup the redundant instance may even be dormant (not
actively serving content) until it is called to service.
Load-balancing clusters connect many instances together to share the workload. From a technical
standpoint there are multiple instances but from the website visitor's perspective they function as a single
virtual instance. A load balancer distributes requests from visitors to instances in the cluster. The result is
a balanced computational workload among different instances, improving the performance of the site as
a whole.

7.1. Jackrabbit clustering


We use Jackrabbit's clustering feature to share content between Magnolia CMS instances. Clustering in
Jackrabbit works on the principle that content is shared between all cluster nodes. This means that all Jackrabbit
cluster nodes need access to the same persistent storage (persistence manager and data store). The persistence
manager must be clusterable. Any database is clusterable by its very nature as it stores content by unique hash
IDs. However, each cluster node needs its own (private) file system and search index. For more details see
Jackrabbit clustering documentation.
As discussed in Workspaces, individual workspaces can be mapped to different repositories. The repository that
holds shared content can reside in clustered storage. This is useful for content that needs to be in sync across all
instances.

24

Magnolia International Ltd.

In the diagram below, each Magnolia CMS instance uses its own persistent storage (gray databases) for storing
the content of website, DMS and data workspaces. However, the comments workspace has shared content that
is stored in a clustered storage (blue database).

User generated content such as comments written by site visitors is a typical clustering case. Imagine that users
John and Jane request the same web page. A load balancer redirects John to public instance A. When John
leaves a comment on the page, his comment is stored in a workspace that resides in clustered storage. Now Jane
requests the same page. The load balancer redirects her to public instance B. John's comment is immediately
visible to Jane since both instances tap into the same clustered storage.
Other examples of shared content are user accounts, permissions of public users and forum posts. They need to
be available regardless of the instance that serves the page.

25

Magnolia International Ltd.

8. Modules
Magnolia CMS has a modular architecture. A module is a independent component that performs a particular task
or is used to package content and functionality. The system itself is built of modules; AdminCentral, Document
Management System and Workflow are all modules.
You can use modules to:
Create a custom component to address a specific requirement or use case. The Forum module is an
example of this. It provides forums where site visitors can participate in the discussion.
Package an entire website for easy deployment, including customized templates, paragraphs and
content.
Package and deliver a set of assets such as images or documents.

8.1. Pluggable and independent


Modules are independent and pluggable in the sense that you can add and remove them at will. For example, if
you don't need the Workflow module and would rather activate pages to the public instance directly, you can
remove the module from Magnolia CMS.

26

Magnolia International Ltd.

A module consists of a set of components packaged in a JAR file. Deploying a module is a matter of copying the
JAR file into the WEB-INF/lib folder and restarting the instance. Magnolia CMS update wizard recognizes the
JAR and installs its contents.

8.2. Configuration
When you start Magnolia CMS, the system identifies available modules by locating each module's descriptor file.
The descriptor is an XML file located in META-INF/magnolia inside the JAR. The name of the file is not
important but we recommend that you follow a naming convention similar to moduleName.xml in your own
modules, such as samples.xml.
A minimal module descriptor looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module SYSTEM "module.dtd">
<module>
<name>samples</name>
<version>4.1.0</version>
</module>

27

Magnolia International Ltd.

The descriptor is quite versatile. You can use it to register servlets and define workspaces too.
After a module is installed it is listed under modules in the config workspace.

Configured items are stored directly under the module node in order to be automatically registered by Magnolia
CMS. As the system monitors configured items, any changes in the configuration of registered items will be active
immediately.

8.3. JAR structure


To use the special features of Magnolia CMS modules you need to follow some conventions and put additional
resources in well-defined places inside the module JAR. Here is a module source in Eclipse:

It is common practice to define two source folders: src/main/java for Java classes and src/main/
resources for module-specific resources. This structure is used in every Magnolia CMS module project. Here's
what the folders should contain:
Path

Contents

META-INF

If you have your own custom tab library put the tag library definition file (.tld) here.

META-INF/magnolia

Module descriptor file. Follow a naming convention like moduleName.xml.

mgnlXML files whose contents you want to be imported into the system when the module
bootstrap/moduleName is installed.

28

Magnolia International Ltd.

mgnl-bootstrapsamples/moduleName

XML samples whose contents you want to be imported into the system when the
module is installed. If property magnolia.bootstrap.samples is set to false
these files are not imported.

mgnl-files

Files in this folder are copied to the web application folder. Folder hierarchy is also
copied.

mgnl-resources

Static resources such as style sheets and JavaScript. They will be available at URI
/.resources/.., for example /.resources/example/style.css.

8.4. Module class


The configuration node uses the Content2Bean mechanism to populate a JavaBean with the content of the config
node and its subnodes. Developers can access the module configuration through the Bean. You can define an
optional module class in your module descriptor if you need a more sophisticated implementation that can interact
with the module dynamically throughout its life-cycle.
The module class is defined in the module descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module SYSTEM "module.dtd">
<module>
<name>samples</name>
<version>4.1.0</version>
<class>info.magnolia.SamplesModule</class>
<versionHandler>info.magnolia.setup.SamplesVersionHandler</versionHandler>
</module>
Note that the Content2Bean mechanism is not limited to module configuration. It is used all over Magnolia CMS.

8.5. Dependencies
Modules can use functionality provided by the Magnolia CMS core code, the Standard Templating Kit and other
modules. When one module uses functionality from another this creates a dependency between modules.

29

Magnolia International Ltd.

You can define run time or install time dependencies but not build dependencies. If you define a dependency on
another module then the target module will be installed and started before your module. A dependency can be
optional which means that if an optional module is not present, installation will still proceed. If the optional module
is present, it will be installed first.
<dependencies>
<dependency>
<name>core</name>
<version>3.6.0/*</version>
</dependency>
<dependency>
<name>cache</name>
<version>3.6.0/*</version>
<optional>true</optional>
</dependency>
</dependencies>

8.6. Module life-cycle


Magnolia CMS monitors the module configuration and restarts a module if there are changes in the configuration.
Be aware that this active monitoring applies to the entire module configuration, not only the config node.
The system provides a simple way to logically associate module classes to the module life-cycle. If your module
class implements info.magnolia.module.ModuleLifecycle then you have to implement:
public void start(ModuleLifecycleContext moduleLifecycleContext);
public void stop(ModuleLifecycleContext moduleLifecycleContext);
These methods are called whenever the module is started or stopped, which allows the inclusion of custom
programmed logic for individualized modules.

8.7. Bootstrap files


A module can provide configuration in a bootstrap file. The bootstrap file is a JCR export of configuration nodes.
Storing the entire configuration for items such as dialogs in a bootstrap file has the advantage of easy repurposing. You can share the XML with others and check it into version control.
To export a configuration, right-click the parent node and select Export tree to XML. The export file format is JCR
System View XML.
The name of the exported XML file is adheres to convention workspace.path-to-configuration. The
export function creates this name automatically. For example, exporting a configuration node at path /modules/
dms/dialogs/dmsEdit in the config workspace will create an XML file
named config.modules.dms.dialogs.dmsEdit.xml.
You should place bootstrap files in the mgnl-bootstrap/moduleName directory inside your module JAR or in
the WEB-INF/bootstrap directory.

30

Magnolia International Ltd.

Bootstrap files are loaded in the same order as module dependencies, which allows them to override the default
configuration. Files in WEB-INF/bootstrap are loaded last. If the target node already exists, it will be deleted
and overwritten.
Bootstrap files are installed only during module installation, not on updates. This guarantees that any
customizations made to the configuration are not overwritten when the module is updated. This behavior can be
changed by providing a custom version handler.

8.8. Version handling


The module mechanism facilitates smoother Magnolia CMS version changes. The version handler registers the
tasks to be executed during installation and tasks executed on updates.
Version handler class is defined in the module descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module SYSTEM "module.dtd">
<module>
<name>samples</name>
<version>4.1.0</version>
<class>info.magnolia.SamplesModule</class>
<versionHandler>info.magnolia.setup.SamplesVersionHandler</versionHandler>
</module>
If no version handler is defined, the system uses the default version handler which executes a basic set of tasks
such as register workspaces, register servlets and import bootstrap files.

31

Magnolia International Ltd.

8.9. Community driven module development


In addition to enterprise modules that ship with the Enterprise Edition, the open-source community contributes
modules for various purposes. You can find a list of available modules in the Magnolia Store. To access the store
click Magnolia Store in AdminCentral or see the listing on the web.

32

Magnolia International Ltd.

9. Magnolia webapp
Java Web Application (webapp) is a collection of servlets, HTML pages, classes and other resources bundled
together and run on a servlet container. The following items can exist in a webapp:
Servlets
JavaServer Pages
Utility classes
Static documents including XHTML and images
Client side classes
Meta information that describes the webapp

9.1. Directory structure


The directory structure is the container that holds the components of a webapp. The first step in creating a
Magnolia CMS webapp is creating this structure. The following table describes what each directory should
contain.
Path

Contents

cache/

Files with cached content

docroot/

Files extracted from mgnl-files/docroot in


the JAR.

logs/

Magnolia log files

META-INF/

Meta information files, e.g. from Maven

repositories/

Repository

templates/

Templates extracted from mgnl-files/


templates in the JAR

tmp/

Temporary work directory

WEB-INF/

All resources related to the application that are


not in the document root. WEB-INF directory is
not part of the public document. No files
contained in this directory can be served directly
to a client.

WEB-INF/bootstrap

Bootstrap files. Empty by default.

WEB-INF/bootstrap/common

Bootstrapped on author and public instances

WEB-INF/bootstrap/author

Bootstrapped on author instance only

WEB-INF/bootstrap/public

Bootstrapped on public instance only

WEB-INF/classes

Class path for manually deployed classes.

WEB-INF/config

Configuration files for repository and properties

33

Magnolia International Ltd.

WEB-INF/config/default

Configuration files

WEB-INF/config/default/magnolia.properties

Properties such as: repository location,


persistence manager to be used, should samples
be bootstrapped, should installation be done in
unattended mode etc.

WEB-INF/config/default/repositories.xml

defines repository configuration

WEB-INF/config/default/log4j.xml

Log4j logging configuration

WEB-INF/config/magnoliaAuthor

Properties used on author instance only

WEB-INF/config/magnoliaPublic

Properties used on public instance only

WEB-INF/config/repo-config/typeOfPM.xml

Persistence manager configuration files

WEB-INF/config/jaas.config

Configuration for authentication and


authorization

WEB-INF/lib

JAR files

WEB-INF/web.xml

Deployment descriptor. Describes configuration


information for the entire web application.

9.2. Adding the Magnolia main filter to the webapp


The Magnolia main filter is registered in the web.xml file. The file only defines one filter:
<filter>
<display-name>Magnolia global filters</display-name>
<filter-name>magnoliaFilterChain</filter-name>
<filter-class>info.magnolia.cms.filters.MgnlMainFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>magnoliaFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
Note: The Magnolia main filter will delegate the request to the Magnolia filter chain. The filter is also mapped to
forward requests, which means that the Magnolia filter chain will be re-executed on internal forwards.

34

Magnolia International Ltd.

9.3. Adding the Magnolia context listener


In web.xml we also register one listener:
<listener>
<listener-class>
info.magnolia.cms.servlets.MgnlServletContextListener
</listener-class>
</listener>
The listener initializes the system, starts the repository and modules, while the filter handles all requests.

35

Magnolia International Ltd.

10. Request processing and filters


Magnolia CMS uses the Java filter concept introduced in the Java Servlet specification version 2.3. A filter
captures and processes a request before it reaches a servlet. Filters typically do not themselves create responses
but provide universal functions that can be "attached" to any type of servlet or JSP page.
Filters provide the ability to encapsulate recurring tasks and modularize code. They can also transform a
response from a servlet or a JSP page. A common task is to format data sent back to the client, such as sending
WML instead of HTML.
Some functions filters can perform:
Authentication based on user identity
Logging, auditing, tracking, personalization
Image conversion, scaling maps
Data compression
Localization

10.1. Magnolia CMS filter chain


The basic idea behind the filter chain is that the filters will be executed one by one until a filter decides that it can
fulfill the request. This is a Magnolia CMS specific implementation of a standard Java filter chain.

In the diagram above you can see the following filters:


Context. The first filter in the filter chain is the ContextFilter. It initializes MgnlContext which is
local to this request and available on every further filter. The context provides a lot of useful functions.
Security. Checks if the request is coming from an authenticated user and if the user is authorized to
access the requested URI.

36

Magnolia International Ltd.

Cache. The CacheFilter manages the cache. It checks if a requested resource is already stored in
the cache to avoid recreation of the resource. If the resource is in the cache, then it will be written to the
response and the filter chain stops. If the resource is not found in the cache, then the filter passes the
request on to the CMS part of the chain.
CMS Filter Chain. Next we arrive at the filter chain which does the page rendering and delivery. The
filters in this sub-chain are grouped so they can share a co-bypass definition.
Aggregation. The AggregatorFilter analyzes the request, selects the content from the repository
and stores it in the AggregationState:
Request URI points to Collected information
Page

Content node of the requested page


Page template

Paragraph

Content node of the requested paragraph


Paragraph template

NodeData

NodeData object of the requested data, for example binary

Rendering. Finally, the RenderingFilter is responsible for delivering the requested resource. If the
requested resource is data such as a file then the data is just streamed to the response. If the requested
resource is a page, then the Rendering Filter calls the rendering engine.
The main filter MgnlMainFilter is a single filter which in turn executes a chain of other filters. The chain is not
configured in web.xml but in the config workspace at /server/filters.

37

Magnolia International Ltd.

In the filter configuration you can again have single filters or filter chains. A filter chain consists of a list of single
filters represented by child nodes. A filter node has a class property which specifies the implementing class and
can optionally have an enabled property.

If the filter is enabled, which it is by default, then the filter will be executed. Otherwise the filter will be bypassed. A
filter or a filter chain can define rules to determine when a filter should be bypassed. The configuration of
bypasses is done using Voters. For more, see Magnolia CMS core filters.

38

Magnolia International Ltd.

11. Templating
All Web pages created with Magnolia CMS are based on templates. Templates ensure that page structure and
presentation remain the same while the content varies from one page to another. For example, an event template
helps you generate event pages that look and feel the same but display a different unique event each.
The system generates pages by merging a template with corresponding content from the repository. The position
and inclusion of each paragraph on the page is defined by the page template. In many instances, the page
template will allow authors to choose from a number of different paragraph types in a single content area.

11.1. Pages and paragraphs


Content nodes in the JCR hierarchy are rendered as headings, paragraphs, images, menus, forms, Javascript,
meta-data and many other things. The following diagram shows the relationship between some content nodes
and the corresponding page elements.
Note! The diagram shows the detailed JCR view on the left. This is not how authors see content. The user
interface for authors and editors hides much of the complexity, providing a user-friendlier way to manage pages
and paragraphs.

39

Magnolia International Ltd.

Numbered items:
1. An article about basketball in the New York Times Sports sections has the following page properties:
title rendered as an H1 element on the page, "Bulls and the Thunder Make a Stand"
date and author rendered on the dateline
abstract to provide an introductory paragraph
2. The next element on the page is the main collection which contains paragraphs.
3. Paragraph 0 is a text paragraph ("LeBron James scored 13...") with a matching image. The image file
and its caption and credit are stored in the document management system (DMS).
4. Paragraph 00 consist of text and an optional subtitle element "THUNDER 101, LAKERS 96".
5. The page ends with a footer singleton paragraph which is a kind of placeholder. It can contain content
such as a copyright statement.

11.2. Templating mechanism


Magnolia CMS templating mechanism consists of the follow components:
Template definition makes a template script available to the system by providing a name for it. It is the
configuration for the template script. For instance, it defines the model class to use.
Template script renders the content. The script is written in FreeMarker, JSP or a custom templating
language. The script instructs the renderer where to place the content on the page and also contains
placeholders for content attributes such as headings and images.
Dialog is used to enter and edit content. It is a customized HTML form with fields for entering text and
meta data and selecting images.
Content for the page or paragraph is retrieved from the repository. It may contain text and references to
images that need to be rendered. The content node meta data assigns it to a particular template
definition. This way the rendering engine knows which template definition applies to the content. Through
the definition, it can then choose the correct renderer. Note that the reference to a template definition is
only a suggestion. It is also possible to use something else to render the content. You might define an
alternative template when rendering content for a mobile device, for example.

40

Magnolia International Ltd.

11.3. Component relations


Below you find a more detailed map of relationships between the components that make up the template
mechanism. Starting at the top left corner, a template definition defines the template script used to render the
content. The location of the script is given in the templatePath property. The template definition also assigns a
dialog definition in the dialog property. The dialog definition is a group of configuration nodes just like the
template definition. It defines what tabs and fields should be present in the dialog.
The template definition further defines a modelClass. Model is a Java program that holds your business logic.
The model can do any task required such as execute a Google search or calculate an insurance policy. It holds
the results of the logic execution and passes them to a renderer.

41

Magnolia International Ltd.

The renderer includes the results on the page as instructed by the template script. The script tells the renderer
where to place the content. It contains placeholders for content attributes such as headings, images and the
results of the business logic execution.
A Web page is the output of the rendering process where template and content are combined.

11.4. Templating languages


The system provides two renderers out-of-the-box: JSP and Freemarker.
JSP stands for Java Server Pages. It is an extension of Java Servlet technology for combining Java server-side
programs and HTML.

42

Magnolia International Ltd.

Writing a Magnolia CMS paragraph in JSP:


<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:directive.page contentType="text/html; charset=UTF-8"
session="false" />
<c:if test="${not empty content.image}">
<img src="${pageContext.request.contextPath}${content.image}"
class="contentImage_${content.imageFloat}"
alt="${content.imageAlt}" />
</c:if>
<c:if test="${not empty content.title}">
<h2>${content.title}</h2>
</c:if> ${content.text}
</jsp:root>
With Magnolia CMS 4.0, we added support for Freemarker for several reasons: not only for its flexibility, cleaner
syntax and better error reporting but also because it does not depend on the file system; templates don't have to
be extracted to the file system so they can easily be stored in the repository.
Writing the same paragraph in Freemarker:
[#if content.image?has_content]
<img src="${contextPath}${content.image}"
class="contentImage_${content.imageFloat}"
alt='${content.imageAlt!""}' />
[/#if]
[#if content.title?has_content]
<h2>${content.title}</h2>
[/#if]
${content.text!""}
You can mix and match templates and paragraphs using both templating languages at will. You can also use
another templating language. If a renderer for your language is available, it is likely that you can incorporate it into
Magnolia CMS. This allows you to use a templating language that you are already familiar with.

11.5. Tag library


The Magnolia CMS tag library allows developers to customize the authoring environment and create templates in
a fast, efficient and re-usable way. The system additionally supports third-party tag libraries such as JSTL to
minimize the amount of code developers have to write.

43

Magnolia International Ltd.

Most important tags:


mainBar. Displays a toolbar that allows you to change page properties and switch to the preview mode.
This tag can also add CSS and JavaScript links on the page if not previously defined but it is
recommended to you add the cms:links tag to the header of the page instead. CSS links are not valid
inside the HTML body element.

[@cms.mainBar label="Page Info" dialog="stkHomeProperties" /]


newBar. Displays a toolbar that allows you to create new paragraphs. The list of available paragraphs is
passed as a list.

[@cms.newBar contentNodeCollectionName="mainColumnParagraphs"
paragraph="samplesTextImage,samplesDownload,samplesLink" /]
editBar. Displays a toolbar that allows you to edit a paragraph. This tag is often used within
contentNodeIterator, which in turn will set all relevant parameters automatically.

[@cms.editBar /]
contentNodeIterator. Iterates over a contentNode collection. This tag is used whenever you want to
loop over content, typically paragraphs. Parameter contentNodeCollectionName contains the name of
the contentNode you are looping over. The contentNodeCollectionName is created in the first place by
providing the name to a newBar. This will result in elements being created within that contentNode, and
allows you to loop over them later.
[@cms.contentNodeIterator contentNodeCollectionName="main"]
[@cms.includeTemplate /]
[/@cms.contentNodeIterator]
includeTemplate. Delegates the task of rendering a paragraph to an appropriate ParagraphRenderer
or includes JSP. When used within contentNodeIterator the parameters are provided automatically by
the loop.
[@cms.includeTemplate contentNode=content.footer /]

44

Magnolia International Ltd.

11.6. Example of CMS tags in use


Here is an example how tags are rendered.
1. The mainBar tag creates a toolbar at the top of the page for setting page properties.
2. The main area of the page includes a contentNodeIterator tag. It looks for any paragraphs that
reside inside the main area and includes their paragraph scripts using the includeTemplate tag. Note
that the paragraph with the basketball players is not rendered by the page script but the included
paragraph script below it. The editBar associated with this paragraph is added in the paragraph script,
not in the page script.
3. A newBar creates a toolbar that allows authors to add new paragraphs on the page.
4. The footer section also uses the includeTemplate tag. It calls another paragraph script (not
displayed) that creates navigation links and a copyright statement.

45

Magnolia International Ltd.

11.7. Templating support objects


These objects are available to template scripts to simplify development.
Object

Purpose

content

Current content node exposed as a map like cms:setNode.

page or actpage

Current page exposed as a map like cms:setNode. This attribute is called actpage in
JSP because the name page is reserved.

def

Current RenderableDefinition (template or paragraph definition object)

model

JavaBean created by the renderer based on a modelClass defined in the paragraph or


template definition. The current content, definition and the parent model are passed to the
constructor.

actionResult

The result of the model's execute method. This string can be used to determine the
template (in the definition) or in the template itself.

mgnl

An object providing access to various components and utility methods, for example to
create links. See MagnoliaTemplatingUtilities.

ctx

Current Context. Depending on the type of request, a different implementation will be


used, but for a web request to a page, this will be a WebContext instance. In a web
request, you can use ${ctx.contextPath} to get the context path corresponding to
the current request.

state

Current AggregationState.

stk

Provides access to STK templates

i18n

Messages from the current message bundle like the "Read on" message. i18n["key"]

46

Magnolia International Ltd.

12. Dialogs
The authoring system uses dialogs for content contribution and control. A dialog is an HTML form with input fields.
Authors type content into the input fields and the dialog stores it in the repository. In addition to content entry, the
system provides standard dialogs for page properties, data nodes, users, roles, workflow notifications and many
other editable items. It's a very agile mechanism; you can create your own dialogs and customize the standard
dialogs.

12.1. Tabs and controls


Dialogs are assembled of controls, grouped into tabs. Text and Image is a typical content-editing dialog. It has
two tabs: "Text" and "Image". The Text tab has a simple text box control for entering a subheading and a more
versatile rich-text control for paragraph body text. Note how internationalization support is enabled in this dialog:
the field label "(en)" indicates that English language content should be entered.

47

Magnolia International Ltd.

The second tab, "Image", allows you to select an image to accompany the text. An option button (radio button)
control is used to choose between uploading the image from the local computer and selecting it from the
document management system. For more examples controls available in Magnolia CMS, see the list of available
controls on the documentation site.

12.2. Dialog configuration


A typical Magnolia CMS installation includes a standard set of dialogs. In many cases it is not necessary to create
a new dialog from scratch; you can copy or extend an existing dialog and adapt it to your needs. Sample dialogs
are provided with the Standard Templating Kit, Templating and Samples modules.
A dialog definition defines the dialog's tabs and fields. Configuring a dialog involves three steps: create a dialog
definition, map the dialog to a paragraph and. add the paragraph on a page.

48

Magnolia International Ltd.

12.2.1. Create a dialog definition


Below is the dialog definition for Text and Image.
1. stkTextImage is the internal name used when referring to this dialog from a paragraph
definition. i18nBasename defines a message bundle. The bundle is a collection of properties files inside
the module JAR that contain default labels for dialogs and fields. A reference to a property will retrieve
the matching label. In this case, the
key dialogs.paragraphs.content.stkTextImage.tabText.label retrieves the dialog title
"Text and Image". Storing field labels in a property file has the advantage that you can hand the file to a
translator when a new UI language is needed. Alternatively, you can type a label here.
2. tabText is the first tab in the dialog.
3. subtitle is the first field on the tab. It is an edit control, rendered as a text box (see screenshot
above). A description is displayed below the field. i18n is enabled which means a language suffix
(en, de, fr...) is displayed next to the field label and the dialog stores language specific content. Instead
of looking up the label from a properties file, a hand-typed string "Subheading" is used here for
illustration purposes.
4. text is a rich text edit control. It's a very common control used in many dialogs. This control has many
configuration options. To ensure that all rich text edit controls are configured the same way, we define it
once in the generic controls folder and reference when needed.

49

Magnolia International Ltd.

12.2.2. Map the dialog to a paragraph


Next, connect a paragraph definition to the dialog definition to make sure the correct dialog is opened when the
user clicks Edit in the editBar. The stkTextImage paragraph definition refers to the its counterpart by the
dialog's internal name stkTextImage:

12.2.3. Add the paragraph on a page


Since the matching dialog is identified in the paragraph definition, the paragraph script doesn't need to know this
detail. The script can render a generic editBar on the page. The reference between the paragraph definition and
the dialog definition takes care of opening the correct dialog.
[#assign cms=JspTaglibs["cms-taglib"]]
[#include "/templating-kit/paragraphs/macros/image.ftl"/]
[#include "/templating-kit/paragraphs/macros/tocMarkup.ftl"/]
[@tocMarkup model content /]
[#if mgnl.editMode]
<div style="clear:both;">
[@cms.editBar /]
</div>
[/#if]
[#if content.subtitle?has_content]<h2 ${id}>${content.subtitle}</h2>[/#if]
[@image image=model.image! imageClass=model.imageClass/]
[#if content.text?has_content]
${stk.decode(content).text}
[/#if]

50

Magnolia International Ltd.

13. Best-practice Standard Templating Kit


The Standard Templating Kit is a best-practice framework for creating websites. It builds upon the generic
templating mechanism described above. The kit ships with configurable, production-ready templates for common
use cases such as articles, news, events, site-maps and image galleries, while letting developers and creative
designers build completely custom sites. Templates can be written in JSP and Freemarker or another templating
language.

13.1. Contents
Standard Templating Kit includes:
Reusable paragraphs
A mechanism for assembling page templates through definition rather than coding.
A mechanism for creating custom paragraphs without affecting or even touching the page templates that
use them.
A set of use case driven page templates which can be used as such, modified or replaced with your own
templates.
Clear and clean separation of HTML, client-side functionality (jQuery), content (JCR), business logic
(Java) and design (CSS). A static HTML prototype is provided for designers who prefer to start with CSS
and a basic HTML wire-frame.
Support for multiple site configurations

13.2. Benefits
Out-of-the-box solution. The use case driven page templates shipped with the kit provide a quick start
to building your website. The kit gives you a significant head start since much of what you need is
already provided. Less effort generally means you will be faster but more importantly it means your
project will be more predictable. You have less uncertainty, which for project managers means less risk.
Use case based templates. Templates and paragraphs included in the kit are all based on real-life use
cases. Templates include home, section, search, news, events, contact form, article and many more.
Numerous ready to go live paragraphs are also available such as content paragraphs, teasers, stages,
promos, event lists and more.
Configurable layout and style. The look and feel of the website is controlled mainly by a single CSS
file. Since the HTML structure is designed to be styled by CSS, the look and feel of the site can be
changed without touching the templates. And since CSS is configured in the site configuration, you can
create a custom CSS for each site.
Role-based development. Designers and CSS developers don't necessarily need to know anything
about Magnolia CMS in order to create a compatible a site design. They can start with the static HTML
prototype shipped with the system. From the prototype they can pick an HTML structure that is a close
match to their original design and modify it further. Style sheets are also provided.
Accessibility. The generated HTML adheres to W3C WCAG2m and German BITV accessibility
standards. Invisible navigation messages for vision-impaired users are included.

51

Magnolia International Ltd.

Extensibility. As the template and model are separated, you can modify the templates or extend the
model. Many aspects can be configured in the template or site definitions without writing code. For
example, you can define paragraphs that are available for individual page templates and their
positioning.

13.3. STK components


The STK consist of:
Site. A site is a combination of web pages, CSS, resources (images, Javascript) and an associated site
definition.
Theme. A theme gives the site its visual identity through the use of images, colors and typography. A
theme consists of Cascading Style Sheets (CSS), Javascript files, and an imaging configuration which
tells the Imaging module how to resize and crop images for a particular page or paragraph. Magnolia
CMS ships with an example theme called "pop". You can see it in action on the demonstration sites (see
below).
Templates. STK templates are normal Magnolia CMS templates but make use of the template definition
mechanism. Thanks to this, all templates (Home, Section, Article...) use the same base.
Digital asset management (DAM) support. You can place images and videos on pages by uploading
them from the user's computer or by selecting from the built-in document management system. Both of
these default mechanisms can be enabled in the site definition. If you want to use your own mechanism,
for example to get images from an external server, you can plug in a custom image processor.

13.4. Site definition


A site definition applies templates, themes and internationalization support to your site. It consists of:
Template prototype. Is a base definition of a template from which all concrete templates (Home,
Section, Article...) inherit.
Template availability. Registration of available templates.

52

Magnolia International Ltd.

Internationalization and localization (i18n). Enabling i18n support in the site definition allows authors
to write foreign-language content. When enabled, the mainBar has a language drop-down. Dialogs
display the language identifier (en, fr, de...) to make it clear what language should be entered. Foreignlanguage content is served to visitors at a specific URL, such as www.mywebsite.com/de/
article.html. Redirecting visitors to the language-specific URL is configured in the web server.

Domains. Mapping of a domain name to a site.


Mappings. Mapping of the requested URI to a repository. Here you can use prefixes and handles. For
example, if a prefix such as dms is detected in the request the requested asset is served from the
repository given in the repository property. A handle can be used in building the URI. For example, if
the requested URL contains /demo-project alone, map it to the website repository. If it contains
/demo-project/docs, map it to the dms repository.
The Standard Templating Kit ships with two fully-functional demonstration sites:
Demo project shows how templates work in realistic site context. It has working examples of article,
news, event and many other page templates as well as paragraphs such as video, teaser and stage.
Author instance username/password: superuser/superuser
Public instance
Demo features shows the same templates grouped categorically: content templates, special templates,
aggregation paragraphs, areas, sections and modules.
Author instance username/password: superuser/superuser
Public instance

53

Magnolia International Ltd.

13.5. Areas
The page templates shipped with the Standard Templating Kit organize the page layout using areas. These are
controllable blocks, typically rendered as div elements, that help you customize the template structure.
Typically each area is wrapped in a div element, having a correspondingly name ID attribute, for example main
area has id=main.
Note: An area is not the same as a paragraph. Paragraph is a content element with an associated paragraph
definition while areas are structural elements in the template script. In fact, areas are dynamic include directives
which together compose a single template script.

54

Magnolia International Ltd.

The following diagram illustrates some key elements you will find on a page based on the article page
template. The box captions indicate div element ID attributes. For example, the element that renders the vertical
navigation on the left is <div id="nav">.

Note! This is not a complete set of areas. There are further smaller div elements to handle logo and breadcrumb
placement, for example. Other page templates again offer drastically different layouts, using elements such as
stages and platforms to promote content.

55

Magnolia International Ltd.

13.6. Template inclusion


Templates at higher level can include lower-level templates using Freemarker's #include directive. This
approach allows you to modularize and re-purpose your template scripts. It also has the benefit of keeping scripts
brief and readable.
The following diagram shows how inclusion works. The page template has a header area. Inside the header div
element there is a Freemarker #include directive that calls another template script, header.ftl. The header
template script in turn includes two further templates to render branding and horizontal navigation.
1. Includes the template script configured in template definition (configured either in the prototype or
overwritten in the concrete template).
2. Template script, referenced from the template definition.

56

Magnolia International Ltd.

13.7. Customization
This dynamic approach allows you to combine your own templates with those of STK. Use the STK templates as
much as you can to speed up development. When you can't move further without customizing, create your own
template.
Three customization options:
Change the main template used by all STK templates if you want to change the main HTML structure.
This is configured in /prototype/templatePath. The default value is /templating-kit/
templates/main.ftl.
Reconfigure template scripts used for specific areas.
All further dynamic includes can continue to be reused elsewhere, and in your custom template if you need them.
In most cases you would copy an existing template. In the site definition, override the used template by setting
the template attribute to the customized one.

Tip: When using Freemarker, you don't need to put the template script in the template workspace. You can load
them from your module JAR. This is what we recommend for production projects.

57

Magnolia International Ltd.

13.7.1. Template prototype


The prototype site definition is a good entry point for understanding the STK. It is a "fallback object" for all
template definitions of a site. Any template will extend the prototype, which means any template configuration that
you don't define in the template is automatically inherited from the prototype. It is likely that you can take
advantage of the prototype templates and reuse them for your custom site with small changes.

58

Magnolia International Ltd.

Examples of template configuration options available in the prototype site definition:


Path

Description

htmlHeader

Configures the template used in the inner part of <head> element.

navigation

Configures navigation. The static HTML prototype includes a page that shows you how the
various navigation menus look at all depths. It allows the CSS designer to see at single glance
whether test CSS is correct.

navigation/ Horizontal navigation, including the number of levels and template script used.
horizontal
navigation/ Vertical navigation, including the number of levels and template script used.
vertical
header

Page header, including the branding, section header and stage.

breadcrumb

Breadcrumb displays the navigated path to the user.

mainArea

Configuration of the main area. In the prototype the area is used for basic content templates
such as articles

extrasArea

Extras area is typically located on the right hand side. This configuration is site-wide and
contains a list of paragraphs available as extras.

footer

Configuration of the footer.

59

Magnolia International Ltd.

This is what happens when a template prototype is merged with a concrete template:
1. Template prototype is the basis.
2. Concrete template definition adds and overrides.
3. The result is exposed as the template definition (def) to the template script

stkHome defines which paragraphs are available in the mainArea. It also uses a custom template script for
the mainArea and disables the extrasArea. The prototype defines the main template (main.ftl) and preconfigures the main and extras areas.

60

Magnolia International Ltd.

13.7.2. Static HTML prototype


The STK bundle (download here) ships with a static HTML prototype. It is a collection of STK page templates
delivered as stand-alone HTML files. Referenced CSS and images are also included. The static prototype is
aimed at creative teams who don't know how Magnolia CMS works or have no particular desire to learn it. It
allows designers to work on positioning, typography and color outside of Magnolia CMS, using their own tools, in
their own environment.
You can (and should) use the HTML prototype to develop your CSS. The advantages of this approach include:
See all possible variations of an element instantly
Perform CSS programming independent of Magnolia CMS
Better testability
Faster turnaround
Whenever Magnolia enhances the STK, we add new HTML to the static prototype first. The static HTML is then
tested on all supported browsers. Once the HTML has been perfected, templates are created.

61

Magnolia International Ltd.

The static prototype contains an index page which serves as the starting point for paragraph and page templates
provided with the STK.

62

Magnolia International Ltd.

Navigation at all levels is also available at a single glance. Developing a CSS against this view saves a lot of time
when you can see all variations right away.

63

Magnolia International Ltd.

13.8. Design with CSS


The modular templating approach gives creative designers free hands. Positioning, layout and styling is
convenient with CSS given that each key page element can have its own template script and is enclosed in a div
element that has an ID attribute.

Magnolia CMS supports role-based development by letting everyone work on what they are good at. Designers
can change the appearance of a page without having to change a template. Likewise, templates do not become
cluttered with design fragments.

13.9. Layout and grid


The template layouts are dynamic. The default layout of three fixed columns is optimized for a screen resolution
of 1024. The grid is extremely flexible and offers easy grid variations.
The dynamic template layouts change on the fly, to adapt to the user's viewport:
For larger screens, with a minimum width of 1200 px an extra style: wide.css is added. The effect of this
is that an additional promo sidebar, is displayed on the right of the screen.
For medium screens, width 981-1199 px, the layout accommodates the narrower viewport by displaying
promo sidebar beneath the main content.
For small screens, with a maximum width of 980px an extra style: small.css is added. The main area
displays two columns of teasers instead of three.

64

Magnolia International Ltd.

Wide: min. width 1200 px

Medium: 981 to 1199 px

Small: max. width 980 px

The technique used to achieve this is CSS media queries and JavaScript. For older browsers that do not
recognize JavaScript it is completely unobtrusive and the default CSS resolution is 1024 x 768 px.

65

Magnolia International Ltd.

13.9.1. HTML structure


HTML structure, as provided by the default template:

66

Magnolia International Ltd.

13.10. Body IDs and classes


The body ID is an attribute on the body HTML element, for example <body id="home">. It represents the page
type such as Home, Section, Article and so on. The body ID of a page is defined in its template definition. This
mechanism allows you to style pages differently while still using a single CSS file.
Some example of body IDs are:
home
section
article
image-gallery
The body class attribute is used to control the number of columns and the column width. It provides for instance
information about whether we have vertical navigation or not.
The Body Classes are automatically generated by the STK system. In the template definition a property
bodyClass can be set. This overwrites the auto generated body class value.
Some body classes are:
nav-col-subcol: Three-column setup with navigation on the left and a small extras area.
nav-col: Two-column setup with a navigation on the left and one large content column.
col-float3: One large column and three floating teasers. Home page is an example of this.

13.10.1. CSS configuration


Style sheets used with STK templates are stored as content nodes within Magnolia CMS. This allows you to
manage them in AdminCentral instead of having to work at the file system level.
STK ships with a collection of style sheets targeted to different viewports and media. You can see these sheets at
work on the demonstration sites and the static HTML prototype.

67

Magnolia International Ltd.

Referencing a style sheet works like this:


1. Style sheets are stored as content nodes under Templating Kit > Resources. They are organized into
folders according to the theme they belong. In this example, the "pop" theme has five style sheets aimed
at different media and viewports.

2. In Templating Kit > Themes, a theme definition contains a link to each sheet. It also defines the
targeted media type (screen, print etc).

Note that in the media property you can use CSS3 media queries to test the features of the output
device. The sheet is applied if the test evaluates to true. In the example above we evaluate the minimum
width of the viewport before applying the wide sheet.

68

Magnolia International Ltd.

3. In the htmlHeader page template, a Freemarker #list directive collects the style sheets from the pop
theme. It creates link elements and writes them in the page head element.
[#list model.site.theme.cssFiles as cssFile]
<link rel="stylesheet" type="text/css" href="${cssFile.link}"
media="${cssFile.media}" />
[/#list]
Tip: In real production projects it is recommended that CSS are stored in the module JAR. They have to reside in
the mgnl-resources folder. In that case the link property will point to /.resources/pathToCss.

13.11. Learn more


Check out these videos of STK templates in action:
Introduction to STK and basic demonstration.
Glossary, grouped teaser paragraphs, events overview, FAQ
Examples of diverse sites built with Magnolia CMS and STK: US Navy, EADS, LOVEFiLM, JBoss.org, Johnson &
Johnson and of course magnolia-cms.com.

69

Magnolia International Ltd.

14. Rendering engine


Rendering is the process of merging templates with content. It generates a meaningful stream of HTML that can
be displayed in a browser. This is the step where content becomes visible to the end user in page context.
The Magnolia CMS component that performs rendering is called the rendering engine. It is the component that
generates HTML output based on templates. The rendering filter which is part of the filter chain submits a content
node to the engine.
Tip! Since submission of content is handled through a filter, an independent servlet or Java application can also
submit content to the Magnolia CMS rendering engine. (Freemarker only)

70

Magnolia International Ltd.

14.1. Steps involved in rendering content


On submission of content to the engine, the following process kicks off:
1. The rendering engine reads the template definition assigned to the content. The template definition
provides the engine with details such as a path to the template script and the templating language used
(FreeMarker, JSP).
2. Based on the templating language, the engine selects a renderer. Renderers for FreeMarker and JSP
are shipped with Magnolia CMS. You can also use your own custom renderer.
3. The renderer is executed which creates the model object. The model is a JavaBean. This is where your
business logic resides. Before the renderer calls the script, the model's execute() method is called.
The model can execute any Java code to retrieve data from the JCR repository or from an external
source.
4. The renderer calls the assigned template script and passes the current content and model to it.
Freemarker interpolations like ${content.title} are replaced with actual values and directives like
#list are processed. The output of the merge process is HTML stream response that can be displayed
in a browser.

71

Magnolia International Ltd.

14.2. Renderers
A renderer is a Java class library that understands a particular templating language and produces text output. For
example, the Freemarker renderer understands Freemarker tags and JSP taglibs and produces output in HTML,
XML, RTF, Java source code and a few other formats. A renderer is not an end-user application but rather
something programmers can embed into their products.
Magnolia CMS ships with JSP and Freemarker renderers. Other popular successfully integrated template
languages are Velocity (similar to Freemarker but lighter) and Coldfusion.
While Magnolia CMS tag library is a native JSP tag library, the tag logic is also available as Java classes. Any
renderer that knows how to call a Java method can theoretically be used to render authoring UI components. The
experimental Templating Components module packages the classes and provides the logic as independent
components. If you want to attempt integrating your favorite Java-aware renderer, the module is included in the
add-ons folder of the Magnolia CMS bundle or available as a separate download.

14.3. Rendering order


Rendering of page content happens in a top-to-bottom fashion. Rendered HTML is sent to the output stream as
soon as it gets rendered.
When a template script calls another script using the includeTemplate tag, the rendering engine follows the
nested scripts down the rabbit hole until it finds the last script in the sequence. It then moves to the next element
on the page, starting where it left off.
As a consequence, you cannot redirect in a paragraph model as the request was already committed when the
rendering of the page started. Any operations changing the HTTP response headers (redirects, setting cookies...)
can only be executed in the page template's model.
Tip: You can use a filter that is executed before the page rendering.

72

Magnolia International Ltd.

15. Magnolia CMS API


Here we provide some essential information about important classes and interfaces in the Magnolia CMS API.
These are good starting points. For more detail see Javadocs.

15.1. Magnolia Context / Aggregation State


Context is an abstraction layer representing the environment of the current the process. This can be a request
process, a scheduled task or a command execution in the workflow. The context provides access to the most
important components like hierarchy managers, current user, context attributes and parameters, response object
and so on. The context is initialized at the beginning of each process: request, workflow step, scheduler command
etc. The context attributes will have a different meaning based on the environment. In case of a request the
attributes are request attributes and request parameters. Magnolia CMS implements context using a thread-local
class.
MgnlContext. This static helper class is the programmer's entry point to work with the current context.
getInstance() Returns the current context.
getUser() Returns the current user.
getHierarchyManager(workspace) HierarchyManager is an entry point into the content
hierarchy.
getAttribute(name) Returns a named context attribute. In case of a request, this can be a
request parameter, request attribute or session attribute.
getWebContext() Returns the Web context if the current thread is processing a request.
getAggregationState()
WebContext. Context interface specialized for servlet requests; knows about HttpServletRequest
and HttpServletResponse. Should be used as little as possible as it makes the calling code
dependent on the servlet API. Use MgnlContext instead if possible.
getRequest() Returns the current servlet request object.
getResponse() Returns the current servlet response object.
AggregationState contains information about the current request and rendering process. It is mostly
initialized by the Aggregation filter.
getOriginalURI() Original URI is the URI as requested by the client.
getCurrentURI() URI as mapped by Magnolia CMS at a given point in processing. This
value is for instance changed by the i18n filter, virtual URI mapping etc.
getMainContent() The content with which we start the rendering process. In general this is
the page node.
getCurrentContent() The content that is processed at the moment. First this is typically the
page, then a paragraph and so on.

73

Magnolia International Ltd.

15.2. Content API


The JCR API is wrapped inside Magnolia CMS API. You can use the JCR API as such but the Magnolia CMS API
is in some cases more programmer friendly. It is simplified and independent from the JCR API. We strive to align
the two APIs as well as possible.
HierarchyManager: Magnolia CMS representation of a workspace or repository. Using the
HierarchyManager you can retrieve content objects such as pages or configuration nodes. It is
equivalent of the JCR Session interface.
getContent(path)
getContentByUUID(uuid)
save()
Content: Represents a node in the repository. This can be a page (type mgnl:content), a paragraph
(type mgnl:contentNode) or any other kind of content. Equivalent of JCR Node interface.
getContent()
getChildren()
getChildren(type)
getNodeData(name)
setNodeData(name, value)
NodeData: Represents a single JCR value. Equivalent of JCR Property interface.
getString()
getLong()
getStream()

15.3. Components and modules


Components. Entry point to the ComponentProvider interface. ComponentProvider is responsible
for providing components, singletons and new instances. Magnolia CMS Beans and managers are
provided by this class.
getSingleton(interface/class). Convenience method for retrieving a component.
ModuleRegistry. Holds instances and definitions of modules.
getModuleInstance(name). Returns the module's instance. This is useful for modules of
known type.

15.4. Templating
RenderingEngine. Entry point for the rendering.
render(content, definition, writer). Render the content by using the passed
definition.
render(content, writer). Determines the definition from the content automatically.

74

Magnolia International Ltd.

RenderableDefinition (Template/Paragraph Definition). Abstract rendering definition used for templates


and paragraphs.
getName()Name of the paragraph or template definition.
getType()Defines the renderer to use. For instance JSP or Freemarker.
getDialog()Dialog assigned to this paragraph or template.
RenderingModel. The model used in the rendering process. It is instantiated for each rendering and ties
the current content and rendering definition together. Concrete classes provide helper methods used in
the template script. The execute() method is executed before the rendering starts, a useful place to
execute any business logic. The model is available in the template script under the name model.
getParent()Parent model. Most often the model of the page rendering.
getContent() Content we are currently rendering.
getDefinition() Definition used for the current rendering. This is either a paragraph or
template definition.
execute() Executed before the rendering starts.
TemplateRenderer. Responsible for generating the actual response from request data and a template.
A typical JSP implementation will simply forward the request to the JSP through request dispatcher. You
can bind a specific implementation to a template type.
renderTemplate(content, template, writer). Generates the actual output using the
selected template.
ParagraphRenderer. An interface to render paragraphs of content.
render(content, paragraph, writer)

75

Magnolia International Ltd.

16. Configuration mechanisms


Magnolia CMS is configured using properties, components, observation and a mechanism known as
Content2Bean.

16.1. Properties
Magnolia CMS is primarily configured using properties. Properties come from multiple different sources,
processed in the following order:
Source

Location

Path

1. Bean properties

magnoliacore.jar

/mgnl-beans.properties

2. Module properties

module descriptor

<properties>
<property>
<name>defaultPublicURI</name>
<value>redirect:/
help.html</value>
</property>
</properties>

3. Global file properties

Web application

WEBINF/config/magnolia.properties

4. Default file properties

Web application

WEB-INF/config/default/
magnolia.properties

5. Web application file properties

Web application

WEB-INF/config/(webapp)/
magnolia.properties

6. Server file properties

Web application

WEB-INF/config/(servername)/
magnolia.properties

7. Web application at server file


properties

Web application

WEBINF/config/(servername)/(webapp)/
magnolia.properties

8. System properties

JVM (-Dx=y)

Existing properties will be overridden by System


properties

Sources processed earlier may be overridden by sources processed later. The distribution of properties into
several sources and the processing order allow flexible customization.

76

Magnolia International Ltd.

Some key properties set in the default magnolia.properties file:


# Repository configuration
magnolia.repositories.config=WEB-INF/config/default/repositories.xml
magnolia.repositories.home=${magnolia.app.rootdir}/repositories
magnolia.repositories.jackrabbit.config=WEB-INF/config/repo-conf/jackrabbitbundle-derby-search.xml
# Defining the instance as author instance
# Only used for the initial installation.
# Afterwards configuration in the config repository is used.
# The value is saved in /server/admin
magnolia.bootstrap.authorInstance=true
# Switch to false to enhance the performance of Javascript generation
magnolia.develop=false
# Set to true if bootstrapping/update should be performed automatically
magnolia.update.auto=false

16.2. Multiple configurations in the same Web application archive (WAR)


You can easily bundle different configuration sets in the same webapp. They are automatically applied depending
on the server name or webapp name.
WEB-INF/config/default/magnolia.properties
WEB-INF/config/${webapp}/magnolia.properties
WEB-INF/config/${servername}/magnolia.properties
WEB-INF/config/${servername}/${webapp}/magnolia.properties
Default properties are common regardless of the server name or webapp name. Webapp specific properties are
installed only if the webapp name matches. Correspondingly, server specific properties are only installed if the
server name matches.
For example, Magnolia CMS ships with two webapps by default: magnoliaAuthor and magnoliaPublic. The
magnoliaPublic app becomes a public instance because of the way it is named.
An example of server specific configuration is setting a different repository per environment. On a development
instance the repository could reside in the default embedded Derby database but on a production instance you
would want to use production-scale persistent storage such as a MySQL database.

16.3. Components
Magnolia CMS uses components provided by a Components service. Magnolia properties can be used to define
which concrete class should be used to instantiate a certain component. The property key is the interface or class
name and value is the concrete class or a path which maps to the config workspace. If the value is a path then
the Content2Bean mechanism is used to build the instance.

77

Magnolia International Ltd.

Example configuration:
# Map to a path in the config workspace
info.magnolia.cms.i18n.I18nContentSupport=/server/i18n/content
# Concrete class implementing the interface
info.magnolia.module.ModuleManager=info.magnolia.module.ModuleManagerImpl
Some default classes are defined in file mgnl-beans.properties provided by the core JAR. The values can
be overwritten and defined in the module descriptor or properties configuration files.
Examples of components:
SecurityManager. Used to read users, groups and roles.
TemplateManager. Provides a template definition used in rendering.
ModuleRegistry. Holds instances and definitions of modules.
To retrieve a component you should use the Components service class. Most components are singletons.
I18nContentSupport i18n = Components.getSingleton(I18nContentSupport.class);

16.4. Content2Bean
Most of Magnolia CMS configuration is stored in the config workspace. A mechanism known as Content2Bean
is used to transfer the configuration from the workspace into a Java object. Content2Bean populates a JavaBean
with the content of a repository node, including sub nodes.
With Content2Bean's "setter" and "adder" methods you can populate configuration collections and maps. The
methods can handle simple data types (String, int, float, double, Boolean), custom data types, collections and
maps with key-value pairs.
The class used to instantiate an object through the Content2Bean mechanism is determined through reflection or
by explicitly referencing a class in the class node data. By referencing a specific class you can override Magnolia
CMS default configuration and implement your own caching behavior, security mechanism and so on.

78

Magnolia International Ltd.

Numbered items:
1. config is the entry point of the transformation. In the module descriptor we define that SampleConfig
class is used. text and number properties will be set.
2. sub is a sub bean. The class is determined using reflection if not explicitly defined.
3. items is a collection. The corresponding add method is used to determine the class and populate the
collection if existing.
4. item2 is a special item. It has its own class and additional properties.
5. parameters is a map of key-value pairs.

16.4.1. Where is Content2Bean used?


Content2Bean is used in:
Module instances. A module's configuration data is transferred into a Bean
from /modules/moduleName/config. The Bean class to build is defined in the module descriptor
XML file.

79

Magnolia International Ltd.

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


<!DOCTYPE module SYSTEM "module.dtd">
<module>
<name>samples</name>
<displayName>Magnolia Samples Module</displayName>
<class>info.magnolia.module.samples.SamplesModule</class>
...
Components. If a path in the config workspace is given rather than a concrete class name, then
Content2Bean is used to build the component instance.
# Map to a path in the config workspace
info.magnolia.cms.i18n.I18nContentSupport=/server/i18n/content
Additional items such as paragraphs, templates and virtual URI mappings configured at module level.

16.4.2. Extending configuration


You configuration can extend an existing configuration. With an extends data node you can point to a source
configuration and save some time and effort by only defining exceptions explicitly. This mechanism is used for
example in site definitions. The demo-project site definition extends the default definition.

16.5. Observation
Observation is a Java Content Repository feature that allows applications to register interest in events that
change a workspace and then monitor and respond to those events. The observation mechanism dispatches
events when a persistent change is made to the workspace. Magnolia CMS uses observation heavily. For
instance, observation is used to reload module configurations and to reload all objects.
The components provided by Magnolia CMS are proxy objects to allow re-initialization of the components upon
configuration changes.

80

Magnolia International Ltd.

17. Integration options


Magnolia CMS can be integrated in various ways ranging from filters and servlets to full Java framework
integration.

17.1. Custom filter.


Additional filters can be added in the filter chain or web.xml file. If you add them in the filter chain you benefit
from Magnolia CMS features such as security and caching. The additional filter can take over the handling of the
request or delegate it to the remaining filter chain.

Tip: If the filter wraps the response like we do in the Cache filter you can also post-process the content.

81

Magnolia International Ltd.

17.2. Custom servlet


An independent servlet can be registered in the servlet filter. The easiest way to do so is to register the servlet in
the module descriptor.
If the servlet maps to the request it will be responsible for rendering.

82

Magnolia International Ltd.

17.3. Forwarding a request


As the Magnolia main filter is registered on forward, any servlet or filter can internally forward to a Magnolia CMS
page. This is normally used if the servlet executes some business logic but the result should be rendered in a
Magnolia page. This strategy is often used to combine Magnolia with other frameworks. The servlet typically puts
the results into the request attributes which are exposed in Magnolia CMS through the context.

17.4. Custom renderer


A custom renderer is needed if you like to support different template script languages or want to perform
additional processing. The template definition will then be of custom type. If you need to delegate the rendering to
a servlet you can use a template definition of type servlet.

17.5. Spring (Blossom) module


Probably the most advanced integration mechanism is provided by the Blossom module which is an integration
with the Spring application framework. The Blossom module provides:
Programmatic registration. Dialogs, page templates and paragraphs can be registered by code or
annotations rather than by configuring them.
Spring MVC or WebFlow for page templates and paragraphs. This allows you to combine Spring with
the authoring facilities of Magnolia CMS.

83

Magnolia International Ltd.

Pre-execution of paragraphs. Enables the use of redirects and forwards in the execution of a
paragraph. The execution is bound to a specific paragraph which allows you to have multiple instances
of the same paragraph on the same page.
More information is on the Blossom module wiki page.

17.6. Direct calls to rendering engine


Any Java code can call the rendering engine to let it render pages or paragraph snippets. The caller will pass
a Writer object to which the result is written. If you use a ByteArrayOutputStream the result can be read into
a String.
Note: This is only possible if all involved template scripts are FreeMarker scripts. JSP scripts depend on a
request.

17.7. Web services, AJAX and snippets


External applications can make requests to Magnolia CMS to get rendered content/snippets. Magnolia supports
for instance direct requests to paragraphs. Magnolia 5.0 will use service oriented architecture (SOA) and will
provide a full set of Web services. A common use case for Web services is displaying content from Magnolia
CMS in an external portal.

17.8. Reading content directly


If the Magnolia context is initialized, which is for instance the case if the context filter was executed, you can
access the HierarchyManager and read content directly from it.

84

Magnolia International Ltd.

18. Internationalization and localization


Internationalization (i18n) and localization are ways to adapt Magnolia CMS to different languages and regional
differences. Internationalization involves designing the system so that it is easy to accommodate new languages
without programming. Localization is the process of adapting Magnolia CMS to a particular region or language by
adding locale-specific configuration and translating text.
Localization is supported on three levels:
System. Controls how the Magnolia CMS user interface, such as AdminCentral and common dialogs,
adapts to different languages and locales. This mechanism is also used for messages in template
scripts.
Content. Handles the storing and serving of localized content in the JCR.
Authoring. Adapts the authoring interface to support localized content entry. The default implementation
adds a language dropdown in the mainBar and displays a two-letter language identifier (en, ge, fr etc.)
next to field labels in the content entry dialog.

18.1. System
The AdminCentral user interface for content authors is available in 16 languages: Chinese (China), Chinese
(Taiwan), Czech, Dutch, English, French, German, Indonesian, Italian, Japanese, Norwegian, Portuguese,
Portuguese (Brazil), Russian, Spanish and Swedish.

85

Magnolia International Ltd.

Supported languages are configured in /config/i18n/system. Each language has a country and language
property so you can define regional variations too, such as zh_TW for traditional Chinese or pt_BR for Brazilian
Portuguese.

One of the languages is always a fallback language. If no target language content is found, the system displays
content in the fallback language instead.
Labels for user interface elements such as dialogs, tabs and buttons are stored in a message bundle. The bundle
is a collection of properties files inside a module JAR. You can retrieve a particular label from the properties file by
referring to it with a key in the UI element's configuration. For example, the reference
key dialogs.paragraphs.content.stkTextImage.tabText.label matches a label for the "Text" tab in
the Text and Image dialog. It is retrieved from the message_en.properties file included in the Standard
Templating Kit module:
dialogs.paragraphs.content.stkTextImage.label=Text and Image
dialogs.paragraphs.content.stkTextImage.tabText.label=Text
dialogs.paragraphs.content.stkTextImage.tabText.subtitle.label=Subheading
Translation of user interface text to another language is a community project coordinated by Magnolia
International Ltd. Community volunteers choose a language to translate and work in Google Spreadsheets. Their
contributions are built into the properties files that ship with the system. We trust enthusiastic users to do a better
job translating the UI than a professional translator who is not familiar with the system.

18.1.1. Dialogs
For dialogs you can define a i18nBasename data node which determines the message bundle to use. Like
above, the bundle contains properties files which have strings for dialog elements. Instead of entering text
manually you can use a key. The key will be substituted by the value from the property file.

86

Magnolia International Ltd.

Here's an example of the Text and Image dialog definition with i18nBasename. The description and
label properties use keys instead of manually entered strings.

18.1.2. Template scripts


Similarly, you define an i18nBasename in the template or paragraph definition. You would then use a key in the
template script.
Freemarker:
${i18n['link.readon']}
JSP (JSTL):
<fmt:message key="link.readon"/>

18.2. Content
Content level internationalization handles the storing of localized content in the JCR and serving it at a languagespecific URL such as mysite.com/de/welcome.html. This option is enabled by default. Language variations
are stored in a single content hierarchy. You have the option to disable the localized content storage and create a
separate site hierarchy for each locale instead.

87

Magnolia International Ltd.

18.2.1. One hierarchy or many


Magnolia CMS' ability to store multi-language content in a single JCR content node means that you only need a
single site hierarchy. As long as your site content is reasonably similar from one language to another, this is the
best option. You have fewer pages to manage and the system takes care of serving the correct language
automatically.
A use case where a single hierarchy makes sense is a white-labeled product such as an insurance policy. The
number of pages and paragraphs needed to describe the policy to customers is likely the same regardless of the
customer's language or locale. Regional affiliate companies offering the same policy can enter content in their
own language and serve it under their own brand.
However, if the number of pages and paragraphs differ greatly from one locale to another, you have the option to
create separate site hierarchies. One site tree for English, another for German and so on. This effectively
duplicates some pages but allows completely customized local content.
The configuration is in /server/i18n/content or in the case of Extended Templating Kit in the site definition.

18.2.3. Storing localized content


If you choose the one-site-hierarchy strategy, language specific variations of a paragraph are stored as separate
properties of a single content node. In the example below, a Text and Image dialog was used to write a paragraph
in English, German and French. The system created subtitle and text properties for each language under the
02 paragraph node. Each property is suffixed with a language identifier: _de or _fr. Since English is the base
locale on this site, no _en identifier is used.

88

Magnolia International Ltd.

18.2.4. Delivering localized content


Localized content is served to visitors at a URL that identifies the locale:
Locale

URL

Base locale, default language www.mywebsite.com/article.html


German

www.mywebsite.com/de/article.html

French

www.mywebsite.com/fr/article.html

Spanish

www.mywebsite.com/es/article.html

Correspondingly, the HTML element on the public page identifies the language with standard lang and
xml:lang attributes since pages based on STK templates adhere to an XHTML doctype.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
Magnolia CMS does not redirect visitors to the localized URL automatically. You need to configure this behavior
on the web server. There are various strategies how you might want to do this. Note that these are not provided
out-of-the-box:
Allow the visitor to select a language or region from a dropdown, then redirect them to the correct URL.
This is a common strategy on airline websites. Airlines serve customers in many countries and
languages, and allow users to select their home country while traveling.
Detect the visitor's origin from their IP or the referring page, then redirect them to the localized site
automatically.
Detect the visitor's preferred locale from their browser settings, then redirect them to the localized site
automatically.

89

Magnolia International Ltd.

18.3. Authoring
This level of internationalization adapts the authoring interface to support localized content entry. The default
implementation adds a language dropdown in the mainBar and displays a two-letter language identifier (en, ge, fr
etc.) next to field labels in the content entry dialog.

Enabling i18n authoring support allows authors to write foreign-language or regionally targeted content. The
relevant configuration node is /config/server/i18n/authoring.

90

Magnolia International Ltd.

Once enabled, the mainBar displays a language dropdown. Selecting a language from the dropdown defines the
content entry language for paragraphs and properties on the page.

Dialogs reflect the choice by displaying an identifier (en, fr, de...) next to field labels. This makes it clear which
language should be entered.
The language dropdown and the identifier are Magnolia CMS default implementations. You can alternatively
develop your own strategy for localized content entry. You could for example create a tab for each language in
the dialog. If the number of supported languages is not very large, say 3 or 4, this might work fine. We opted for
the field label strategy because it works well with a large number of languages and keeps UI changes minimal.

91

Magnolia International Ltd.

18.4. Unicode
Magnolia CMS supports UTF-8 character encoding for Unicode. UTF-8 is able to represent any character in the
Unicode standard, yet is backwards compatible with ASCII.
To enable Unicode support for content node and page names, set the magnolia.utf8.enabled property in
magnolia.properties. This allows you to handle non-ASCII characters in URLs, for example.
# Activate UTF-8 support to pages
magnolia.utf8.enabled=true
Sites built using STK templates identify the encoding as UTF-8 with an HTML meta element.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
Here is an example of a Russian travel site built with Magnolia CMS. Russian uses the Cyrillic alphabet included
in UTF-8.

92

Magnolia International Ltd.

19. Security
Security is controlled with a built-in access management system. The purpose of this system is to:
Authenticate. Reliably and securely determine who is using the system and provide them with means to
sign into the application.
Authorize. Ensure that users have the permissions to do the actions required such as editing pages or
creating categories.
The system is based on the Java Authentication and Authorization Service (JAAS). You can set permissions for
all types of users whether real people or processes, and control access to resources such as Web pages,
documents, data, forums and templates. Permissions are controlled through a combination of users, groups, roles
and ACLs in AdminCentral.
In a small site you can manage users and groups in Magnolia CMS. On a larger site (hundreds of users) it is
better to manage users and groups in an enterprise-grade user directory such as LDAP. You would define roles
and ACLs in Magnolia CMS but manage users and groups in the external system. Magnolia CMS supports
directories via the LDAP Connector, a standard JAAS login module.

19.1. Users
A user is an account that identifies the person accessing Magnolia CMS. In addition to a username, the system
stores the user's full name, password, language preference and email address by default. Users inherit their
permissions from the groups and roles they are attached to. Users are organized as follows:
Users can have both roles and groups.
Groups can have roles.
Roles can have only ACLs.

Permissions are defined in the ACL. Users inherit permissions from the roles and groups assigned to them.
On a small site you can manage users and groups in Magnolia CMS. On a larger site with hundreds of users it is
better to manage users and groups in an enterprise-grade user management infrastructure such as Microsoft
Active Directory. In such case you would define roles and ACLs in Magnolia CMS but manage users and groups
in the external system.

93

Magnolia International Ltd.

19.2. Groups
Users with similar privileges are grouped together. The purpose of a group is to define settings for the group as a
whole rather than each individual user. Permissions that apply to the group are inherited by its users. By
assigning a role to a group, all users in the group will inherit the permissions granted to the role.

19.3. Roles
A role is a function a user performs in the management of a Magnolia CMS website. It reflects the actions and
activities assigned to or required or expected of a user. For example, the role Editor is responsible for day-to-day
editing of content displayed on the site. Permissions granted to the Editor role allow users in this role to edit
content and submit it for review. The role Publisher on the other hand is tasked with reviewing content and
publishing it from the authoring instance to public instances. Note that role names and permissions are completely
configurable to match your actual requirements.
The standard installation of Magnolia CMS includes default definitions of roles, groups and users. A sample
structure is provided to demonstrate a typical setup, and it can be adapted.

19.4. ACLs
Access to resources is controlled with an access control list (ACL). An ACL consists of one or more rules where
permissions are applied to the controlled resource. The ACL itself defines what permission is granted. Attaching
the ACL to a role defines who has the permission. Any groups and users that belong to the role either directly or
through groups have the permissions granted in the ACL.
Example of ACL rules defining permissions to access a site:

94

Magnolia International Ltd.

An ACL rule defines:


Controlled space. ACL rules are defined per controlled space, for example Website, Data or URL. A
single ACL can contain rules for several spaces. What you select in the dropdown limits the types of
permissions and scopes available. For example, the Selected node permission is only available in
Config, Store and Expressions workspaces, not in the Website workspace.
Permission. Type of permission applied to the controlled resource, for example Deny access, Read only
or Read/Write. Other options are possible depending on the controlled space.
Scope. Does the permission apply to the selected node only or also to its sub nodes?
Path pointing to the resource being controlled.
For example, the following ACL rule attached to the Editor role gives editors permission to edit news pages under
siteA/news.
Permission

Scope

Path

Read/Write

Sub page

/siteA/news

The power of ACLs is in the combination of rules. The following ACL first denies access to the complete website,
then specifically allows read access to /siteA and write access to subpages under /siteA/news. Users whose
access is controlled with this ACL can see /siteA and all its subpages but can edit only pages under /siteA/
news.
Permission

Scope

Path

Read only

Selected and sub pages /$

Ready only

Selected and sub pages /siteA

Read/Write

Sub pages

/siteA/news

Note: For technical reasons you can only select "Selected and subpages" or "Subpages" scope in the website
workspace, not "Selected page only". When you need to restrict user access to just the root node (/), use the
dollar character ($). The dollar character means "end the expression here". It allows the user to expand the site
tree in AdminCentral. Then create further rules to grant explicit access to paths (/siteA) the user should be able
to access.

95

Magnolia International Ltd.

19.5. Custom login forms


You can configure your own login form in the uriSecurity filter to replace the default Magnolia CMS login form.
The form is configured in /server/filters/uriSecurity/clientCallback. Here you find an example of a
custom form used to grant public users access to a restricted members' area. Authentication is delegated to the
custom form when a particular URL is accessed.

96

Magnolia International Ltd.

20. Data module


The purpose of the Data module is to manage structured, hierarchical data. The module stores data independent
of page structure. To use the data on a Web page you retrieve it using a paragraph or page template.
Here are some ideas how to use the module in your projects:
Boiler plate text. Define text modules which can be referenced either within the template script or
through a simple reference paragraph.
Look-up tables. Define a folder US States and a node for each state with properties such as
abbreviation, name, size and population.
Product catalogs for e-commerce solutions.
Client references. The list of references on the Magnolia International website is driven by the Data
module. By storing client information in the Data module you can generate different types of lists and
choose the amount of detail displayed from same set of data.
Contact database. Store contacts and display them on Web pages. For example, display the author's
bio on any article they wrote.
Categories and taxonomies. Create categories to characterize the site content and use them to tag
articles. You can create an ad hoc taxonomy or import a third party classification scheme. Once an
article is tagged the tag behaves as a navigation mechanism for finding related content.
The Data module also allows you to import external data. This is useful for exposing or re-purposing data from
other systems such as data warehousing or CRM solutions. Using the Data module as an intermediary allows you
to import data into Magnolia CMS though a single entry point. The data can then be used on Web pages in a
uniform way. The module lets you modify the imported data further in case it is not ready for publishing. You can
do this manually or with a script.

97

Magnolia International Ltd.

20.1. Types
Start by creating a new data type. Type is a content node that acts as a label for the data such as "products",
"clients" or "books". Types can be hierarchical, consisting of subtypes.
Magnolia CMS ships with four sample data types:
Company is a hierarchical type consisting of departments and employees.
RSS Aggregators allows you to aggregate feeds from multiple sources.
Contact is a basic example of how to store personal details for use on pages.
Category shows how to create a taxonomy of terms that can be used to tag content.

Types have to be registered before they can be used. This is done automatically when you create a new type by
hand. When you introduce new types with a custom module, bootstrap the types first before bootstrapping their
dialog configurations and content. The Data module provides a special install task to do this.

98

Magnolia International Ltd.

20.2. Dialogs
To edit the data you need a dialog. You can build the dialog using standard Magnolia CMS controls such as text
boxes, tabs and date pickers, or create your own custom control.
Here is a definition for a dialog used to edit contacts. The definition is on the left and the rendered dialog on the
right.

99

Magnolia International Ltd.

20.3. Content
The actual data is stored as folders and properties at the repository level. You can view the underlying structure
with the JCR Browser. If a data type allows hierarchical organization, the content item folders have subfolders
correspondingly.

100

Magnolia International Ltd.

21. Cache
Magnolia CMS employs a web cache to store server responses so that future requests for the same content can
be served faster. Using a cache reduces the amount of information that needs to be transmitted across the
network, easing the bandwidth and processing requirements and improving responsiveness.

21.1. Cache filter


Caching is performed by the Cache filter which is part of standard Magnolia CMS filter chain. The Cache filter
attempts to serve the requested content directly from the cache store. If the content is not available, the filter
passes the request on to the CMS part of the filter chain. On the return trip the filter reads the content from the
response and stores it in the cache store for future use.

21.2. Policy configuration


Magnolia CMS allows you to define several alternative cache configurations in the Cache module and select one
of them by setting the cacheConfigurationName parameter in the Cache filter. The chosen configuration is
read into a JavaBean using the Content2Bean mechanism, which makes it dynamically available to your own
module code.
Caching behavior for each configuration is defined with policies:
Server cache policy defines whether the requested content should be cached or not. The standard
Magnolia CMS way to make such decisions is with voters. Voters are used whenever configuration
values are not assigned at start-up but depend on rules. Voters evaluate a rule such as "should content
residing at this URL be cached" and return a positive or negative response. By default, all content on
public instances is cached except the AdminCentral UI at /.magnolia.

101

Magnolia International Ltd.

Client (browser) cache policy defines how long the browser may cache a document. The time is
passed to the browser in the response header. The default FixedDuration option instructs the
browser to cache the document for 30 minutes. Another option is Never which tells the browser to do
nothing.

Flush policy defines when to flush the cache. The default configuration observes changes in a
repository and flushes the cache if new or modified content is detected. You can flush the cache
completely, partially or not at all. Multiple flush policies can be registered. Each module can register its
own flush policy (or multiple policies) and be notified about new or modified content in each repository.

Executors are actions taken once a caching decision has been made. There are three possible actions.
useCache retrieves the cached item from the cache and streams it to the client, store stores the
response in the cache for future use, and bypass skips caching altogether.

21.3. Caching while developing


Important! The system caches resources such as JavaScript files and CSS files on the author instance by default
to make authoring more responsive. When you develop, you want to disable this behavior. Set the
magnolia.develop property to true in the default magnolia.properties file.

21.4. How caching works


When a request arrives to the Cache filter, the filter passes it first to the browser cache policy. In case content has
not been modified and the client already has the latest version, the browser cache policy instructs the filter to
simply respond with "304 Not Modified".

102

Magnolia International Ltd.

If content has been modified or it does not exist in the cache, the filter passes the request to the server cache
policy. Server cache policy analyses the request and replies with the expected behavior. Based on the expected
behavior the filter invokes the appropriate executor. This mechanism allows you to add and remove executors
and use them by changing the current cache policy to a different one.

21.5. Ehcache back end


Magnolia CMS uses Ehcache for its back-end cache functionality. Ehcache is a robust, proven and full-featured
cache product which has made it the most widely-used Java cache. You can use another cache engine as long
as you implement Java interfaces that allow you to configure caching behavior from AdminCentral.

21.6. Advanced cache strategies


The Advanced Cache module is a collection of cache strategies to help minimize load on the server while
ensuring fresh content is served to users.
Serve old content while re-caching. When using this strategy, cache will not be completely cleaned
when content update is detected. All cached entries are retained. When the first request comes in after
content update, generation of a fresh cache entry is triggered while further requests for the same entry
are served from old cache content until the new entry is ready. Magnolia will wait 10 seconds by default
while still serving the old version of the content before attempting to re-cache. The waiting time is
configurable.
Eager re-caching. When using this strategy, cache will keep a list of most often served entries and
attempts to refresh those as soon as an update of content is detected. All other entries are re-cached
when requested again, as is the case with the strategy above. The number and lifetime of the mostserved content entries is configurable. Statistics about served pages are kept forever by default but you
can force Magnolia CMS to clean them after each content update.

103

Magnolia International Ltd.

22. Workflow
Magnolia CMS ships with a basic "four-eye" editorial content workflow. Authors and editors come across this predefined workflow for the first time when they activate content. Activations are submitted to a workflow queue for
approval. A publisher can examine the workflow item, see what the changes are, who made them and when, and
decide whether to publish the modified content to a public instance.
The key point about the default workflow is that authoring and editorial review happen on the author instance.
Content is published to public instance only when the workflow is completed.

104

Magnolia International Ltd.

22.1. Engine
Magnolia CMS uses the cross-platform OpenWFE workflow engine. OpenWFE allows extensive workflow
customization, making it possible to integrate Magnolia CMS into your legacy business processes. You can define
your own activation and publishing workflows with as many stages and participants as needed.
The engine supports:
Linear modeling and approvals
Branching and merging
Conditionals such as IF and multi-choice
Auto-escalation
Email notifications
Pre-defined workflows
Workflows are defined in XML. You can use a third party editor with syntax highlighting to enhance the editing
experience. Graphical tools exist but experience using them with Magnolia CMS is limited. Generally we assume
that workflows are defined by suitably skilled people. OpenWFE provides a flexible set of rules to accommodate
business requirements and the XML markup is clean.
<process-definition name="activation" revision="j0.0.2">
<sequence>
<set field="activator" field-value="userName"/>
<!-- go to publisher first -->
<to-publisher/>
<!-- will loop if rejected -->
<if test="${field:action} == reject">
<revision-round/>
</if>
<log message="activate: ${field:action}"/>
<!-- if the last action was proceed: activate-->
<if test="${field:action} == proceed">
<activate/>
</if>
</sequence>

22.2. Participants
A participant is a reference to a user or program that takes part in the workflow. Participants are identified in the
workflow definition by their name. OpenWFE understands four kinds of participants:
user-username
group-groupname
role-rolename
command-commandname

105

Magnolia International Ltd.

So if you want to route a publication approval to user "john", make sure that the process definition states:
<participant ref="user-john" />

22.3. Workitems in inbox


Workflow tasks are called workitems. They arrive to a workflow participants Magnolia CMS inbox.

A participant acts on the workitem by completing the required task such as reviewing a page change.
Permissions to view workflow items are controlled through Magnolia CMS user rights management. This allows
an administrator or workflow supervisor see workitems assigned to other users. Their inbox effectively functions
as a "dashboard", displaying the status of the workflow process.
Since commands and processes can participate in a workflow, you can send email notifications on pending
workitems. A workflow command can be attached to any event such as move page, delete page, activate, rename
etc.

22.4. Integration with external processes


While users are the typical workflow participants, scripts and commands can also participate. This opens up the
possibility to execute jobs and launch external processes at a given workflow stage. Conversely, an external
process can participate in a Magnolia CMS workflow through a command or script.

106

Magnolia International Ltd.

Each module can provide its own commands. Commands are configured in
/modules/moduleName/commands/catalogName/commandName.

A command name is linked to a Java implementation. For example, you could write a command that encapsulates
the decision who (or which group or role) should receive the workitem next. The name of the "real participant"
could be placed in a workitem field such as receiver.
<sequence>
<participant ref="command-determinereceiver" />
<participant field-ref="receiver" />
</sequence>

107

Magnolia International Ltd.

23. Resources
Here's what you should do next:
Visit Magnolia home page
Download Magnolia CMS and the Standard Templating Kit
Read official documentation and create an account on the community wiki.
Join the users mailing list,
Follow us on Twitter

and "like" us on Facebook

108

Das könnte Ihnen auch gefallen