« Posts under Programming

Friendlier Friendly URL Mapper for Liferay 6

It’s been a while since I written a post, but last Thursday I was working on Liferay portlet which involved using Liferay’s built-in Friendly URL Mapping functionality, and I hit a small snag which I thought I’d write about now.

I’m going to assume that you already know about Friendly URL Mapper in Liferay 6. If not then you should take a look at the Liferay Wiki page on it, or get the great Liferay In Action book, then come back here!

The Friendly URL Mapper is great. It’s quick and simple to set up, and hides a lot of the complexities of creating friendly URLs in Liferay. However it has one characteristic that I had to get rid of for my portlet. This was the Friendly URL Mapper prefix! If you have a look at the URL below between the two mentions of /wiki/ you’ll see what I’m talking about:

http://www.liferay.com/community/wiki/-/wiki/Main/FriendlyURLMapper

That /-/ is the Friendly URL Mapper prefix, and to my mind looks really bad! However I believe the reason behind it’s existence is also shown in the above URL. The prefix signifies the beginning of the Friendly URL, and the end of the actual URL. So you can have a page named the same as the as name of the mapping (as you can see the page above is “wiki” and the mapping is also “wiki”. With the code I’m showing you below, this won’t work so bare that in mind!

So there are two changes you need to make to your existing Friendly URL Mapping code to remove that prefix. The first is to create a new a class along the lines of MyPortletNameFriendlyURLMapper. This class needs to extend com.liferay.portal.kernel.portlet.DefaultFriendlyURLMapper. Then you all you need to do is override the isCheckMappingWithPrefix method of the BaseFriendlyURLMapper, by returning false. The code for this class can be seen below:

package com.mysmallcornerstudios.friendlierurlmapping.portlet;

import com.liferay.portal.kernel.portlet.DefaultFriendlyURLMapper;

public class FriendlierFriendlyURLMapper extends DefaultFriendlyURLMapper {

@Override
public boolean isCheckMappingWithPrefix() {

return false;

}

}

Then all we have to do is update the liferay-portlet.xml to say use our new FriendlyURLMapper class instead of the Default one, but the Default one is still doing most of the work for us. So in my liferay-portlet.xml I just change the <friendly-url-mapper-class> to the below:

<friendly-url-mapper-class>

com.mysmallcornerstudios.friendlierurlmapping.portlet.FriendlierFriendlyURLMapper

</friendly-url-mapper-class>

That’s it! Job done! So an example of what we’ve done here is change this URL:

http://mysite.com/somepage/-/friendlier/someParameter/

to:

http://mysite.com/somepage/friendlier/someParameter/

So it’s even friendlier to look at! The source code for this can be found in my GitHub repository called Liferay-6-Friendlier-Friendly-URL-Mapper. I’ve also added a WAR file to my repository so you can easily deploy this portlet. The WAR file can be found here.

I hope this helps people!

PowerShell: Creating & configuring a Active Directory user

This is a very bare bones PowerShell script for creating new users in Active Directory environment.

It can save huge amounts of time if you’re creating large numbers of new users as you can pipe values into the function like:

$firstNames = @("John","Jane")
$lastNames = @("Smith","Doe")

for ($i = 0; $i -lt $firstNames.Count; $i++) {
        Add-ADUser -FirstName $firstNames[$i] -LastName $lastNames[$i]
}

This basic skeleton can be changed to:

  • Have a different Login naming convention
  • Add more default groups
  • Add checks to change login names if it already exists

This will work with PowerShell version 1 and upwards.

If you have any questions, ask away in the comments section!

function Add-ADUser ($FirstName, $LastName) {

	$logon = $lastName + $firstName.subString(0,1)

	$domain = "DC=domainName,DC=com"

	# Bind to Users a particular OU
	$ou = [ADSI]"LDAP://OU=Users,$domain"

	# Create new user in AD
	$newUser = $ou.Create("user","CN=$lastName $firstName")

	# Bind common Mememberships
	$allUsers = [ADSI]"LDAP://CN=AllUsers,OU=Recipients,$domain"

	$groups = @($allUsers)

	# Modify new users details
	$newUser.put("sAMAccountName",$logon)
	$newUser.put("givenName",$firstName)
	$newUser.put("sn",$lastName)
	$newUser.put("DisplayName","$lastName $firstName")
	$newUser.put("userPrincipalName", $logon + "@domain.com")
	$newUser.put("profilePath","\\domainController\profiles\$logon")
	$newUser.SetInfo()

	$newUser.put("userAccountControl","512")
	$newUser.SetInfo()

	$newUser.psbase.Invoke("SetPassword","Password1")
	$newUser.psbase.CommitChanges()

	# Add user to required memberships

	foreach ($group in $groups) {
		$members = $group.member
		$group.member = $members + $newUser.distinguishedName
		$group.setInfo()
	}

        # Optional code for creating a Exchange Mailbox for the newly created user
	Enable-Mailbox -Identity "domain\$logon" `
		-Database "exchangeServer\Storage Group\Mailbox Database"
}

Powershell: Auditing Active Directory group

This is a bare bones Powershell script that is used for outputting the members of a Active Directory group, as well as the Managed By user.

You can pipe this to get a print out of multiple groups by doing:

“Group1″,”Group2″,”Group3″ | ForEach-Object { Audit-ADGroup -Group $_ }

This basic skeleton can be changed to work with:

  • A different LDAP / OU Structure
  • Output the groups in a more meaningful way
  • Add check to see if group exists

Add a comment if you have any questions or suggestions as to how you would improve this!

function Audit-ADGroup {
        param (
                [Parameter(mandatory=$true,Position=0)][ValidateNotNullOrEmpty()]
                [String]$Group
        )

        $grp = [ADSI]"LDAP://CN=$Group,OU=SomeOU,DC=SomeDomain,DC=com"

        [String]$managedBy = $grp.ManagedBy
        Write-Host "$Group " + $managedBy.Split(",")[0].Replace("CN=",""))

        $members = New-Object System.Collections.ArrayList

        foreach ($g in $grp.member) {
                $members.Add($g.Split(",")[0].Replace("CN=",""))
        }

        $members.Sort()

        $members | ForEach-Object {
                Write-Host $_
        }
}

How to install Apache, MySQL, and PHP (LAMP) on Ubuntu

This is a HOW TO guide to installing LAMP (Linux Apache MySQL PHP). This consists of Apache web server, MySQL database (as well as a DB tool), and PHP. Together these can be used to run as a local web server on your computer, using Ubuntu distribution of Linux. This is similar to WAMP, which is the Windows version.

The idea of this HOW TO is to explain how to get these working together, with little to no use of the Terminal Command Line, but I will give the command line interface (from now on I will call this CLI) as well as they do make life a little faster. For this we will be using the “Synaptic Package Manager” (from now on I will call this SPM) which can be found on Ubuntu in System -> Administration -> Synaptic Package Manager.

So first up we need to install the Apache Web Server. Type the following into the SPM Quick Search box:

apache2

If you add a space after it will be the first result returned, without and it will be the third. For all SPM options make sure you mark them for The command line alternative is (it assumes that you are running as a sudo user, this is the same for all CLI alternatives written here):

sudo apt-get install apache2

To check if this works, click http://localhost, which points to your new local web server. If the words “It works!” appear then everything is on track!

With Apache installed, we now want to install PHP. For this use either SPM and search for:

php5 and libapache2-mod-php5

Or using the CLI: sudo apt-get install php 5 libapache2-mod-php5

Next we need to restart the Apache server so it loads PHP. To do this without the CLI you need to use “Run Application…”, this can be found by right clicking one of the task-bars and and adding the “Run Application..” to the task bar panel. Once this is done type the following command:

gksudo /etc/init.d/apache2 restart Note: This will prompt for your password

Or using the CLI: sudo /etc/init.d/apache2 restart

Now you need to check that PHP is installed correctly. We need to create a small PHP file in the Web Servers directory that displays the PHP info. To do this we are going to run the following command under “Run Application…”:

gksudo gedit /var/www/testphp.php

Or using the CLI: sudo gedit /var/www/testphp.php

Once GEdit is open add the following line and save the file: phpinfo(); inside opening and closing PHP tags

Now check that this has worked by clicking : http://localhost/testphp.php

This should display all the information about the PHP configuration that’s just been installed. Now we move on to the last part which is to install the MySQL server. Using the SPM find and install:

mysql-server

Or using the CLI: sudo apt-get install mysql-server

This will run the MySQL set-up which will at some point prompt you for a root password. This is for root login to your MySQL server, and you’ll need to enter it twice.

After MySQL has been set-up there are two more packages that you need, the first is MySQL libraries for PHP 5, and the second is for Apache to use MySQL.

php5-mysql and libapache2-mod-auth-mysql

Or using the CLI: sudo apt-get install libapache2-mod-auth-mysql php5-mysql

Once these have been installed you need to tell PHP about the MySQL extension by editing the php configuration file. This can be done using “Run Application..” using:

gksudo gedit /etc/php5/apache2/php.ini

In this file you need to find the line that says ; extension=msql.so, remove the ; from the begining of the line, save and close the file.

That’s it, Apache, PHP & MySQL are all installed and set-up. However there is one more stage that might be of use. That is to install Navicat, which allows easy administration to a MySQL Database. First head to the Navicat Download Page and get the appropriate version. I use the Lite (non-commercial) version.

Once your downloaded the tar ball, extract it to where ever you want Navicat to be installed. To run it create a shortcut to the start_navicat file.

Scala – New alternative to Java!

SCALA to quote the scala website found here:

“Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java.”

In other words if you are a Java programmer like myself & you find yourself looking at your code and saying “I wonder if I could make that smaller” then Scala is the language for you!

The Scala syntax has several “shortcuts” that allow very clean & simple code that still greatly resembles Java syntax. So if you are a Java programmer you should be able read Scala code without looking much up. Anyway the best way to demonstrate this is by showing some actual Java & Scala code side by side.

So here is the code example for a very simple & boring “Hello World” style program!:

JAVA
public static void main (String [] args) {
    System.out.println("Welcome to My Small Corner Of The Web!");
}

SCALA
object HelloWorld extends Application {
    println(”Welcome to My Small Corner Of The Web!”)
}

So here we can see that even for just a simple program that the Scala syntax is a lot simpler. A better example to show the Scala power is shown below:

JAVA
public class Name {
    private String firstName, lastName;

    public Name (String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName(){
        return firstName;
    }

    public void setFirstName (String firstName){
    this.firstName = firstName;
    }

    public String getSecondName(){
        return secondName;
    }

    public void setSecondName (String secondName){
        this.secondName = secondName;
    }
}

public static void main (String [] args){
    Name n = new Name ("Joe", "");
    name.setLastName("Bloggs");
    System.out.println("Name: " + n.getFirstName() + " "         + n.getLasName());
}

So here we have a Java class that takes two parameters and holds two variables. There are also getter & setter methods for both variables. This is quite a lot of code for very little function, so in Scala we:

SCALA
class Name(var firstName:String, var lastName:String)

val n = new Name("Joe", "")

n.lastName = "Bloggs"

println("Name: " + n.firstName + " " + n.lastName)

So these two code snippets do exactly the same thing! That is a demonstration of how Scala can be used to write simple, clean, & elegant code.

This is only a very brief example of why Scala is a very possible alternative to Java or addition to Java (you can use Java & Scala code in the same project). However for a much more in depth look at Scala & a decent tutorial to start you off I would visit Daniel Spiewak’s Scala for Java Refugees. This is where I have taken these code snippets from, and where I learnt the basics of Scala.