Pages

Monday, November 15, 2010

Introducing JSON

(from: http://www.json.org/)
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Conditional branches


(beq, bne, slt, slti,  sltu( chck unsigned number) )

MIPS
if ( i == j )
  f = g + h;
else
  g = g - h;
assume:
f = $s0, g = $s1,  h = $s2
i = $s3,  j = $s4

#---------------
bne   $s3, $s4, ELSE
add   $s0, $s1, $2
j    Exit     # skip else

ELSE:
sub   $s1, $s1, $s2

Exit:
if ( i < j )
  f = g + h;
else
 g = g - h;
slt $t0, $s3, $s4    # i < j, $t0 = 0, else $t0=1

bne $t0, 1, Else
add    $s0, $s1, $s2
j    Exit      # skip else part

Else:
sub $s1, $s1, $s2

Exit:



While Loop


MIPS
while ( save[i] == k )
  i += 1;
assume:  i = $s3, k = $s5 , save[0] = $s6

#------------------------
(convert lw $t0, 4i($s6) )

Loop:
sll    $s3, $s3, 2        #  i = 4i
add  $t1, $s3, $s6    # 4i($s6)
lw    $t0, 0($t1)         #  lw $t0, 4i($s6)

bne $t0, $s5, Exit
addi $s3,$s3, 1
j  Loop                      # loop again

Exit:




Case / Switch Statement



switch (k)
{
 case 0:  f = i + j; break;
 case 1:  f = g + h; break;
 case 2:  f = i - j;  break;
 case 3:  f = g - h; break;

}

---------------------------------------
assume:  f = $s0, g = $s1, h = $s2, i = $s3,
j = $s4, k = $s5
$t2 = 4
$t4 contains address of an array, jumptable

slt $t0, $s5, $0   # k < 0; $t0 = 1; else $t0 =0
beq $t0, 1, Exit  # k < 0, go to L1
beq $s5, 0, L0   # k = 0, go to L2
beq $s5, 1, L1
beq $s5, 2, L2
beq $s5, 3, L3
slt  $t0, 3, $s5  # k > 3, $t0 = 1; else $t0 = 0
beq $t0, 1, Exit

L0:
  add $s0, $s3, $s4
  j Exit
L1:
  add $s0, $s1, $s2
  j Exit
L2:
  sub $s0, $3, $s4
  j Exit
L3:
  sub $s0, $s1,$s2
  j Exit

Exit:



Procedures



MIPS
int leaf_example ( int g, int h, int i, int j )
{
   int f;
   f = ( g + h )  - ( i + j );
   return f;
}

f, g, h , i,  j are local variables in the procedure.

any declaired variable in procedure use
$s0  - $s7

addi $sp, $sp, -12
sw    $t1,  8($sp)
sw    $t0,  4($sp)
sw    $s0, 0($sp)

add $t0, $a0, $a1
add $t1, $a2, $a3
sub $s0, $t0, $t1
add $v0, $s0, $0

lw  $s0, 0($sp)
lw  $t0,  4($sp)
lw  $t1,  8($sp)
addi $sp, $sp, 12

jr $ra
Does it work??? If I don’t store in the stack?

add $v0, $a0, $a1
add $t0, $a2, $a3
sub $v0, $v0, $t0

jr $ra

is it right????
#--------------------------------
addi $sp, $sp, -8
sw $t0, 4($sp)
sw $t1, 0($sp)

add $t0, $a0, $a1
add $t1, $a2, $a3
sub $v0, $t0, $t1

lw $t1, 0($sp)
lw $t0, 4($sp)
addi $sp, $sp,8

jr $ra



Nested Procedures


int fact ( int n )
{   
   if ( n < 1 ) return (1);
   else
          return ( N * fact ( n - 1));
}
#----------------------
fact:
addi   $sp, $sp, -8
sw     $ra, 4($sp)    # save the return address
sw     $a0, 0($sp)   # save the argument n

slti   $t0, $a0, 1      # n < 1; $t0 = 1; else $t0 = 0
beq  $t0, $0, L1     # n >= 1 go to L1

addi  $v0, $0, 1      # return 1
addi  $sp, $sp, 8
jr    $ra

L1:
addi  $a0, $a0, -1    # n >= 1; argument gets ( n - 1 )
jal fact
lw     $a0, 0($sp)
lw     $v0, 4($sp)
addi $sp, $sp,8

mul   $v0, $a0, $v0    # return n * fact ( n - 1 )

jr     $ra
int fact ( int n )
{   
   if ( n < 1 ) return (1);
   else
          return ( N * fact ( n - 1));
}
2 values need to be stored:
n, return value

fact:
addi $sp, $sp, -8
sw $a0, 4($sp)
sw $ra, 0($sp)

slt $t0, $a0, 1        # $a0 < 1 , $t0 = 1; else $t0 = 0
beq $t0, $0, L1      # n >= 1
# n < 1
add $v0, $0, 1       # return 1  
addi $sp, 8($sp)   #
jr $ra

L1:  # (n >= 1)
addi $a0, $a0, -1   # n--
jal  fact

lw $ra, 0($sp)
lw $a0, 4($sp)
addi $sp, $sp, -8
mul $v0, $a0, $v0   # N * fact (n -1)

jr $ra

Sunday, November 14, 2010

DATABASE: EXTERNAL SORTING

CH12 External Sorting

Generate XML using SAX


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;



.......

//generating XML file using SAX
SAXTransformerFactory fac = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
File outFile = new File("/test.xml");
OutputStream outStream = new FileOutputStream(outFile);
StreamResult resultxml = new StreamResult(outStream);


try {
String data=null;
//SAX ContentHandler
TransformerHandler handler = fac.newTransformerHandler();
handler.setResult(resultxml);

Transformer transformer = handler.getTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");


//start the document

handler.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.clear();
handler.startElement("", "", "Students", atts);
handler.startElement("", "", "Student", null);
        handler.startElement("""""ID"null);

data = "12345";
handler.characters(data.toCharArray(), 0, data.length());        handler.endElement("", "", "ID");
        handler.startElement("""""Name"null);
data = "John Smith";
handler.characters(data.toCharArray(), 0, data.length());        handler.endElement("""""Name");
handler.endElement("""""Student");

handler.endElement("""""Students");
handler.endDocument();
handler.setResult(resultxml);
outStream.close();


Genrated test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Students>
<Student>
<ID>12345</ID>
<Name>John Smith</Name>
</Student>
</Stueents>



Generating XML via Java

Most of the attention in the XML world focuses on parsing XML and walking an XML structure. The W3C provides the DOM and SAX specifications to parse data, Sun provides the Java XML Pack, and Apache has Xerces and Xalan. However, very little attention is paid to the techniques for XML output. Projects are looking into turning JavaBeans and Swing components into XML, but most of the time, developers simply want to output a data structure in a custom-formatted way.

This article concentrates on methods for creating XML documents via Java. I offer a few different methods to create XML documents in Java. They have differing advantages—some are ridiculously simple, and others rely on heavy, powerful libraries. I’ll begin with the simplest.

Using the StringBuffer class
The simplest, and most commonly used, method for creating XML documents is to do it yourself. You can do so by using the StringBuffer class or some form of theWriter class. The advantages are that you don’t need any additional libraries, and you create no extra objects. However, this approach has many disadvantages. There is no validation to ensure properly formed XML. Characters must be escaped when placed in String objects. And you can’t escape XML entities, such as replacing < with&lt;. Listing A provides an example.

The output of Listing A is:
<person name="Jon Smith" age="21"/>

The simple example from Listing A falls flat on its face when presented with an odd name, such as Jon "The Cat" Smith. The code will not escape the quote (") characters when retrieving the name, and the output will be erroneous:
<person name="Jon "The Cat" Smith" age="21"/>

It is difficult to keep track of the XML hidden inside the Java when trying to read the source code. Indeed, half of the errors of this development approach will come down to unclosed tags and bad handling of quotes. In short, the result will be invalid XML.

A cleaner and easier way: DOM
The next method is the Document Object Model (DOM) way. Given an object structure, you convert it to some form of XML-object structure and then traverse that structure and output it. Many types of structures are available, ranging from the Jakarta Element Construction Kit (ECS) project's XML class to a full DOM with a DOM-compliant parser such as Xerces. The smaller versions often come with very simple methods to output the XML. Listing B shows an example in ECS.

Listing B offers a nice, concise way to output the data. In fact, you could merge the two output lines into one by appending the output method onto the newXMLDocument. This is a classic syntax pattern with ECS and is easy to work with. However, it does not nicely replicate the if-null protection for the person's age. To achieve this protection, you have to break the code as shown in Listing C.

ECS presents several advantages. You don’t have to escape quote characters ("). You don’t need to close the tags at all—the objects take care of that for you, and any XML characters, such as < or >, are escaped to &lt; and &gt;. Also, ECS is the simplest of the DOM-style methodologies. Handling this style of code in W3C's DOM, JDOM, or Dom4J is a layer of complexity higher, although the advantage of W3C's DOM is that of parser independence.

Among the disadvantages of outputting XML using ECS is the object structure. You must build it before writing things out. While doing so might be fine in most cases, you wouldn't want to be assembling this XML structure when outputting a large XML file. The same disadvantage holds for most other DOM-style methodologies.

ECS is much closer to the mark than the previous methodology of using simpleWriters or StringBuffer classes. It has a big jar size, but only a small part is necessary to output XML. The biggest failing is that it doesn't scope well. It beats out any of its brethren because they are all larger, heavier, and more complicated.

Great SAX
There is an alternative to the DOM-style of XML parsing: the Simple API for XML (SAX). It consists of a series of events or callbacks that are called on your code while the XML file is parsed. It is not much use when you want to output directly to Strings, but it can be used in an indirect, more complex way.

Code that outputs Strings can instead output SAX events. This is more powerful than just outputting Strings, and it can be added to a simple generic class that turns SAX events into XML.

Let’s look at an example that uses the following classes:

  • ·        Person: A business object, described previously
  • ·        PersonInputSource: Holds a Person object
  • ·        PersonXMLReader: Knows how to turn a PersonInputSource into SAX events
  • ·        XMLPrettyPrinter: A ContentHandler that turns SAX events into XML

The most important piece of code is in PersonXMLReader, as shown in Listing D.

The code in Listing D is the guts of how the Person object is turned into a series of SAX events. It is not the simplest thing to do. Transforming a Person to XML via SAX functionality is implemented by the top-level code in Listing E.

Using SAX definitely gives you added power, because you can attach a SAX parser to the XML instead of the XMLPrettyPrinter. However, complexity increases when you add the handler; SAX is a more complicated concept. In many cases, it is true that the simple approach is best.

Once the generic components are written (XMLPrettyPrinter, a generic InputSource, and an XMLParser object), the event firing is simplified. The output of a new XML structure requires only the parse method and the top-level plugging together of components.

Having an XML-output system around SAX events has a lot going for it, but it is not a quick, off-the-shelf approach.

Using an XmlWriter class
Finally, I present my own alternative, an XmlWriter class. The idea is to output XML using a technique that fills the niche between too simple and too complex.

The important design requirements are as follows:
  • ·        Wrap a java.io.Writer
  • ·        Provide a Writer-like API
  • ·        Take care of as much of the XML handling as possible
  • ·        Avoid a large object structure
  • ·        Allow the ECS chaining style

These requirements allow the XML to be written in two distinct styles. First, it can be written in the style of a java.lang.Writer code snippet, as shown in Listing F.

Second, it can be written in the chained-method style of coding, just like ECS, because each write method returns the XmlWriter itself. Listing G gives an example.

In terms of performance, XmlWriter is lean and creates few other objects. It is functional, and it can handle basic XML snippets (but not comments, indentation, or doctypes). Most important, it is easy to use.

On the downside, as already mentioned, it doesn't handle comments, indentation, or doctypes. Unlike ECS, which closes tags when the XML object writes itself,XmlWriter requires you to call an endEntity method. This method will throw anXmlWritingException if it is called when there are no entities to end. Finally, a closemethod exists. It does not close the underlying writer object, but finishes any XML that is being written. Perhaps most important, it will throw an XmlWritingException if there are unended entities.

Conclusion
Many options are available for generating XML documents. XmlWriter is by no means the best tool for every XML creation task, but it can fill the gap that exists between approaches that are too simple, too heavy, and too complex.


(ref: http://articles.techrepublic.com.com/5100-10878_11-1044810.html# )