Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

JAVA SCRIPT - Creating a Dynamic Line Chart in Canvas

Creating a Dynamic Line Chart in Canvas


Problem

You want to display a line chart in your web page, but the data changes over time, and you want to dynamically update it. 

Solution

Use the canvas element and the path method to create the chart. When the data changes, update the chart: 

var array1 = [[100,100], [150, 50], [200,185],
 [250, 185], [300,250], [350,100], [400,250],
 [450, 100], [500,20], [550,80], [600, 120]];
var imgcanvas = document.getElementById("imgcanvas");
if (imgcanvas.getContext) {
 var ctx = imgcanvas.getContext('2d');
 // rect one
 ctx.strokeRect(0,0,600,300);
 // line path
 ctx.beginPath();
 ctx.moveTo(0,100);
 for (var i = 0; i < array1.length; i++) {
 ctx.lineTo(array1[i][0], array1[i][1]);
 }
 ctx.stroke();
}


EXPLAIN

Canvas paths are the way to create arbitrary shapes in Canvas. After getting the canvas context, ctx, the path is begun with a call to ctx.beginPath(), which begins a new Canvas path. The next line of code is ctx.moveTo, which moves the drawing “pen” to a beginning location, but without drawing. From that point, several lineTo() calls are made using an array of paired values representing the x,y location for each line endpoint. 


After the path has been defined, it’s drawn. We’re not creating a closed path, so I’m not using ctx.closePath(), which would draw all the defined lines and then attempt to draw a line from the ending point to the beginning point. Instead, I’m drawing the line given the points that have been defined, using ctx.stroke(). 

The appearance of the drawing is influenced by two Canvas settings: strokeStyle and fillStyle. The strokeStyle setting sets the color for the outline of a drawing, while the fillStyle does the same for the drawing filling:


ctx.strokeStyle="black";
ctx.fillStyle="#ff0000;

Any CSS setting will do, or you can use a CanvasGradient or CanvasPattern. You can use the rgba setting to add transparency:

ctx.fillStyle="rgba(255,0,0,0.5)";

You can also use the globalAlpha setting to set the transparency for any drawing that follows:

ctx.globalAlpha = 0.2;

You can further control the appearance of the drawing outline by changing the stroke’s line width:

ctx.line

To dynamically update the chart, you can incorporate timers, and either replace the path (by creating an entirely new context, which would erase the old), or add the new line chart to the same chart.

Shows a web page that creates the line in the solution and then creates two others, each drawn after a short period of time using timers. The colors for the stroke path are changed between lines.

Using timers to dynamically update a line chart


<!DOCTYPE html>
<head>
<title>Canvas Chart</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id="imgcanvas" width="650" height="350">
<p>Include an image that has a static representation of the chart</p>
</canvas>
<script>
 var points = [[[100,100], [150, 50], [200,185],
 [250, 185], [300,250], [350,100], [400,250],
 [450, 100], [500,20], [550,80], [600, 120]],
 [[100,100], [150, 150], [200,135],
 [250, 285], [300,150], [350,150], [400,280],
 [450, 100], [500,120], [550,80], [600, 190]],
 [[100,200], [150, 100], [200,35],
 [250, 185], [300,10], [350,15], [400,80],
 [450, 100], [500,120], [550,80], [600, 120]]];
 var colors = ['black','red','green'];
 var imgcanvas = document.getElementById("imgcanvas");
 if (imgcanvas.getContext) {
 var ctx = imgcanvas.getContext('2d');
// rectangle wrapping line chart
 ctx.strokeRect(0,0,600,300);
 points.forEach(function(element, indx, arry) {
 setTimeout(function() {
 // set up beginning
 ctx.beginPath();
 ctx.moveTo(0,100);
 ctx.strokeStyle = colors[indx];
 for (var i = 0; i < element.length; i++) {
 ctx.lineTo(element[i][0], element[i][1]);
 }
 ctx.stroke();
 }, indx * 5000);
 });
 }
</script>
</body>

Simplify Your Canvas Charts Using a Library

It doesn’t have to be difficult to create a chart using Canvas from scratch, but why walk the steps taken by others? There are several excellent libraries that can simplify not only chart making but other Canvas effects. Over 50 libraries for chart making are listed in a TechSlides Page, including the in‐ creasingly popular D3, which I’ll cover in . 

Most of the libraries are freely available, though some do charge a fee for commercial use. One of the libraries, Highcharts, even provides demonstrations that you can edit in jsFiddle, making it easy to try out the library’s capability. It’s dependent on jQuery, reducing the code to an absurdly simple level. As an example, one of the demonstrations is for a very professional line chart, with plot lines and labels, 


Yet the code to create this example is equivalent to that in the following code block, which I modified to feature my own locations and temperature metric, which you can try yourself at jsFiddle:

$(function () {
 $('#container').highcharts({
 title: {
 text: 'Monthly Average Temperature',
 x: -20 //center
},
 subtitle: {
 text: 'Source: Weather.com',
 x: -20
 },
 xAxis: {
 categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
 },
 yAxis: {
 title: {
 text: 'Temperature (°F)'
 },
 plotLines: [{
 value: 0,
 width: 1,
 color: '#808080'
 }]
 },
 tooltip: {
 valueSuffix: '°F'
 },
 legend: {
 layout: 'vertical',
 align: 'right',
 verticalAlign: 'middle',
 borderWidth: 0
 },
 series: [{
 name: 'Seattle, WA',
 data: [47,51,55,59,65,70,75,75,70,60,52,47]
 }, {
 name: 'Grand Isle, VT',
 data: [27,31,40,54,67,76,81,79,71,57,45,33]
 }, {
 name: 'St. Louis, MO',
 data: [40,45,55,67,77,85,89,88,81,69,56,43]
 }]
 });
 });


Not only is the plotted chart professional looking, it’s zoomable, which means you can move your mouse cursor over the chart to examine the plot points in detail. That level of interactivity isn’t necessarily trivial in Canvas, because one of the downsides to Canvas is the fact that you can’t attach event handlers to the individual elements of Canvas— only to the Canvas area itself.

Not being able to attach an event to individual elements means that you’ll have to keep track of where the mouse is, and what’s underneath it at any point in time.

Thankfully, you can attach event handlers to SVG elements, as demonstrated.

Java Parsing Strings into Dates

Java Parsing Strings into Dates

Problem

You need to convert user input into Date or Calendar objects.

Solution

Use a DateFormat .

Explained

The DateFormat class introduced in Recipe 6.2 has some additional methods, notably
parse( ) , which tries to parse a string according to the format stored in the given
DateFormat object:

// DateParse1.java
SimpleDateFormat formatter
= new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " parses as ");
Date t;
try {
t = formatter.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("unparseable using " + formatter);
}

This program parses any date back to Year Zero and well beyond Year 2000. What if the date is embedded in an input string? You could, of course, use the string’s substring( ) method to extract it, but there is an easier way. The ParsePosition object from java.text is designed to represent (and track) the posi- tion of an imaginary cursor in a string. Suppose we have genealogical data with input strings representing the times of a person’s life:

BD: 1913-10-01 Vancouver, B.C.
DD: 1983-06-06 Toronto, ON

This lists one person’s birth date (BD) and place, and death date (DD) and place. We can parse these using String.indexOf(' ') to find the space after the : character, DateFormat parse( ) to parse the date, and String.substring( ) to get the city and other geographic information. Here’s how:

// DateParse2.java
SimpleDateFormat formatter =
new SimpleDateFormat ("yyyy-MM-dd");
String input[] = {
"BD: 1913-10-01 Vancouver, B.C.",
"MD: 1948-03-01 Ottawa, ON",
"DD: 1983-06-06 Toronto, ON" };
for (int i=0; i<input.length; i++) {
String aLine = input[i];
String action;
switch(aLine.charAt(0)) {
case 'B': action = "Born"; break;
case 'M': action = "Married"; break;
case 'D': action = "Died"; break;
// others...
default: System.err.println("Invalid code in " + aLine);
continue;
}
int p = aLine.indexOf(' ');
ParsePosition pp = new ParsePosition(p);
Date d = formatter.parse(aLine, pp);
if (d == null) {
System.err.println("Invalid date in " + aLine);
continue;
}
String location = aLine.substring(pp.getIndex( ));
System.out.println(
action + " on " + d + " in " + location);
}

This works like I said it would:

Born on Wed Oct 01 00:00:00 PDT 1913 in Vancouver, B.C.
Married on Mon Mar 01 00:00:00 PST 1948 in Ottawa, ON
Died on Mon Jun 06 00:00:00 PDT 1983 in Toronto, ON

Note that the polymorphic form of parse( ) that takes one argument throws a ParseException if the input cannot be parsed, while the form that takes a ParsePosition as its second argument returns null to indicate failure.

Java Converting YMDHMS to a Calendar or Epoch Seconds

Java Converting YMDHMS to a Calendar
or Epoch Seconds

Problem

You have year, month, day, hour, minute, and maybe even seconds, and you need to
convert it to a Calendar or a Date .

Solution

Use the Calendar class’s set(y,m,d,h,m[,s]) method, which allows you to set the
date/time fields to whatever you wish. Note that when using this form and providing
your own numbers, or when constructing either a Date or a GregorianCalendar
object, the month value is zero-based while all the other values are true-origin. Pre-
sumably, this is to allow you to print the month name from an array without having
to remember to subtract one, but it is still confusing.

// GregCalDemo.java
GregorianCalendar d1 = new GregorianCalendar(1986, 04, 05); // May 5
GregorianCalendar d2 = new GregorianCalendar( );
// today
Calendar d3 = Calendar.getInstance( );
// today
System.out.println("It was then " + d1.getTime( ));
System.out.println("It is now " + d2.getTime( ));
System.out.println("It is now " + d3.getTime( ));
d3.set(Calendar.YEAR, 1915);
d3.set(Calendar.MONTH, Calendar.APRIL);
d3.set(Calendar.DAY_OF_MONTH, 12);
System.out.println("D3 set to " + d3.getTime( ));

This prints the dates as shown:

It was then Mon May 05 00:00:00 EDT 1986
It is now Thu Mar 25 16:36:07 EST 2004
It is now Thu Mar 25 16:36:07 EST 2004
D3 set to Mon Apr 12 16:36:07 EST 1915

Java Representing Dates in Other Epochs

Java Representing Dates in Other Epochs

Problem

You need to deal with dates in a form other than the Gregorian Calendar used in the
Western world.

Solution

Download the IBM calendar classes.

Explained

The only nonabstract Calendar subclass is the GregorianCalendar , as mentioned pre-
viously. However, other calendar classes do exist. IBM has a set of calendars—
Hebrew, Islamic, Buddhist, Japanese, and even an Astronomical Calendar class—that
covers most of the rest of the world. This work has been open sourced and is now
part of a project called International Components for Unicode for Java.

The calendar classes in ICU4J work in a similar fashion to the standard
GregorianCalendar class, but they have constants for month names and other infor-
mation relevant to each particular calendar. They are not subclassed from java.util.
Calendar , however, so they must be referred to by their full class name:

import
import
import
import
java.util.Locale;
com.ibm.icu.util.Calendar;
java.text.DateFormat;
com.ibm.icu.util.IslamicCalendar;
public class IBMCalDemo {
public static void main(String[] args) {
Locale ar_loc = new Locale("ar");
Calendar c = new com.ibm.icu.util.IslamicCalendar( );
DateFormat d = DateFormat.getDateInstance(DateFormat.LONG, ar_loc);
System.out.println(d.format(c.getTime( )));
}
}

I can’t include the textual output because of font limitations.

JAVA SCRIPT - Populating a Selection List from the Server

Populating a Selection List from the Server


Problem

Based on a user’s actions with another form element, you want to populate a selection list with values.

Solution

Capture the change event for the form element: 

document.getElementById("nicething").onchange=populateSelect;
In the event handler function, make an Ajax call with the form data:
var url = "nicething.php?nicething=" + value;
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = getThings;
xmlhttp.send(null);
In the Ajax result function, populate the selection list:
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var select = document.getElementById("nicestuff");
 select.length=0;
 var nicethings = xmlhttp.responseText.split(",");
 for (var i = 0; i < nicethings.length; i++) {
 select.options[select.length] =
 new Option(nicethings[i],nicethings[i]);
 }
select.style.display="block";
} else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 document.getElementById('nicestuff').innerHTML =
 'Error: Search Failed!';
}

EXPLAIN

One of the more common forms of Ajax is to populate a select or other form element based on a choice made by the user. Instead of populating a select element with many options, or building a set of 10 or 20 radio buttons, you can capture the user’s choice in another form element, query a server application based on the value, and build the other form elements based on the value—all without leaving the page. 


demonstrates a simple page that captures the change event for radio but‐ tons within a fieldset element, makes an Ajax query with the value of the selected radio button, and populates a selection list by parsing the returned option list.

A comma separates each of the option items, and new options are created with the returned text having both an option label and option value. Before populating the select element, its length is set to 0. This is a quick and easy way to truncate the select element— removing all existing options, and starting fresh. 

 Creating an on-demand select Ajax application


<!DOCTYPE html>
<head>
<title>On Demand Select</title>
<style>
#nicestuff
{
 display: none;
 margin: 10px 0;
}
#nicething
{
 width: 400px;
}
</style>
</head>
<body>
<form action="backuppage.php" method="get">
 <p>Select one:</p>
 <fieldset id="nicething">
 <input type="radio" name="nicethings" value="bird" />
 <label for="bird">Birds</label><br />
 <input type="radio" name="nicethings" value="flower" />
 <label for="flower">Flowers</label><br />
 <input type="radio" name="nicethings" value="sweets" />
<label for="sweets">Sweets</label><br />
 <input type="radio" name="nicethings" value="cuddles" />
 <label for="cuddles">Cute Critters</label>
 </fieldset>
 <input type="submit" id="submitbutton" value="get nice things" />
 <select id="nicestuff"></select>
</form>
<script>
var xmlhttp;
function populateSelect() {
 var value;
 var inputs = this.getElementsByTagName('input');
 for (var i = 0; i < inputs.length; i++) {
 if (inputs[i].checked) {
 value = inputs[i].value;
 break;
 }
 }
 // prepare request
 if (!xmlhttp) {
 xmlhttp = new XMLHttpRequest();
 }
 var url = "nicething.php?nicething=" + value;
 xmlhttp.open('GET', url, true);
 xmlhttp.onreadystatechange = getThings;
 xmlhttp.send(null);
}
// process return
function getThings() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var select = document.getElementById("nicestuff");
 select.length=0;
 var nicethings = xmlhttp.responseText.split(",");
 for (var i = 0; i < nicethings.length; i++) {
 select.options[select.length] =
 new Option(nicethings[i], nicethings[i]);
 }
 select.style.display="block";
 } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 alert("No items returned for request");
 }
}
document.getElementById("submitbutton").style.display="none";
document.getElementById("nicething").onclick=populateSelect;
</script>
</body>

The form does have an assigned action page, and a submit button that’s hidden when the script is first run. These are the backup if scripting is turned off. The application is also old school—text-based data that you can either append directly to the page (if for‐ matted as HTML), or parse using the String functions.

JSON is nice, but there’s always room for just plain text. The example uses a PHP application to populate the selection list. It could also be a Node application if you want to use JavaScript in both the client and server:

<?php
//If no search string is passed, then we can't search
if(empty($_REQUEST['nicething'])) {
 echo "No State Sent";
} else {
 //Remove whitespace from beginning & end of passed search.
 $search = trim($_REQUEST['nicething']);
 switch($search) {
 case "cuddles" :
 $result = "puppies,kittens,gerbils";
 break;
 case "sweets" :
 $result = "licorice,cake,cookies,custard";
 break;
 case "bird" :
 $result = "robin,mockingbird,finch,dove";
 break;
 case "flower" :
 $result = "roses,lilys,daffodils,pansies";
 break;
 default :
 $result = "No Nice Things Found";
 break;
 }
 echo $result;
}
?>


Progressively building form elements using Ajax or another communication technique isn’t necessary in all applications, but it is a great way to ensure a more effective form in cases where the data can change, or the form is complex.

JAVA SCRIPT - Processing JSON from an Ajax Request

Processing JSON from an Ajax Request


Problem

You want to format Ajax data as JSON, rather than text or XML. 

Solution

Create and initiate the Ajax request the same as for an XML or text data request. In this code, the service is a Node application, accessible at port 8080:

// ajax object
if (window.XMLHttpRequest) {
 httpRequest = new XMLHttpRequest();
}
// build request
var url = "http://shelleystoybox.com:8080";
httpRequest.open('GET', url, true);
httpRequest.onreadystatechange = getData;
httpRequest.send();

In the function to process the response, use the JSON object’s parse()method to convert the returned text into a JavaScript object:

function getData() {
 if (httpRequest.readyState == 4 && httpRequest.status == 200) {
 try {
 // Javascript function JSON.parse to parse JSON data
 var jsonObj = JSON.parse(httpRequest.responseText);
 console.log(jsonObj.list[0].name);
 } catch (e) {
 console.log(e.message);
 }
 }
}


The key to sending JSON in response to an Ajax request is to use whatever language’s version of the JSON.stringify() method to convert the object into a JSON-formatted string. In the following Node application, we can use the Node version of JSON to format the data. The MIME type for the data is also set to application/json:


var http = require('http');
// start server, listen for requests
var server = http.createServer().listen(8080);
server.on('request', function(req, res) {
 var titleList = {
 "list" : [
 { "id": "id1",
 "name": "Title One"
 },
 { "id": "id12",
 "name": "Another Value"
 },
 { "id": "id20",
 "name": "End of the Road"
 },
 { "id": "id24",
 "name": "One More"
 }
 ],
 "totalRecords": 4
 };
res.writeHeader(200, {"Content-Type": "application/json", "Access-Control-All
ow-Origin": "*"});
 res.end(JSON.stringify(titleList));
});

Processing JSON data from an Ajax request


var httpRequest;
// ajax object
if (window.XMLHttpRequest) {
 httpRequest = new XMLHttpRequest();
}
// build request
var url = "http://shelleystoybox.com:8080";
httpRequest.open('GET', url, true);
httpRequest.onreadystatechange = getData;
httpRequest.send();
function printData(element) {
 console.log(element.name);
}
function getData() {
 if (httpRequest.readyState == 4 && httpRequest.status == 200) {
 try {
 // Javascript function JSON.parse to parse JSON data
 var jsonObj = JSON.parse(httpRequest.responseText);
 jsonObj.list.forEach (function(element) {
 console.log(element.name);
 });
 } catch (e) {
 console.log(e.message);
 }
 }
}

Java printing Date/Time in a Given Format

Java printing Date/Time in a Given Format

Problem

You want to print the date and/or time in a locale-sensitive or otherwise-specified
format.

Solution

Use java.text.DateFormat .

Explained

To print the date in the correct format for whatever locale your software lands in,
simply use the default DateFormat formatter, which is obtained by calling DateFormat.
getInstance( ) :

import java.util.*;
import java.text.*;
public class DateFormatBest {
public static void main(String[] args) {
Date today = new Date( );
DateFormat df = DateFormat.getInstance( );
System.out.println(df.format(today));
DateFormat df_fr =
DateFormat.getDateInstance(DateFormat.FULL, Locale.FRENCH);
System.out.println(df_fr.format(today));
}
}

When I run this, it prints:

3/3/04 12:17 PM
mercredi 3 mars 2004

You can ask for a default date and time formatter ( df in the example), or a TimeFormatter or DateFormatter that extracts just the time or date portion of the Date object ( df_fr in the example). You can also request a nondefault Locale ( df_fr in the example). Five codes—FULL, LONG, MEDIUM, SHORT and DEFAULT—can be passed to describe how verbose a format you want. Suppose you want the date printed, but instead of the default format, you want it printed like “Sun 2004.07.18 at 04:14:09 PM PDT”. A look at the Javadoc page for SimpleDateFormat —the only nonabstract subclass of DateFormat —reveals that it has a rich language for specifying date and time formatting. Be aware that in so doing you are presuming to know the correct format in all locales; see Chapter 15 for why this may be a bad idea. To use a default format, of course, we can just use the Date object’s toString( ) method, and for a localized default format, we use DateFormat.getInstance( ) . But to have full control and get the “Sun 2004.07.18 at 04:14:09 PM PDT”, we construct an instance explicitly, like so:

new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

E means the day of the week; yyyy , MM , and dd are obviously year, month, and day. The quoted string 'at' means the string “at”. hh:mm:ss is the time; a means A.M. or P.M., and zzz means the time zone. Some of these are more memorable than others; I find the zzz tends to put me to sleep. Here’s the code:

// DateDemo.java
Date dNow = new Date( );
/* Simple, Java 1.0 date printing */
System.out.println("It is now " + dNow.toString( ));
// Use a SimpleDateFormat to print the date our way.
SimpleDateFormat formatter
= new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("It is " + formatter.format(dNow));

You can use as many of the given symbols as needed. Where a format can be used either in text or numeric context, you can set it to a longer form by repetitions of the character. For codes marked Text , four or more pattern letters cause the formatter to use the long form; fewer cause it to use the short or abbreviated form if one exists. Thus, E might yield Mon, whereas EEEE would yield Monday. For those marked Number , the number of repetitions of the symbol gives the minimum number of dig- its. Shorter numbers are zero-padded to the given number of digits. The year is han- dled specially: yy yields an ambiguous * two-digit year (98, 99, 00, 01...), whereas yyyy yields a valid year (2001). For those marked Text and Number , three or more symbols causes the formatter to use text, while one or two make it use a number: MM might yield 01, while MMM would yield January.

Java Finding Today’s Date

Java Finding Today’s Date

Problem

You want to find today’s date.

Solution

Use a Date object’s toString( ) method.

Explained

The quick and simple way to get today’s date and time is to construct a Date object
with no arguments in the constructor call, and call its toString( ) method:

// Date0.java
System.out.println(new java.util.Date( ));

However, for reasons just outlined, we want to use a Calendar object. Just use Calendar.getInstance( ).getTime( ) , which returns a Date object (even though the name makes it seem like it should return a Time value * ) and prints the resulting Date object, using its toString( ) method or preferably a DateFormat object. You might be tempted to construct a GregorianCalendar object, using the no-argument construc- tor, but if you do this, your program will not give the correct answer when non- Western locales get Calendar subclasses of their own (which might occur in some future release of Java). The static factory method Calendar.getInstance( ) returns a localized Calendar subclass for the locale you are in. In North America and Europe it will likely return a GregorianCalendar , but in other parts of the world it might (some- day) return a different kind of Calendar . Do not try to use a GregorianCalendar ’s toString( ) method; the results are truly impressive, but not very interesting. Sun’s implementation prints all its internal state information; Kaffe’s inherits Object ’s toString( ) , which just prints the class name and the hashcode. Neither is useful for our purposes.

C> java Date1
java.util.
GregorianCalendar[time=932363506950,areFieldsSet=true,areAllFieldsSet=true,lenient=tr
ue,zone=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-
28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=3,sta
rtDay=1,startDayOfWeek=1,startTime=7200000,endMode=2,endMonth=9,endDay=-
1,endDayOfWeek=1,endTime=7200000],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEA
R=1999,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_
OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=10,HOUR_OF_
DAY=22,MINUTE=51,SECOND=46,MILLISECOND=950,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]

Calendar ’s getTime( ) returns a Date object, which can be passed to println( ) to print today’s date (and time) in the traditional (but non-localized) format:

/ Date2.java
System.out.println(Calendar.getInstance( ).getTime( ));

Java Program: Number Palindromes

Java Program: Number Palindromes


My wife, Betty, recently reminded me of a theorem that I must have studied in high
school but whose name I have long since forgotten: that any positive integer number
can be used to generate a palindrome by adding to it the number comprised of its
digits in reverse order. Palindromes are sequences that read the same in either direc-
tion, such as the name “Anna” or the phrase “Madam, I’m Adam” (ignoring spaces
and punctuation). 

We normally think of palindromes as composed of text, but the
concept can be applied to numbers: 13531 is a palindrome. Start with the number
72, for example, and add to it the number 27. The results of this addition is 99,
which is a (short) palindrome. Starting with 142, add 241, and you get 383. Some
numbers take more than one try to generate a palindrome. 1951 + 1591 yields 3542,
which is not palindromic. The second round, however, 3542 + 2453, yields 5995,
which is. The number 17,892, which my son Benjamin picked out of the air, requires
12 rounds to generate a palindrome, but it does terminate:

C:\javasrc\numbers>java Palindrome 72 142 1951 17892
Trying 72
72->99
Trying 142
142->383
Trying 1951
Trying 3542
1951->5995
Trying 17892
Trying 47763
Trying 84537
Trying 158085
Trying 738936
Trying 1378773
Trying 5157504
Trying 9215019
Trying 18320148
Trying 102422529
Trying 1027646730
Trying 1404113931
17892->2797227972
C:\javasrc\numbers>

If this sounds to you like a natural candidate for recursion, you are correct. Recur- sion involves dividing a problem into simple and identical steps, which can be imple- mented by a function that calls itself and provides a way of termination. Our basic approach, as shown in method findPalindrome , is:

long findPalindrome(long num) {
if (isPalindrome(num))
return num;
return findPalindrome(num + reverseNumber(num));
}

That is, if the starting number is already a palindromic number, return it; otherwise, add it to its reverse, and try again. The version of the code shown here handles sim- ple cases directly (single digits are always palindromic, for example). We won’t think about negative numbers, as these have a character at the front that loses its meaning if placed at the end, and hence are not strictly palindromic. Further, palindromic forms of certain numbers are too long to fit in Java’s 64-bit long integer. These cause underflow, which is trapped. As a result, an error message like “too big” is reported. * Having said all that, Example shows the code.

Example. Palindrome.java
/** Compute the Palindrome of a number by adding the number composed of
* its digits in reverse order, until a Palindrome occurs.
* e.g., 42->66 (42+24); 1951->5995 (1951+1591=3542; 3542+2453=5995).
*/
public class Palindrome {
public static void main(String[] argv) {
for (int i=0; i<argv.length; i++)
try {
long l = Long.parseLong(argv[i]);
if (l < 0) {
System.err.println(argv[i] + " -> TOO SMALL");
continue;
}
System.out.println(argv[i] + "->" + findPalindrome(l));
} catch (NumberFormatException e) {
System.err.println(argv[i] + "-> INVALID");
} catch (IllegalStateException e) {
System.err.println(argv[i] + "-> TOO BIG(went negative)");
}
}
/** find a palindromic number given a starting point, by
* calling ourself until we get a number that is palindromic.
*/
static long findPalindrome(long num) {
if (num < 0)
throw new IllegalStateException("went negative");
if (isPalindrome(num))
return num;
System.out.println("Trying " + num);
return findPalindrome(num + reverseNumber(num));
}
/** The number of digits in Long.MAX_VALUE */
protected static final int MAX_DIGITS = 19;
// digits array is shared by isPalindrome and reverseNumber,
// which cannot both be running at the same time.
/* Statically allocated array to avoid new-ing each time. */
static long[] digits = new long[MAX_DIGITS];
/** Check if a number is palindromic. */
static boolean isPalindrome(long num) {
if (num >= 0 && num <= 9)
return true;
int nDigits = 0;
while (num > 0) {
digits[nDigits++] = num % 10;
num /= 10;
}
for (int i=0; i<nDigits/2; i++)
if (digits[i] != digits[nDigits - i - 1])
return false;
return true;
}
static long reverseNumber(long num) {
int nDigits = 0;
while (num > 0) {
digits[nDigits++] = num % 10;
num /= 10;
}
long ret = 0;
for (int i=0; i<nDigits; i++) {
ret *= 10;
ret += digits[i];
}
return ret;
}
}

JAVA SCRIPT - Making an Ajax Request to Another Domain (Using JSONP)

Making an Ajax Request to Another Domain (Using JSONP)


Problem

You want to query for data using a web service API, such as the Rotten Tomatoes API, or the Flicker API. However, the Ajax same-origin security policy prevents cross-domain communication

Solution

One approach is to use JSONP (JSON with padding) to work around the security issues.

First, you create a new script element, making the URL the endpoint for the API method call. The following creates a script element with a call to Flickr’s photo search API method: 


function addScript( url) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src = url;
 document.getElementsByTagName('head')[0].appendChild(script);
}

The URL looks like the following, including a request to return the data formatted as JSON, and providing a callback function name. The api_key is generated by Flickr, and the user_id is the unique user identifier, the NSID, for your account. Note this isn’t the same as the username. I’m asking for the first page of results for a given user:

http://api.flickr.com/services/rest/?method=flickr.photos.search&user_id=xxx
&api_key=xxx&page=1&format=json&jsoncallback=processPhotos

When the script tag is created, the request to Flickr is made, and because I passed in the request for a JSON-formatted result and provided a callback function name, that’s how the return is provided. The following is a basic callback function that just displays the results to the console:

function processPhotos(obj) {
 photos = obj.photos.photo;
 var str = '';
 photos.forEach(function(photo) {
 str+=photo.title + '
 ';
 });
 document.getElementById('result').innerHTML = str;
}

EXPLAIN

Ajax works within a protected environment that ensures we don’t end up embedding dangerous text or code into a web page because of a call to an external application (which may or may not be secure).The downside to this security is that we can’t directly access services to external APIs. Instead, we have to create a server-side proxy application because server applications don’t face the cross-domain restriction.

One workaround is to use JSONP, demonstrated in the solution. Instead of using XMLHttpRequest, we convert the request URL into one that we can attach to a script’s src attribute, because the script element does not follow the same-origin policy. If the service is amenable, it returns the data formatted as JSON, even wrapping it in a callback function. 

When the script is created, it’s no different than if the function call is made directly in our code, and we’ve passed an object as a parameter. We don’t even have to worry about converting the string to a JavaScript object.The callback’s argument is a JSON object. 


The photos are returned in pages, and you can repeat the calls as many times as you want to get as many photos as you need, changing the page number with each call. contains a simple, working example of using JSONP to access information from Flickr. Just remember to use your own API key and NSID. 

 Using JSONP to circumvent cross-domain restrictions and processing the result


<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>JSONP</title>
</head>
<body>
 <div id="result">
 </div>
<script >
function addScript( url) {
 var script = document.createElement('script');
 script.src = url;
 document.getElementsByTagName('head')[0].appendChild(script);
}
addScript('https://api.flickr.com/services/rest/?method=flickr.photos.search
&user_id=NSID&api_key=yourapikey&page=1&format=json&jsoncallback=processPhotos');
// assign photos globally, call first to load
function processPhotos(obj) {
 photos = obj.photos.photo;
 var str = '';
 photos.forEach(function(photo) {
 str+=photo.title + '<br /> ';
 });
 document.getElementById('result').innerHTML = str;
}
</script>
</body>
</html>

It’s a clever trick, but should only be used with caution. Even with secure services such as Flickr, there is the remote possibility that someone could find a way to inject JavaScript into the data via the client-side application for the service, which can cause havoc in the application.