Wednesday, August 24, 2011

[Javascript] Newline Character or Break Line in Textarea Field

Hi Friends,

We put a textarea to a form. Submit the form. Edit the form. Everything works fine. Textarea seems to display everything alright. But what if we want to load the form using javascript for editing?

In this case, if the text in textarea has a newline character, Javascript will throw error. Since it will be coming like this.. if text area text is  "This is my msg.\nRavi" then to javascript it will appear like
var msg = "This is my msg.
Ravi";
Which is an error.. Javascript will not do anything further. I could not find any solid solution for this but here is what can be done. I was getting the data from java so..

<%
// In java the data is stored with Html escape for all special characters etc.
msg = msg.replaceAll("\n", "<br />"); 
%>

// In javascript get the msg and replace all <br> with \n
var tmsg = "<%=msg%>";
tmsg = replaceAll(tmsg, "<br />", "\n");
tmsg = unescape(tmsg); // needed to get all special characters

Now put this content anywhere you want. 
$(#textAreaMsg).html(tmsg);

And the replaceAll function is  
function replaceAll(txt, replace, with_this) {   return txt.replace(new RegExp(replace, 'g'),with_this); }
Thats it.:)

Monday, August 22, 2011

[MySQL] Users and Permissions : Grant all on..

To create a user in mysql use -
CREATE USER 'ravi'@'localhost' IDENTIFIED BY 'password';
To grant all permissions use -
GRANT ALL PRIVILEGES ON *.* TO 'ravi'@'localhost' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'ravi'@'localhost' WITH GRANT OPTION; //also works
To grant selected permissions use -
GRANT SELECT,DELETE,UPDATE ON *.* TO 'ravi'@'localhost' WITH GRANT OPTION;

Reference : MySQL Reference

Enjoy :) 
 

Thursday, August 4, 2011

PDF Viewer : View PDF on Websites

Hi Friends,
Did you ever think of any apporach about viewing pdf files on website.. Its not difficult one. Just convert the pdf to image and display. I wondered how google worked and set up Google books, well you will have the answer. Click on this link. If the link is not working no issue. Whats in that is written in next lines.

The link which you just clicked is http://books.google.com/books?id=fcW1xl1BejUC&pg=PA308&img=1&zoom=3&hl=en&sig=ACfU3U0viP5hPVQFiFCyoDc4_zeXPmco-Q&w=685 which is nothing but a dynamic generated url to get the image from google servers. So, even Google is using the images. Answer of standard question "Why" is simple.. Browsers. They cant render parse and render pdf(AFAIK) but they can display images.
The same approach we followed when it came to think about a pdf viewer. There are some very powerful libraries are availabe which can convert any pdf to certain images formats without any error. Unfortunately most of them are not free.. To help open source in this area Apache provided PDFbox and Swinglabs provided PDF renderer. Both are very small and lightweight libraries which enable us to create/edit/convert pdfs.
Below code shows how we can convert pdf to images. But for basics, A pdf is actually a document with pages. And when I say convert to image its not like taking a screenshot but the content of pdf are drawn in a 2d image(At least pdfbox does).To know more about the API docs just download the libraries along with the documentation.
Convert using PDFBox-
    public GetSpecificPage(int pageNum, String pathFile, String pathPage) {
        try {
            PDDocument document = PDDocument.load(pathFile);
            List list = document.getDocumentCatalog().getAllPages();
            int count = document.getNumberOfPages();
            PDPage page = list.get(pageNum);
            int dpi = 75; // Dots per inch
            BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, dpi);
            File imageFile = new File("D:/tests/pdfbox/" + pageNum + "-dpi-" + dpi + ".png");
            ImageIO.write(image, "png", imageFile);
        } catch (Exception ex) {
            Logger.getLogger(GetSpecificPage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Well even using PDFBox this is not the only approach to extract something out.
            File f = new File("D:/tests/pdfbox/1.pdf");
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            PDFParser parser = new PDFParser(fis);
            parser.parse();
            COSDocument cosDoc = parser.getDocument();
            PDDocument pdDoc = new PDDocument(cosDoc);
            Splitter splitter = new Splitter();
            List pages = splitter.split(pdDoc);
            for (int i = 0; i < pages.size(); i++) {
                PDDocument pageDoc = pages.get(i);
                String fileNameNew = "page_" + i + ".pdf";
                pageDoc.save("D:/tests/pdfs/" + fileNameNew);
                pageDoc.close();
            }
            fis.close();
            cosDoc.close();
            pdDoc.close();

And now with the PDF Renderer- Its bit different.
            File file = new File("D:/tests/pdfbox/1.pdf");
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdfFile = new PDFFile(buf);
            int num = pdfFile.getNumPages();
            for (int i = 0; i < 100; i++) {
                PDFPage page = pdfFile.getPage(i);

                //get the width and height for the doc at the default zoom
                int width = (int) page.getBBox().getWidth();
                int height = (int) page.getBBox().getHeight();

                Rectangle rect = new Rectangle(0, 0, width+(width%60), height+(height%60));
                int rotation = page.getRotation();
                Rectangle rect1 = rect;
                if (rotation == 90 || rotation == 270) {
                    rect1 = new Rectangle(0, 0, rect.height, rect.width);
                }

                //generate the image
                BufferedImage img = (BufferedImage) page.getImage(
                        rect.width, rect.height, //width & height
                        rect1, // clip rect
                        null, // null for the ImageObserver
                        true, // fill background with white
                        true // block until drawing is done
                        );

                ImageIO.write(img, "png", new File("D:/tests/pdf1/" + i + ".png"));
            }

Thats it in this. We explored just one small but powerful feature of both Libraries. To learn more just download and use.. Its simple.

Next step is to view the images on browser.. That's an easy task if you dont want to take care of security and performance. I believe a lot of free javascript libraries are available which can display. But if we need security and performance we need to take care of images which we are rendering on browser and caching + some other applicable mechanisms which can help with the performance. Anyways It completely depends on the user's choice on how to view them on Web. :D

Cheers!!!
Ravi Kumar Gupta

Wednesday, July 20, 2011

[Servers] Setup and provide basic Chat Server using Openfire

Hi Friends,
Openfire is an opensource, cross-platform chat server which uses XMPP (also called Jabber). It has a very simple installation procedure, easy to use web based Admin panel. In this post I will install openfire on Windows, configure it with LDAP, Use it with Web Chat Client Spark and Desktop Client Pidgin.

Openfire can be downloaded from http://www.igniterealtime.org/projects/openfire/ in form of executables containing JRE and just archives. Download and extract archive to a directory lets say D:/pFiles/openfire.


All the required documentation is available in documentation directory. To complete installation we need to setup
  1. Database
  2. LDAP Server (optional, but recommended)
For the database use one of these supported databases
  • MySQL
  • Oracle
  • Microsoft SQLServer
  • PostgreSQL
  • IBM DB2
  • HSQLDB
After database server installation create a database lets say openfire.
And for LDAP, please refer this post to setup OpenDS. Any LDAP can be installed and used.
Now when we have LDAP and Database ready, we are ready to setup Openfire.
Go to bin directory and run openfire.exe It will show that server is running and the address:port where admin console is running.














Now open browser and go to the link provided.. in this case http://127.0.0.1:9090 which will open the web-setup




Select the language and continue..


Select the server settings for our Openfire chat server.. provide the domain name which you want to choose. This domain will be used while login... for user ravi it ravi@rkg.test will be the login username.


We have an option to choose embedded database or use our own database server. Lets go for Standard connection.


Provide the correct details in the form and continue..


We can here select where we want to store the users data. I recommend LDAP since every organization has one LDAP and the same can be integrated and used easily. Remember that.. Users and groups are stored in the directory and treated as read-only. We can not modify anything using Admin console here.

Press continue to get form to fill the LDAP credentials and other details.





























We can also test connection settings using Test Settings Button.



Press Save and Continue to see user mappings. Change according to the LDAP you have. For my system I took all default so no need to change anything.


Same is the case for Group settings..


After filling all correct settings press Save and Continue. Next we should add one admin account to manage admin console. Add a user in next screen



If we add admin it will search and show users present in ldap as well.



Select user if present and then continue. Now login to the admin console using the link http://127.0.0.1:9090/index.jsp or whatever is applicable for your system.


Now the server is running and up. We can configure any client to connect to server and chat with other users. Popular desktop clients which can be used are Pidgin, trillian, empathy etc. For web client we can use SparkWeb.
Below are the steps to add account in pidgin. Click on Manage Accounts in Account in Menu.














Now add one more account..




















The account type will be xmpp. Fill correct username and password. If needed put domain as we provided earlier.. in this case it is rkg.test.


















We need to modify the advance settings as well



















Now after adding we can chat to other users on the server. Next few screens will show the sparkweb client which can be put in any webserver like apache and used using browser. In my case I have put it in a folder called chat and accessing with url http://rkg.test:4000/chat/SparkWeb.html. This is a flash based client which can be used on web and connects to the server we want.






















Thats it for the Chat Server and Clients.. We have one chat server running now, one Desktop client configured, one web client configured.

Cheers!!!

Ravi Kumar Gupta

[Servers] Setup and provide basic LDAP Server using OpenDS

Hi Friends,
Many times we need to integrate LDAP server with our softwares for user authentication. This blog will explain how to setup a basic LDAP server on a machine using OpenDS.

For the basics, LDAP is Lightweight Directory Access Protocol more on which can be read on LDAP: Wikipedia. OpenDS is one LDAP Server which can be downloaded from this link of OpenDS.org . I will recommend to download the zip version which contains setup script.













Download and extract this to a directory lets say D:/pFiles/OpenDS. Now run setup.bat which will launch the installation..






















Make sure you have already setup a proper hostname for your system. Like for me I have chosen rkg.test and put it in hosts file.
Just press next and fill server settings. Give a port number which is more than 1024; this is because ports between 0-1024(not an exact figure) are reserved and sometimes blocked in intranet. I chose 11389 for this installation. Choose the Root User DN which will be used to connect to LDAP and for all other admin tasks like create/edit/delete etc. DN stands for Distinguished Name. 























For a basic server we don't need to setup replication so just leave the options as it is in next screen.






















Now fill the Directory Data, Here we will Base DN which is must when we try to connect to LDAP through our softwares. Optionally we can install sample data if we want. 
 
Click next and Review the settings.























Now finish the installation. We can here choose to run this as service, optionally.























After setup is finished Launch Control Panel. Control panel is where we can manage all the entries. Clicking on the button will prompt to fill Bind DN which is nothing but Root User DN and password.
















This will connect to Control panel where we can see all the options provided to manage OpenDS.


































Click on Manage Entries and we will see a new screen where we can view the tree of all the entries. We can modify/delete/add any entry.

After our all the entries are setup now we are ready to use this LDAP for any integration needed. Now the most important thing, features which OpenDS is providing to us(Probably I should have listed them before in this post, but I feel this position better since now we have a basic understanding how LDAP looks like :D)
This listing is directly copied from OpenDS.org from this page

Directory Server Features

The OpenDS directory server is an LDAPv3 compliant directory server written entirely in Java. The directory server includes the following high-level functionality:
  • Full LDAPv3 compliance (RFC 4510–4519) with support for numerous standard and experimental extensions
  • High performance and space effective data storage
  • Ease of configuration and administration

    • A highly extensible administrative framework that enables you to customize most of the features listed below.
    • An administration connector that manages all administration traffic to the server. The administration connector enables the separation of user traffic and administration traffic to simplify logging and monitoring, and to ensure that administrative commands take precedence over commands that manipulate user data.
    • A graphical control panel that displays server status information and enables you to perform basic server and data administration.
    • Several command-line utilities to assist with configuration, administration tasks, basic monitoring, and data management. The main configuration utility (dsconfig) provides an interactive mode that walks you through most configuration tasks.
  • An advanced replication mechanism

    • Enhanced multi-master replication across directory server instances
    • An assured replication feature that ensures high availability of data and immediacy of data availability for specific deployment requirements
    • Fractional replication capabilities
    • Support for an external change log that publicizes all changes that have occurred in a directory server database
  • An extensible security model

    • Support for various levels of authentication and confidentiality
    • Access to resources based on privileges
    • An advanced access control mechanism
  • Multi-faceted monitoring capabilities
  • Rich user management functionality

    • Password policies
    • Identity mapping
    • Account status notification
  • A DSML to LDAP gateway
Read and Enjoy
Cheers!!!
Ravi Kumar Gupta

Wednesday, July 13, 2011

[HTML5] Adding Text to your Canvas

Hi Friends,
My last post was just an intro to Canvas and some line drawings. Whenever I see some board, canvas I always want my name written on it.. so i tried adding some text. I will show you how can you put your name over there..

1. Select a font style, size, weight just like css properties and assign like this
c.font = "bold 20px verdana";

2. Now we have two ways to draw it.. either fill or stroke.
c.fillStyle = "#ff0022";
c.strokeText("Only Stroke", 10, 60);
and for stroke
c.strokeStyle = "#00ff00";
c.strokeText("Only Stroke", 10, 60);
Remember if you want both fill and stroke then use both ways like this-
c.fillText("Both Stroke and Filled", 10, 90);
c.strokeText("Both Stroke and Filled", 10, 90);


3. Alignment of text is alwyas important. We can align text to both verticle and horizontal directions.
For horizontal just assign any of these properties start, end, left, center, or right. For ex.
c.textAlign = "left";

For verticle assign any of these properties top, hanging, middle, alphabetic, ideographic, and bottom. For ex.
c.textBaseline = "top";


Easy.. right? And this is output when I was trying something.. :)


Cheers!!!
Ravi Kumar Gupta