Chapter 14. Custom Knowledge Base: Getting Started

WHAT'S IN THIS CHAPTER?

  • Defining a content model in the Alfresco repository

  • Building a Knowledge Base space template

  • Configuring business process rules

  • Writing articles in Alfresco Explorer

This chapter guides you through the foundation work required as a first step for building a compelling Knowledge Base application. This chapter focuses on the Alfresco repository and Alfresco Explorer. It walks you through the design and implementation of the content model and content rules required to implement a lifecycle for your Knowledge Base articles.

Familiarity with Chapter 13, which discusses levels of customization and their associated terminology, will be helpful to you in working through this chapter. Subsequent chapters build on the foundation work presented in this chapter. They focus on how to customize Alfresco Share to incorporate your Knowledge Base lifecycle within collaborative projects.

This chapter is structured to provide the following sections:

  • Overview—A high-level explanation of the concepts and application extension points that you will use in the example. You don't have to type in any of the code in this section; it is simply provided to help guide along the conversation.

  • Installing the Code—A step-by-step guide to the approach you will need to take in order to install all of the sample code on your own Alfresco installation.

  • Putting It into Action—A walkthrough of your new extensions. Try them out and see what they do!

At the end of this chapter you will find the source code for the samples. This is only provided for reference. To install the samples, you should download the source files from the book's page at www.wrox.com and follow the instructions provided in the section titled "Installing the Code."

OVERVIEW

This section provides an overview of the concepts and product features you'll take advantage of as you build out your Knowledge Base foundation. You'll start by defining your content and content lifecycle. From this you can derive your content model requirements. You'll examine Alfresco Explorer and see some of the extension points that it provides. Finally, you'll look at how you can use space templates and rules in Alfresco Explorer to make things really easy.

You don't have to type in any code in this section. Just read and enjoy!

Content Lifecycle

Your Knowledge Base will consist of articles that are contributed and collaborated upon by an internal team of knowledge experts. External consumers of the articles expect them to contain valid and approved information.

Content contributors can author new articles or work on existing articles using any of the authoring facilities in Alfresco. They can use Alfresco Explorer to navigate the content hierarchy to find and work on articles. Contributors can also use conventional desktop applications, such as Microsoft Word, to open and save files directly against Alfresco through its CIFS interface.

Articles must have a lifecycle state. For example, when an article is first authored, it is assigned with a draft status. This simply means that the article's content has not yet been approved. It may require more work before it can be considered complete, or it may be essentially complete and just need someone to sign off on its validity.

The workflow engine is responsible for handling the routing of the article to the appropriate people for sign-off and approval. This process may be instantaneous or take quite a while, even days, depending on the availability of staff to participate in the process. During this time, the article is assigned with a pending approval status.

As a positive outcome of this workflow process, the article's status should be modifiable to an approved current state. An article with a current status is valid and the external consumer audience should be able to retrieve it.

Alternatively, the workflow process may discover a problem with the article. In that case, it sets the article's status back to draft and allows the internal staff to continue making modifications.

Figure 14-1 shows an overview of this workflow process.

The Knowledge Base article conforms to this lifecycle. Now you'll look at how you can model your Knowledge Base article using the content modeling facilities of the Alfresco repository.

FIGURE 14-1

Figure 14.1. FIGURE 14-1

Content Model

To define a content model for the Knowledge Base metadata, you first determine a namespace URI and a prefix you want to use. While you can use anything you like as long as it is unique, it helps to have a short prefix. This example uses the following:

  • URIhttp://www.alfresco.org/model/knowledgebase/1.0

  • Prefixkb

With this in place, you can reference anything you define in the model by using the simple kb prefix. Now you can start defining things inside of the model. You should focus on two primary entities:

  • Knowledge Base space

  • Knowledge Base article

The next sections look at Knowledge Base spaces and articles in detail.

Knowledge Base Spaces

Your Knowledge Base articles will be authored and managed within a container known as a Knowledge Base space. As you saw earlier, a space is an Alfresco container that behaves a lot like a folder. It may even appear like a folder on your desktop (for example, if you are using the Alfresco CIFS desktop integration). However, while it looks like a folder, it may have custom business logic and behavior wired up behind it.

You can define the Knowledge Base space as a content type inside of your content model and extend it from cm:folder. The content type cm:folder is an out-of-the-box content type provided by the Alfresco repository. By inheriting from cm:folder, your Knowledge Base space will automatically be endowed with everything it needs to act and behave like a folder. You can then plug in additional properties and other good things on top.

You define the kb:space content type using XML like this:

<types>
   <type name="kb:space">
      <title>Knowledge Base Space</title>
      <parent>cm:folder</parent>
   </type>
</types>

This defines a "Knowledge Base space" content type called kb:space. Having your own content type for the Knowledge Base space gives you a number of advantages. For example, you can:

  • Add metadata to the Knowledge Base space (such as properties or associations).

  • Plug aspects onto the space. These let you wire in your own Java code to intercept events that occur to the folder (for example, when someone drops content into it).

  • Tell Alfresco Explorer, Alfresco Share, or your own custom Web applications to treat this folder uniquely. For instance, you can easily configure Alfresco Explorer to show a different icon for this folder.

This is a good design practice. You may not use all of these advantages right away, but you have a good foundation to do so in the future.

Knowledge Base Articles

A Knowledge Base article is a document submitted by a knowledge expert. It might be a Word document, a PDF, a text file, or even an Excel file. Assume that your knowledge experts are a diverse bunch – you don't want to constrain them with respect to the kinds of files they can submit. After all, Alfresco works very well with any file type you drop in.

You would like to define some metadata to wrap this Knowledge Base article. This additional metadata would let you store things on the document that aren't part of the document's internal representation or binary payload. If that's a little confusing, that's all right. Consider the following example.

Imagine you have a Word document. Your desktop users like to use Word – they're comfortable with it and they have a passion for Bill Gates. So they save their Word documents into Alfresco. At that moment, you can tell Alfresco to wrap metadata around the document. You can have as many properties and associations on this metadata as you would like. You can use that metadata to store things that the end user never sees or has to know about. As far as they are concerned, it is just a Word document.

For example, you may want to store an internal representation of the lifecycle state (such as draft, pending approval, and so on). Or perhaps a field that indicates the type of document (such as article, FAQ, or White Paper). One valid way you might think to do this would be to do as you did in the previous section. You could create another content type, call it kb:article, and add metadata to the kb:article content type. If you did that, it might appear like this:

<types>
   <type name="kb:article">
      <title>Knowledge Base Article</title>
      <parent>cm:content</parent>
      <properties>
         <property name="kb:status">
            <title>Status</title>
            <type>d:text</type>
            <default>Draft</default>
         </property>
         <property name="kb:articletype">
            <title>Article Type</title>
            <type>d:text</type>
            <default>Article</default>
         </property>
      </properties>
   </type>
</types>

This snippet declares the kb:article content type and gives it two d:text properties: kb:status and kb:articletype. The kb:status property tracks the lifecycle status of the Knowledge Base article. The kb:articletype property describes the type of article.

This approach would work, but you may eventually discover it to be too constraining. Why? Well, requiring Knowledge Base articles to be typed as kb:article means that you will forever require anyone who uses your Knowledge Base to have their content typed as kb:article. Since documents can only have one base content type, it is quite restrictive.

If you went with this approach, you would require that any Knowledge Base articles be of either type kb:article or another type that extends from kb:article. This would then force other third-party applications to consider your Knowledge Base schema ahead of time, which is often very inconvenient. Instead, you could use an approach that does not require rebasing the content instances onto a base type from your schema.

It would be ideal to take an arbitrary content item or document and mark it as a Knowledge Base article. By doing this, the content item would take on the additional metadata (kb:status and kb:articletype). You could mark any number of content items this way, no matter if they are desktop documents, XML files, or custom object types.

Alfresco makes all of this possible with content aspects. Instead of defining a Knowledge Base article content type, you can define content aspects and then mark up your content using these aspects as you see fit.

Here is what the revised code might look like:

<aspects>

   <aspect name="kb:status">
      <title>Status</title>
      <properties>
         <property name="kb:status">
            <title>Status</title>
            <type>d:text</type>
            <default>Draft</default>
</property>
      </properties>
   </aspect>

   <aspect name="kb:article">
      <title>Article</title>
      <properties>
         <property name="kb:articletype">
            <title>Article Type</title>
            <type>d:text</type>
            <default>Article</default>
         </property>
      </properties>
      <mandatory-aspects>
         <aspect>kb:status</aspect>
      </mandatory-aspects>
   </aspect>

</aspects>

You have defined kb:article as an aspect in the XML fragment previously shown. The kb:article aspect has the kb:articletype text property on it. It also has a mandatory inclusion of the kb:status aspect. The kb:status aspect is defined as a separate aspect and defines the kb:status text property.

You can now mark content in the Alfresco repository with the kb:article aspect. By doing so, the content item will have two aspects applied: kb:article and, by implication, kb:status. It will therefore have two properties on it: kb:articletype and kb:status.

Why two aspects? One reason is that it offers a more flexible forward-thinking approach. Imagine that in the near future you need to add support for Knowledge Base videos. You could create a Knowledge Base video aspect called kb:video. This aspect would have unique video-related properties on it, but it would like to reuse the same kb:status fields that the rest of the Knowledge Base application uses. All you have to do is specify kb:status as a mandatory aspect for the new kb:video aspect, and away you go.

Constraints

One additional improvement you can introduce is to apply a few constraints to your defined aspect properties. Property constraints allow you to specify checks that must pass before the property value is considered valid and safe for persistence. Constraints fire when the property values change. A content item must have all of its constraints pass before it can be created or saved.

Alfresco provides several default constraint types that you can use in your content model. These include regular-expression evaluators and value lists. Of course, you are also free to write your own constraint implementations. Large projects will use custom constraints to perform complex lookups in third-party databases or services to assert the correctness of property values.

In this case, you can use some of the default out-of-the-box constraints to ensure the validity of any content marked with your aspects. Here, you can declare two constraints that specify the valid values for kb:status and kb:articletype:

<constraints>
   <constraint name="kb:status_constraint" type="LIST">
      <parameter name="allowedValues">
         <list>
            <value>Draft</value>
            <value>Pending Approval</value>
            <value>Current</value>
            <value>Archived</value>
         </list>
      </parameter>
   </constraint>
   <constraint name="kb:articletype_constraint" type="LIST">
      <parameter name="allowedValues">
         <list>
            <value>Any</value>
            <value>Article</value>
            <value>FAQ</value>
            <value>White Paper</value>
         </list>
      </parameter>
   </constraint>
</constraints>

These declare the constraints. All you need to do then is tell your properties to use these as property constraints by simply modifying the property declarations on your aspects:

<property name="kb:status">
   <title>Status</title>
   <type>d:text</type>
   <default>Draft</default>
   <constraints>
      <constraint ref="kb:status_constraint" />
   </constraints>
</property>
<property name="kb:articletype">
   <title>Article Type</title>
   <type>d:text</type>
   <default>Article</default>
   <constraints>
      <constraint ref="kb:articletype_constraint" />
   </constraints>
</property>

That's about it. By putting the content model together, you effectively inform the Alfresco repository how to manage the interaction and persistence of Knowledge Base assets.

Alfresco Explorer Extensions

Alfresco Explorer is an out-of-the-box Web application that provides a useful interface for content contributors. For example, content contributors can use Alfresco Explorer to create new Knowledge Base articles and adjust metadata properties using automatically rendered property sheets.

Alfresco Explorer features a number of configuration options that you can tweak to make it easier to work with your Knowledge Base spaces and articles.

Property Sheets

Alfresco Explorer automatically renders content metadata to the end user for viewing and editing. It generates a property sheet for content in the Knowledge Base. You can tweak this property sheet by informing Alfresco Explorer of properties that exist on the kb:status and kb:article aspects.

The following code provides this configuration for Alfresco Explorer. It defines how to render property sheets for matching aspect and content-type names. Each property sheet can have zero or more fields that render controls for displaying and editing individual properties of the content model.

<config evaluator="aspect-name" condition="kb:article">
   <property-sheet>
      <separator name="sep" display-label="KB Article Properties"
                 component-generator="HeaderSeparatorGenerator"
                 show-in-edit-mode="false"/>
      <show-property name="kb:kbid"  show-in-edit-mode="true"/>
      <show-property name="kb:article_type"  show-in-edit-mode="true"/>
      <show-property name="kb:status" display-label="kb:status"
                     show-in-edit-mode="true"/>
   </property-sheet>
</config>
<config evaluator="aspect-name" condition="kb:status">
   <property-sheet>
      <show-property name="kb:status" display-label="kb:status"/>
   </property-sheet>
</config>

Alfresco Explorer will now display your Knowledge Base properties to end users for viewing and editing.

Wizards and Icons

Alfresco Explorer features a number of wizards that let you do things like fire off actions or create new content. These wizards are configurable and you can plug in your Knowledge Base assets straight away.

You can inform Alfresco Explorer to let you create spaces of type kb:space by using the following code snippet:

<config evaluator="string-compare" condition="Space Wizards">
   <folder-types>
      <type name="kb:space" icon="/images/icons/space-icon-pen.gif" />
   </folder-types>
</config>

You can also inform Alfresco Explorer to include your kb:article aspect as one of the available aspect options in the Action Wizard. The following code snippet achieves this:

<config evaluator="string-compare" condition="Action Wizard">
   <aspects>
      <aspect name="kb:article"/>
   </aspects>
</config>

Finally, you may want to adjust the way that Knowledge Base spaces appear in the Alfresco Explorer navigator. You can set up a custom icon for the kb:space content type with the following snippet.

<config evaluator="string-compare" condition="kb:space icons">
   <icons>
      <icon name="space-icon-pen" path="/images/icons/space-icon-pen.gif" />
   </icons>
</config>

Your kb:space spaces will now show up with a different icon – a folder superimposed with a pen. This is simply a cosmetic change, but a useful one nonetheless. It will help end users locate the Knowledge Base space. You could also make additional customizations to the Alfresco Explorer configuration file.

Smart Spaces and Scripting

A space in the Alfresco repository is fundamentally a container. Users who interact with a space through a CIFS file share will really see nothing more than a folder. For all intents and purposes, they believe they are actually working with content in a folder.

In reality, however, you can make your spaces smart by wiring in business logic behind them. You can tell your spaces how to behave when certain things occur to them or within them. For example, you could tell your spaces to perform specific actions when content is newly placed within. You could tell them to launch workflows, automatically tag content, or fire off emails to notify collaborators of updates and activities.

You can do this because Alfresco provides out-of-the-box event handling for interactions with spaces and content. Alfresco fires events when interactions occur between a user or the environment and a piece of content. These events are like signals that your custom code or scripts can listen for. When they hear these signals, they can react.

The principal hook point for these interactions is achieved using aspects. You have seen aspects throughout this book. Aspects let you catch these signals and then act on them. They provide a code-level interface for intercepting the events and triggering a repository action as a response.

This means that you could write custom aspects to wire in some intense behavior behind your content spaces. This is ideal for developers and for testing. You can write custom handlers along with unit and integration tests.

However, there are many times when you do not need as much rigor. Alfresco makes things easier for non-developers by providing simple user interface tools for applying business logic behind your spaces.

Rules let you describe actions that should be triggered when one or more conditions are met. Rules were discussed in Chapter 13. They are accessible through Alfresco Explorer and appear as shown in Figure 14-2.

FIGURE 14-2

Figure 14.2. FIGURE 14-2

A rule fires when one or more of its conditions is met. For example, if a rule has a single condition for the content item's mimetype property to equal application/word, the rule will only trigger for Microsoft Word documents. When a rule triggers, it fires off one or more repository actions that you configure.

For example, you may tell the rule to copy the content item to another place in the repository or you may have it transform the content into another MIME type (such as PDF). A large number of repository actions are available out of the box for you to work with or you can add your own.

Alfresco makes things even easier by letting you create scriptable actions using server-side JavaScript. You can write your own JavaScript files and have them do anything you would like to your content.

JavaScript files can be defined in one of two places:

  • A file in the application classpath

  • Content in the Data Dictionary

Thus, you really do not have to do any development at all! Using rules and scripting, you can wire custom business logic into your space without the need for any Java code. No compilers, no server restarts.

Space Templates

Using content types, rules, and server-side JavaScript, you can implement a wide variety of custom workspaces. You may have elaborate folder structures or a complex chain of rules established. You may have set up permissions and groups exactly according to the needs of your project or task. It would be ideal if there were an easy way to capture and reuse that work!

Fortunately—you guessed it—there is! Alfresco lets you capture your smart spaces into space templates. A space template is a bit like a cookie cutter – you can apply it to any location in the repository and stamp out an exact copy of your entire preconfigured workspace. This includes

  • The entire folder structure of your project

  • All of the rules on the folders in your project

  • All of the permissions on the folders in your project

  • All of the server-side JavaScript or FreeMarker templates you have configured for the folders of your project

  • Any sample content you have placed in the folders of your project

You'll walk through the creation of a space template when you get to the "Putting It into Action" section. You'll actually build your Knowledge Base space as a space template. That way, you can stamp out Knowledge Base spaces very quickly (and so can anyone else)!

INSTALLING THE CODE

This section provides step-by-step instructions for installing this chapter's code into your Alfresco installation. It assumes that you have downloaded the sample source code from www.wrox.com. This is available as a ZIP compressed file.

Inside of the ZIP file, you will find the following folder structure:

/chapter14
      /extension
      /scripts
      install_chapter_14.bat
      readme.txt

If you've performed a default installation on Windows under the C:Alfresco directory, you can run the install_chapter_14.bat file to quickly install all of this chapter's sample code in one quick step! If you elect to do so, you can skip ahead to the section titled "Putting It into Action."

Otherwise, follow the manual installation instructions provided here. The sample files are assumed to have been extracted into a location referred to as <sampleLocation>. Bear in mind that the path references in this section use a Windows file convention. If you are using a non-Windows box (such as a Linux distribution), you will need to adjust the file paths accordingly.

Please read through the readme.txt file for last-minute updates and tips on installing the sample code.

Stopping the Alfresco Server

Before doing anything else, you should stop the Alfresco server. You can do this either from a command line or through the Windows Start menu (if you used the Windows Installer).

From the command line, type the following:

cd <installLocation>
alf_stop.bat

This shuts down Alfresco and returns you to the command prompt.

Adding the Knowledge Base Content Model

Begin by introducing the Knowledge Base content model to the Alfresco repository. This informs Alfresco how to deal with your Knowledge Base content types and aspects.

From the following directory:

  • <sampleLocation>chapter14extension

copy the following files:

  • kbModel.xml

  • kbModel-model-context.xml

to:

  • <installLocation> omcatsharedclassesalfrescoextension

Adding Alfresco Explorer Configuration

Next, you can plug in your Alfresco Explorer configurations. This enables the additional property sheets, wizards, and icons for your Knowledge Base space content type and Knowledge Base aspects.

From the following directory:

  • <sampleLocation>chapter14extension

copy the following files:

  • web-client-config-knowledgebase-config.xml

  • web-client-config-knowledgebase-context.xml

to:

  • <installLocation> omcatsharedclassesalfrescoextension

Adding the Knowledge Base Search Web Script

Finally, install the Knowledge Base Search Web script into the Alfresco repository.

From the following directory:

  • <sampleLocation>chapter14extension emplateswebscriptsorgalfrescoknowledgebase

copy the following files:

  • kb-search.get.desc.xml

  • kb-search.get.js

  • kb-search.get.json.ftl

to:

  • <installLocation> omcatsharedclassesalfrescoextension emplateswebscriptsorgalfrescoknowledgebase

PUTTING IT INTO ACTION

If you have followed the instructions, you should be ready to try things out.

Starting the Alfresco Server

You can start up the Alfresco server either from a command prompt or through the Windows Start menu (if you used the Windows Installer).

From the command line, type the following:

cd <installLocation>
alf_start.bat

This starts Alfresco and returns you to the command prompt.

Signing on to Alfresco Explorer

You are going to use Alfresco Explorer to set up the Alfresco Knowledge Base workspace. Follow these instructions:

  1. Open a browser and go to Alfresco Explorer. You can access Alfresco Explorer using the following URL: http://localhost:8080/alfresco

  2. Click the Login link at the top of the page to log in to Alfresco Explorer (see Figure 14-3).

    FIGURE 14-3

    Figure 14.3. FIGURE 14-3

You can use the administrator account with the user name admin and password admin. Your user dashboard will display once you log in.

Adding a Script to the Data Dictionary

The Alfresco repository provides a Data Dictionary into which you can place your custom script files. This is the ideal place for you to put your custom server-side JavaScript file.

You want to add a custom JavaScript file that will use the Alfresco Tagging Service to apply tags to your document. Tags are universal throughout the repository and they provide an elegant way to discover relevant information. By applying lifecycle tags to your documents, you simply make it easier for other people to locate knowledge in the Knowledge Base.

  1. Click the Company Home link at the top left of the page (see Figure 14-4).

    This takes you to the root space of the repository.

    FIGURE 14-4

    Figure 14.4. FIGURE 14-4

  2. On the left-hand side of the page you will see a Navigator view of the repository. Click the small arrow next to the Data Dictionary space to reveal the subspaces inside the Data Dictionary. You should see something like what is shown in Figure 14-5.

  3. Click on Scripts in the Navigator's subspaces. This will take you into the Scripts space. It should look a little like what is shown in Figure 14-6.

  4. Click the Add Content link at the top of the page. This brings up the Add Content dialog.

  5. Click the Browse button to select the file on disk you want to upload. In this case, upload the following file:

    <sampleLocation>chapter14scriptsadd-and-update-knowledge-base-tags.js
  6. In the Other Properties area, clear the check box.

  7. Click OK to upload the file.

  8. Click OK again to complete the installation. You should then see your file in the Scripts folder along with the rest of the out-of-the-box scripts.

FIGURE 14-5

Figure 14.5. FIGURE 14-5

FIGURE 14-6

Figure 14.6. FIGURE 14-6

Creating a Knowledge Base Space Template

Now you'll have some fun. You will create a Knowledge Base space template inside of Alfresco Explorer. In doing so, you're creating a "cookie cutter" that you can use to quickly stamp out preconfigured workspaces that implement all of your Knowledge Base functionality.

Creating the Space Template

Follow these instructions to create the Space template:

  1. Click the Company Home link at the top left of the page.

  2. In the Navigator view on the left-hand side of the page, click the small arrow next to the Data Dictionary space to reveal its subspaces.

  3. Click on Space Templates in the Navigator's subspaces. This will take you into the Space Templates space. You should only see one subspace inside, called Software Engineering Project.

  4. Click the Create menu to display options for content creation and select Advanced Space Wizard from the drop-down list (see Figure 14-7).

    FIGURE 14-7

    Figure 14.7. FIGURE 14-7

    This brings up the Create Space Wizard that lets you create different kinds of spaces.

  5. On the Step One - Starting Space page, choose the From Scratch option and click Next (see Figure 14-8).

    FIGURE 14-8

    Figure 14.8. FIGURE 14-8

    The next page you see will be titled Step Two – Space Options. This will show you the various kinds of spaces that you can create. Notice there is now an extra icon for a Knowledge Base Space (as shown in Figure 14-9). This is because you configured it to be thus using the Alfresco Explorer configuration file that you provided (web-client-config-knowledgebase-custom.xml).

    FIGURE 14-9

    Figure 14.9. FIGURE 14-9

  6. Select the Knowledge Base Space option and click Next.

  7. On the Step Three - Space Details page, enter the details about the Knowledge Base space you wish to create (see Figure 14-10), and then click Finish. In this example, you've elected to call the space template "Knowledge Base Project."

    FIGURE 14-10

    Figure 14.10. FIGURE 14-10

    You have created your Knowledge Base space. It should appear similar to Figure 14-11.

FIGURE 14-11

Figure 14.11. FIGURE 14-11

Adding an Archived Space

In the previous section, you created a space template for your Knowledge Base. So far, this space template is empty. Now you'll add an Archived subspace inside of it to store documents that have been moved into an archived lifecycle state.

Follow these instructions:

  1. Click on the Knowledge Base Project space template. This will navigate down into the Knowledge Base Project space. It should be empty right now.

  2. Click the Create menu to display options for content creation and select Create Space from the list.

  3. On the Create Space page, give the new space the name Archived. It should have a capital A. You can give it any description you like.

  4. Click Create Space to create the Archived space. When the Knowledge Base space refreshes, you should see your Archived folder there (see Figure 14-12).

Setting Up Content Rules

Now add some rules to the space. That way, when people stamp out a Knowledge Base space, you can provide them with some pre-wired behavior behind their space.

  1. Make sure you are in the Knowledge Base Project template space. You should see the Archived space within it, as shown in Figure 14-12.

    FIGURE 14-12

    Figure 14.12. FIGURE 14-12

  2. Click More Actions at the top of the page, and select Manage Content Rules from the drop-down list.

This will take you to the Content Rules page where you can see all the rules set up for this space. Currently there shouldn't be any so you will create a few. In fact, you will create three rules.

Rule 1: Apply KB Article Aspect and Tag Draft

The purpose of this rule is to automatically apply the kb:article aspect to any document that arrives into the Knowledge Base space. In addition, a server-side JavaScript will be executed that will update all of the tags on the newly arrived content.

  1. On the Content Rules page, click the Create Rule link. This opens the Create Rule Wizard that lets you create new rules.

  2. On the Step One - Select Conditions page, perform the following:

    1. In the Select a condition list, choose All Items.

    2. Click Add to List.

    3. Click Next.

  3. On the Step Two - Select Actions page, perform the following:

    1. In the Select an action list, choose Add aspect to item.

    2. Click Set Values and Add.

    3. In the Set action values list, select Knowledge Base Article.

    4. Click OK.

      You should now see Add aspect 'Knowledge Base Article' appear under Summary in the Selected Rule Actions area. Keep going.

  4. On the same page, Step Two – Select Actions, continue by performing the following:

    1. In the Select an action list, choose Execute a script.

    2. Click Set Values and Add.

    3. In the Set action values list, select add-and-update-knowledge-base-tags.js.

    4. Click OK.

    5. Click Next.

  5. On the third page, Step 3 – Enter Details, perform the following:

    1. In the Type list, select Inbound.

    2. In the Title field, type Apply KB Article Aspect and Tag draft.

    3. In the Other Options area, select the Apply rule to sub spaces option.

    4. Click Finish.

Rule 2: Apply Move Archived Documents to Archived Folder

The purpose of this rule is to automatically move some items into the Archived folder. The items that should be moved are any items where the kb:status property value is equal to "Archived."

  1. On the Content Rules page, click the Create Rule link to create a new rule.

  2. On the Step One - Select Conditions page, perform the following:

    1. In the Select a condition list, select Items with a specific text value in property.

    2. Click Set Values and Add.

    3. In the Property name field, type kb:status.

    4. Set the Operation to Equals To.

    5. For the Value field, type Archived.

    6. Click OK.

    7. Click Next.

  3. On the Step Two – Select Actions page, perform the following:

    1. In the Select an action list, choose Move item to a specific space.

    2. Click Set Values and Add.

    3. Click on the Click here to select a destination link.

    4. Click the Add icon (green + sign) in the same row as Archived. This selects the Archived folder.

    5. Click OK.

    6. Click Next.

  4. On the Step 3 – Enter Details page, perform the following:

    1. In the Type list, select Update.

    2. In the Title field, type Apply Move Archived Documents to Archived Folder.

    3. In the Other Options area, select the Apply rule to subspaces option.

    4. Click Finish.

Rule 3: Update Status Tag

The purpose of this rule is to automatically execute the server-side JavaScript responsible for updating tags on a document if a document is updated while it is in the Knowledge Base space.

  1. Click the Create Rule link to create a new rule.

  2. On the Step One - Select Conditions page, perform the following:

    1. In the Select a condition list, select All Items.

    2. Click Add to List.

    3. Click Next.

  3. On the Step Two – Select Actions page, perform the following:

    1. In the Select an action list, choose Execute a script.

    2. Click Set Values and Add.

    3. In the Set action values list, select add-and-update-knowledge-base-tags.js.

    4. Click OK.

    5. Click Next.

  4. On the Step 3 – Enter Details page, perform the following:

    1. In the Type list, select Update.

    2. In the Title field, type Update Status Tags.

    3. Select the Apply rule to sub spaces option.

    4. Click Finish.

That's all there is to it. You have created three business rules and wired them in behind your Knowledge Base space template. Now, whenever you work with content inside a Knowledge Base space these rules will be triggered automatically.

Creating a Knowledge Base

Now that you've built your Knowledge Base space template, you can use it to stamp out Knowledge Base workspaces quite easily. You'll create a test space under the Company Home space to see how it works.

Follow these steps:

  1. Click the Company Home link at the top left of the page. This takes you to the root folder of the repository.

  2. Click the Create menu to display options for content creation, and select the Advanced Space Wizard option from the list. This brings up the Create Space Wizard for creating different kinds of spaces.

  3. On the Step One - Starting Space page, choose the Using a template option and click Next.

    The next page you see will be titled Step Two – Space Options. Here, you will see a drop-down list in which all of the space templates appear. Notice that the Knowledge Base Project is available (see Figure 14-13).

    FIGURE 14-13

    Figure 14.13. FIGURE 14-13

  4. Select Knowledge Base Project from the drop-down list.

  5. Click Next.

  6. Give your new Knowledge Base space a name, title, and description. You might choose to use the values as shown in Figure 14-14.

  7. Click Finish to create the space.

FIGURE 14-14

Figure 14.14. FIGURE 14-14

With that, your new Knowledge Base space is created in the Company Home folder. You should see it appear alongside the other folders, as shown in Figure 14-15.

FIGURE 14-15

Figure 14.15. FIGURE 14-15

Contribute a Document

You can now create a Knowledge Base article and contribute it to your new Knowledge Base. You can do this using either Alfresco Explorer or CIFS desktop integration.

Using Alfresco Explorer

You can use Alfresco Explorer to create a Knowledge Base article and contribute it to your new My First Knowledge Base workspace.

  1. Browse into the My First Knowledge Base space by clicking on it in Alfresco Explorer.

  2. Click the Create menu for content creation options, and select Create Content from the list.

    You will use the Create Content Wizard to create a Knowledge Base article.

  3. On the first page of the Create Content Wizard, do the following (see Figure 14-16):

    1. In the Name field, type a name for your Knowledge Base article, such as Article1.txt. For this example, make sure it ends in .txt so you can treat the article as plain text.

    2. In the Type menu, select Content.

    3. In the Content Type menu, select Plain Text.

    4. In the Other Properties area, clear the check box.

    5. Click Next.

      FIGURE 14-16

      Figure 14.16. FIGURE 14-16

  4. On the second page, titled Step Two- Enter Content, type the following text content:

    A book is a gift you can open again and again.
  5. Once you have finished entering your content, click Finish.

Your content has been created. Your space titled My First Knowledge Base should appear similar to what is shown in Figure 14-17.

FIGURE 14-17

Figure 14.17. FIGURE 14-17

Using CIFS

Alternatively, you can contribute documents directly using the file system. If you are on a Windows system, this is easy to try out. All you need to do is map a drive to your Alfresco instance. Alfresco then appears on your desktop as a shared drive.

From a command prompt, run the following:

net use z: \<MACHINE_NAME>A

You can log in to the drive using the administrator credentials (admin/admin). Once you do that, you should have a Z: drive mapped to your desktop. You can browse this drive just as you would a normal drive or folder. You can even drag and drop content into this drive.

This means that you use your desktop applications to create documents and save them directly into Alfresco. Feel free to do so!

Editing Your Knowledge Base Article

If you like, you can modify the properties of your Knowledge Base article in Alfresco Explorer.

  1. Under the Article1.txt file in your Knowledge Base space, you will see a set of icons. Click the View Details icon. This icon is identified in Figure 14-18.

    You will now see the Details page. The Details page displays a pane that lists all the properties of your content item (see Figure 14-19).

    Notice that your additional kb:articletype and kb:status properties appear, exactly as you instructed.

    FIGURE 14-18

    Figure 14.18. FIGURE 14-18

    FIGURE 14-19

    Figure 14.19. FIGURE 14-19

  2. To edit these values, click the Modify icon on the top right of the Properties pane to bring up the Modify Content Properties page (see Figure 14-20).

    FIGURE 14-20

    Figure 14.20. FIGURE 14-20

    You can make any changes you like.

  3. Click OK to commit the changes and save your content item.

Seeing It in JSON!

So far, you've used Alfresco Explorer and/or desktop integration via CIFS to create and modify Knowledge Base articles. All of these articles are ultimately stored in the Alfresco repository as pure content objects with metadata, aspects, and content types, exactly as you prescribed.

You can now try fetching this content via HTTP by calling into your custom Knowledge Base Web script. The HTTP interface lets third-party systems or external applications (such as Alfresco Share) interact with your Knowledge Base and interrogate the data inside.

It's pretty simple to try this out. Just do the following:

  1. Open a new browser.

  2. In the URL field, type the following:

    http://localhost:8080/alfresco/service/knowledgebase/search

  3. Press Enter.

  4. If you are challenged for authentication credentials, just use the user name admin and the password admin.

If things are working correctly, you should be given back a JSON (JavaScript Object Notation) structure as a bit of text. You might see this show up in your browser or you may be asked to download it. You can simply save it somewhere and then open it inside of a text editor.

The JSON text is pure data. It contains the search results for content in the Knowledge Base. This includes your Article1.txt file. It is pure data – ready for consumption by external applications, including Alfresco Share!

SAMPLE CODE

This section provides sample code used in this chapter. This code is also available from www.wrox.com. This is available as a ZIP compressed file. The paths to source files mentioned in this section are relative to the root of the ZIP file.

Alfresco Repository

This section describes the configuration of the Alfresco repository. The following content model files should be placed into this directory:

  • <installLocation> omcatsharedclassesalfrescoextension

Defines the Knowledge Base content model

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

<!--                              -->
<!-- Knowledge Base Content Model -->
<!--                              -->

<model name="kb:contentmodel" xmlns="http://www.alfresco.org/model/dictionary/1.0">

   <!-- Metadata about the model -->
   <description>Knowledge Base Content Model</description>
<author>alfresco_professional</author>
   <version>1.0</version>

   <!-- Imports are required to allow references to definitions in other models -->
   <imports>
     <!-- Import Alfresco Dictionary Definitions -->
      <import uri="http://www.alfresco.org/model/dictionary/1.0" prefix="d"/>
      <!-- Import Alfresco Content Domain Model Definitions -->
      <import uri="http://www.alfresco.org/model/content/1.0" prefix="cm"/>
   </imports>

   <!-- Define the URI and Prefix for this content model -->
   <namespaces>
      <namespace uri="http://www.alfresco.org/model/knowledgebase/1.0"
      prefix="kb"/>
   </namespaces>

   <!-- Define constraints -->
   <constraints>

      <!-- Ensures that one of the allowed values is assigned -->
      <constraint name="kb:status_constraint" type="LIST">
         <parameter name="allowedValues">
            <list>
               <value>Draft</value>
               <value>Pending Approval</value>
               <value>Current</value>
               <value>Archived</value>
            </list>
         </parameter>
      </constraint>

      <!-- Ensures that one of the allowed values is assigned -->
      <constraint name="kb:articletype_constraint" type="LIST">
         <parameter name="allowedValues">
            <list>
               <value>Any</value>
               <value>Article</value>
               <value>FAQ</value>
               <value>White Paper</value>
            </list>
         </parameter>
      </constraint>
   </constraints>

   <!-- Content Types -->
   <types>
      <type name="kb:space">
         <title>Knowledge Base Space</title>
         <parent>cm:folder</parent>
      </type>
   </types>
<!-- Aspects -->
   <aspects>

      <!-- Marks a content item as having status -->
      <aspect name="kb:status">
         <title>Knowledge Base Status</title>
         <properties>

            <!-- Adds a new metadata property to the KB article -->
            <!-- Constrains the value -->
            <property name="kb:status">
               <title>Status</title>
               <type>d:text</type>
               <default>Draft</default>
               <constraints>
                  <constraint ref="kb:status_constraint" />
               </constraints>
            </property>

         </properties>
      </aspect>

      <!-- Marks a content item as a KB Article -->
      <aspect name="kb:article">
         <title>Knowledge Base Article</title>
         <properties>

            <!-- Adds a new metadata property to the KB article -->
            <!-- Constrains the value -->
            <property name="kb:articletype">
               <title>Article Type</title>
               <type>d:text</type>
               <default>Article</default>
               <constraints>
                  <constraint ref="kb:articletype_constraint" />
               </constraints>
            </property>

         </properties>

         <!-- Content with this aspect also receive kb:status aspect -->
         <mandatory-aspects>
            <aspect>kb:status</aspect>
         </mandatory-aspects>
      </aspect>

   </aspects>

</model>

Code snippet extensionkbModel.xml

Bootstraps the Knowledge Base content model into the Alfresco repository

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN'
'http://www.springframework.org/dtd/spring-beans.dtd'>
<beans>

<!-- Registration of new models -->
<bean id="kbmodel.extension.dictionaryBootstrap"
      parent="dictionaryModelBootstrap"
      depends-on="dictionaryBootstrap">
<property name="models">
<list>
<value>alfresco/extension/kbModel.xml</value>
</list>
</property>
</bean>

</beans>

Code snippet extensionkbModel-model-context.xml

Alfresco Explorer

The following files should be placed into this directory:

  • <installLocation> omcatsharedclassesalfrescoextension

Defines customizations for Alfresco Explorer

<alfresco-config>

   <!--  Configuration for the kb:article aspect -->
   <config evaluator="aspect-name" condition="kb:article">

      <!-- Display the kb:article properties -->
      <property-sheet>
         <separator name="sep" display-label="Knowledge Base Article Properties"
                    component-generator="HeaderSeparatorGenerator"
                    show-in-edit-mode="false"/>
         <show-property name="kb:articletype" display-label="Article Type"
                        show-in-edit-mode="true" />
      </property-sheet>

   </config>
<!-- Configuration for the kb:status aspect -->
   <config evaluator="aspect-name" condition="kb:status">

      <!-- Display the kb:status property -->
      <property-sheet>
         <show-property name="kb:status" display-label="KB Status"
                        show-in-edit-mode="true" />
      </property-sheet>
   </config>

   <!--  Configures the space wizards -->
   <config evaluator="string-compare" condition="Space Wizards">

      <!-- Allow for the creation of kb:folder instances -->
      <folder-types>
         <type name="kb:space" icon="/images/icons/space-icon-pen.gif" />
      </folder-types>

   </config>

   <!-- Configures the action wizards -->
   <config evaluator="string-compare" condition="Action Wizards">

      <!-- Allow the kb:article aspect to be added and removed -->
      <aspects>
         <aspect name="kb:article"/>
      </aspects>

   </config>

   <!-- Specify icon for the kb:space instances -->
   <config evaluator="string-compare" condition="kb:space icons">
      <icons>
         <icon name="space-icon-pen" path="/images/icons/space-icon-pen.gif" />
      </icons>
   </config>

</alfresco-config>

Code snippet extensionweb-client-config-knowledgebase-custom.xml

Bootstraps the Alfresco Explorer customizations into Alfresco Explorer

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN'
'http://www.springframework.org/dtd/spring-beans.dtd'>

<beans>
<!--  Bootstraps the Web client configuration -->
<bean id="kb.extension.webClientBootstrap"
      class="org.alfresco.web.config.WebClientConfigBootstrap"
      init-method="init">
   <property name="configs">
      <list>
         <value>
            classpath:alfresco/extension/web-client-config-
            knowledgebase-custom.xml
         </value>
      </list>
   </property>
</bean>

</beans>

Code snippet extensionweb-client-config-knowledgebase-context.xml

Data Dictionary Script

The following file should be copied into the Alfresco repository using Alfresco Explorer and placed in the following path:

  • /Company Home/Data Dictionary/Scripts

Updates the tags for a content item based on the content item's status

if (document.type != "{http://www.alfresco.org/model/content/1.0}thumbnail" &&
document.type != "{http://www.alfresco.org/model/content/1.0}folder")
{
 // All Knowledge Base status ids
 var kbStatusIds = ["draft", "pending", "current", "archived"];

 // Remove all previous status tags so you only have the latest one added
 document.removeTags(kbStatusIds);

 // Add a tag to reflect the status
 switch (document.properties["kb:status"])
 {
case "Draft":
 document.addTag("draft");
 break;

case "Pending Approval":
 document.addTag("pending");
 break;

case "Current":
document.addTag("current");
break;
case "Archived":
 document.addTag("archived");
 break;

default:
 }

 // Save changes
 document.save();
}

Code snippet scriptsadd-and-update-knowledge-base-tags.js

Knowledge Base–Search Web Script

The following files should be placed into this directory:

  • <installLocation> omcatsharedclassesalfrescoextension emplateswebscriptsorgalfrescoknowledgebase

Knowledge Base–search Web script descriptor file

<webscript>
   <shortname>Knowledge Base Search</shortname>
   <description>Searches for knowledge base articles</description>
   <url>/knowledgebase/search?maxResults={maxResults?}</url>
   <url>/knowledgebase/search/site/{site}?maxResults={maxResults?}</url>
   <format default="json">argument</format>
   <authentication>user</authentication>
</webscript>

Code snippet extension emplateswebscriptsorgalfrescoknowledgebasekb-search.get.desc.xml

Knowledge Base–search Web script controller

/**
 * KnowledgeBase Search Web Script
 *
 * Inputs:
 *   optional:  siteId = site ID to search in
 *   optional:  maxResults = max items to return.
 *
 * Outputs:
 *   data.items/data.error - object containing list of search results
 *
 * If siteId is null, the entire repository will be searched.
 */
/**
* Search constants
 */
const DEFAULT_MAX_RESULTS = 500;
const SITES_SPACE_QNAME_PATH = "/app:company_home/st:sites/";

/**
 * Performs a search for knowledge base articles in a site
 *
 * @method doSearch
 * @param siteId {string} The site to search in (or null to search full repository)
 * @param maxResults {int} Maximum number of results to return
 * @return {array} Articles matching the query in the same format that toArticle()
                   method returns
 */
function doSearch(siteId, maxResults)
{
   // The initial template
   var alfQuery='ASPECT:"{http://www.alfresco.org/model/knowledgebase/1.0}article"'
      + ' AND NOT TYPE:"{http://www.alfresco.org/model/content/1.0}thumbnail"'
      + ' AND NOT TYPE:"{http://www.alfresco.org/model/content/1.0}folder"';

   // if you have a siteId, append it into the query
   if (siteId != null)
   {
      alfQuery += ' AND PATH:"' + SITES_SPACE_QNAME_PATH + '/cm:' + siteId;
      alfQuery += '/cm:documentLibrary//*"';
   }

   // Perform fts-alfresco language query for articles
   var queryDef = {
      query: alfQuery,
      language: "fts-alfresco",
      page: {maxItems: maxResults},
      templates: []
   };

   // Get article nodes
   var nodes = search.query(queryDef),
      articles = [],
      item;

   // Turn nodes into article objects
   for (var i = 0, j = nodes.length; i < j; i++)
   {
      // Create core object
      node = nodes[i];
      item =
      {
         nodeRef: node.nodeRef.toString(),
         type: node.typeShort,
         name: node.name,
         title: node.properties["cm:title"],
         description: node.properties["cm:description"],
         modifiedOn: node.properties["cm:modified"],
         modifiedByUser: node.properties["cm:modifier"],
createdOn: node.properties["cm:created"],
         createdByUser: node.properties["cm:creator"],
         author: node.properties["cm:author"],
         nodeDBID: node.properties["sys:node-dbid"],
         properties: {}
      };

      // Calculate display names for users
      var person = people.getPerson(item.modifiedByUser);
      item.modifiedBy = (person != null ? (person.properties.firstName + " " +
                        person.properties.lastName) : item.modifiedByUser);
      person = people.getPerson(item.createdByUser);
      item.createdBy = (person != null ? (person.properties.firstName + " " +
                       person.properties.lastName) : item.createdByUser);

      // Add the Article namespace properties
      for (var k in node.properties)
      {
         if (k.match("ˆ{http://www.alfresco.org/model/knowledgebase/1.0}") ==
             "{http://www.alfresco.org/model/knowledgebase/1.0}")
         {
            item.properties["kb_" + k.split('}')[1]] = node.properties[k];
         }
      }
      articles.push(item);
   }

   return articles;
}

/**
 * The WebScript bootstrap method
 *
 * @method main
 */
function main()
{
   // Gather webscript parameters
   var siteId = url.templateArgs.site;
   var maxResults = (args.maxResults !== null) ? parseInt(args.maxResults) :
                    DEFAULT_MAX_RESULTS;

   // Perform search
   var articles = doSearch(siteId, maxResults);

   // Generate model from results
   model.data = {
      items: articles
   };
}

main();

Code snippet extension emplateswebscriptsorgalfrescoknowledgebasekb-search.get.js

Knowledge Base–search Web script JSON template

<#escape x as jsonUtils.encodeJSONString(x)>
{
   "items":
   [
   <#list data.items as item>
      {
         "nodeRef": "${item.nodeRef}",
         "type": "${item.type}",
         "name": "${item.name}",
         "title": "${item.title!''}",
         "description": "${item.description!''}",
         "modifiedOn": "${xmldate(item.modifiedOn)}",
         "modifiedByUser": "${item.modifiedByUser}",
         "modifiedBy": "${item.modifiedBy}",
         "createdOn": "${xmldate(item.createdOn)}",
         "createdByUser": "${item.createdByUser}",
         "createdBy": "${item.createdBy}",
         "author": "${item.author!''}",
         "nodeDBID": "${item.nodeDBID}",
         "properties":
         {
         <#assign first=true>
         <#list item.properties?keys as k>
         <#if item.properties[k]??>
            <#if !first>,<#else><#assign first=false></#if>"${k}":
            <#assign prop = item.properties[k]>
            <#if prop?is_date>
               "${xmldate(prop)}"
            <#elseif prop?is_boolean>
               ${prop?string("true", "false")}
            <#elseif prop?is_enumerable>
              [<#list prop as p>"${p}"<#if p_has_next>,</#if></#list>]
            <#elseif prop?is_number>${prop?c}
            <#else>"${prop}"
            </#if>
         </#if>
         </#list>
         }
      }
      <#if item_has_next>,</#if>
   </#list>
   ]
}
</#escape>

Code snippet extension emplateswebscriptsorgalfrescoknowledgebasekb-search.get.json.ftl

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.154.86