Wednesday, 22 April 2009

Simple Java XML Tag Value Extractor

This Java method is a simple routine to extract values from a simple xml message. It is not a replacement for XPath, which is much more fundamental.

The requirement for this method arose when I had to extract a couple of tags from small xml files, that weren't actually xml! As XPath is pretty strict it couldn't be used as the files wouldn't compile successfully.

So we have "simpleGetTagValue", which accepts the xml and the tag as Strings.

private static String simpleGetTagValue(String xml, String tag) {
String tagValue = new String();
StringBuilder startTag = new StringBuilder("<").append(tag).append(">");
StringBuilder endTag = new StringBuilder("");
int startIndex = xml.indexOf(startTag.toString());
int endIndex = xml.indexOf(endTag.toString());
if(startIndex!=-1 && endIndex !=-1)
tagValue = xml.substring(startIndex+(startTag.length()), endIndex);
return tagValue;
}


Done.

Tuesday, 21 April 2009

Java Method to Read Text File Contents Into a String

This Java method takes a File as a parameter and returns the text contents of that file as a String.

private static String readFileToString(File f) throws IOException {
StringBuffer sb = new StringBuffer(1000);
BufferedReader br = new BufferedReader(new FileReader(f));
char[] buf = new char[1024];
int readSoFar = 0;
while((readSoFar = br.read(buf)) != -1) {
sb.append(String.valueOf(buf, 0, readSoFar));
buf = new char[1024];
}
br.close();
return sb.toString();
}

It can be modified to take the qualified file name as a String

private static String readFileToString(String f) throws IOException {
...

Done.

Tuesday, 14 April 2009

JSP Substring (and other string manipulations)

I only have a little knowledge of jsp, so my first stab at trying to modify a page I thought I'd try just using some Java to see happened.

The modification was just to substring a variable that already existed, so in went the Java and out came the error.

The function substring must be used with a prefix when a default namespace is not specified

What? So I did some searches for this error and eventually found that using Java was very wide of the mark.

You need to use the jstl tag library for string manipulation.

So after adding the taglib to the top of the page, my substring that trims the first five characters and the last character looks something like:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:set var="myValue" value="${fn:substring(myValue,5,fn:length(myValue)-1)}" />
...

A summary of all the functions in the jstl library, including: contains, endsWith, escapeXml, indexOf, join, length, replace, split, trim, can be found at JSTL functions.


${fn:replace("Done","one","umb")}

Quick Find for Browser User Agent

To quickly find a browsers user agent enter the following line into the address bar of the browser.

javascript:document.write(navigator.userAgent)

This browser user agent is:



Done.

Thursday, 2 April 2009

Position an Element Horizontally and Vertically Using CSS. (Take 2)

Positioning an element so that it is centred on the page, both horizontally and verticalally, is very simple to achieve. We do need to know the width of the element, so this does need to be fixed.

It has been tested in IE7, Firefox3 and Safari3 and all work fine. (It may work in other browsers I just haven't tested it)
This idea expands our first idea as this only worked in quirks mode. This second solution uses the xhtml transitional doctype.

The idea is quite straight forward, we position the element so the top left corner is in the middle of the page. Then we adjust the top and left margins so the centre of the element is in the middle of the page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style>

* {
margin: 0;
padding: 0;
}

#layoutwrapper {
height: 200px; /* Adjust as appropriate */
width: 550px; /* Adjust as appropriate */
margin-left: -275px; /* (Width/2)*-1 */
margin-top: -100px; /* (Height/2)*-1 */
left: 50%;
top: 50%;
overflow: hidden;
position: absolute;
background: yellow;
}

</style>
</head>
<body>

<div id="layoutwrapper">
Enter content here
</div>

</body>
</html>

...Centred with doctype...

Friday, 20 March 2009

Convert a String to an ASCII / Unicode String with JavaScript

This JavaScript function converts a string of characters to a corresponding string of each characters unicode value.

function stringToAscii(s)
{
var ascii="";
if(s.length>0)
for(i=0; i<s.length; i++)
{
var c = ""+s.charCodeAt(i);
while(c.length < 3)
c = "0"+c;
ascii += c;
}
return(ascii);
}

If a characters unicode value is less than one hundred, zeros are prefixed to for that character, so that each original character has three digits in the returned unicode string.

And a test page

<html>
<head>
<script type="text/javascript">

function convertMe()
{
var converted = stringToAscii(document.getElementById('string').value);
document.getElementById('answer').innerHTML = converted;
}

function stringToAscii(s)
{
var ascii="";
if(s.length>0)
for(i=0; i<s.length; i++)
{
var c = ""+s.charCodeAt(i);
while(c.length < 3)
c = "0"+c;
ascii += c;
}
return(ascii);
}

</script>
</head>
<body>

<h1>String To ASCII/Unicode</h1>
<input id="string" type="text"/>
<input type="button" value="Convert" onclick="convertMe();"/>
<h1 id="answer"></h1>

</body>
</html>

068111110101.

Wednesday, 11 March 2009

Javascript Function to Check Email Address Format using RegExp

This Javascript function performs a basic test to validate an email address.

The only true way of validating an email is to send an email and ask for a reply of some kind. This function is an initial step by making sure the format is correct.

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}

And an example html page.

<html>
<head>
<script>

function testEmail(e)
{
if(isEmail(e))
alert('true');
else
alert('false');
}

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}


</script>
</head>

<body>
<h1>Email RegExp Test</h1>
<input id="email" type="text"/>
<input type="button" value="Test" onclick="testEmail(document.getElementById('email').value);"/>
</body>

</html>

Validated.