Programming tutorials, examples and code snippets. C++, Java, Perl, PHP and javascript. Enterprise examples using javaEE, JNDI and Beans. Core tutorials using sockets, threads, database, IPC, XML etc. Web 2 widgets using javascrpt. Simple easy to understand step by step tutorials,
The aim of this Perl tutorial is to use Perl to read and write to a database. In this example the database connection is an ODBC DSN attached to a Microsoft SQL Database. However, this can be used for any database. This perl example will open a connection to a database and create SQL queries to fetch and insert data.
First lets have a look at the example. It's really self explanatory.
1. use DBI;
2. 3. # Connect to database
4. my $dbh = DBI->connect("dbi:ODBC:mydsn", "sa", "Admin-123",
5. {RaiseError => 1})
6. or die "Couldn't connect to database: " . DBI->errstr;
7. 8. #Retrieve data
9. my $sth = $dbh->prepare(<<SQL);
10. select * from testtable
11. where id < 1000
12. SQL
13. $sth->execute;
14. while (my @row = $sth->fetchrow_array()) {
15. my ($id, $name, $address) = @row;
16. print "$id $name $address\n";
17. }
18. 19. #Insert data
20. $sth = $dbh->prepare("insert into callexpert (starttime, url) values( CONVERT(datetime, ?), ?)");
21. $sth->execute("08.09.2009 6:00:00 AM", "www.google.com");
22. $sth->execute("08.09.2009 6:24:00 AM", "www.facebook.com");
23. 24. #Finish up
25. $sth->finish();
26. $dbh->disconnect;
Hide line numbers
Line 3 We connect to the Data Source Name that is pointing to the SQL Server. For MySQL the connection url will look something like "dbi:mysql:MyDatabase;host=www.myhost.com"
Lines 8-17 Read data from testtable and display it on the screan
Lines 19-22 Insert some data into the callexpert table. Here we are using the MS SQL CONVERT function to convert a string into a datetime format.
This example demonstrates how to create a class in Perl and use accessor methods such as 'get' and 'set' to access variables/attributes. Also demonstrates 'blessing' with the perl function bless. This is very useful as it allows the encapsulation of related data and helps to neaten code.
Let us have a look at the example. It is self explanatory. We create two files. One file will be named ComplexNumber.pm and the other run.pl. Make sure both these files are in the same place. FYI: The class models a complex number with real and imaginary components - not important
ComplexNumber.pm is the Perl package or 'class'
1. package ComplexNumber;
2. 3. sub new {
4. my $class = shift;
5. my $self = {
6. REAL => shift,
7. IMAGINARY => shift
8. };
9. bless $self, $class;
10. return $self;
11. }
12. 13. sub getReal(){
14. my $self = shift;
15. return $self->{REAL};
16. }
17. 18. sub setReal(){
19. my $self = shift;
20. $self->{REAL} = shift;
21. }
22. 23. sub printNumber(){
24. my $self = shift;
25. print "$self->{REAL} + $self->{IMAGINARY}i\n";
26. }
27. 1;
Hide line numbers
run.pl is the script that will instantiate the class and call some of the getter and setter methods.
1. use ComplexNumber;
2. 3. 4. my $num1 = ComplexNumber->new(1,2);
5. my $num2 = ComplexNumber->new(3,4);
6. 7. $num1->printNumber();
8. $num2->printNumber();
9. 10. print "Changing real from ".$num1->getReal()." to 20\n";
11. $num1->setReal(20);
12. 13. $num1->printNumber();
This simple example shows you how to move a layer, show and hide a layer and change the contents of a layer dynamically from Javascript. This kind of layer manipulation in fundamental to all web 2 applications.
This uses a randomly generated number to move the layer. This also uses document.body.scrollTop to adjust for scrolling and innerHTML to write to the layer.
Aim
The aim of this tutorial is to demonstate a simple yet effective Perl based webcrawler. In this example we will initially open a socket to a starting website, grab the links and then recursively trawl those links for more links. This builds on the previous perl tutorial Perl Socket and File Example. This is a great starting point to building your very own customized perl web crawler. I am not using the Mechanize package as the aim is to keep everthing light and tight and hard core. Leave any questions or problems as comments and I will endeavour to answer them.
Assumptions
This article assumes that you have a compatible Perl installation and a reasonable understanding or regular expressions. Previous perl experience not required.
Versions used in this example
Sofware/Component
Image
Active Perl 5
ActivePerl-5.10.1.1006-MSWin32-x86-291086.msi
Microsoft Windows XP
N/A
Quick Overview
The aim of this example is to trawl through a website and it's links, find all the images and write the references to a file. You can then simple view the html file and see all the images, without having to navigate throught the site. To keep life simple this is a recursive program so we don't need to a database to store our urls and everything is kept simple.
The depth of the drill specifies how deep the crawler will go. Be careful, because if a site has an average of 10 links and you drill to a depth of 5 links deep you will end up reading 100, 000 pages and finishing up your badwidth. If you give a regex to the script it will then ignore all pages that do not match the regex in the thml body. As you can see I'm not actually downloading any images, there is no need to. All you need are the HTML IMG tags and you can view them in your browser.
Will start at codediaries.blogspot.com will follow links 3 deep, and save all the images it finds in myimages.html file with 50 pics per page, but only images referenced from pages that have the word either "java" or "C++" in them.
This is a simple javascript AJAX tutorial using php, javascript and XMLHttpRequest. AJAX is the fundamental lynchpin of web 2 services and underpins almost every widget today. This is the simplest javascript example that demonstrates AJAX. No prior php knowledge required. Great for beginers to AJAX.
This example consists of two files. ajaxexample.html contains all the javascript and getresult.php is the php backend that returns an xml result. Create or copy these two files into the same directory on a webserver (such as apache) that supports php.
ajaxexample.html
1. <html>
2. <head>
3. <script language="javascript">
4. function new_XHR() {
5. var xhr;
6. try{
7. xhr = new ActiveXObject("Msxml2.XMLHTTP");
8. }catch(e){
9. try{
10. xhr = new ActiveXObject("Microsoft.XMLHTTP");
11. }catch(E){
12. xhr = false;
13. }
14. }
15. if(!xhr && typeof XMLHttpRequest != 'undefined'){
16. xhr = new XMLHttpRequest();
17. }
18. return xhr;
19. }
20. 21. var myxhr;
22. function DoAjaxCall(){
23. myxhr = new_XHR();
24. myxhr.onreadystatechange=MyAjaxCallback;
25. myxhr.open('GET',"getresult.php?"
26. +"name="+document.getElementById("NameBox").value);
27. myxhr.send(null);
28. }
29. 30. function MyAjaxCallback(){
31. var name;
32. var message;
33. if(myxhr.readyState==4 && myxhr.status==200){
34. var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35. for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36. var node = subrootNode[0].childNodes[i];
37. if(node.tagName=="name")
38. name=node.firstChild.nodeValue;
39. else if(node.tagName=="message")
40. message=node.firstChild.nodeValue;
41. else{}
42. }
43. document.getElementById("MessagePane").innerHTML =
44. "<b>"+name+" :</b> \""+message+"\"";
45. }
46. }
47. </script>
48. </head>
49. <body>
50. <form>
51. Name <input id="NameBox" type="text"/>
52. <a href="javascript:DoAjaxCall()">Send the data without submitting the form</a>
53. </form>
54. <div id="MessagePane"/>
55. </body>
56. </html>
Hide line numbers
Now type http://127.0.0.1/WEB/AJAXExample/ajaxexample.html in a browser, type your name in the textbox and click on the link.
lines 4-19 Creates an XMLHttpRequest object
lines 22-28 DoAjaxCall get's called when you click on the link. This creates an XMLHttpRequest object sets MyAjaxCallback as the callback function and adds the url to call.
lines 30-46 Once getresult.php is called the MyAjaxCallback function is called with the reuslt. You can then 'decode' the XMLHttpRequest object by traversing the sctructure and extracting the information.
This example demonstrates how to create a pseudo class in javascript. The javascript class is actually an empty function and you can assign attributes to it at runtime. This is very useful as it allows the encapsulation of related data and helps to make code neat.
Let us have a look at the example. It is self explanatory. We create two instances of MyClass, a and b, but assign different attributes to them.
1. function MyClass(){}
2. 3. a = new MyClass();
4. a.text = "The sum is "
5. a.num1 = 10;
6. a.num2 = 20;
7. 8. b = new MyClass();
9. b.firstname = "Jason";
10. b.lastname = "Bourne";
11. 12. function X(p){
13. if(p.num1!=null)
14. alert(p.text +(p.num1 + p.num2));
15. else
16. alert(p.firstname+" "+p.lastname);
17. }
18. 19. X(a);
20. X(b);
This example illustrates how Javascript extracts name and value pairs from a 'GET' submission or an url. You can use this as a means to pass Javascript values from one HTML page to another.
This code will extract name/value pairs from a URL such as http://codediarie.com/test.html?name=charlie&address=15%20Monterey%20Place%20Cherrybrook%20NSW%Australia.
1. function MyGetUrlParams(){
2. var url_params = new Array();
3. var urla = location.href.substring(location.href.indexOf('?')+1).split('&');
4. for(i=0;i< urla.length ;i++){
5. url_params[urla[i].substring(0,urla[i].indexOf('='))]=
6. urla[i].substring(urla[i].indexOf('=')+1);
7. }
8. return url_params;
9. }
10. 11. ...
12. #stuff
13. ...
14. 15. alert(MyGetUrlParams()['name']);
16. alert(MyGetUrlParams()['address']);
17. 18. var params = MyGetUrlParams();
19. for (i in params){
20. alert(params[i]);
21. }
Hide line numbers
Line 3 We decode location.href and put the values into an associative array with the names as keys.
Line 15-21 We can then use this array to get the values using the names - in many ways.
Examples and snippets about javascript, web 2, ajax, php, perl and much more. Learn how to create exciting widgets using yahoo, google and wtitter apis and DOM. Harness the power of web 2 to deliver rich content. Simple to understand yet comprehensive examples and tutorials.
Every application tutorial is listed here. Clean, simple and concise. C++ and Java tutorials based on application and technologies. This is frequently updated as tutorials are added. For core tutorials such as sockets, threads etc please see Core Tutorial Trail.
Aim
The aim of this tutorial is to demonstrate how you can add Headers to the ServletRequest and HttpServletRequest objects in either servlets or filters. This requires subclassing the HttpServletRequestWrapper class.
Assumptions
This article assumes that you can compile, deploy and test the filter/servlet. For an example that demonstrates compiling and deploying a filter please go to Complete Java Filter Example. To create a JSP page that will display headers please have a look at JSP Page That Displays All Headers and Parameters.
First let us have a look at subclassing the HttpServletRequestWrapper class. As you can see we have overridden getHeaderNames and getHeader to include our custom headers. These custom header are added through the addHeader function which is a new function. Our custom headers are stored in a hashmap.
Now let's have a look at a filter that will use this wrapper to add some custom headers. You can observe on line 31 how we use the wrapper to wrap the HttpServletRequest.
Aim
The aim of this tutorial is to create a simple yet fully functional Java Filter. This filter will redirect a request based on a URL parameter and modify the "body" text in a response. This filter can be deployed in any java container. Please leave any question or comments at the end and I will endeavour to answer them.
Assumptions
This article assumes that you have Glassfish or Tomcat or an equivalent java container installed and configured.
First let's write the filter and save it as MyFilter.java in the web_src/myfilter directory. As you can see we inspect the request for a parameter named "redirect." If we find it we redirect the page to google. This is configured throught the init-parameters for the filter and is in the web.xml file. The response is modified by appending "hello There" just before the closing body tag.
Now cd into the web_src directory and compile the source. Replace the path to Glassfish's lib directory with your local path. This could be lib in tomcat or any servlet container.
Now create the war file. Cd into the web_bin directory and jar it all up.
..FilterExample\web_bin>jar -cvf myfilter.war *
Finally deploy this war file in the servlet container of your choice. Glassfish in this example.
Testing the filter
First navigate to
http://localhost:8080/myfilter/index.html.
No change as the html is just served up.
Now navigate to
http://localhost:8080/myfilter/filtered/index.html.
This url matches the url pattern in the web.xml file and the filter gets called. You will notice that "Hello There" appended to the html.
Now navigate to
http://localhost:8080/myfilter/filtered/index.html?redirectme=foo.
This time the filter catches the redirectme using getParameterValues and redirect the browser to google.
Aim
The aim of this Windows C++ tutorial is to build a simple Dynamic Link Library or DLL using the command line Visual C++ compiler (cl.exe0. Then create two small C++ test programs that will call this DLL implicitly by linking with the lib file and explicitly using LoadLibrary and GetProcAddress. Also note that the explicit linking requires a "def" definition file with the exported funtion names.
Assumptions
This article assumes that you have a compatible version of Visual C++ installed and you have run vcvars32. The file is called MyHook because it will be used later as a windows keyboard hook dll.
Open a command prompt into your working directory and the executables. You should be able to see the results. Delete the dll and run them again - you should get an error message