Wednesday, August 31, 2011

An Historical History of Java Applets

I have stumbled across an eleven year old (2000 vintage) article, which already describes Applets as if they were "has been" technology. I quote:

SUN Microsystems introduced Java applets with much fanfare back in 1995. Applets immediately took the web world by storm because they added the ability to display dynamic web content within browsers in what was essentially a static HTML world.

During those initial days, it appeared that using Java applets was the best way to add dynamic content to web pages [but when] Dynamic HTML finally started taking shape, things changed drastically. The Document Object Model (DOM) exposes elements within a web page as programmable components with their own set of properties and methods ... Applets suddenly started to look old and primitive. The W3C’s endorsement of Dynamic HTML finally set the tone for the new breed of sophisticated, dynamic web pages.

Oh dear!

The author does mention some advantages to Applets. I shall cite just a couple, relevant to me:

  • The JDK comes with many useful classes that are typically found only in a high-level class library.
  • Applets can communicate back to the web server for sending customized messages, uploading / downloading [data].

The shuffling function I use in my Applet. I'm sure that would not be available in JavaScript. And there are other fairly complex calculations I intend to build in, which I am sure would be better run in compiled code than in a script.

And Applets are supposed to communicate with a server, which is what I am trying to do.

Yet almost all the material at least on the top page of a web search is as old as the article I am citing today.

Tuesday, August 30, 2011

Java Applet Revision

I first posted an entry on this topic back in February 2009. To refresh my memory, I'll just run through the steps of adding a very simple applet to a web page again. The code for the simple applet is as follows:

import javax.swing.JApplet;
import java.awt.Graphics;

public class HelloWorld extends JApplet {
public void paint(Graphics g) {
g.drawRect(0, 0,
getSize().width - 1,
getSize().height - 1);
g.drawString("Hello world!", 5, 15);
}
}

This was borrowed from the old (pre-Oracle) Java tutorial. A slightly more sophisticated version is offered in the current Java Applet tutorial.

The code to include the applet in a web page might be:

<html>
<body>

<applet code="HelloWorld.class"
width="150" height="50">
</applet>

</body>
</html>

And the page might look like this.

Monday, August 29, 2011

Asynchronous JavaScript and XML (AJAX)

I am looking at the W3Schools tutorial on AJAX. The tutorial begins with the statements:

AJAX is not a new programming language, but a new way to use existing standards. AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.

It is the exchanging data with a server phrase which interests me.

AJAX was made popular in 2005 by Google, with Google Suggest. Google Suggest [uses] AJAX to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.

I used the same concept in the 90's in a VB application I created for the WA Trotting Association to help them maintain a database of competition entrants. So that idea is not new, but I guess doing it on a web page must be.

Apparently modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) support the keystone of AJAX, the XMLHttpRequest object. Earlier versions of Internet Explorer (IE5 and IE6) use the MS ActiveXObject. The code examples in the tutorial allow for older IE versions, but in the example quoted below, I have edited this out for simplicity of analysis.

<html>

<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>

<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

The HTML code above sets out a web page comprising a header and a button (see below).

The header is enclosed within the <div> tag. A <div> tag usually divides a big web page into sections. It seems a bit redundant here, so I tried removing it, and labeling the header instead:

<h2 id="myDiv">Let AJAX change this text</h2>

It still worked, but the text, invoked by the button click, all appeared in the header style.

The JavaScript is all contained in the function loadXMLDoc, which is called by the button click event.

Within the function, the variable xmlhttp is declared and set as a new XMLHttpRequest object. I'd love to find this XMLHttpRequest object in a reference library, but I can't find it on the W3Schools JavaScript/DOM reference page. So from the tutorial I learn of two methods: open() and send(). The open() method seems to require the following parameters:

  • method - the type of request: GET or POST
  • url - the location of the file on the server
  • async - true (asynchronous) or false (synchronous)

The send() method allows the following parameter:

  • string: Used for POST requests

In the code above, the open() method is used with

  • method = "GET",
  • url = "ajax_info.txt" and
  • async = true.

The text contained in the file ajax_info.txt is:

<p>AJAX is not a new programming language.</p>
<p>AJAX is a technique for creating fast and dynamic web pages.</p>

Now from the code, it seems the XMLHttpRequest object has at least 3 properties:

  • .readyState
  • .status
  • .responseText

Just by reading the code it is not clear whether .responseText is populated by .open or .send. Intuitive logic would suggest the former, but in that case it is not clear what .send doing in there as well, although in the tutorial it says:

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object

And it shows the two methods being used one after the other, as they are in the code. The lesson then goes on to say a little more about the .responseText property and one more:

  • .responseText - holds the response data as a string
  • .responseXML - holds the response data as a XML data

It gives a further example using XML, which I shall skip at this stage, because on the next page we get clarification on the .readyState and .status properties, together with one I had failed to notice, .onreadystatechange. The last one appears to be both a property and an event:

  • The onreadystatechange event is triggered every time the readyState changes.
  • The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readyState property changes.
  • The readyState property holds the status of the XMLHttpRequest.

I have to say this leaves a question mark over what the .status property holds - a question not answered by the tutorial. What it does give is a list of acceptable values for these properties. For .readyState these are:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready

For .status these are:

  • 200: "OK"
  • 404: Page not found

By my calculation the property changes four times with every server request, so the onreadystatechange event must be triggered four times. I guess that explains the conditional clause in the function:

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}

This function is called four times, but it only does anything on the fourth occasion, when "the request finished and response is ready" and the .status property is "OK". (And on closer reading this is mentioned in the tutorial.)

At first I was confused by the above code segment, because I didn't realize it is an unnamed function within the function loadXMLDoc() and is called by a different event. The loadXMLDoc() function is called be the button click event, while the unnamed function is both contained by the onreadystatechange property and called by the onreadystatechange event.

So when the button is clicked, everything inside the tag labeled "myDiv" is replaced with the text in the file. In its original version this appears as regular text (see below).

In my alternative version both paragraphs appear as headers because they both fall within the header tag (see below).

If the button is clicked again, nothing appears to happen, because the text is replaced by identical text. Again, I was initially confused here, because I thought the conditional clause had something to do with what was being displayed.

Anyway, this is all a bit disappointing, because I also misunderstood the exchanging data with a server phrase to mean exchanging data with a database on a server, not a measly old text file.

Friday, August 26, 2011

Document Object Model (DOM)

I remember once attending a seminar by Microsoft where they were describing themselves as the cleverest people in the world for inventing what they called the Component Object Model (COM). It was only years later that I learned that they didn't really invent the idea at all, but copied it from other object oriented programming languages.

Anyway, the Document Object Model (DOM), although it rhymes with COM, has nothing to do with Microsoft, but is a World Wide Web Consortium (W3C) standard defined as:

A platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

According to the W3Schools tutorial on DOM:

The DOM is separated into 3 different parts / levels:

  • Core DOM - standard model for any structured document
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

The DOM defines the objects and properties of all document elements, and the methods (interface) to access them. [It] is a standard for how to get, change, add, or delete [XML/HTML] elements.

According to the tutorial:

DOM views an HTML document as a tree-structure ... called a node-tree.

And it goes on to show a diagram of a node tree. I'm not sure how useful this form of representation is for me, but I'll show it below for completeness:

Essentially, the DOM breaks web documents into a set of objects, which it calls nodes, and these nodes have properties which can be read or acted upon by methods. The Tutorial provides a link to a reference page listing DOM objects and their properties, along with JavaScript objects and Browser objects.

The Tutorial gives a "hello world" example, which to me illustrates the extraordinary messiness of this language/methodology. Before citing the example, I shall mention that two of the objects listed on the reference page are the document object and the HTMLElement object. One of the methods listed for the is the getElementById() method. One of the properties listed for the HTMLElement object is .innerHTML, which in any other language would probably be .text. Another is .id. So now here is the code:

<html>
<body>

<p id="intro">Hello World!</p>

<script type="text/javascript">
txt=document.getElementById("intro").innerHTML;
document.write("<p>The intro paragraph text is: " + txt + "</p>");
</script>

</body>
</html>

So the first paragraph is assigned the id "intro" by the HTML. Then in the JavaScript this HTMLElement object is referred to by its id, and its innerHTML property is assigned to the JavaScript variable txt. The content of this variable is then concatenated with the text of a second paragraph created with the JavaScript document.write method. The result is shown in the image below:

That seems a lot of work to achieve something fairly trivial, but at least now I have some understanding of what DOM is all about. It is essentially a labeling system for HTML elements, which enables them to be changed programmatically (usually with JavaScript). In fact it is really just an extension of JavaScript to embrace HTML elements and their properties.

Wednesday, August 24, 2011

eXtensible Markup Language (XML)

I am looking at the W3Schools tutorial on XML. I like the clarification on the roles of HTML and XML:
  • HTML was designed to display data, with focus on how data looks.
  • HTML truncates multiple white-space characters to one single white-space.
  • XML was designed to transport and store data, with focus on what data is.
  • White-space is Preserved in XML. XML Stores New Line as LF.
  • XML tags are not predefined. You must define your own tags.
  • XML documents must include an XML declaration and can include a DOCTYPE declaration, which in turn refers to "system" of tags/elements, set out in either a DTD file or in a Schema.
  • XML does not DO anything other than to transport and store data.
  • XML data is stored in plain text format. This provides a software and hardware independent way of storing data.
  • XML documents must contain a root element. This element is "the parent" of all other elements. All elements can have sub elements (child elements).

The tutorial gives an example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

Here first line is the XML declaration and the root element is <bookstore>. The <bookstore> contains 3 <book> elements, each of which had a lang attribute, and in turn has 4 child elements. It seems to me analogous to a data table entitled "bookstore", with 6 columns and 3 rows. I say 6 columns, because in a data table, the lang attribute and the book category would be stored as columns, possibly integer indices linked to other tables.

My interpretation is confirmed in a section entitled Elements vs. Attributes, where the following examples are said to be equivalent:

<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

Indeed the tutorial goes on to say:

There are no rules about when to use attributes or when to use elements [but while] attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead.

My first impression is that this is not an "efficient" way to store data, not least because the row "headers" have to be repeated in every row. But then HTML tables are messy to look at (in HTML code) and nightmarish to produce (manually).

Interestingly, although XML does not render in a browser in the same way as HTML, it does come up a bit like code in a code editor (see below). So "parent" elements can be expanded or contracted to show or hide their "child" elements. In the image below, the "cooking" book element has been expanded, but the other two book elements left closed.

It's interesting, but I am still no closer to connecting my Applet to a database.

Monday, August 22, 2011

JavaScript by w3schools

I was planning to slot in an entry on XML here, but I note the W3Schools tutorial on XML puts JavaScript as required knowledge. As I branched into web language revision because HTML and XHTML were required knowledge for JavaScript, I might as well start on that now.

I have to say that having praised the W3Schools tutorial on PHP, I am a little disappointed by this one. It is all over the place. I came here because the Mozilla Getting Started with JavaScript page began with a "corny" example but zero explanation of the language structure or syntax. And now this one does the same thing:

<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>

<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>

It's rubbish without a proper explanation. If all I want to do is reverse engineer someone else's code, I won't bother with a tutorial, I'll just search for code examples.

So what do we have in the next few pages that is useful?

To insert a JavaScript into an HTML page, use the <script> tag. Inside the <script> tag use the type attribute to define the scripting language.

This is shown in line 3 of the code quoted above.

The lines between the <script> and </script> contain the JavaScript and are executed by the browser. JavaScripts can be put in the <body> and in the <head> sections of an HTML page. JavaScripts in an HTML page will be executed when the page loads. This is not always what we want. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. When this is the case we can put the script inside a function [which is called by the event].

This strategy is executed in line 4 of the code quoted above, where the function displayDate is defined, and in the third from last line, where a button click is set to call the function.

You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions [either] in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag:

For example:

<head>
<script type="text/javascript" src="xxx.js"></script>
</head>

I thought they might give an example of a .js document, but they did not.

Let's hope the XML lesson is more interesting.

Sunday, August 21, 2011

Web language Revision

I'm probably stretching the definition of revision here. My only formal tuition in web languages was in HyperText Markup Language (HTML)(1 - except there was no number then) and it wasn't very formal. From memory it was a free one hour lecture provided by UWA to encourage research students to use the new medium to publicize their work.

Anyway, disappointed by the Mozilla Getting Started with JavaScript page, I went back to a Google search on "JavaScript Tutorial" and W3Schools was on top of the list again. Curious, I checked Wikipedia to find:

W3Schools is not affiliated in any way with the World Wide Web Consortium (W3C). It is created and owned by Refsnes Data, a Norwegian family-owned software development and consulting company.

Affiliated with W3C or not, I liked the style of their PHP tutorial, so I checked out their JavaScript tutorial. Listed as required knowledge was HTML and CSS, and a link was provided to their Home Page, in case of any doubt. I followed the link, because the initials CSS meant nothing to me. And listed with CSS were the languages of the web - HTML, and XHTML. So I decided the time had come for a refresher and catch up on what has happened in the last fifteen years.

I noted a few more formatting tags than were available in the olden days - whether one really needs them all or not is another question. Styles are completely new to me, and it looks as if I have been doing a few things wrong, or at least, not consistently with current standards. But at least I have a jogged a vague recollection that CSS stands for Cascading Style Sheets. I also noted on the images page that the language and syntax of what used to be the ismap attribute has changed a lot. It's not something I use much, but I now have an easy link to the correct form if I need it.

Forms came in well after my time. I've cribbed other people's code, but it's nice to see it all laid out properly. Frames came a little after my time (HTML2 I think) and I never liked them. I was pleased to read that they are being phased out and will not be supported in future HTML versions. The Iframe is completely new to me. Defined as a web page within a web page, I can see there might be applications for it.

When I was a boy, you began an HTML document with the HTML tag, and that told the browser what type of document it was. Nowadays, apparently, you need a document type declaration as well. In practice you can get away without it with ordinary HTML documents (none of the pages on my web site use it), but perhaps you need it for other document types, such as XHTML.

This brings me to the tutorial on EXtensible HyperText Markup Language (XHTML), which I am surprised to learn is simply a stricter and cleaner version of HTML:

XHTML consists of all the elements in HTML 4.01, combined with the strict syntax of XML.

  • XHTML elements must be properly nested
  • XHTML elements must always be closed
  • XHTML elements must be in lowercase
  • XHTML documents must have one root element

An XHTML document must have a DOCTYPE declaration. The html, head, title, and body elements must also be present.

Next came the tutorial on the search term which led me into this - CSS. To be honest, now that I have confirmed what the initials stand for, I can't see that it will be of much use to me. For my purposes, the "styles" defined in HTML(1) - H1, H2 etc - were more than enough for me. I'm not looking to edit a magazine here; I just want a page to host my Applet. Just in case, a style sheet is referenced inside the header as follows:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>

And the style sheet itself is simply a text document saved with the .css extension and written out something like this:

hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}

And the "cascading" works as follows:

Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:

  1. Browser default
  2. External style sheet
  3. Internal style sheet (in the head section)
  4. Inline style (inside an HTML element)

So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value).

The tutorial goes on and on, but I think I have what I need for now. And that's it for what W3Schools calls the HTML group of tutorials. When I saw XHTML in there I was hoping it might be just a trendy way of saying XML, but I see now that it is part of a whole group on its own, so it is probably worthy of its own blog entry.

Wednesday, August 17, 2011

Mozilla JavaScript Learning Material

A Google search on "JavaScript Tutorial" brings up an abundance of online learning materials. I added Mozilla to the search string to find their Getting Started with JavaScript page.

I can't resist commenting on the style of the page. There are comments like:

JavaScript is a very easy language to start programming with. All you need is a text editor and a web browser to get started.

And:

JavaScript is a great programming language for introductory computer languages. It allows instant feedback to the new student and teaches them about tools they will likely find useful in their real life. This is in stark contrast to C, C++ and Java which are really only useful for dedicated software developers.

And then the first code example is:

<span onclick="alert ('Hello World!');">Click Here</span>

With zero explanation besides a list of mouse "events" other than onclick. To be fair, the code works. When slotted into an empty browser page, it comes up as shown below:

and if you click over the text it comes up as shown below:

The second code example is a more complex and wordy way of achieving the same thing:

<script type="text/javascript">
function onclick_callback ()
{
alert ("Hello, World!");
}
</script>
<span onclick="onclick_callback();">Click Here</span>

Slotting that into an empty web page achieves exactly the same as shown in the illustrations above.

The third code example shows an even more complex way of achieving almost the same thing:

<script type="text/javascript">
function onclick_callback(event)
{
var eType = event.type;
/* the following is for compatability */
/* Moz populates the target property of the event object */
/* IE populates the srcElement property */
var eTarget = event.target || event.srcElement;

alert ("Captured Event (type="+ eType +", target="+ eTarget);
}
</script>
<span onclick="onclick_callback(event);">Click Here</span>

This shows the same text as before and the following message:

The fourth code example introduces still more complexity, and this time the message box (shown below) is invoked by a larger range of possible mouse events:

<script type="text/javascript">
function mouseevent_callback(event)
{
/* The following is for compatability */
/* IE does NOT by default pass the event object */
/* obtain a ref to the event if one was not given */
if (!event) event = window.event;

/* obtain event type and target as earlier */
var eType = event.type;
var eTarget = event.target || event.srcElement;
alert(eType +' event on element with id: '+ eTarget.id);
}

function onload ()
{
/* obtain a ref to the 'body' element of the page */
var body = document.body;
/* create a span element to be clicked */
var span = document.createElement('span');
span.id = 'ExampleSpan';
span.appendChild(document.createTextNode ('Click Here!'));

/* register the span object to receive specific mouse events */
span.onmousedown = mouseevent_callback;
span.onmouseup = mouseevent_callback;
span.onmouseover = mouseevent_callback;
span.onmouseout = mouseevent_callback;

/* display the span on the page */
body.appendChild(span);
}
</script>

This is great, but it's not really what I'm looking for.

Sunday, August 14, 2011

Playing with PHP

I'm not sure who w3schools are, but they have a tutorial on PHP. They offer a list of things you need, including MySQL, Apache and PHP. I'm going to ignore this, because I am tired of getting things to work at home and then scratching my head to make them work on a production server.

I do note however that my web host claims to offer MySQL, Apache and PHP on its server. I shall therefore do all of my experimenting in a live environment. Unprofessional perhaps, but how many people look at my web site anyway?

The first code sample is a good old "Hello World" message:

<html>
<body>

<?php
echo "Hello World";
?>

</body>
</html>

I popped this in a text file, called it hello.php, and uploaded it to my web host. I then typed:

http://www.interactived.com/hello.php

into my browser, and what do you know, the following page appeared:

So far so good.

There followed a number of boring chapters on linguistics, most of which I tried out but will omit here. The next more interesting one was an example of a form:

<html>
<body>

<form action="welcome.php" method="post">
<p align=right>
Name: <input type="text" name="fname" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" />
</p>
</form>

</body>
</html>

I saved this as hello.htm, uploaded it and typed:

http://www.interactived.com/hello.htm

into my browser. A nice neat form appeared on the screen (see below) and I typed Jonathan into the name field and 24 into the age field.

Before clicking the Submit button, I also saved the following code as welcome.php and uploaded it:

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Then, when I clicked the Submit button, the following text appeared in the browser:

Most interestingly (for me at least), when I tried to view the source code, it came up as shown below.

So the source code displayed was the rendered HTML, and NOT the PHP source code. This is quite good news, although I am still not quite sure how secure that PHP file is.

After skipping more linguistics chapters the time came to try a data connection. As I had deleted nearly everything from my table in a previous exercise, I decided to try an insert:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("dbAMJ", $con);

mysql_query("INSERT INTO Items (Partid, OpCode, Itemdet, Raw, Rate)
VALUES (1, 1, '2+2=', 1, 1), (1, 1, '3+3=', 1, 1)");

mysql_close($con);
?>

I substituted my credentials, saved it as dbtestin.php, uploaded it and tried it in the browser. That code displays nothing on success (or failure of the sql query), so I visited my web host again and used their phpMyAdmin facility to check that the extra lines had been inserted, and sure enough they had.

I then tried the following code to apply a simple query:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("dbAMJ", $con);

$result = mysql_query("SELECT * FROM Items") or die(mysql_error());

echo "<table border='1'>
<tr>
<th>Itemdet</th>
<th>Raw</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Itemdet'] . "</td>";
echo "<td>" . $row['Raw'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);
?>

The following table was displayed:

So it seems that I can run PHP on my live web site, and I can use it to connect to my database. Furthermore, the PHP source code does not appear to be accessible for viewing in the browser. This would appear to be a step in the right direction.

Saturday, August 13, 2011

J2EE

Three years ago I began this blog with a discussion of The Java Tutorial. I didn't read it from top to bottom. I took what I needed to do what I wanted to do. I left some quite large chunks unread, so when I decided to research Java Servlets, I fully expected to find them there.

Certainly they were part of a tutorial, but it had an unfamiliar feel to it. When I clicked on the home link, I found myself looking at the J2EE 1.3 Tutorial - "A beginner's guide to developing enterprise applications on the Java 2 Platform, Enterprise Edition SDK version 1.3".

"Beginners guide" sounds good, but "developing enterprise applications" is something I neither need nor want to do.

In my first post I suggested that using NetBeans to craft "Hello World" was like using a sledge hammer to crack a nut, and at first glance, using J2EE to make a simple connection between my little applet and a database is worthy of the same analogy. There has to be a simpler way to do it.

During my VB programming days I used ASP, the MS equivalent of JSP, and it really wasn't that hard. In those days, I owned the server, and controlled everything on it, including user accounts and passwords. From memory, the user had to supply credentials every time they accessed the intranet site, so the issue of embedding credentials in code didn't arise.

I have just touched base with my web host, and from my account stats, as well as a MySQL version number, I see one for Apache and PHP. I guess that means I can use PHP. I've never done so before, but from the w3schools site, connecting to a MySQL database doesn't look very hard.

A couple of questions arise. First where is the PHP code hidden, and is that a better place to hide my username and password than an Applet? Second, can my Applet talk to the PHP code and vice versa? I suspect the answer to both questions is NO, but at least reading up on PHP looks a little less daunting than J2EE.

Thursday, August 11, 2011

A few notes on JavaScript

I am one the 99% of the world who has long nursed the misconception that JavaScript has something to do with Java. And why not? The name sort of implies it.

It was only after I searched without success on the Java Tutorial site for some mention of JavaScript that I stumbled across the knowledge that JavaScript was in fact developed by Netscape, under the name LiveScript. Armed with that knowledge, it is not surprising to find the best reference information on Mozilla site.

According to Wikipedia, the nonsensical name choice had something to do with Netscape wanting to cash in on the popularity and cachet of Java, and Sun wanting support for Java technology in the then popular Netscape browser.

For a while only the Netscape family of browsers supported JavaScript. Microsoft later produced what it calls JScript to run in its browser. JScript is similar but not identical to Javascript.

According to Foldoc JavaScript runs a hundred times slower than C, and ten times slower than Java.

According to Wikipedia:

JavaScript very quickly gained widespread success as a client-side scripting language for web pages [and] has become one of the most popular programming languages on the web. Initially ... many professional programmers denigrated the language because its target audience was web authors and other such "amateurs" ... The advent of Ajax returned JavaScript to the spotlight and brought more professional programming attention.

So what is Ajax? The link is to another Wiki page, which gives lots of details, but I'll quote a bit of the history, as it mentions Applets:

In the 1990s, most web sites were based on complete HTML pages; each user action required that the page be re-loaded from the server (or a new page loaded) ... Asynchronous loading of content first became practical when Java applets were introduced in the first version of the Java language in 1995. These allow compiled client-side code to load data asynchronously from the web server after a web page is loaded.

But as I have reported in previous posts, Applets are fraught with difficulties. This brings me back to the definition of Ajax, which is an acronym for "asynchronous JavaScript and XML"

In summary, JavaScript is a scripting language used in web pages in conjunction with other languages and technologies to achieve ends more complex than can be achieved with simple HTML. The language looks a bit like Java (and C) and meshes with Java, but it was developed independently by the creators of the Netscape browser.

Saturday, August 6, 2011

Forum Comments on Java Applets

It is so long since I last posted on the once was Sun/Java now is Oracle developer forum my account seems to have been ditched. While I wait to have it resurrected I've done a little searching in the Java Database Connectivity (JDBC) forum using the search term "Applet".

My first search, using the default 3 month period, yielded nothing. No one had posted anything about or even mentioned Applets in the last three months. So either they are very easy to use and work very well, so hardly anyone has any problems with them, or maybe ... not very many people use them at all.

My stomach was beginning to churn a bit, when I extended the search period to the current year - and with good reason. Somebody, a little bit like me I think, had written a game in an applet, and wanted to record top scores in a database. He described his connection problem in this thread, and the first reply began:

Doing JDBC calls from an Applet is such a bad idea that I am glad you are having trouble with it. You might want to reconsider your design! If you persist on going this way, I can tell you that there will be many more even more difficult hurdles that you will need to overcome which would make this problem seem like a piece of cake ...

The OP opened his question with the phrase:

I'm trying to write a very basic test applet ...

One reply to this specific phrase was:

You may as well be hunting unicorns. Applets are never easy.

Another reply, to the post as a whole began:

Apart from the bad idea of connecting to your db from an applet (security is one that springs to mind ...

and concluded his reply with:

...Exactly how this wires up for an applet I can't say since I've not written one in a decade.

So perhaps 10 years ago Applets were "hip" for whatever reason, but now they seem definitely not to be.

Another thread actually opened with a quote from another website, inviting comments and clarification. The quote was:

It is generally not a good idea to use JDBC directly in an Applet. You need to presume some brat will decompile your Applet and use that knowledge to create a substitute Applet that causes as much havoc as possible. If your Applet has direct access to JDBC, the brat’s substitute can snoop or pillage the database to its heart’s content.

Most of the posts are pretty uncomplimentary about Applets and the ODBC-JDBC bridge (which I looked at but gave up on because it was too hard to get it to work), but one of them suggests a solution using servlets:

What you could do is write two servlets. One is called "gimmethescores". The applet calls http://www.example.com/gimmethescores and gets a list of high scores to display. You can use a simple line by line text format, or XML, or whatever you wish.

The other servlet is "setscore". After the game is over, the applet calls http://www.example.com/setscore?user=jim&score=1050. The servlet then checks the parameters look sane and updates the high score table.


So now I'm thinking I need to study up on servlets.

Thursday, August 4, 2011

Webcity

My web site is hosted by WebCity, an Australian domain registrar and web host, whose motto is "Self Service Savings". And when they say self service they mean self service. They offer a very comprehensive self help library, supplemented by a range of good video tutorials, but the whole site is somewhat cryptic, if you don't know your way around, and they don't really like being contacted.

However, they are also true to their word on savings. Certainly they saved me money on my original domain registrar and on my traditional ISP. The ISP offered free web space, but charged a ridiculous annual fee to domain holders. This didn't include domain registration, which I paid for separately. I guess it covered the one off three minute task of letting the domain registrar know my physical web address, but apart from that, I have no idea how they justified it.

Webcity also offer a MySQL server, and when I plucked courage to ask them about it they assured me that it was on the same server as my web code, and that the server name "localhost" should be used for connections. That sounded pretty good news. It might be an unusual set up, but it gives me a chance to try out my existing Applet code on a commercial server, before re-writing in a more rigorous or generalist way. I therefore set about creating a database on their server.

I mentioned that the Webcity web site is a bit cryptic. Most websites offer on their home page a bold login button, or clearly labeled user id and password fields. Not so this one. You have to know to type "yourdomain/cPanel" into the address field of your browser, and then you will be offered user id and password fields to fill in.

The cPanel, as the name suggests, is a bit like the Control Panel in Windows, with an array of icons allowing you to tweak this and that. They are arranged into groups such as mail files, logs etc. Well down the page is a group called Databases. The first item called MySQL databases offers a GUI to create databases and users. Another item, called phpMyAdmin, offers a GUI to create a table and define fields in one tab, and in another tab it offers an SQL window to type or paste one's own queries. I cut and pasted the one I had used to create the dbAMJ database on my own server. It ran fine, and I added a few lines in the format I intend to use. That was fine, and I deleted a couple as well.

I then modified my applet code to include the following URL for the database:

String url = "jdbc:mysql://localhost:3306/int22853_dbAMJ";

I modified the username and password for Webcity, compiled and uploaded the code files and uploaded the MySQL JDBC driver. I included in the code modifications a few extra diagnostic messages. The applet is designed to display these in a text field.

The applet loaded, and it displayed a message to confirm that the JDBC driver had been loaded. It then displayed an extra message to confirm that it had moved to the next line of code. But nothing came back from the connection "Try" loop. There was no success message and no fail or error message. It was as if it just did not run.

It did this from the website hosted by Webcity, and it did exactly the same on the site hosted on my own IIS server. So after a break of two years, I think I need to post a question in the Java forum.

Wednesday, August 3, 2011

Limitations of Java Applets

Having installed IIS, I was still struggling to get my Applet to connect to the MySQL database, and I stumbled across this post. The grammar is questionable but of relevance to me is:

This keeps coming up ... applets trying to make JDBC database connections don't work in general ... Mainly because JDBC is a server side technology. Where applets may only always and forever communicate with the HTTP server ... which they originated from (same server as their code base) ... and in general the database will almost always be on a different server.

In other words, it doesn't matter how hard I work to get the Applet working at home, when I upload to my ISP it probably won't work, because their MySQL server is most likely on a different box to the web server with my code on it. I guess I could send them a question, but if I want to make my code robust, I probably need a more general solution. The post quoted above goes on to suggest solutions, but at this stage of my knowledge development they are all gibberish to me. I'll quote them because they include a nice collection of search strings for possible use in my research:

So, we need some kind of web service or custom query mechanism, e.g. XML RPC over HTTP, or JSON over HTTP ... where we have the APPLET invoke HTTP requests to a Servlet in the server ... which receives these requests (also handles authentication, authorization) and then uses a JDBC connection to the database to invoke some query, unpack the result set into the HTTP servlet response in a suitable format (e.g XML, JSON, etc, what ever was used for request and what ever the applet is expecting as a response).

[This] means you'd need a web app at least with a servlet listening on a URL that your applet is able to invoke, and have the database JDBC connection available to this servlet.

Years ago I posted a question on some Java forum about JDBC and Applets, and I was asked why I was using an Applet and not writing a web application with Java Script. I gave some bullshit answer at the time, but the honest answer would have been that I had never used Java script, and didn't know the first thing about it. I have used Java, I have used VB script, and I have used HTML, so I can't believe it would be that hard; but I guess I need to hit the text books again.