Java API for sending content to Drupal via Services API released

0

Written on September 30, 2012 by Allan Lykke Christensen

Just a quick post. For Converge, Raymond Wanyoike of I2M developed a pretty good API for sending content to a Drupal 7 installation from Java. The API requires that the Services API is installed and configured on Drupal, but once that is done you can transfer content directly from Java into Drupal. You can use the API by including the following Maven dependency in your code.

<dependency>
    <groupId>dk.i2m.drupal</groupId>
    <artifactId>services-api-client</artifactId>
    <version>1.0</version>
    <scope>compile</scope>
</dependency>
 
<repositories>
    <repository>
        <id>m2.i2m.dk</id>
        <name>I2M Maven Repository</name>
        <url>http://m2.i2m.dk</url>
    </repository>
</repositories>

Information on how to use the API can be found on the Bitbucket repo where the project is hosted: http://scm.i2m.dk/drupal-services-api/

LDAP Group Authentication with SugarCRM

3

Written on March 31, 2012 by Allan Lykke Christensen

For those of you who follow me on Twitter, you know that I’m not very pleased about the whole architecture and documentation of SugarCRM. Sugar is great out of the box, but if you try to do something slightly advanced it quickly becomes very troublesome. Anyway, this post is not to complain about SugarCRM, instead I wanted to show how set-up Sugar to authenticate users based on an LDAP server containing user groups.

Use Case

One of my clients is a medium-size media house with about 500 employees. 100 of those work in sales and customer relations. I was asked by my client to configure SugarCRM so that new users accounts would not need to be set-up for the 100 sales staff. Also, it was necessary that the other 400 staff do not get access to system. The client is using Microsoft Active Directory to authenticate users on the network and would like to reuse it for SugarCRM.

Implementation

The Active Directory is structured in the following way:

  • Users reside in the tree DC=mediacompany,DC=com
  • Groups reside in the tree OU=GROUPS,DC=mediacompany,DC=com

Step 1) Creating a CRM group on the LDAP server

Since access should be limited to a group of users, we’ll start by creating a group on the Active Directory called CRM where all the sales and customer relations staff are added. This group is called crm.

DN: CN=crm,OU=GROUPS,DC=mediacompany,DC=com

Step 2) Enabling LDAP Authentication

In SugarCRM, go to Administration and click Password Management. Scroll down to the bottom of the page and click “Enable LDAP Authentication”

The fields that must be filled out to enable LDAP Authentication

You can set-up Sugar’s LDAP authentication to allow any user residing on an LDAP server to be able to log-in, or you can set it up to only allow users in a particular group to log-in. In our use case I need it to check that the user is in a particular group (crm) before allowing them access.

Step 3) Specifying the LDAP server details

In the field “Server” we specific the address of the LDAP server prefixed with ldap:// (or ldaps:// for secure access). E.g.   ldap://172.16.20.1

In the field “Port” we specific the port that the LDAP server is bound to, E.g. 389

Tick the checkbox field “Authentication” at the bottom of the page. This is necessary for must Active Directory servers as you need an administrative user that can do the look ups in the directory. Enter the username (DN) of the user and the matching password. E.g. CN=Administrator,DC=mediacompany,DC=com as the username

Tick the checkbox field “Auto Create Users”. This will automatically create a SugarCRM for any user that has a valid account on Active Directory upon their first login. If you don’t tick this field you’ll have to still create the users one-by-one in Sugar.

Step 4) Specifying how to retrieve users

In the field User DN we specific the tree containing the users. If you have users stored in different leafs you can specific the base DN of your directory. In our case we use DC=mediacompany,DC=com as our User DN

In the field User Filter, we can specific a filter that should be used to filter users based on an attribute on your LDAP profile. Since we will use groups we can leave the User Filter empty.

In the field Bind Attribute enter the field that should be used to bind with the directory. In the case of Active Directory this field is userPrincipalName.

In the field Login Attribute enter the field that should be used as the username for logging into Sugar. I prefer that the name is the same as the username used for logging into machines on the network. In the case of Active Directory this field is sAMAccountName.

If you don’t want to authenticate against a particular user group you can skip the next step and save your settings and start authenticating against active users.

Step 5) Specifying how to retrieve groups and relate them to users

Tick the checkbox field “Group Membership”.

In the field Group DN you specify the tree containing all your groups. In our case this value is OU=GROUPS,DC=mediacompany,DC=com.

In the field Group Name you specific the name of the group that users must be a “member of” to be able to log-in. In our case this value is CN=crm (It’s important to remember the CN or whichever value you’ve chosen for the identifier of the group).

In the field User Attribute you specific the name of the attribute on the user record that will match with the member attribute on the Group record. In our case we store the complete distinguished name (DN) of the user in the record, and the value is therefore dn as this field contains the full distinguished name of a member.

In the field Group Attribute you specific the name of the field that contains the distinguished name of each member. In many LDAP servers the field uniqueMember is used, but on Active Directory the field member is used. Browse your LDAP directory to determine the field names to use.

That’s it! Well, not exactly, cause there is a bug in the codebase of SugarCRM. Actually it would all work up till when you specify the group membership. See the next step

Step 6) Patching the LDAP Group Membership code

This example is based on SugarCRM 6.4.0. It should work on previous versions as well. I’m not sure when they will fix the bug in in the code base, so you might find that this patch works in newer versions as well.

The problem is in the file LDAPAuthenticateUser.php located in modules/Users/authentication/LDAPAuthenticate in line 149.

The line says:

if(!isset($user_uid[0]) || ldap_count_entries($ldapconn, ldap_search($ldapconn,$GLOBALS['ldap_config']->settings['ldap_group_name'] . ",". $GLOBALS['ldap_config']->settings['ldap_group_dn']  ,"($group_attr=" . $user_uid[0] . ")")) ==  0){

Notice in the end of the line where it says

"($group_attr=" . $user_uid[0] . ")

The problem is that $user_uid[0] is not an array, it is a string containing the distinguished name of a user, e.g. CN=Allan Lykke Christensen,DC=mediacompany,DC=com. When you try to access a string as if it was an array, it will give you the character at the position, e.g. $user_uid[0] would return C in the example above. The fix is to remove [0] from $user_uid like so:

if(!isset($user_uid[0]) || ldap_count_entries($ldapconn, ldap_search($ldapconn,$GLOBALS['ldap_config']->settings['ldap_group_name'] . ",". $GLOBALS['ldap_config']->settings['ldap_group_dn']  ,"($group_attr=" . $user_uid . ")")) ==  0){

That’s it! Hope it’s been helpful.

LDAP Settings for Active Directory

Creating Composite Components in JSF2

0

Written on March 26, 2012 by Allan Lykke Christensen

I’m in the early stages of upgrading Converge from JSF 1.2 to JSF 2. I’ve been holding back for too long but finally decided that now is the time to get it done. Initially I was waiting for component libraries to be released for JSF 2. In the current version of Converge we are using RichFaces 3, which we’ve been very happy with (We tried out other component libraries but non of them worked out very well for us). However, with JSF2 it is now possible to easily create your own components using the Composite Components setup. For people who are sharp with client-side technologies such as Ajax, you may actually end up creating all your owner components rather than using the available third party libraries such as RichFaces, IceFaces and PrimeFaces. It is not that the third party libraries are bad, but with custom components you’ve got 100% control of exactly how your components get rendered. To give a small demonstration of composite components I put together a small simple example. The purpose of the example is to demonstrate the ease of creating components.

Open Data

Anyone body who knows me, knows that I love Open Data. I use a lot of datasets from Google Fusion Tables, Infochimps, and the numerous Open Data Initiatives (such as http://data.worldbank.org and http://data.un.org).  So, in my simple example, I’ll create a component that generates an HTML table based on an existing, public Google Fusion table.

Step 1: Defining the tag

The first step in creating a composite component is to define its interface (i.e. the attributes you allow developers to specify when using your tag). For our component we need the developer to specific which Google Fusion table to show data from. We’ll call this attribute tableId. We also need the developer to specific which fields of the table to display. We’ll call this attribute fields.

So our tag would look like this:

<my:fusionTable tableId="..." fields="..." />

Step 2: Creating the composite tag file

Composite component tag fields reside in the directory /resources/ of your web-application. By adding another directory in this directory you create a namespace for your components. In our case we use the namespace my so you’d have a directory structure like this: /resources/my/. Create a file in this directory called fusionTable.xhtml with the following content:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:cc="http://java.sun.com/jsf/composite">
 
    <!-- INTERFACE -->
    <cc:interface>
    </cc:interface>
 
    <!-- IMPLEMENTATION -->
    <cc:implementation>
    </cc:implementation>
</html>

The section <cc:interface /> is for defining what the component accept of attributes and action sources. The <cc:implementation /> section is for implementing the actual output of the component.

Since we already defined the attributes of the component we can declare it in the <cc:interface /> section like so:

<!-- INTERFACE -->
<cc:interface>
    <cc:attribute name="tableId" required="true" type="java.lang.String"  />
    <cc:attribute name="fields" required="true" type="java.lang.String" />
</cc:interface>

The section above declares the tableId and fields attribute. It also specifies that the two attribute are plain strings and that they are required.

Step 3: Implement the tag

Now that the interface is in place we need to specify the output of the tag. If you use the tag as it is now, it will require you to specify the declared attributes, but the output will be a blank screen. To get the content of a Fusion Table we use the public SQL API provided by Google. The API supports the JSON format which is convenient to work with in jQuery and JavaScript. To use jQuery in our component we must first download a copy of the jQuery library and place it in the /resources/js directory. Next we must indicate that the component needs this JavaScript to operate. We do that using the outputScript tag in <cc:implementation /> section:

<!-- IMPLEMENTATION -->
<cc:implementation>
    <h:outputScript library="js" name="jquery.js" target="head" />
</cc:implementation>

Note: If the jQuery script has already been included by another component or page, it will not be included again.

Next we need to call the Fusion Tables API using the getJSON jQuery function and process the output returned. We do all of this in a JavaScript contained in the implementation of the component:

    <!-- IMPLEMENTATION -->
    <cc:implementation>
        <h:outputScript library="js" name="jquery.js" target="head" />
        <script type="text/javascript">
            // URL encode the fields
            var fields = "";
            // Unique ID of the Fusion Table
            var tableId = "";
 
            // Construct the FusionTable service URL
            // Note: jsonCallback ensures that the call is jsonp
            var service = 'https://www.google.com/fusiontables/api/query?sql=SELECT%20' 
                + fields + '%20FROM%20#' + tableId + '&amp;jsonCallback=?';
 
            // Call the service and generate HTML based on the response
            $.getJSON(service, 
            function(data) {
 
                // Array used to collect HTML as the response is processed
                var items = [];
 
                // Generate the table header (columns)
                items.push('<thead>');
                items.push('<tr>');
                for (var key in data.table.cols) {
                    items.push('<th>' + data.table.cols[key] + '</th>');
                }
                items.push('</tr>');
                items.push('</thead>');
 
                // Generate the table data rows
                items.push('<tbody>');
                // Read data rows into an array
                for (var key in data.table.rows) {
 
                    items.push('<tr>');
                    for (var col in data.table.rows[key]) {
                        items.push('<td>' + data.table.rows[key][col] + '</td>');
                    }
                    items.push('</tr>');
                }
                items.push('</tbody>');
 
                // Output generated table
                $('<table />', { 
                    'class': '#{cc.attrs.styleClass}', 
                    'id': '#{cc.attrs.clientId}',  
                    html: items.join('')
                }).appendTo('body');
            });
        </script>

The URL for retrieving a Fusion Table is:

https://www.google.com/fusiontables/api/query?sql=SELECT fields FROM table&jsonCallback=?

The URL has two query parameters sql containing the SQL statement to execute and jsonCallback=? which allows the call to be turned into a JSONP call to avoid cross-domain query restrictions in the browser. Note that you must URL encode the query parameters to avoid problems submitting the query.

Once the query has been posted, the response is processed and the HTML of the component is generated by iterating over the content.

The last thing we need to do is to take the values entered by the developer and put them in the JavaScript. This is done by replacing the empty values in the beginning of the implementation section:

var fields = escape("#{cc.attrs.fields}");
var tableId= "#{cc.attrs.tableId}";

This will take the value specified in the fields attribute, URL encoded it, and store it in the JavaScript variable fields. The tableId does not need to be URL encoded and is copied across to JavaScript verbatim.

Step 4: Using the tag

All that is remaining now is to use the tag. Before we can use the tag we must first identify a Google Fusion Table and its fields. For my example I found a public Fusion Table containing the Corruption Index for 2011 by Transparency International. The field names are easy to see, e.g. 2011 rank (containing the ranking of a given country on the corruption index), Country / Territory (containing the name of the country), ISO (containing the ISO code of the country), etc. To find the TableId click File and select About. The TableID is the string specified as the Encrypted ID (in our case 1QWBy7LcULz6pN1SuHxm2HtSSd9jMg9IYbPDZRiM).

Using our component we want to show the ranking and name of the country. The component usage would therefore look something like this:

 
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:my="http://java.sun.com/jsf/composite/my">
    <h:head>
        <title>FusionTable Component Test</title>
    </h:head>
    <h:body>  
        <h1>Corruption Index</h1>
        <my:fusionTable id="tblCorruption" 
                        tableId="1QWBy7LcULz6pN1SuHxm2HtSSd9jMg9IYbPDZRiM" 
                        fields="'2011 rank','Country / Territory'" />
    </h:body>
</html>

Notice that field names with spaces must be included in single quotes.

That’s all. As you can see, it is really easy to create your own components. The speed of creation comes down to your skills with the client-side technology (e.g. jQuery). If you are terrible with HTML, CSS, JavaScript and jQuery, I’d suggest you stick to the available third party component libraries. If you are fluent in the client technologies and want full control over what you are doing you should go ahead and experiment with custom composite components.

Review: NetBeans IDE 7 Cookbook

1

Written on September 6, 2011 by Allan Lykke Christensen

NetBeans IDE 7 Cookbook. Click to go to Packt PublishingI recently got a copy of the newly release NetBeans cookbook from Packt Publishing. Being a huge fan of NetBeans I was excited to see a cookbook on the subject. The book is split into 12 chapters focusing on the main types of applications you can develop in NetBeans. Being a cookbook you can easily jump between the recipes based on what you you’re cooking. This is a great advantage if you want to learn something new in NetBeans without having to trawl through a lot of basic information. There are more than 70 recipes ranging for basic tasks such as debugging classes to more advanced tasks such as profiling your applications. My favourite recipes fall into the category of refactoring. The refactoring recipes saves developers an enormous amount of time. There is something for developers at all levels. Even if you are a seasoned NetBeans developer you’ll find some recipes that you’ve never heard of. For NetBeans newcomers there are many gems that will make your life easier. If you are studying or considering to study for the NetBeans Certification, this book is a great companion. My only critic of the book is that it could contain a few more advanced recipes for the routined NetBeans developers,

You can check out a sample of the book on the Packt Publishing website.

The book is excellent for beginners and because of that I give it 3.5 stars of 5.

Demonstration of Workflows in CONVERGE

0

Written on October 30, 2010 by Allan Lykke Christensen

To get some of the early adapters going, I’ve created a demonstration of setting up an outlet with a simple workflow. The video is about 45 mins. Enjoy.

Demonstration of the News Wire feature in Converge

1

Written on October 7, 2010 by Allan Lykke Christensen

Here’s a small video demonstration of the news wire services feature in Converge. The video shows how to subscribe to news wires and how to search subscribed news wires.

Preview of the Compare function in Converge

0

Written on October 5, 2010 by Allan Lykke Christensen

Oh man, time flies. Lately I’ve had absolutely no time to blog. In August my daughter Mackenzie was born and on top of that, every third week I am in Brussels working for PRO€INVEST (an EU organisation). A few weeks ago I picked up my work on CONVERGE, an Open Source Editorial Content Management System that I’m building for media houses. Last night I put a “Compare” function into the version view of a story. You can check it out here.

Compare preview from Allan Lykke Christensen on Vimeo.

This video previews the compare function in Converge

Review: JBoss AS 5 Development

0

Written on April 2, 2010 by Allan Lykke Christensen

JBoss AS 5 Development

Back in January I was about to embark on a new Java enterprise project. For the past few years I’ve mainly been doing Glassfish-based projects, but being frustrated with some of its features I decided to look into the JBoss Application Server. Prior to JavaEE 5 I used JBoss (4.0) and was very happy with it. Its ability to configure every aspect of the application server using XML files is fantastic when exercising continuous integration/deployment. Anyway, I changed to Glassfish due to its support for JavaEE5. So to catch up on the latest development in JBoss I decided to get “JBoss AS 5 Development” by Francesco Marchioni from Packt Publishing. Wow, was I surprised. The book was really excellent. The book starts with instructions on how to setup JBoss and get started. This was followed with a chapter on the new features of JBoss 5. The remaining of the book focuses on developing JavaEE5 components and configuring JBoss to get the most out of your applications. One of the things I really liked about this book was how many of the advice could easily be applied to other application servers. The main reason why I think this book is awesome is because it is great for developers who want to tweak and understand their application server. Many developers are use to having other people setup their application in production environments, but with this book you’ll gain the confidence to configure your application and server for a production environment.

Every application server should have a book like this!

You can check out a free chapter of the book here

LDAP Explorer 0.4 released

0

Written on March 6, 2010 by Allan Lykke Christensen

I managed to put the 0.4 release together before the original deadline of 13. March. In version 0.4 you’ll find:

  • Attributes are now sortable by clicking the column headings
  • Possible to give each LDAP server connection a label
  • Fixed NamingException when having more than one server connection / window open
  • Added connection timeout setting to LDAP server connection
  • More friendly attribute names
  • Support for Lotus Notes object classes
  • Silently accepts self-signed SSL certificates
  • Basic filtering

For the next release the UI will be changed slightly to accommodate query building and displaying of search results.

Note: From version 0.3 an update center was automatically created upon installation. To upgrade simply go to Tools – Plugins – Updates and click “Reload Catalog” followed by selecting the new version and clicking “Upgrade”

 

 

You can find the project site on Google Code: http://code.google.com/p/nb-ldap-explorer/

LDAP Explorer 0.3 and NetBeans Doxia Support

0

Written on February 27, 2010 by Allan Lykke Christensen

LDAP Explorer 0.3LDAP Explorer

This evening I released the third version of LDAP Explorer. The changes include:

  • Scrolling in the LDAP tree (could only view very small trees in 0.2 due to missing scrollers)
  • Replaced Swing-code with NetBeans classes (mainly replacing JTree with NetBeans nodes)
  • Nicer-looking icons + different icons depending on the type of LDAP entry
  • Includes an update center for ease of upgrading to future versions

You can grab a copy of the new version from the Google Code project page or the NetBeans Plugin Portal

NetBeans Doxia Support

In August 2009 I started a “NetBeans Goodies” project at Kenai.com where I intended to collect a bunch of NetBeans modules. The first Goodie would be support for APT files (Maven Doxia). If you’ve been reading my blog you’ll know that I got the basic code hacked together but then ran into some problems with defining the APT language in JavaCC. Anyway, This week I got prompted to continue the development of Doxia support by a keen user. I’ve therefore transfer the code from Kenai to Google Code and intent to pick up the coding in the upcoming weeks. You can find the project at Google Code. I haven’t released any versions of Doxia support yet, so if you want to give it a go you’ll have to check out the code from the Mercurial repository.

Previous blog entries about Doxia support: