Using Java application to access web application

I’ve been working a bit with needing to utilise a web service built in PHP from a Java application (it would be easier to just run a full-screen browser, but other constraints remove this option). What this has necessitated is scripting the Java app so that it makes calls to the web app’s API and then parses and utilises the data correctly.

Other than the writing of variations to the existing web app, so that function calls etc are accessed externally and correctly, the main functionality of the Java app has needed to be built into standard function calls which take in parameters and then parse them to dynamically create the correct URL to be called. Essentially the generalised function takes the parameters given and creates a URL which specifies the function required as well as necessary input data for the web app. Unfortunately, Java doesn’t have a nice foreach array iterator that can reference both the key and the value; like PHPs foreach($array as $key=>$val)):

public string makeURL(string baseURL, string pageName, string[][] params) {
    string queryURL = baseURL + "/" + pageName + "?";
    for(int i=0; i<params.length(); i++) {
	string param = params[i][0] + "=" + params[i][1] + "&";
	queryURL += param;
    }
    queryURL = queryURL.subString(0, queryURL.length() - 1);
    return queryURL;
} 

Next we use a function call to wrap up all the creation of a URL, requesting it, and receiving the response:

public string callURL(string queryURL) { 
    URLConnection queryConn = queryURL.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
	    queryConn.getInputStream()));
    String inputLine;
    String result = ""; 
    while ((inputLine = in.readLine()) != null) {
	result += inputLine;
    }
    in.close();
    return result;
}

The second general function is given the returned data from the URL request and parses it into variables for use by the Java app; the data returned is structured as a 2-D array with the equivalent of a key and value held in the 2nd dimension:

public string[] extractData(string response, string[] nodeNames = null) { 
    string[] data = new Array();
    string[] tokens = StringUtils.splitspanserveAllTokens(response, ":");
    for(int i=0; i<tokens.length(); i++) {
	string[] step = StringUtils.splitspanserveAllTokens(tokens[i], "$");
	data[i][0] = step[0];
	data[i][1] = step[1];
    } 	
    return data; 
} 

Of course, my extractData function is extremely simplistic and only splits a string up. Parsing XML is a better solution if the URL returns XML formatted data. This would require either explicit foreknowledge of the exact nodes being returned by a request (I have allowed for this with the string[] nodeNames) or a much bigger function to allow for searching through and detecting all node names and then dynamically iterating them.

I’m sure there are cleaner, and better, implementations of this, however I felt the need to build my own since I’m dabbling back into Java at present. And once it’s built, I believe it’s best to share. Hopefully this helps someone, let me know.

Advertisements

quick update – what I’ve been up to

Well, obviously, I’ve been knocking out quite a few tutorials over the past week or so, but not so much about moi. Basically, I’ve been working hard and prepping for interviews. A couple of promising leads ahead, with possible offers due in from a few options in the next week or two. I have some opinions about which I want, or don’t; but I’m waiting for paper before I decide.

Last weekend, as I posted, I was down in Napier for the wedding of my good friends Hamish and Julie. It was a great day, and the weather held absolutely perfect for all of Saturday. I’m yet to post photos to facebook, but I will this weekend as soon as I get some decent internet time. My blogging recently has been in offline mode, with updating when connected.

Looking forward to Easter weekend, with some gardening and chores, but mainly chilling out and relaxing; as well as ongoing interview prep and reading. Also attempting to keep my various languages active, so I’ll probably focus on XML and C# over the weekend. Clash of the Titans is out today, so I may make it to the cinema for that also.

No-one’s announced iPad availability in New Zealand yet either, so it’s just a waiting game here. At least none of the telcos have announced a bundled deal yet either, which is great as that’ll just destroy half the point of it. Still hoping Apple sells it directly un-contracted, so we can actually use it as intended.

Anyway, no major developments in my life this week, just the ongoing job hunt really. I’ve got a couple more PHP tutorials to post, and then I’ll deal to a few others in various languages.

Dynamic JavaScript generation with PHP

Creating dynamic JavaScript on the fly can be useful when needing to target differing dynamically generated xml files for example. In my example below, I am creating the xml as I do here, and then using the dynamic JS to pass this new xml to a Flash template for display on the fly. The necessity for a dynamic JS script in this case is that the name of the xml changes dynamically, and also the JS script is named dynamically with a random value in order to prevent caching of the script.

To begin, the script is predominantly static, and is simply written to a JS file. Make sure every line is ended with the \r\n chararcters in order to be correctly written to the file. Essentially as below. I am using dynamic variables for the Flash height and the xml name:

<?php

$xyz = fopen("xml/".$jsname, "w");

fwrite($xyz, "<!--\r\n");
fwrite($xyz, "if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {\r\n");
fwrite($xyz, " alert(\"This page requires AC_RunActiveContent.js.\");\r\n");
fwrite($xyz, "} else {\r\n");
fwrite($xyz, " var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);\r\n");
fwrite($xyz, " if(hasRightVersion) {\r\n");
fwrite($xyz, " AC_FL_RunContent(\r\n");
fwrite($xyz, " 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',\r\n");
fwrite($xyz, " 'width', '870',\r\n");
fwrite($xyz, " 'height', '".$heightval."',\r\n");
fwrite($xyz, " 'scale', 'noscale',\r\n");
fwrite($xyz, " 'salign', 'TL',\r\n");
fwrite($xyz, " 'bgcolor', '#777788',\r\n");
fwrite($xyz, " 'wmode', 'transparent',\r\n");
fwrite($xyz, " 'movie', 'flash',\r\n");
fwrite($xyz, " 'src', 'flash',\r\n");
fwrite($xyz, " 'FlashVars', 'library_path=flash/librarypath&xml_source=xml/".$xmlname."',\r\n");
fwrite($xyz, " 'id', 'my_flash',\r\n");
fwrite($xyz, " 'name', 'my_flash',\r\n");
fwrite($xyz, " 'menu', 'true',\r\n");
fwrite($xyz, " 'allowFullScreen', 'true',\r\n");
fwrite($xyz, " 'allowScriptAccess','sameDomain',\r\n");
fwrite($xyz, " 'quality', 'high',\r\n");
fwrite($xyz, " 'align', 'middle',\r\n");
fwrite($xyz, " 'pluginspage', 'http://www.macromedia.com/go/getflashplayer',\r\n");
fwrite($xyz, " 'play', 'true',\r\n");
fwrite($xyz, " 'devicefont', 'false'\r\n");
fwrite($xyz, " );\r\n");
fwrite($xyz, " } else {\r\n");
fwrite($xyz, " var alternateContent = 'This content requires the Adobe Flash Player. '\r\n");
fwrite($xyz, " + '<a href="http://www.macromedia.com/go/getflash/">Get Flash</a>.';\r\n");
fwrite($xyz, " document.write(alternateContent);\r\n");
fwrite($xyz, " }\r\n");
fwrite($xyz, "}\r\n");
fwrite($xyz, "// -->\r\n");

fclose($xyz);

?>

As you can see, I pass in variables $jsname, $xmlname, and $heightval which are used to construct the script. This is then called by setting a dynamic call to the JS script within the webpage itself using PHP, as below:

<?php

$rndnum = rand(1234, 9876);
$jsname = "script_name_".$rndnum.".js";
// make the JavaScript here
echo '';

?>

This can be linked to a script to create XML dynamically, as here, and there you have a truly dynamic display.

first post for August…..

Here’s my first post for August. Found this cool list of 20 technothriller tropes we hope never to see again on io9.com. Built a new site over the weekend, just getting the PHP/XML linking back to the other site I’ve been doing. So now I’ve got two to launch in the next week or two. Fun times to be had by all!!

Assignments are starting to be released at uni now, so the workload is actually beginning to kick in. Not too bad though, but it means I need to focus on that instead of fun projects. Ah, well.

Time to check out the beginnings of the Iron Man 2 hype here. That’s the Stark Industries website. Also, I just won tickets to GI Joe, so I guess I’ll be checking it out soon. Hopefully it lives up to the hype and isn’t destroyed by Hollywood marketing crap. GI Joe is an icon of our generation, so I’m hoping the movie gives it the respect it deserves and doesn’t turn it to $#@&. Hey, they made Iron Man work, so there is still hope.

I have a few opinions about various stuff that’s been going on, but I can’t be bothered pulling it all together now. So, I’ll do a big post tomorrow to catch up on my ranting and opinionating.

Peace, out.

a new semester begins

Today is Tuesday (duh!), and uni started back yesterday. I am lucky enough to start my week at 8am on a Monday, so no easing into the lecture schedule for me. I was pleasantly surprised to find that one of my papers has already released the first assignment. This means that I will actually be able to get onto it in a timely manner. Normally they all wait until third/fourth week to all release them at the same time, and then are all due at the same time. I’m a bit sick today, so I’ll be starting on this assignment tomorrow and trying to get it done by the end of the weekend.

Also discovered that one of my other papers get to play with Windows source code (WRK). Very cool!! It’s only the WRK for Server 2003 but, as they say, that’s pretty much the same as XP, which is almost the same as Vista; so there we go. My schedule isn’t too bad for my – touch wood – final semester before returning to the real world, so I’m not stressing over possible time issues at all. I’m doing mainly CompSci papers to finish off, but most of them are network related, so I’m really weighing towards mainly InfoSys in reality. I’ll also be completing my CCNA semesters 3 & 4 as part of one of my InfoSys papers which is a bonus. And, I believe my other InfoSys paper allows me to sit an Oracle certification at the end too. Look at me the uber-student.

Check this link out for a bit of a laugh when you get the chance (make sure you have sound!). It is safe for work. Also, notpron.com is classic. It’s also safe for work, but the url my cause filters to trigger, so best to do it at home. I have to put in the following video, just because I hadn’t seen it for ages, and I re-watched it again over the weekend. It’s still as ridiculously funny as it was when it first came out!!

As you’ll soon see, I’ve been going through my favourites folder on YouTube, and I went right to the very back end for the oldest (possibly forgotten) vids I could track down. Here’s Best Baby Break Dance:

and this one of a guy catching glasses with his face:

I’ll end the queue of videos with this one. It’s actually quite heart-touching, so enjoy and be happy for him:

I’ll be doing some more tuts this afternoon, or tomorrow. Something to do with XML and HTTP now that I’ve had a bit of fun setting that up for my site (launch will be within the next two weeks I think!!) and coordinating it with JS so that other sites can call to mine and get responses back. I’ll also look at something to do with dynamic JS creation from PHP.

Dynamic XML document construction with the PHP DOM

This tutorial is sourced directly from techrepublic.com, but it fits in perfectly with my tutorial on dynamic JavaScript creation so I’ve posted it here too; I found it fantastic, and figured it was best shared with everyone. Original post here. Don’t just follow through to their link, because I have included it here as a perfect complement to some of my other tutorials.

When working with XML-based applications, developers often find themselves facing the requirement to generate XML-encoded data structures on the fly. Examples of this include an XML order template based on user input in a Web form, or an XML representation of a server request or client response based on run-time parameters.

Although this task might seem intimidating, it’s actually quite simple when one takes into account PHP’s sophisticated DOM API for dynamic node construction and manipulation. Over the course of this article, I’ll be introducing you to the main functions in this API, showing you how to programmatically generate a complete well-formed XML document from scratch and save it to disk.

Note: This article assumes a working Apache/PHP5 installation with the DOM functions enabled, and a working knowledge of basic XML constructs such as elements, attributes and CDATA blocks. You can obtain an introduction to these topics from the introductory material at Melonfire.

Creating the Doctype declaration

Let’s start right at the top, with the XML declaration. In PHP, this is fairly simple; it only requires you to instantiate an object of the DOMDocument class and supply it with a version number. To see it in action type out the example script in Listing A.

Listing A

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// save and display tree
echo $dom->saveXML();
?>

Notice the saveXML() method of the DOMDocument object — I’ll come back to this later, but for the moment simply realize that this is the method used to output a current snapshot of the XML tree, either to a file or to the browser. In this case, I’ve sent the output directly to the browser as ASCII text for readability purposes; in real-world applications, you would probably send this with a Content-Type: text/xml header.

When you view the output in your browser, you should see something like this:

<?xml version="1.0"?>

Adding elements and text nodes

Now that’s all very pretty and fine, but the real power of XML comes from its elements and the content they enclose. Fortunately, once you’ve got the basic DOMDocumentinitialized, this becomes extremely simple. There are two steps to the process:

  1. For each element or text node you wish to add, call the DOMDocument object’screateElement() or createTextNode() method with the element name or text content. This will result in the creation of a new object corresponding to the element or text node.
  2. Append the element or text node to a parent node in the XML tree by calling that node’s appendChild() method and passing it the object produced in the previous step.

An example will make this clearer. Consider the script in Listing B.

Listing B

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// save and display tree
echo $dom->saveXML();
?>

Here, I’ve first created a root element named <toppings> and attached it to the XML header. Next, I’ve created an element named <item> and attached it to the root element. And finally, I’ve created a text node with the value “pepperoni” and attached it to the <item> element. The result should look like this:

<?xml version="1.0"?>
<toppings>
<item>pepperoni</item>
</toppings>

If you’d like to add another topping, simply create another <item> and populate it with different content (Listing C).

Listing C

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create another text node
$text = $dom->createTextNode("tomato");
$item->appendChild($text);

// save and display tree
echo $dom->saveXML();
?>

And here’s the revised output:

<?xml version="1.0"?>
<toppings>
<item>pepperoni</item>
<item>tomato</item>
</toppings>

Adding attributes

You can also add qualifying information to your elements, through the thoughtful use of attributes. With the PHP DOM API, attributes are added in a two-step process: first create an attribute node holding the name of the attribute with the DOMDocumentobject’s createAttribute() method, and then append a text node to it holding the attribute value. Listing D is an example.

Listing D

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// save and display tree
echo $dom->saveXML();
?>

And here’s what the output will look like:

<?xml version="1.0"?>
<toppings>
<item price="4">pepperoni</item>
</toppings>

Adding CDATA blocks and processing instructions

While not used quite as often, CDATA blocks and processing instructions (PI) are also well-supported by the PHP API, through the DOMDocument object’screateCDATASection() and createProcessingInstruction() methods. Listing E shows you an example.

Listing E

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// create CDATA section
$cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
$root->appendChild($cdata);

// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);

// save and display tree
echo $dom->saveXML();
?>

And here’s the output:

<?xml version="1.0"?>
<toppings>
<item price="4">pepperoni</item>
<![CDATA[
Customer requests that pizza be sliced into 16 square pieces
]]>
<?pizza bake()?>
</toppings>

Saving the results

Once you’ve got the tree the way you want it, you can either save it to a file or store it in a PHP variable. The former function is performed by calling the save() method with a file name, while the latter is performed by calling the saveXML() method and assigning the result to a string. Here’s an example (Listing F).

Listing F

<?php
// create doctype
$dom = new DOMDocument("1.0");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
$dom->formatOutput=true;

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// create CDATA section
$cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
$root->appendChild($cdata);

// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);

// save tree to file
$dom->save("order.xml");

// save tree to string
$order = $dom->save("order.xml");
?>

And that’s about it. Hopefully you found this article interesting, and will be able to use these techniques in your daily work with XML. Happy coding!