Search This Blog

Sunday, August 29, 2010

LDAP - Creating the root

To start with, we will need a root node under which other nodes will be stored. To store our data we need to dedicate a database to it. In this case we will use Berkley's DB (BDB or HDB).
Creating A Database :
Move to /etc/ldap ,Create a directory 'data' and move into it. Create a file in the current directory and name it db.ldif. Add the following content to it.

# Load dynamic backend modules
dn: cn=module{0},cn=config
objectClass: olcModuleList
cn: module
olcModulepath: /usr/lib/ldap
olcModuleload: {0}back_hdb

# Create the database
dn: olcDatabase={1}hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {1}hdb
olcDbDirectory: /var/lib/ldap
olcSuffix: dc=example,dc=com
olcRootDN: cn=admin,dc=example,dc=com
olcRootPW: 12345
olcDbConfig: {0}set_cachesize 0 2097152 0
olcDbConfig: {1}set_lk_max_objects 1500
olcDbConfig: {2}set_lk_max_locks 1500
olcDbConfig: {3}set_lk_max_lockers 1500
olcLastMod: TRUE
olcDbCheckpoint: 512 30
olcDbIndex: uid pres,eq
olcDbIndex: cn,sn,mail pres,eq,approx,sub
olcDbIndex: objectClass eq

Save it
Here we define our root node called as, and identified by DN (distinguished name) 'dc=example,dc=com'. We also create an admin for that node with password 12345, required for performing any actions on the root. Again, the password used here is plaintext and this password is used when we alter or perform any action within the root. You will see olcDbIndex attribute which tells the server what attributes it has to index.
Run
$sudo ldapadd -W -D 'cn=admin,cn=config' -f db.ldif
This will create your database. It will ask for a password which is the LDAP admin password we defined when creating an admin for the server (1234).

Next we create an entry for our root node. Create a file called root-node.ldif with following code.

dn: dc=example,dc=com
objectClass: dcObject
objectclass: organization
o: example.com
dc: example
description: My LDAP Root

Then run
$sudo ldapadd -W -D 'cn=admin,dc=example,dc=com' -f base.ldif
It will prompt for a password, which now is the password we defined in db.ldif, for the root node (12345).
Now our root is ready. Lets add child nodes to it, say for example, the organization 'example.com' has departments.
Create a new file departments.ldif and add data below to it.

dn: ou=department1,dc=example,dc=com
objectClass: organizationalUnit
ou: department1

dn: ou=department2,dc=example,dc=com
objectClass: organizationalUnit
ou: department2

Then add it.
$sudo ldapadd -W -D 'cn=admin,dc=example,dc=com' -f dept.ldif
Enter password (12345 in my case) and it should be added.
Find it in the root node.
$sudo ldapsearch -W -D 'cn=admin,dc=example,dc=com' -b 'dc=example,dc=com'
You will see entries for department1 and department2

Now lets add employees to the departments
For attributes or employees to be identified we have to add schemas(available in /etc/ldap/schema) to cn=config. Other way is including the path in the ldif file itself.
$sudo ldapadd -W -D 'cn=admin,cn=config' -f /etc/ldap/schema/cosine.ldif
$sudo ldapadd -W -D 'cn=admin,cn=config' -f /etc/ldap/schema/inetorgperson.ldif
Password is 1234 because this is cn=config

In emp.ldif file

dn: uid=johnsmar,ou=department1,dc=example,dc=com
objectClass: inetOrgPerson
sn: Smart
cn: John Smart
mail: john.smart@example.com
postalCode: 31000
mobile: +33 (0)6 654321
title: Supervisor
postalAddress: h23, smart lane

dn: uid=tonygeek,ou=department1,dc=example,dc=com
objectClass: inetOrgPerson
sn: Geek
cn: Tony Geek
mail: tony.geek@example.com
postalCode: 31001
mobile: +33 (0)6 123456
title: Clerk
postalAddress: h26, geek tower

dn: uid=davidlazy,ou=department2,dc=example,dc=com
objectClass: inetOrgPerson
sn: Lazy
cn: David Lazy
mail: david.lazy@example.com
postalCode: 31000
mobile: +33 (0)6 78987
title: Supervisor
postalAddress: h27, lazy street

Then
$sudo ldapadd -W -D 'cn=admin,dc=example,dc=com' -f emp.ldif
This will add 3 employees,2 (john and tony) to department1 and 1 (david) to department2.

$sudo ldapsearch -W -D 'cn=admin,dc=example,dc=com' -b 'dc=example,dc=com'
You should get the entire hierarchy now.

Got my LDAP server finally running and up on Ubuntu.

In some discussion on database performance i came across this term called LDAP. LDAP (Lightweight Directory Access Protocol), yes sounds simple but i almost spent a whole day understanding what it is and getting its server(OpenLDAP) running on Ubuntu. LDAP is a protocol(Not a database or dbms) and from what i understood, its 'like' an interface for data that makes retrieval easy and quick. It represents data in the form of directories (hierarchy,tree). There is a root node under which all your data is stored as child nodes. The fact that its quick is due to its ability to maintain an index for desired attributes. But the performance of LDAP usually depends on where it is been used. For optimal performance, the reads are expected to be huge compared to writes. The reason being the index, which in opposite case will need lots of updates and make it slow.

The form in which the data is represented by LDAP may not be how it is stored. LDAP can use different backends to save its data, like berkleys database (bdb), mysql etc you just need to specify which one to use and not how to use.

Next thing was to run the OpenLDAP server, and was heck of a job. OpenLDAP went a crucial change but its documentation did not. I referred to old documentations initially (readily available) and found most of the things missing in my current server, specially the slapd.conf configuration of the OpenLDAP server slapd. Later i came to know that versions from 2.3 allow dynamically configuring the server and does not use slapd.conf for this purpose. slapd.conf may be still used but any updates to it need server restart.

What i Expected
During installation process it was supposed to ask for a fresh password.
There was supposed to be slapd.conf.

What i found
No password is asked. So there is some other way of configuring your server.
slapd.conf in new versions is replaced by slapd.d or cn=config which holds the ACLs or access control list, backend information and root information.

Installing OpenLDAP on Ubuntu
$sudo apt-get install slapd ldap-utils
The server and utilities will be installed and the slapd server will start.
To completely remove the OpenLDAP for fresh install :
$sudo dpkg --remove slapd ldap-utils
$sudo dpkg --purge slapd ldap-utils
To configure(initial) OpenLDAP :
$sudo dpkg-reconfigure slapd
To start,stop,restart :
$sudo /etc/init.d/slapd start
$sudo /etc/init.d/slapd stop
$sudo /etc/init.d/slapd restart

Creating Admin
Since no password was asked during installation we will have to create one for us.
It is better we create a separate directory to store our ldif files, say initialize created in /etc/ldap. ldif (ldap data interchange format) files are used as a medium for communicating to the server. Move to the initialize directory.
$cd /etc/ldap
$sudo mkdir initialize
$cd /initialize
Create a file called admin-create.ldif which will contain our new password.
$sudo nano admin-create.ldif
Change the password(olcRootPW) and paste this code into above file :

dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootDN
olcRootDN: cn=admin,cn=config

dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: 1234

Save it.
The password used above is in plaintext and not secure. To generate encrypted password use slappasswd utility.
$slappasswd -h {MD5}
$slappasswd -h {SSHA}

Next we have to add that information it to cn=config like this :
$sudo ldapadd -Y EXTERNAL -H ldapi:/// -f admin-create.ldif
Admin has been created.

Trying the admin privileges.
$sudo ldapsearch -W -D 'cn=admin,cn=config' -b 'cn=config'
You will get lots of entries, one showing your password if it is not encrypted.

Please feel free to correct me if i am wrong or my concepts are wrong.
In my next post i will write about creating root node and adding child nodes.
Code Connect

Thursday, August 26, 2010

Connect Java with MySql database

This is a simple Java code which connects to a mysql database, adds and retrieves data from it. For that purpose we will need the mysql driver for java, which can be downloaded here : MysqlConnectorJava
Extract it to a appropriate location (preferably where java is installed)
The folder contains the driver file named mysql-connector-java-5.1.8-bin.jar whose location has to be added to the CLASSPATH so that java finds it.

In windows CLASSPATH can be accessed from My Computer(right click)->properties->Advanced tab->Environment Variables. In system variables if you see a variable named CLASSPATH, edit it and append the driver path for ex. 'C:\j2sdk1.4.2_15\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar' to the existing value with ';' seperating each entry in classpath.

Or open the command prompt and type -> 

set CLASSPATH=%CLASSPATH%;C:\j2sdk1.4.2_15\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar

replacing my path with yours. Type set CLASSPATH to verify if it has been added to CLASSPATH variable.

In linux shell>
setenv CLASSPATH /path/mysql-connector-java-[ver]-bin.jar:$CLASSPATH

The following code is supposed to create a database, add data to it, read the added data and finally drop the database. The database user is 'root' with password 'password'

The Code


Wednesday, August 25, 2010

Show IFrame content in plain-text using javascript/jquery

Today i was working on a html page, wherein another page would be displayed in an iframe and the user gets an option to see the iframe's html. Using raw javascript it became bit confusing and i didn't get the desired result , so i switched over to my favorite jquery. Jquery fulfilled 2 of my requirements at once. First one was retrieving the code and second converting html characters to corresponding html character codes so that it shows up as text and not in rendered form. Next it would display the text in a textarea.

Note: Only content on local domain is accessible for security purpose, so it may not be possible to show html content of pages external to the local domain even though the page loads in iframe.

Key Components :
$.get(url,callback-function) : A get request for retrieving the iframe html page
$('textarea').text(data) : For html conversion

How it works :
On a click of the specified entity, the jquery makes a request for the desired page using $.post() function. The iframe source url is retrieved using $('iframe').attr('src'). $get(url,callback-function) in this case takes 2 arguments, the url will be the iframe location and callback-function is the function called on the event of success. The callback-function gets the received data as argument
In the callback-function we use $('textarea').text(data) to convert the received data to code form and set it as the content of textarea.

The Code :




Wednesday, August 18, 2010

Time for some SEO

This blog is new and not yet been indexed by any search engines. So i will start the experiment of getting my blog indexed by using some of the primary techniques that i learnt while running my previous blogs.
First interesting thing to notice is that google quickly notices new blogs on blogger/blogspot, the reason being simple, google owns it. So if you are planning to start a blog, it is preferred to get one on blogger and later switch (provided domain name remains same).
Next on the list is submitting your blog link to social bookmarking (SB) sites. The reason being, the content of these SB sites frequently change as a result google bot also has to make frequent visits there to keep its data updated. Google will index your pages once it finds your blog link on such sites. I have built up a list of some social bookmarking sites.

Add your sites here :
Twitter
Digg
Mybloglog
Technorati
Blogcatalog

I added my blog to all these, and the quickest one to show my blog in google search was digg (same day), next day result from technorati showed up.

You can use one of the following tools to ping/notify the major search engines.

Ping Tools :
Pingoat
Pingomatic
Ipings

Tuesday, August 17, 2010

Add Settings/Options Page To Wordpress Theme


If you have developed a theme for wordpress and wondering if you could have a settings/options page, here is a quick tutorial. Having a custom theme settings page has its own advantage over hard-coding it. It avoids frequent edits to code, eases and simplifies operation, saves time and has lot many other benefits. Okay so lets move on.



The Logic :
Wordpress is a powerful framework that lets you add so many functionalities to your site. In this case we are concerned about what are called as 'hooks' that wordpress provides. Hooks are of 2 types Action and filter. As the name suggests action hooks are meant to perform some action on occurrence of some event while latter is used to modify the existing functions as per your convenience.

Here we make use of action hooks. I will be creating a settings page that will allow editing a custom content say a marquee somewhere on the page. To start with, we open the functions.php file, which is included on every page as long as your theme is active. Here we get a chance to define our starting or triggering point. We start off by registering our action hooks. We will use 3 hooks :
1)admin_menu : actions to be performed when admin enters the control panel or settings
2)switch_theme : actions to be performed when admin changes the theme
3)wp_head : actions to add something in the head section when header is requested.

Initialization :
Unfortunately there is no hook to define our initialization routine. So we use another method to detect theme change from previous theme to your theme. We analyze the parameters in the url for keyword 'activated' while on 'themes.php' page.
The code :



This code above will go into functions.php anywhere after the initial declarations. It will create a table in database called wp-prefix_mytheme_data where we can store our theme data. Manipulate the query based on your needs.

Registration :
We will use admin_menu hook to add our Theme Settings link to the sidebar.
The Code :



The above hook will call the add_to_menu function which will register the settings page defined in settings_form function.

In action :
We will use wp_head to add data(java scripts) to the head section.
The Code :



The above code will add jquery and jquery code to the head. In my theme i will have a div with id="marque-area", and the marquee with my data will be added within this div.

Unregister :
we will use switch_theme to destroy all the data after theme deactivation
The Code :



We have destroyed everything we had created as user no longer uses our theme.

Combine these codes into one contineous code and add it anywhere in functions.php file(Take care of php open and close tags)
Final Code :


Monday, August 16, 2010

Image preloaders and progress bar : Part 3

Till now we have seen how we can tackle with the images within the html code. But in most cases the number of images in CSS is much greater than the img tags within the html. Also we cannot use our normal element referring for css images. So we have to extract them ourself.



The logic :
First we grab all the css linked to the html document, merge them into one and then search for the images. The images are identified by their extension. So we use a regular expression to get the image url within background-image:Url('') property. We also have to extract all inline image urls using jquery. Next we merge both these lists of css and inline images and start preloading.

The Issues :
The first issue that come up when implementing this technique is the way in which the browser represents the url in css. For eg. Firefox uses a relative url (/images/xyz.jpg) where as chrome uses an absolute url (http://yoursite.com/images/xyz.jpg).
The second issue is the way in which css content is retrieved by browsers. In IE stylesheet content is retrieved by using StylesheetObject.cssRules.cssText whereas in other browsers it is retrieved using StylesheetObject.cssText.

The Code :






Still this code is not 100% compatible and will work only for css images that are referenced using url relative to the root (eg. /images/xyz.jpg). But i guess u must have got an idea of what i am trying to do. If you have any ideas please post them in comments.
This ends up the preloader tutorial. Have a nice day :)

Saturday, August 14, 2010

Image preloaders and progress bar : Part 2

In the previous post we had seen how we can create a simple progress bar, but it did not have any image preloader script and just depended on 2 events. In this post we will see how we can create a progress bar with simple image preloader, this means it will show the actual progress based on the total images loaded.


The Logic :
The basic requirement for this script is the knowledge of how many images exist. So for that purpose we have to count the number of images in the document. In this simple preloader, we will consider only the images in img tags. Jquery provides a powerful function for counting these or any other tags. We just have to say $('img').length() and we get the total count of the given element. Next we find the percentage each image contributes to the total.
Once we have the count we have to find the sources of these images so that they can be loaded one by one. While loading the image we also assign event trigger to the image so that it notifies us that it is loaded and we can proceed with incrementing the progressbar by the smallest percentage.
Once the percentage reaches 100% we can fade out the overlay screen.

The code :




So this was a simple preloader with progress bar which took all the html images into consideration. In our next post we will make our script a bit complex by taking the css images into consideration.

Have a nice day :)

Tuesday, August 10, 2010

Image preloaders and progress bar : Part 1

Are you looking for a preloader that shows a loading screen while your page is been loaded?. Here is a quick tutorial on creating one.


The Theory :
Lets look into the page components that should be taken into consideration while showing the load progress. First is the document itself that is been loaded which is pretty small and also cannot be analyzed as that itself will contain our preloader code. Next components are external stylesheets, scripts and other linked materials. Browser usually loads them before executing any javascript. So this either cannot be counted. The major components are images which are usually large in number and huge as well. In this tutorial we will use jquery for animating the progressbar. We will first make a simple preloader with a progressbar. Lets take a quick look on two functions in javascript/jquery: $(document).ready() and $(window).load() . The first function,as the name suggests, is called by the browser as soon as the script is completely loaded. This marks the start point of our preloader. The second function is called by the browser when all the components on the page are loaded. This marks the end point.

First lets create a simple preloader with progress bar :

The Logic :
We will divide the page contents into 2 parts(50% + 50%) : The text and The images. The point at which our script will start will give an indication that the html text has been loaded. At this point $(document).ready() will be triggered. Hence we can increment the progressbar to 50% of its area. Next the loading of images will occur, and once complete it will call $(window).load(). Now we can increment the progressbar to 100%, following it, a fade out effect.

The code :





This was a simple preloader... in the next post we shall consider counting the total images and then showing the real progress on the progressbar.

Sunday, August 1, 2010

What Programming is all about.

Okay this is my first post on this blog. This post closely relates to my life in the journey of programming. Today most of us are dependent on computers, may be it for work, for leisure or rather most of our work. Its surprising to see the advancement done in this field. There were days when a simple '16 bit' games like Dangerous Dave were favourites and downloading an mp3 used to take an hour. But advancement in hardware has led to even faster advancement in software. So a person entering this field of programming has to cope up with the current speed. The outdated technologies may have been vanished from the software industry but have always served as a base for new ones. Here in this post i am listing the primary languages that a programmer should know in chronological order. I'd like to start off with an overview of kinds of programming a programmer is involved in. I like to classify these kinds based on the following three fields :

1) Embedded Systems Software
2) Computers Software
3) Web applications

The reason behind this classification being, each of them can survive as an independent industry.

The niche of embedded systems deals with programming the microcontrollers. The language used for programming these tiny microcontrollers is Assembly language. Each microcontroller has its own set of instructions (Instruction set) but the basic instructions remain the same. This language is easy to learn and the real deal is watching these programs in action. You could write programs to turn on or off the LEDs, run a stepper motor, do some calculations, communicate to other devices, etc. These microcontrollers are now available at a very low costs. One of the famous 8 bit µC(microcontroller) is 8051, which has 128 bytes RAM and 4Kb of ROM. Since most of the µCs have ROM to store programs, testing becomes a difficult part. Hence the program needs to be finalized first, then tested and once its bug free it is burnt on the ROM. You must be wondering about how one could test the program without burning it on the µC?. The answer is using Simulators. Simulators create an environment similar to the µC on the computer. They have all the features and resources that a µC has (resources being virtual), but also includes extra tools which help in debugging (The primary reason for using simulators). You can actually monitor the running of program and the resources used and once satisfied you can burn the program on the µC. One of the simulator which simulates 8051 µC is EdSim51. Here are some interesting examples of 8051 programs by Mike Predko. Complex embedded systems make use of operating systems like embedded linux, specially designed to take care of limitations of the system(eg. mobile) and use modules to do application specific tasks.

Now lets move on to computer softwares. Usually programmers start with learning languages like C. C is a powerful language which can be used to write programs ranging from simple console applications to applications with GUI(Graphical User Interface). It serves as a strong base to learning the programming techniques. It gives the 1st feeling of what programming is. Once familiar with the syntax and data structures, next stage introduces a new language C++ with new concept. C++ is an object oriented programming (OOP) language where everything is considered as an object. The syntax however remains similar to C. C++ is usually followed by adapting to Java, another powerful OOP language which claims to be platform independent, ie. it can run on any machine unlike C and C++. Syntax is a bit different but influenced by C and C++. Next comes a language which is widely used to create applications with GUI easily and called Visual Basic(VB). It is an event driven programming language by Microsoft i.e. doing a particular task when something occurs. eg. showing a message on button click where button click is an event and showing of message is a task. At this stage, there is also a need felt to efficiently store data, where Databases come into picture. GUI serves as the front end while database serves as the back end. Microsoft provided an Integrated Development Environment (IDE) for developing VB applications. Structured Query Language (SQL) is a common language to query the databases.
VB was followed by VB.NET which added more features and functionality to existing VB.

Web is a very interesting and one of the very advanced field. Today every one is aware of web and taking the full advantage of it. Its members are increasing from the users side as well as developers side. Okay so lets start with the basic element of world wide web, the HTML(Hyper Text Markup Language). Using HTML we could create web pages, but it did not give it a professional look. To make it better CSS (Cascaded Style Sheets) were used which allowed elements in the HTML to be styled and properly arranged, made web pages eye catching. But it still did not make it interactive. DHTML(Dynamic HTML) added features that would make page interactive to some extent. To make it even more interactive JavaScript was used. Since all of the pages with these technologies used to sit on clients machine it was unsafe to supply sensitive data with the pages. Hence server side scripting was in need. ASP (Active server pages),JSP (Java server pages), PHP (Hypertext Pre-processor) are some of the server side scripting languages and used with databases to provide interactive sessions to the users. Among them PHP is the popular one, and my favourite.

This post was not intended to teach any language or any technology, but to give an idea of what a person learns along the time line to the newcomers in this field.

I'll make sure the next posts aren't so dry as these :)