In this chapter, we will cover:
Setting and creating a GUI language
Backing up your knowledge
Configuring MySQL as default rules repository
Configuring the repository files location
Obtaining resources using the REST API
Beyond rules authoring and knowledge centralization, which are the main purposes of Guvnor, there are some extra features that can help you in the rules management process. This chapter is focused on these non-authoring features, such as repository files storage configuration, external interaction with the repository using the REST API, and so on.
Guvnor allows us to change the default GUI language thanks to it being developed using internationalization support. In this recipe, we will see how to change the default language and how to create our own translation.
Carry out the following steps in order to change the default language:
Download Drools Guvnor 5.2.0.Final from http://www.jboss.org/drools/downloads/. Copy the guvnor-5.2.0.Final-jboss-as-5.1.war
file in a JBoss Application Server 5.1 and start it.
Open your web browser and type http://127.0.0.1:8080/guvnor-5.2.0.Final-jboss-as-5.1/
in the URL address bar, which will redirect you to the full URL address http://127.0.0.1:8080/guvnor-5.2.0.Final-jboss-as-5.1/org.drools.guvnor.Guvnor/Guvnor.html
. The following screenshot shows this.
Add the locale=pt_BR
parameter at the end of the URL to change the language to, for example, Brazilian Portuguese. In this case, the full URL will be http://127.0.0.1:8080/guvnor-5.2.0.Final-jboss-as-5.1/org.drools.guvnor.Guvnor/Guvnor.html?locale=pt_BR
. This is shown in the following screenshot:
Now, you are ready to use Drools Guvnor in another language. But if your language isn't available, you may like to take a look at the following sections in order to create your own customized GUI language resource.
Drools Guvnor was designed to support internationalization and localization to adapt the user interface to different languages. As you saw in the How to do it... section of this recipe, to use this feature you have to add the locale=$language
parameter at the end of the URL, where $language
can be one of the following supported languages:
es_ES:
Spanish
fr_FR:
French
ja_JP:
Japanese
pt_BR:
Brazilian Portuguese
zh_CN:
Chinese
What if Guvnor doesn't currently support your language? Well, you can always translate and create your custom bundle, and of course show your appreciation to the community by donating your translation.
In order to create your Guvnor translation, first you will have to obtain the source code following the latest available instructions at http://www.jboss.org/drools/. Once you obtain the source code, you will find the I8N
resource files inside the drools-webapp/src/main/java/org/drools/guvnor/client/messages/folder, as shown in the following screenshot:
Each of these properties files represents one translation bundle and the language can be discovered by taking a look at the filename (as you already figured out), where the Constants.properties
file is the default English translation.
The easiest step to start the translation is by creating a copy of the Constants.properties
file and changing the name by adding the localization ID at the end (for example, Constants_de_DE.properties
for a German translation). With this new file you can start to translate the values by opening it with a text editor or your favorite IDE resource bundles editor.
It has a simple format, as you can see in the following code snippet, where each line represents one of the strings to be replaced in the Guvnor UI and the right side is the current translation. If your language has non-standard characters they have to be replaced using Unicode characters, as you can see in the following Spanish translation excerpt:
Pattern=Patru00f3n: Assets=Recurso CreateNew=Crear Nuevo Category=Categoru00eda
Once you have finished all the translation, which will take some time because at this moment there are more than 1000 lines, you will have to compile the Guvnor source code to make the language available. To compile the source code, you need some knowledge about Apache Maven, but as a quick hint you can use the following command line to do a full build:
mvn clean package -Dfull
However, if you would like to skip the testing phase you can add the -DskipTests
parameter, shown as follows:
mvn clean package -Dfull DskipTests
Once the compilation is successful, the generated war
file can be deployed into a JBoss Application Server or a servlet container, and the translation can be accessed by adding the locale parameter into the URL address.
Lastly, don't forget to donate your translation to the community!
One of the most important tasks when you store data is backup, and this recipe will show how it can be done in Guvnor when you are using the default Jackrabbit file-based repository. This feature allows you to manually export all your data to back up your knowledge in case of information loss.
Carry out the following steps in order to create a backup of your knowledge stored in Drools Guvnor:
It's a simple task; open your favorite web browser. Type http://localhost:8080/drools-guvnor/
and once the application is loaded, select the Import Export option in the Administration section, as shown in the following screenshot:
In this new tab, you will see the options to import and export backups. Click on the Export button and a pop-up will appear on the screen, which will ask you for a confirmation. Once you agree, a database backup will be generated in a zipped file. Finally, the web browser will ask you to save the backup with a common save dialog.
The Guvnor data storage API is based on the Java Content Repository (JCR) standard, using the Apache Jackrabbit (http://jackrabbit.apache.org/) as the default implementation. Using a standard implementation, it's possible to interchange the JCR implementation without any issue.
Getting back on track, the backup option in Guvnor exports all the assets created with the UI in a ZIP file that contains a single XML file. In order to import this data, you will only have to use the Import option from the backup module.
Another optimization that can be added to Guvnor storage configuration is to use an RDBMS instead of storing the assets in a file directory. With this configuration, Guvnor will have a more solid storage engine and also will obtain more advanced storage features such as clustering, advanced backup system, and so on. This recipe will cover the configuration needed to change the JCR repository storage to use a MySQL database, but as you will see at the end of the recipe it's also possible to use another RDBMS.
The only requirement is to install a MySQL database on your computer. The latest Community Server can be downloaded from http://dev.mysql.com/downloads/mysql/. The installation and configuration procedure is far from the scope of this recipe, but instead you can follow the official documentation http://dev.mysql.com/doc/refman/5.5/en/ to achieve it.
Once the MySQL database is up and running, it is time to create the database and user permissions. Open a terminal or command-line console and carry out the following steps:
Log in as the root user using the MySQL command-line client:
shell>mysql -u root -p
Enter password:
Once you are logged in, create a guvnordb
database/schema with the following SQL query:
mysql> CREATE DATABASE guvnordb;
If you want to verify the schema creation, the available schemas can be displayed by executing the following query:
mysql>SHOW DATABASES;
After the schema creation you have to create the guvnor user
, which in this example only can connect to the database server from the localhost
host, and also assign an access password to the user:
mysql> CREATE USER 'guvnor'@'localhost' IDENTIFIED BY 'guvnor';
Once the user is created, the only remaining step is assigning it the full access permissions to the guvnordb
schema:
mysql>GRANT ALL PRIVILEGES ON guvnordb.* TO 'guvnor'@'localhost' WITH GRANT OPTION;
After the configuration of the MySQL database, you can start the migration of the current Guvnor storage configuration.
Carry out the following steps in order to configure a MySQL database to store your knowledge instead of using the default Apache Jackrabbit file-based storage:
In order to migrate to an existing repository, you will have to generate an information export, as was seen in the previous recipe, which will be used later to restore the information previously stored using the Apache Jackrabbit file-based storage. If you didn't start Drools Guvnor earlier, you will need to execute it once to create the default repository.xml
file that will be later modified.
Shut down the JBoss Application Server or the Servlet container where Guvnor is deployed if it's currently running.
Open the repository.xml
file with your favorite text editor, generated by default in the bin/
folder of the JBoss Application Server or the Servlet container directory, and be ready to search and replace XML tags.
Replace all the<FileSystem />
tags with the following configuration:
<FileSystem class="org.apache.jackrabbit.core.fs.db.DbFileSystem"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnodb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="FS_"/> </FileSystem>
Replace all the<PersistenceManager />
tags with the following configuration:
<PersistenceManager class="org.apache.jackrabbit.core.persistence.bundle.MySqlPersistenceManager"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="PM_WS_${wsp.name}_" /> </PersistenceManager>
Save the repository.xml
file and remove the repository
folder, which is going to be replaced with new data.
Download the latest MySQL Java Connector from http://dev.mysql.com/downloads/connector/j/5.1.html and copy the JAR file into the lib
directory of the JBoss Application Server or the Servlet container common libraries folder.
Start the JBoss Application or Servlet Container, and if applicable, import the backup generated in the first step as we saw in the previous recipe.
The default Guvnor storage implementation, Apache Jackrabbit, makes it possible to interchange the backend engine storage. By default, it uses an embeddable Java open source relational database, Apache Derby, as its Persistence Manager to store the Guvnor's assets into the file system. This Persistence Manager lets us configure it in an easy way to be used with one of the following RDBMS:
If your database engine isn't listed it is also possible to configure it using a generic Jackrabbit Persistence Manager.
In order to configure Apache Jackrabbit to use a different database, in this case MySQL, you have to configure the virtual file system, workspace, and versioning features configuration. Carry out the following steps in order to configure all the requirements:
The Virtual File System configuration is one level below the initial<Repository/>
XML tag under the<FileSystem/>
XML tag, and you can deduce how it simply stores the assets into the file system:
<Repository> <FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem"> <param name="path" value="${rep.home}/repository"/> </FileSystem> <!-- more configurations --> <Repository/>
Then, the first step to start the configuration is to change the FileSystem
class value to org.apache.jackrabbit.core.fs.db.DbFileSystem
and add the connection parameters, which are pretty similar to any JDBC configuration:
<Repository> <FileSystem class="org.apache.jackrabbit.core.fs.db.DbFileSystem"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="FS_"/> </FileSystem> <!-- more configurations --> <Repository />
There are three places where the FileSystem
configuration must be modified and all of them must have the same configuration. The other two are used to configure the workspace and versioning, and can be founded under the<Workspace />
and<Versioning />
tags respectively.
Once all the<FileSystem/>
tags are modified, it's time to configure the Persistence Manager. In this case, the<PersistenceManager/>
tag can only be modified in the workspace and versioning sections, which with the default file storage have the following configuration:
<PersistenceManager class="org.apache.jackrabbit.core.persistence.pool.DerbyPersistenceManager"> <param name="url" value="jdbc:derby:${wsp.home}/db;create=true"/> <param name="schemaObjectPrefix" value="${wsp.name}_"/> </PersistenceManager>
As you can see, the Persistence Manager relies on an Apache Derby Persistence Manager to store the assets, so we are going to change this to use a MySQLPersistenceManager
object and also configure the parameters' connections:
<PersistenceManager class="org.apache.jackrabbit.core.persistence.bundle.MySqlPersistenceManager"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="PM_WS_${wsp.name}_" /> </PersistenceManager>
Once the Persistence Manager is configured in the workspace and versioning sections, you have finished the repository XML configuration. Now, you will only have to download and copy the Java JDBC connector library of MySQL into the lib
directory of the JBoss Application Server or your Servlet container.
Finally, you can see an almost complete repository.xml
file with the relevant persistence modifications, shown as follows:
<?xml version="1.0"?> <Repository> <FileSystem class="org.apache.jackrabbit.core.fs.db. DbFileSystem"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="FS_"/> </FileSystem> <!-- securityconfiguration --> <Security appName="Jackrabbit"> <SecurityManager class= "org.apache.jackrabbit.core.security.simple.SimpleSecurityManager" workspaceName="security"> </SecurityManager> <AccessManager class= "org.apache.jackrabbit.core.security.simple.SimpleAccessManager"> </AccessManager> <LoginModule class= "org.apache.jackrabbit.core.security.simple.SimpleLoginModule"> <param name="anonymousId" value="anonymous"/> <param name="adminId" value="admin"/> </LoginModule> </Security> <Workspaces rootPath="${rep.home}/workspaces" defaultWorkspace="default"/> <!-workspace configuration --> <Workspace name="${wsp.name}"> <FileSystem class="org.apache.jackrabbit.core.fs.db.DbFileSystem"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="FS_WS_${wsp.name}_"/> </FileSystem> <PersistenceManager class="org.apache.jackrabbit.core.persistence.bundle.MySqlPersistenceManager"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="PM_WS_${wsp.name}_" /> </PersistenceManager> <SearchIndex class="org.apache.jackrabbit.core.query.lucene.SearchIndex"> <param name="path" value="${wsp.home}/index"/> <param name="supportHighlighting" value="true"/> </SearchIndex> <! - more configurations --> </Workspace> <Versioning rootPath="${rep.home}/version"> <FileSystem class="org.apache.jackrabbit.core.fs.db.DbFileSystem"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="Versioning_FS_"/> </FileSystem> <PersistenceManager class="org.apache.jackrabbit.core.persistence.bundle.MySqlPersistenceManager"> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="url" value="jdbc:mysql://localhost/guvnordb"/> <param name="user" value="guvnor"/> <param name="password" value="guvnor"/> <param name="schema" value="mysql"/> <param name="schemaObjectPrefix" value="Versioning_PM_" /> </PersistenceManager> </Versioning> <SearchIndex class= "org.apache.jackrabbit.core.query.lucene.SearchIndex"> <param name="path" value="${rep.home}/repository/index"/> <param name="supportHighlighting" value="true"/> </SearchIndex> </Repository>
For further information about the PersistenceManager
configuration you can take a look at http://wiki.apache.org/jackrabbit/PersistenceManagerFAQ.
Another option to create JCR database persistence configurations is using the Repository Configuration option that can be found in the Administration section, as shown in the following screenshot:
It comes with several predefined configurations that can be used to migrate the repository storage, and also allows you to create JNDI configurations to use together with data sources. Once you have selected the RDBMS, and clicked on the Continue button, four text boxes will be displayed to complete with the same information that was configured in the How to do it... section of this recipe, which is as follows and is also shown in the following screenshot:
Driver:
com.mysql.jdbc.Driver
URL:
jdbc:mysql://localhost/guvnordb
User:
guvnor
Password:
guvnor
When the Generate repository config is clicked, a ready-to-use repository.xml
file configuration will be displayed on the right side of the screen, as shown in the following screenshot, which can be saved by clicking on the Save Configuration button:
Once the file is saved into your hard drive, it is ready to replace the default Guvnor repository configuration file. Don't forget to add the appropriate JDBC library into the servlet container library
folder.
When you start the JBoss Application Server or servlet container where Guvnor was deployed, you will see how the repository configurations files are created in the directory where the servlet container was started. Instead of this, the best approach is to store the configuration in a secure and easy-to-identify directory. Let's see how this can be done.
The following steps will explain how to modify the default directory where the repository files are going to be stored:
First, you have to unzip the guvnor-5.2.0.Final-jboss-as-5.1.war
file and then delete or move this file to another directory.
Open the components.xml
file, located in the WEB-INF
folder, with your favorite text editor and identify the section where the repository component is configured, as you can see in the following XML code snippet:
<component name="repositoryConfiguration"> <!-- JackRabbit --> <property name="properties"> <key>org.drools.repository.configurator</key> <value>org.drools.repository.jackrabbit.JackrabbitRepositoryConfigurator</value> <!--<key>repository.root.directory</key><value>/opt/yourpath</value> --> </property> </component>
Uncomment the repository.root.directory
property key and assign the directory where you want to store the repository configuration files as the property value:
<key>repository.root.directory</key><value>/opt/configurations/</value>
Once the file is modified, zip the guvnor-5.2.0.Final-jboss-as-5.1
folder and rename the generated ZIP file with a .war
extension.
If you have data that was previously stored, you should move the files generated in the bin/
folder to the new storage folder. After this you are ready to start the JBoss Application Server or the Servlet Container where it was deployed.
Guvnor depends on JBoss Seam to configure features, such as the security management and the repository component. All these components are installed when the deployment scanner discovers a Java Bean annotated with an @Name
Seam annotation, and these components use the components.xml
configuration file to override or add the default properties.
Inside the components.xml
file you will find a section where the repositoryConfiguration
component is configured:
<component name="repositoryConfiguration"> <!-- JackRabbit --> <property name="properties"> <key>org.drools.repository.configurator</key> <value>org.drools.repository.jackrabbit.JackrabbitRepositoryConfigurator</value> <!-- <key>repository.root.directory</key><value>/opt/yourpath</value> --> </property> </component>
The important property here is repository.root.directory
, which is disabled by default, and is the one in which we are interested. By enabling this property key, you can specify the directory where the JCR repository files are going to be stored. Actually, it is really useful to know the location where these files are located instead of having them inside the bin
directory of the servlet container, where they can be accidently removed or can get lost in a migration.
Unzip the guvnor-5.2.0.Final-jboss-as-5.1.war
file and modify the files. Alternatively, you can use the GNU Midnight Commander to edit the components.xml
file (no need to unzip). Once you are done with modifying the files, you are ready to move your repository.xml
file and the repository
folder to the new location.
The Drools Guvnor 5.2.0.Final release includes a new REST API created to remotely interact with the repository to obtain resources such as packages, assets, and categories, update assets, invoke package compilation, and so on, without the need to use the GUI. In this recipe, you will learn how to interact with the repository using the API and the different format responses available.
Carry out the following steps in order to obtain the generated rule package using the REST API:
Create a new Maven project and add the following dependencies in the pom.xml
file:
<dependencies> <dependency> <groupId>org.drools</groupId> <artifactId>knowledge-api</artifactId> <version>5.2.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>5.2.0.Final</version> </dependency> </dependencies>
Create a GuvnorRestApi
Java class file in your project with the following code:
package.drools.cookbook; public class GuvnorRestApi { private String guvnorURI; public GuvnorRestApi(String guvnorURI) { This.guvnorURI = guvnorURI; } }
Add the following method in the same class file. This method will be used to create the connection with Drools Guvnor to obtain a compiled binary package:
publicInputStreamgetBinaryPackage(String packageName) throws Exception { URL url = new URL(guvnorURI + "/rest/packages/" + packageName + "/binary"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); connection.connect(); if (connection.getResponseCode() != 200) { throw new Exception("Bad response code: " + connection.getResponseCode()); } if (!connection.getContentType().equalsIgnoreCase( MediaType.APPLICATION_OCTET_STREAM)) { throw new Exception("Bad response content type: " + connection.getContentType()); } returnconnection.getInputStream(); }
Use the following code in a Java main
method to instantiate a GuvnorRestApi
object and interact with the repository using the REST API:
String guvnorURI = "http://localhost:8080/guvnor-5.2.0.Final-jboss-as-5.1"; GuvnorRestApi guvnorRestApi = new GuvnorRestApi(guvnorURI); InputStream binaryPackage = guvnorRestApi .getBinaryPackage("drools.cookbook"); KnowledgeBuilderkbuilder = KnowledgeBuilderFactory. newKnowledgeBuilder(); kbuilder.add(new InputStreamResource(binaryPackage), ResourceType.PKG); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnowledgeSessionksession = kbase.newStatefulKnowledgeSession();
The Guvnor REST API is implemented using the JAX-RS standard that allows you to communicate using the HTTP protocol, using the common PUT, GET, POST
, and DELETE
methods.
At this moment there are two exposed resources to interact with the repository:
Packages and Assets
Categories
The Packages and Assets resource is used to obtain the available packages and assets by sending a GET
method to the Guvnor REST URI. There are many available possibilities to obtain different information, for example, you can:
Obtain all the available packages and their assets using the following URI:
http://address:port/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages
Obtain specific information about a package with all its assets:
http://address:port/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages/drools.cookbook
Obtain the generated rules of a package:
http://address:port/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages/drools.cookbook/source
Obtain a package compilation:
http://address:port/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages/drools.cookbook/binary
Obtain all the assets from a specific package:
http://address:port/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages/drools.cookbook/assets
Using this URI, you can obtain specific information from an asset adding its name after it, and also you can add the /source
and /binary
parameters, as seen earlier, to obtain the source code or the binary compilation.
This API also can be used to create new assets or packages by sending a POST
message to the following URI:
http://address:port/guvnor-webapp/rest/packages
The assets and packages are also updateable by sending a PUT
message to the correct one of the following URIs:
http://address:port/guvnor-webapp/rest/packages/name/
http://address:port/guvnor-webapp/rest/packages/name/assets/name
Also, these resources can also be deleted with a DELETE
message to the previous URIs.
Those are almost all the available interfaces to interact with Guvnor using an HTTP communication. The last thing you should know is that these exposed resources expect information in one of the following formats:
Application/ATOM+XML
Application/XML
Application/JSON
Getting back on the recipe content, carry out the followings steps:
The first thing that you have to do is the configuration of the project dependencies. In this case, you have to add the minimum Drools dependencies, because in this recipe we are going to create a StatefulKnowledgeSession
using a binary package obtained from Guvnor using the REST API. Open the pom.xml
file and add the following dependencies in it:
<dependencies> <dependency> <groupId>org.drools</groupId> <artifactId>knowledge-api</artifactId> <version>5.2.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>5.2.0.Final</version> </dependency> </dependencies>
Once your project dependencies are updated then it's time to write some code. Create a GuvnorRestApi
Java class file in the project and add the following code:
public class GuvnorRestApi { private String guvnorURI; public GuvnorRestApi(String guvnorURI) { this.guvnorURI = guvnorURI; } }
This class doesn't say too much right now, so add the following code snippet inside this class to add the needed behavior in order to communicate with Guvnor and obtain a binary package:
publicInputStreamgetBinaryPackage(String packageName) throws Exception { URL url = new URL(guvnorURI + "/ rest/packages/" + packageName + "/binary"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); connection.connect(); if (connection.getResponseCode() != 200) { throw new Exception("Bad response code: " + connection.getResponseCode()); } if (!connection.getContentType().equalsIgnoreCase( MediaType.APPLICATION_OCTET_STREAM)) { throw new Exception("Bad response content type: " + connection.getContentType()); } returnconnection.getInputStream(); }
As you can see, the getBinaryPackage(String packageName)
method contains the logic to obtain a binary package opening a connection with the Guvnor REST resources using an HttpURLConnection
object.
This HttpURLConnection
object is created using a URL
object that contains the full URI, which in this case will be http://localhost:8080/guvnor-5.2.0.Final-jboss-as-5.1/rest/packages/drools.cookbook/binary
.
Once the HttpURLConnection
is created, you have to configure the request parameters before connecting to it. The REST resource should be invoked by sending a GET
method to obtain a binary package and configuring the request media type as application/octet-stream
using the Accept
request property:
connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_ STREAM);
Once the HttpURLConnection
is configured, you only have to connect with the REST resource and check the response code and the content type of the response:
connection.connect(); if (connection.getResponseCode() != 200) { throw new Exception("Bad response code: " + connection.getResponseCode()); } if (!connection.getContentType().equalsIgnoreCase( MediaType.APPLICATION_OCTET_STREAM)) { throw new Exception("Bad response content type: " + connection.getContentType()); }
Finally, you have to return the response, reading the connection with the getInputStream()
method of the HttpURLConnection
object.
Once you write this class, you are ready to use it to interact with the REST API. Create a Java main
method in the same class file with the following code:
public static void main(String[] args) throws Exception { GuvnorRestApiguvnorRestApi = new GuvnorRestApi("http://localhost:8080/guvnor-5.2.0.Final-jboss-as- 5.1"); InputStreambinaryPackage =guvnorRestApi .getBinaryPackage("defaultPackage"); KnowledgeBuilderkbuilder = KnowledgeBuilderFactory .newKnowledgeBuilder(); kbuilder.add(new InputStreamResource(binaryPackage), ResourceType.PKG); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); for (KnowledgePackagekpackage : kbase.getKnowledgePackages()) { System.out.println(kpackage.getName()); for (Rule rule : kpackage.getRules()) { System.out.println(" " + rule.getName()); } } StatefulKnowledgeSession ksession = kbase .newStatefulKnowledgeSession(); }
The purpose of this main
method is only to show you how to use the GuvnorRestApi
class to interact with Guvnor. In this main
method, you have to instantiate a GuvnorRestApi
object with the Guvnor URI as the constructor parameter. This URI is the same that you use to access the Guvnor GUI that was deployed in a JBoss AS or another servlet container:
GuvnorRestApi guvnorRestApi = new GuvnorRestApi("http://localhost:8080/guvnor- 5.2.0.Final-jboss-as-5.1");
Once the GuvnorRestApi
object is instantiated, you can use the getBinaryPackage(StringpackageName)
method to obtain the binary package of the package whose name used is as the method parameter. In this example, we are going to obtain the binary package of the defaultPackage:
InputStream binaryPackage =guvnorRestApi .getBinaryPackage("defaultPackage");
The execution of this method will return the binary package in an InputStream
object that you have to add into a new KnowledgeBuilder
object as a PKG Resource:
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory .newKnowledgeBuilder(); kbuilder.add(new InputStreamResource(binaryPackage), ResourceType.PKG);
After adding all the resources in the KnowledgeBuilder
object, you are ready to create a KnowledgeBase
object and then a StatefulKnowledgeSession
as you always do:
KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnoledgeSessionksession =kbase .newStatefulKnowledgeSession();
There's nothing remaining to do at this point, so you can start asserting facts into the StatefulKnowledgeSession
and firing rules as you usually do.
3.149.240.185