text:
Fortran/Fortran examples

The following Fortran code examples or sample programs show different situations depending on the compiler. The first set of examples are for the Fortran II, IV, and 77 compilers. The remaining examples can be compiled and run with any newer standard Fortran compiler (see the end of the main Fortran article for lists of compilers). By convention most contemporary Fortran compilers select the language standard to use during compilation based on source code file name suffix: FORTRAN 77 for  (or the less common  ), Fortran 90 for , Fortran 95 for. Other standards, if supported, may be selected manually with a command line option.

FORTRAN II, IV, and 77 compilers
NOTE: Before FORTRAN 90, most FORTRAN compilers enforced fixed-format source code, a carryover from IBM punch cards
 * comments must begin with a * or C or ! in column 1
 * statement labels must occur in columns 1-5
 * continuation lines must have a non-blank character in column 6
 * statements must start in column 7
 * the line-length may be limited to 72 characters (derived from the 80-byte width of a punch-card, with last 8 characters reserved for (optional) sequence numbers)

If errors are produced when you compile your FORTRAN code, first check the column alignment. Some compilers also offer free form source by using a compiler flag

Simple Fortran II program
One data card input

If one of the input values is zero, then the program will end with an error code of "1" in the job control card listing following the execution of the program. Normal output will be one line printed with A, B, C, and AREA. No specific units are stated.

Simple Fortran IV program
Multiple data card input

This program has two input checks: one for a blank card to indicate end-of-data, and the other for a zero value within the input data. Either condition causes a message to be printed.

Simple Fortran 77 program
Multiple data card input

This program has two input checks in the READ statement with the END and ERR parameters, one for a blank card to indicate end-of-data; and the other for zero value along with valid data. In either condition, a message will be printed.

"Retro" FORTRAN IV
A retro example of a FORTRAN IV (later evolved into FORTRAN 66) program deck is available on the IBM 1130 page, including the IBM 1130 DM2 JCL required for compilation and execution. An IBM 1130 emulator is available at IBM 1130.org that will allow the FORTRAN IV program to be compiled and run on a PC.

Hello, World program
In keeping with computing tradition, the first example presented is a simple program to display the words "Hello, world" on the screen (or printer).

FORTRAN 66 (also FORTRAN IV)
This program prints "HELLO, WORLD" to Fortran unit number 6, which on most machines was the line printer or terminal. (The card reader or keyboard was usually connected as unit 5). The number 7 in the  statement refers to the statement number of the corresponding   statement. statements may be placed anywhere in the same program or function/subroutine block as the  statements which reference them. Typically a  statement is placed immediately following the   statement which invokes it; alternatively,   statements are grouped together at the end of the program or subprogram block. If execution flows into a  statement, it is a no-op; thus, the example above has only two executable statements,   and.

The initial  in the   statement in the above example defines a Hollerith constant, here meaning that the 13 characters immediately following are to be taken as a character constant (note that the Hollerith constant is not surrounded by delimiters). (Some compilers also supported character literals enclosed in single quotes, a practice that came to be standard with FORTRAN 77.)

The space immediately following the 13H is a carriage control character, telling the I/O system to advance to a new line on the output. A zero in this position advances two lines (double space), a 1 advances to the top of a new page and + character will not advance to a new line, allowing overprinting.

FORTRAN 77
As of FORTRAN 77, single quotes are used to delimit character literals, and inline character strings may be used instead of references to  statements. Comment lines may be indicated with either a  or an asterisk  in column 1.

Fortran 90
As of Fortran 90, double quotes are allowed in addition to single quotes. An updated version of the Hello, world example (which here makes use of list-directed I/O, supported as of FORTRAN 77) could be written in Fortran 90 as follows:

Greatest common divisor
The following introductory example in FORTRAN 77 finds the greatest common divisor for two numbers $$A$$ and $$B$$ using a verbatim implementation of Euclid's algorithm.

The above example is intended to illustrate the following:
 * The  and   statements in the above use ' ' as a format, specifying list-directed formatting. List-directed formatting instructs the compiler to make an educated guess about the required input or output format based on the following arguments.
 * As the earliest machines running Fortran had restricted character sets, FORTRAN 77 uses abbreviations such as,  ,  ,  ,  , and   to represent the relational operators =, ≠, <, >, ≤, and ≥, respectively.
 * This example relies on the implicit typing mechanism to specify the INTEGER types of,  ,  ,  , and.
 * In the function, the values of the function arguments   and   are copied into the local variables   and   respectively. This is necessary as the values of   and   are altered within the function. Because argument passing in Fortran functions and subroutines utilize call by reference by default (rather than call by value, as is the default in languages such as C), modifying   and   from within the function would effectively have modified the corresponding actual arguments in the main   unit which called the function.

The following shows the results of compiling and running the program.

Complex numbers
The following FORTRAN 77 example prints out the values of $$e^{j i \pi / 4}$$ (where $$j = \sqrt{-1}$$) for values of $$i = 0, 1, \ldots, 7$$.

The above example is intended to illustrate the following:
 * The  statement can be used to specify the implicit type of variables based on their initial letter if different from the default implicit typing scheme described above. In this example, this statement specifies that the implicit type of variables beginning with the letter   shall be.
 * The  statement may be used to specify constants. The second constant in this example  is given the complex-valued value $$0 + j1$$, where $$j$$ is the imaginary unit $$\sqrt{-1}$$.
 * The first number in the  statement specifies the number of the last statement considered to be within the body of the   loop. In this example, as neither the   nor the   is a single executable statement, the   statement (which does nothing) is used simply in order for there to be some statement to denote as the final statement of the loop.
 * corresponds to the exponential function $$e^x$$. In FORTRAN 77, this is a generic function, meaning that it accepts arguments of multiple types (such as  and, in this example,  ). In FORTRAN 66, a specific function would have to be called by name depending on the type of the function arguments (for this example,   for a  -valued argument).
 * When applied to a -valued argument,   and   return the values of the argument's real and imaginary components, respectively.

Incidentally, the output of the above program is as follows (see the article on Euler's formula for the geometric interpretation of these values as eight points spaced evenly about a unit circle in the complex plane).

Error can be seen occurring in the last decimal place in some of the numbers above, a result of the  data type representing its real and imaginary components in single precision. Incidentally, Fortran 90 also made standard a double-precision complex-number data type (although several compilers provided such a type even earlier).

Summations with a DO loop
In this example of Fortran 90 code, the programmer has written the bulk of the code inside of a DO loop. Upon execution, instructions are printed to the screen and a SUM variable is initialized to zero outside the loop. Once the loop begins, it asks the user to input any number. This number is added to the variable SUM every time the loop repeats. If the user inputs 0, the EXIT statement terminates the loop, and the value of SUM is displayed on screen.

Also apparent in this program is a data file. Before the loop begins, the program creates (or opens, if it has already been run before) a text file called "SumData.DAT". During the loop, the WRITE statement stores any user-inputted number in this file, and upon termination of the loop, also saves the answer.

When executed, the console would display the following:

And the file SumData.DAT would contain:

Calculating cylinder area
The following program, which calculates the surface area of a cylinder, illustrates free-form source input and other features introduced by Fortran 90.

Dynamic memory allocation and arrays
The following program illustrates dynamic memory allocation and array-based operations, two features introduced with Fortran 90. Particularly noteworthy is the absence of  loops and  /  statements in manipulating the array; mathematical operations are applied to the array as a whole. Also apparent is the use of descriptive variable names and general code formatting that comport with contemporary programming style. This example computes an average over data entered interactively.

Writing functions
Modern Fortran features available for use with procedures, including deferred-shape, protected, and optional arguments, are illustrated in the following example, a function to solve a system of linear equations.

Note that an explicit interface to this routine must be available to its caller so that the type signature is known. This is preferably done by placing the function in a  and then  ing the module in the calling routine. An alternative is to use an  block, as shown by the following example:

Writing subroutines
In those cases where it is desired to return values via a procedure's arguments, a subroutine is preferred over a function; this is illustrated by the following subroutine to swap the contents of two arrays:

As in the previous example, an explicit interface to this routine must be available to its caller so that the type signature is known. As before, this is preferably done by placing the function in a  and then  ing the module in the calling routine. An alternative is to use a  block.

Internal and Elemental Procedures
An alternative way to write the  subroutine from the previous example, is:

In the example, the  subroutine is elemental, i.e., it acts upon its array arguments, on an element-by-element basis. Elemental procedures must be pure (i.e., they must have no side effects and can invoke only pure procedures), and all the arguments must be scalar. Since  is internal to the   subroutine, no other program unit can invoke it.

The following program serves as a test for any of the two  subroutines presented:

Pointers and targets methods
In Fortran, the concept of pointers differs from that in C-like languages. A Fortran 90 pointer does not merely store the memory address of a target variable; it also contains additional descriptive information such as the target's rank, the upper and lower bounds of each dimension, and even strides through memory. This allows a Fortran 90 pointer to point at submatrices.

Fortran 90 pointers are "associated" with well-defined "target" variables, via either the pointer assignment operator or an   statement. When appearing in expressions, pointers are always dereferenced; no "pointer arithmetic" is possible.

The following example illustrates the concept:

Module programming
A module is a program unit which contains data definitions, global data, and ed procedures. Unlike a simple  file, a module is an independent program unit that can be compiled separately and linked in its binary form. Once compiled, a module's public contents can be made visible to a calling routine via the  statement.

The module mechanism makes the explicit interface of procedures easily available to calling routines. In fact, modern Fortran encourages every  and   to be  ed in a. This allows the programmer to use the newer argument passing options and allows the compiler to perform full type checking on the interface.

The following example also illustrates derived types, overloading of operators and generic procedures.

title: Fortran/Fortran examples


text:
Talk:Fortran/Fortran examples

examples for Fortran II, Fortran IV and FORTRAN 77
can be compiled now with gfortran

Example 1
Compiles/runs successfully with g77 g77 *.fpp -o new -Wall -pedantic --H2g2bob 00:30, 29 January 2006 (UTC)

Dual License
I agree to license, the version of this page for which I hold the copyright (this version), under the GNU General Public License (GPL) version 2. Please be aware that other contributors might not do the same, so if you want to use my contributions under the GPL terms, please check the Multi-licensing guides. --H2g2bob 22:46, 27 June 2006 (UTC)

Moving
To comply with the standard wikibook naming policy, I will be moving this page to a section in the Programming:Fortran wikibook, if there are no objections.

Transwiki
I've just added content from Wikipedia article Fortran code examples, which is about to be deleted via AfD. Main authors are mentioned in edit summary, here is the full list:

21:15, 25 October 2007 Hq3473 (27,764 bytes) (Nominated for deletion: see Wikipedia:Articles for deletion/PageName) 09:29, 21 October 2007 Jwmwalrus (27,544 bytes) (>Writing functions) 00:40, 15 October 2007 LanceBarber (27,544 bytes) (adjust sections and subsections) 00:23, 15 October 2007 LanceBarber (27,582 bytes) (fix Main) 12:50, 14 October 2007 24.9.10.202 (Talk | block) (27,596 bytes) (Add fortran 77 example) 12:29, 14 October 2007 24.9.10.202 (Talk | block) (26,580 bytes) (add section breaks, move text) 12:26, 14 October 2007 24.9.10.202 (Talk | block) (26,547 bytes) (fix intro for added examples) 12:21, 14 October 2007 24.9.10.202 (Talk | block) (26,401 bytes) (>Simple Fortran IV program - note) 12:18, 14 October 2007 24.9.10.202 (Talk | block) (26,223 bytes) (>Simple Fortran II program) 12:10, 14 October 2007 24.9.10.202 (Talk | block) (25,969 bytes) (add simple Fortran IV prog) 10:39, 14 October 2007 LanceBarber (24,617 bytes) (wikify lead-in sentence, add internal links) 20:46, 10 October 2007 Hyperionred (24,560 bytes) (The Snoopy Calendar page was deleted by the humorless fascists that run this place. Removing here, too = 01:19, 31 August 2007 Tripodics (24,802 bytes) (>Summations with a DO loop (FORTRAN 90) - Unfortunately, the END DO and EXIT statements were not added until Fortran 90.) 16:35, 6 July 2007 82.18.15.2 (Talk | block) (24,802 bytes) (>Greatest common divisor (FORTRAN 77) - Broken internal link) 14:56, 8 June 2007 Rezd (24,785 bytes) (>Complex numbers (FORTRAN 77)) 14:56, 8 June 2007 Rezd (24,799 bytes) (Cleared up prompt as it may be confusing to some. - >Greatest common divisor (FORTRAN 77)) 22:15, 10 May 2007 Hq3473 (24,827 bytes) (>"Retro" FORTRAN IV - no link) 05:31, 24 April 2007 69.123.129.152 (Talk | block) (24,831 bytes) (>Summations with a DO loop (FORTRAN 77)) 05:31, 24 April 2007 69.123.129.152 (Talk | block) (24,832 bytes) (>Summations with a DO loop (FORTRAN 77)) 21:36, 16 February 2007 131.239.52.20 (Talk | block) (removed a superfluous comma) 10:28, 9 February 2007 Jayvdb m (avoid redirect to Job Control Language, Replaced: JCL > JCL using AWB) 21:56, 11 January 2007 Minnaert (added categories) 10:27, 18 December 2006 Alaibot m (Robot: tagging as uncategorised) 22:08, 5 December 2006 12.14.71.50 (Talk | block) 02:00, 5 December 2006 69.123.129.152 (Talk | block) (I've added a small program I wrote to test certain kinds of DO loops, then enhanced it with an example of writing to data files.) 01:19, 24 November 2006 24.197.168.66 (Talk | block) (>Writing subroutines (Fortran 90)) 02:24, 18 October 2006 STBot m (clean up using AWB) 18:05, 16 August 2006 Rwwww 10:34, 10 August 2006 KymFarnik m 06:10, 10 August 2006 KymFarnik (Tidy) 08:34, 9 August 2006 Rwwww 07:43, 9 August 2006 Rwwww 07:40, 9 August 2006 Rwwww MaxSem 19:18, 3 November 2007 (UTC)

Fortran 2 does NOT know Boolean if statemens
The same example of the Heron's Formula is also on Wikipedia itself. I dare now to rectify.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Talk:Fortran/Fortran examples


text:
Programming Mac OS X with Cocoa for Beginners/Archiving

Previous Page: An Inspector calls | Next Page: Adding finesse

We already discussed some of the general principles of archiving, now we'll make it happen for our drawing documents. Once we have the ability to archive shapes, we will find that implementing things such as cut and paste become straightforward.

You'll recall that when we added code to MyDocument to read and write the document to and from a file, we used a pair of objects called an NSKeyedArchiver and an NSKeyedUnarchiver. At that point, we simply archived our entire 'objects' array as the so-called root object. We didn't really care what happened behind the scenes - the archiver turned the array into an NSData object which we handed off to Cocoa which wrote the data to a file. When we opened a file, the unarchiver rebuilt our array which we then used as our objects array. So we should be able to save a drawing as a file and open it again, shouldn't we? No, not yet. The problem is that so far we haven't archived the actual properties of our shapes. WKDShape is a class we designed, so Cocoa doesn't yet know how to archive it. Thus if we try and save our drawings, we'll be disappointed that we get a blank document back when we open them again.

We tell Cocoa how to archive our shapes by writing a little code. We need these two methods:

- (void)		encodeWithCoder:(NSCoder*) coder; - (id)			initWithCoder:(NSCoder*) coder;

These two are part of a formal protocol, NSCoding. We already met an informal protocol, which is just some methods that we agreed amongst ourselves to implement. A formal protocol is similar, except that it is strictly enforced - an object that implements a formal protocol MUST do so. In order to tell Cocoa that we want to be part of the formal protocol, we modify our class declaration like so:

@interface WKDShape : NSObject

This says we are going to be implementing the formal protocol NSCoding. If we fail to do so, we'll get an error at compile time and will be unable to build our application.

Earlier we used NSKeyedArchiver, and its counterpart NSKeyedUnarchiver. Examination of the header files for these will show that these are in fact subclasses of a more general class called an NSCoder. This is what is passed to the two methods above, the pair of which are required to implement the NSCoding protocol. All we need to do is to tell the coder which properties to add to its archive, it does the rest. We give each property a name or key, and then use that key to retrieve the same property later. The properties we need to save for each shape are:

 * its size
 * its position
 * its fill and stroke colours
 * its stroke width

NSCoder has methods such as encodeObject:ForKey: and encodeFloat:forKey: that will handle the hard work. So here are our archiving methods:

- (void)		encodeWithCoder:(NSCoder*) coder {	[coder encodeRect:[self bounds] forKey:@"bounds"]; [coder encodeObject:[self fillColour] forKey:@"fill_colour"]; [coder encodeObject:[self strokeColour] forKey:@"stroke_colour"]; [coder encodeFloat:[self strokeWidth] forKey:@"stroke_width"]; }

- (id)			initWithCoder:(NSCoder*) coder {	[self init]; [self setBounds:[coder decodeRectForKey:@"bounds"]]; [self setFillColour:[coder decodeObjectForKey:@"fill_colour"]]; [self setStrokeColour:[coder decodeObjectForKey:@"stroke_colour"]]; [self setStrokeWidth:[coder decodeFloatForKey:@"stroke_width"]]; return self; }

The first, encodeWithCoder, is used when saving. The properties are saved to the coder using the keys given here, which are just strings that identify the property. The decode method is the reverse. Note that it is an init method, which makes sense - the object is created from the data stream by the coder, so it needs to be initialised using the saved properties. Normally, an object will call [super initWithCoder:coder] and [super encodeWithCoder:coder] before doing anything else, so that properties of all the subclasses are also saved as needed. In this case, because we have inherited from NSObject, which doesn't implement , we don't need to do this (in fact it would be an error to do so). That's why in this case we call [self init] instead.

Now if you compile and run, you'll find that saving a drawing to a file works - when you open that file again, your drawing reappears exactly as it was when it was saved, including all the properties such as colours, etc.

Cut and Paste
Cut and Paste leverages archiving so that we can move objects between documents, etc. Now we are able to archive a WKDShape, we are also able to archive any set of these shapes reliably and easily. Recall that an NSKeyedArchiver converts a "root object" of some kind to a NSData object, which is just a block of data containing an encoded version of that object. NSData is written to a file in the case of saving the document, but if we write it to an object called a pasteboard instead, we have put that data on the clipboard, thus implementing a cut or copy. Paste is the reverse operation, similar to dearchiving a file; we unarchive the clipboard data and add the objects so created to the document.

Cut and Paste are commands, so we implement them as action methods in MyDocument. Add the following to the class definition in MyDocument.h and SAVE the file:

- (IBAction)	cut:(id) sender; - (IBAction)	copy:(id) sender; - (IBAction)	paste:(id) sender; - (IBAction)	delete:(id) sender;

We will be implementing all four. Note however that a cut is equivalent to a copy followed by a delete, and a delete is just a case of deleting the objects in the selection, so the only 'hard' work is in the copy: and paste: methods. Before we implement them, let's hook them up in IB.

double-click 'MainMenu.nib' to open it (if it's not open already in IB), and double-click the 'FirstResponder' icon. Recall that we use FirstResponder whenever commands can be implemented in a variety of places that depend on the context. This is just such a time, since cut and paste etc can be implemented in all sorts of ways by all sorts of objects. As it happens, you'll find that we don't need to do anything - cut, paste etc are all prewired for you when Mainmenu.nib was created. Verify that the menu commands are indeed connected to these methods.

In Xcode, flesh out these four methods in MyDocument.m. For now, don't add any code. Compile and Run the project. You'll now see that the Cut, Paste commands are available in the Edit menu. In fact we'd rather that these only became available when there was something selected to actually cut, but for now we'll accept the default behaviour until we have built and tested the code.

The object responsible for the clipboard behaviour in Cocoa is NSPasteboard. There are in fact a number of pasteboards for different tasks but the one we need is the basic one, called the 'general' pasteboard. When we receive a 'cut' command, we archive the selection into an NSData object, then place this data on the general pasteboard. Because this data is private to our application, we don't need to worry at this stage about converting it to a form that would be readable by other applications, such as TIFF or PDF.

Here is the implementation for our edit methods:

- (IBAction)	cut:(id) sender {	[self copy:sender]; [self delete:sender]; }

- (IBAction)	copy:(id) sender {	if (self selection] count] > 0 )	{		NSData* clipData = [NSKeyedArchiver archivedDataWithRootObject:[self selection; NSPasteboard* cb = [NSPasteboard generalPasteboard]; [cb declareTypes:[NSArray arrayWithObjects:@"wikidrawprivate", nil] owner:self]; [cb setData:clipData forType:@"wikidrawprivate"]; } }

- (IBAction)	paste:(id) sender {	NSPasteboard* cb = [NSPasteboard generalPasteboard]; NSString* type = [cb availableTypeFromArray:[NSArray arrayWithObjects:@"wikidrawprivate", nil]]; if ( type ) {		NSData* clipData = [cb dataForType:type]; NSArray* objects = [NSKeyedUnarchiver unarchiveObjectWithData:clipData]; NSEnumerator* iter = [objects objectEnumerator]; id obj; [self deselectAll]; while( obj = [iter nextObject]) {			[self addObject:obj]; [self selectObject:obj]; [(WKDShape*)obj repaint]; }	} }

- (IBAction)	delete:(id) sender {	NSArray* sel = [[self selection] copy];	NSEnumerator* iter = [sel objectEnumerator];	id obj;	while ( obj = [iter nextObject])		[self removeObject:obj];	[sel release]; }

cut: is simply a copy: followed by a delete:

copy: first checks that the selection isn't empty, and if not, it archives the selection to an NSData object using a keyed archiver. Then it obtains the general pasteboard. To put data on the pasteboard, you first declare the types that the data will have. This allows multiple representations to be placed on the clipboard of the same data - the receiver can decide which representation suits it best - for example a graphics program might want a TIFF image of the data, whereas a word processior might want a text representation, etc. Here, we only have one representation, which is a private format we call "wikidrawprivate". Thus the "list" of types in fact only contains one item. Once we have declared the type, we can put the data on the pasteboard associated with that type.

paste: reverses this procedure. First it obtains the general pasteboard and checks that data of the type "wikidrawprivate" does exist. If not, it does nothing, so it won't attempt to paste data from another application that it cannot understand. Then we download the data fron the pasteboard, and unarchive it. We know it's an array of shape objects - whatever the copied selection contained in fact. We need to ADD these objects to the document, so we just iterate over the array and add and select the objects we come across. We also first deselect all the objects in the document so that the user gets the expected result - the pasted objects are selected after the paste.

The delete: method deletes the selected objects from the document. It does this by iterating over a COPY of the selection array. A copy is needed here because removing an object also deselects it - if we didn't make a copy we'd be modifying the same array that we are iterating over and things wouldn't work correctly. Once we've removed the objects from the document, we are done with the copy so we release it.

Compile and run the project and confirm that you have the ability to cut and paste objects between different documents.

Further exercises:

 * Modify the code so that it also exports a PDF representation of the selection. This is moderately involved, but not that difficult. Hint: look at NSView's writePDFInsideRect:toPasteboard: method

 * More complex: Add drag and drop behaviour. This is almost the same as Cut and Paste, and uses the 'drag' pasteboard. Override methods from NSView to get notified when to create the drag data and when to receive data dragged to the view.

Previous Page: An Inspector calls | Next Page: Adding finesse


text:
Talk:XML - Managing Data Exchange/The one-to-one relationship

Revisions to One-to-One Relationship Dustin K. Pitts January 28, 2006

The following things are suggestions for the revision of my chapter over one-to-one relationships.

 * 1) Have a brief overview of what XML is.  Define the XML Schema, XML Style Sheet, and the XML Document.
 * 2) Have a better definition of the one-to-one relationship.  Relate it to the data model that is given.
 * 3) Reword the introduction so that the goals of the chapter a little more clear.
 * 4) In the new elements and attributes part of the Schema the third bullet should be its not it’s.
 * 5) Have a separate category for the restrictions in the XML Schema.  It will set them apart more and allow for more organization.  Maybe a label or something would help this.
 * 6) Bold the titles of the restrictions so you can easily find them.
 * 7) Have a separate category for the If Statement.  Make it stand out.
 * 8) Have a more in depth summary so that someone skimming the chapter can get a more general idea of what is going on.

Editorial Board Suggestions
MIST 5730 Advanced Data Management, University of Georgia, in response to Dustin

 * 1) The overview of XML is covered in a previous chapter. You could link to this information at the beginning of the chapter.
 * 2) It may be helpful to include a new section header entitled "Prerequisites" (or something similar) at the beginning of the chapter and link to chapters that the learner should have already read. This resource also could have answered some of Mr. McCreary's questions (below).
 * 3) Focus on the one-to-one relationship and how this relationship is represented in the schema.
 * 4) Cut advanced topic information and paste within your chapter link on the "Chapter XSL" page that Viji created (accessible from the main table of contents). This would address your suggestions concerning the "if statements" and "restrictions." The editorial board will need to discuss whether "Chapter XSL" is the correct descriptor for the chapter link Viji created. Not all advanced topics are related to XSL; some are related to Java.
 * 5) To address your suggestions to reword and go more in depth with some of the content, I agree. If you didn't really understand the chapter, add and reword content in the way that you think makes the most sense.
 * 6) And, of course, please make the changes specified by the author guidelines.

Christina Serrano, 2/1/06

Excellent Start
Hi Dustin,

First of all. Great Job! Keep up the good work.

Yes, I agree that we need to start out with some basics of XML Schema. I got very confused by the title. Creating one-to-one relationships is not the right topic.

I think that restrictions are an advanced topic. I don't even teach it in my beginning classes.

Here are the key concepts I introduce in one-day (8 hour class) on XML Schemas:
 * 1) History of XML and XML Schema
 * 2) XML Schema as compared to a DTD?  Why are Schemas better?
 * 3) What is it used for? (Validation of structure and data type checking)
 * 4) What is the structure of an XML Schema file?
 * 5) How do you add elements and attributes?
 * 6) How do you assign simple data types (string, boolean, integer and date)
 * 7) Adding enumerations
 * 8) Adding a pattern to validate a zip code
 * 9) How do you use an XML schema to validate an XML file (need a lab)
 * 10) What else are schemas used for (e.g. data mapping)

At the end of the class students feel they can create a simple XML Schema to validate some simple data.

I am looking forward to working with you on this. Let me know if you want me to make any changes. Collaborative writing is a challenge.

- Dan Feb. 2nd 2006 User:dmccreary

Professor's comments
rtw 01:20, 2 Feb 2006 (UTC)

We need to make clear to the reader that the schema is mapping only a portion of the model (the 1:1 aspect). Maybe the model should be redrawn with a color box around country and destination. If you want, I can do this, as all the models need to be maintained by one person. The prerequisites section should go in the first chapter and include topics such as knowledge of HTML and data modeling. It can be assumed that the preceding chapter is a prerequisite for the current chapter. Section summaries are useful and there is an author guideline on how to make these standout in the text.

Editorial Board Comments - Christina
2/21/06

Dustin, thanks for making all of the changes that we suggested. I also like Dr. Watson's suggestion to highlight the 1:1 relationship in the data model presented in this chapter. And perhaps the data model could be truncated. For example, I don't know that it's necessary to include the "hotel" entity--if this were removed, the schema and document could also be simplified.

I removed references in the chapter in regards to style sheets and Java parsing because there is no longer content in the chapter to explain these topics.


text:
Programming Mac OS X with Cocoa for Beginners/Adding finesse

Previous Page: Archiving

So far we have built a fairly crude drawing program, but one that is starting to look like a real application. We have covered many of the core principles of Cocoa that you'll need to write any application. If you look at how much code we've actually written, it's not that much, yet our application is already quite functional. In this section, we'll look at adding finesse - those touches that separate real, well-designed and implemented applications from those lesser amateur efforts we've no doubt all seen.

Undo
The first thing to tackle is Undo. A real application should allow almost all actions to be undoable, in the spirit of forgiveness of the user. Without Undo, your application is likely to be discarded in favour of another one that has it, as punishing the user for mistakes, or not allowing them to experiment is a cardinal design sin!

Undo is traditionally one of the "hard" parts of implementing an application. Cocoa helps us massively here, and so Undo is not so hard. Usually, adding Undo as an afterthought is not a good idea - you need to design your application from the ground up to cope with the undo task. So far we have not mentioned Undo, but we have in fact designed our application to allow it to be added easily.

The principle of Undo is straightforward - whenever we do anything to change the state of the data model, the previous state is recorded so it can be put back. We can record this previous state in different ways, either just record the whole state, or parts of it along with tags to tell us what was changed, or we can record actions and perform the opposite action to implement Undo. We'll be using a combination of these things. Cocoa automatically combines several undoable "recordings" into one Undoable action for each event, which really makes life very simple for us - we simply need to make sure the recording happens at each editable point of interest.

We'd like the following to be undoable:

 * adding new objects
 * deleting objects
 * changing the position or size of an object
 * changing the stroke and fill colours
 * changing the stroke width

Note that we could also make the selections themselves undoable, but in this exercise we won't do this.

In Cocoa, the object responsible for handling Undo is the undo manager. It is embodied in the class NSUndoManager. The way it works is by storing invocations. We already discussed how Objective-C uses runtime binding of class methods. An invocation is just a stored description of a method call. When the invocation is "replayed" the stored method call is actually made. The invocation not only records the target and method to be called, but also all of the method's parameters at the time the invocation was recorded. Thus we can create an invocation which when called, will undo the current action we are performing. Both the action and the invocation to undo the same action are created at the same time.

First let's add the code for undoing adding and deleting objects. Here is the modified code in MyDocument.m for addObject and removeObject:

- (void)		addObject:(id) object {	if(![_objects containsObject:object]) {		self undoManager] registerUndoWithTarget:self							selector:@selector(removeObject:)							object:object];		[_objects addObject:object];		[_mainView setNeedsDisplayInRect:[object drawBounds; } }

- (void)		removeObject:(id) object {	if([_objects containsObject:object]) {		NSRect br = [object drawBounds]; [[self undoManager] registerUndoWithTarget:self							selector:@selector(addObject:)							object:object];

[self deselectObject:object]; [_objects removeObject:object]; [_mainView setNeedsDisplayInRect:br]; } }

We obtain an undo manager by calling [self undoManager]. Every document has its own undo manager instance already set up, we just need to use it. We then use the registerUndoWithTarget:selector:object: method to build an invocation that the undo manager stores. When we add an object, we build an invocation to removeObject. When we remove an object, be build an invocation to addObject. In other words, we record the OPPOSITE of what we are doing. We have also added code here to refresh the main view when the objects come and go, so that we can see the effect that our actions have.

Compile and run the project. Create some shapes. Now Undo them. You'll find you can Undo and Redo as many actions as you want - everything works as you would expect for the Undo command. Not bad for just two lines of code!

Note that when Undo is performed, it calls, say removeObject, which in turn records another addObject undo action. This is how redo works - NSUndoManager knows the context it is called in, so can add tasks to the appropriate stack. Now let's make editable actions Undoable. For this, we'll need to add code to WKDShape, and at present shapes don't have an undomanager, nor do they know anything about the document they are part of, so they can't obtain one. So the first thing we need to do is to provide a way to allow shapes to obtain an appropriate undo manager.

In WKDShape.h, add a data member to the class called _owner, typed as NSDocument*. Add accessor methods setOwner: and owner. In the .m file, add the implementation:

- (void)		setOwner:(NSDocument*) doc {	_owner = doc; }

- (NSDocument*)	owner {	return _owner; }

In MyDocument.m, add a line to addObject that calls setOwner with self - this makes sure that whenever an object is added to a document, the object is updated with which document it belongs to. Note that since everything that ever adds an object to a document calls this method, including paste for example, this information is always up to date. This is a strong design principle - always try to minimise the number of places in your code that change the data model by factoring code into a few key methods. Then you can add code to those methods in the knowledge that they will always be called, and nothing can get in "through the back door". If we hadn't done this, implementing Undo would be very much harder than it has been so far.

Now we have a way for a WKDShape to obtain its owning document's undoManager, we can implement undo easily.

- (void)		setFillColour:(NSColor*) colour {	[[[self owner] undoManager] registerUndoWithTarget:self								selector:@selector(setFillColour:)								object:_fillColour];	[colour retain];	[_fillColour release];	_fillColour = colour;	[self repaint]; }

Here, we don't set up the undo using a different method, we use the same method, but with the OLD value of the colour. When the undo command is called, it calls this same method, passing back the original colour. The code for the stroke colour is identical.

The case for the stroke width is slightly more involved, because the undo manager doesn't directly store simple scalar values such as a float. Instead we need to pack the value up into an object. Cocoa provides a simple class for doing just this - NSNumber. As we need to be able to call a method that takes an object parameter, we must now create one. We'll refactor the code so that all the calls to set the stroke width now go through it.

- (void)		setStrokeWidth:(float) width {	[self owner] undoManager] registerUndoWithTarget:self								selector:@selector(setStrokeWidthObject:)								object:[NSNumber numberWithFloat:_strokeWidth; _strokeWidth = width; [self repaint]; }

- (void)		setStrokeWidthObject:(NSNumber*) value {	[self setStrokeWidth:[value floatValue]]; }

Don't forget to add the method setStrokeWidthObject: to your class declaration. Now if anyone calls setStrokeWidth, the old value is turned into an NSNumber object and used to build the undo invocation on setStrokeWidthObject: When Undo is called, setStrokeWidthObject: unpacks the encapsulated value and calls setStrokeWidth:, so everything works correctly.

Compile and go to test that changing properties using the inspector is now fully undoable. They should be!

Notice how Cocoa has separated each editing action into different Undo commands for you. If you drag around in the colour picker for example, the colour of the object will change many, many times until you stop dragging. But only one Undo command is needed to put back the previous colour - it doesn't visibly "replay" all of the individual intermediate colours.

There is one thing that isn't so great now however. If we Undo an editing change, the Inspector doesn't change! If we think about it, it's obvious why - previously we only set up the inspector to respond to selection changes which also set up the state of the controls. After that the inspector changes the object's state so they were always in "synch". Undo isn't changing the selection state, but it is changing the object's state behind the inspector's back, so we need to tell the inspector to resynch when this occurs. To do this we need to add a new notification that the inspector can respond to.

This is very similar to the "repaint" notification - in fact it would be possible to use that one in this case, but since semantically it does have a different meaning, it is good practice to make it a separate notification. If later you extended the design you might find combining the notifications led to awkward problems. So create a new notification name and a method for sending it. I called it resynch. Call this method from every place that the object state can be changed from - setFillColour:, setStrokeColour:, setStrokeWidth: In the inspector, create a new responder method - I called it resynch: - taking a single NSNotification parameter. Subscribe to the resynch notification in the awakeFromNib method as before. The resynch: method looks like:

- (void)		resynch:(NSNotification*) note {	WKDShape* shp = (WKDShape*)[note object]; if ( shp == editShape ) [self setupWithShape:shp]; }

As you can se, it's very simple - we find out which object was changed. If it's the one we are in fact currently editing, we simply call our setup method so that the control states match the object's state. Compile and run again to verify that this time, Undoing an edit operation also reflects the change in the Inspector.

Finally, we need to Undo moves and resizes of the object. By factoring all of this information through the setBounds: method, we have just one place to add the undo recording to. As with setStrokeWidth, we'll need to use an NSValue object to store the old rect.

Here's the refactored and modified code in WKDShape:

- (void)		setBounds:(NSRect) bounds {	[self repaint]; [self owner] undoManager] registerUndoWithTarget:self								selector:@selector(setBoundsObject:)								object:[NSValue valueWithRect:[self bounds]; _bounds = bounds; [self repaint]; [self resynch]; }

- (void)		setBoundsObject:(id) value {	[self setBounds:[value rectValue]]; }

- (void)		setLocation:(NSPoint) loc {	NSRect br = [self bounds]; br.origin = loc; [self setBounds:br]; }

- (void)		offsetLocationByX:(float) x byY:(float) y { NSRect br = [self bounds]; br.origin.x += x;	br.origin.y += y;	[self setBounds:br]; }

- (void)		setSize:(NSSize) size {	NSRect br = [self bounds]; br.size = size; [self setBounds:br]; }

Compile and run... create a shape and move it. Now Undo. Is the action undoable in the way you expected? No, it's not. The action is undoable, but unlike the colour case, each individual small amount of motion has been recorded as a separate Undo task. The Undo manager has failed to group the motions into one big single action. Why is that? NSUndoManager groups all undo actions that occur within a single event. However, dragging an object consists of multiple events. We can't change that, but we can change the way that the undo manager groups things by giving it some hints.

In WKDDrawView.m, in the method mouseDown:, add the following line at the top of the method:

[[[self delegate] undoManager] beginUndoGrouping];

and in the mouseUp: method, add the following line at the bottom of the method:

[[[self delegate] undoManager] endUndoGrouping];

This will fix the problem - compile and run to verify. What this does it do tell the undo manager to group any undo recording it receives from now until the call to endUndoGrouping. We beging grouping on a mouse down, and end on a mouse up, so all the actions that occur during the drag will end up in the same group, and will be replayed under the single Undo command. Each individual offset of the shape is still recorded, but when played back the entire move is replayed so the effect for the user is the expected behaviour.

Finally, you'll probably have noticed that the menu command only shows a generic "Undo". It would be nice if we could give our users a more meaningful indication of what the Undo operation will accomplish. To do this, we pass a string to the undo manager which is uses to build the menu command text. Whatever was the most recent string it received in a group will be the one used. The method is NSUndoManager's setActionName: method. For now we will just hard-code the strings for each action - in a real app we'd need to allow this to be localizable.

In WKDShape, this is straightforward. For example, in setFillColour, add:

[[[self owner] undoManager] setActionName:@"Change Fill Colour"];

just after the current undo recording operation. For all similar state changes, you can add a line with a string indicating the thing actually changed. Remember that the user will see this; you don't need to include "Undo" or "Redo". To distinguish between resizing and moving a shape, you can include this line in the appropriate routines - they don't need to go directly in setBounds: also, don't forget the code where a handle is dragged interactively - mouseDragged:

The MyDocument changes are similar with one small kink - because we are using the 'opposite' method approach, we need to tell apart the case of undo/redo and a normal call and make sure we only update the string if we were called normally - i.e. not from an undo invocation. To do this, we use:

if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])			[[self undoManager] setActionName:@"Delete Object"];

Run again to check that everything works as expected.

As a bonus, you'll notice that now, changes to the document automatically result in you being asked if you want to save changes when you quit or close a document. This is because by recording undo tasks, you are also notifying the document that its state is different from the disk file. Previously, it had no way to tell. Cocoa now steps in and adds that small piece of functionality for you "for free". Neat!

Further exercises:

 * Add the ability to undo selection changes. This will often result in a more usable application in practice.

Printing
Real applications should print. Again, in a traditional Mac application, adding the ability to print was usually hard work, and very often added as an afterthought, making it harder still! Cocoa is much easier, since there is no major difference between its on-screen graphics model and the printing model. In fact we already have most of the code written.

Printing is handled by an object called an NSPrintOperation, working in conjunction with an NSView. The view draws the content to the paper. For our simple exercise, we need very little code, since the default pagination scheme of tiling across pages is adequate. As you might imagine Cocoa provides numerous alternative approaches, but these are rather beyond the scope of just getting basic printing working.

As we have a document-based application, we use the printDocument: action method to get things going. Here's the code:

- (IBAction)	printDocument:(id) sender {   NSPrintOperation *op = [NSPrintOperation printOperationWithView:_mainView printInfo:[self printInfo]]; [op runOperationModalForWindow:[self windowForSheet] delegate:self didRunSelector: @selector(printOperationDidRun:success:contextInfo:) contextInfo:NULL]; }

We create an NSPrintOperation, passing it our main view which will render the drawing. Once we have this, we then just run it using a sheet dialog. That takes care of the rest. The sheet requires a completion routine, but in this case we don't need it to actually do anything, so we simply provide it as an empty method:

- (void)		printOperationDidRun:(NSPrintOperation*) printOperation success:(BOOL)success contextInfo:(void *)info { }

Don't forget to add this to your class definition.

That's it! Compile and run it and you'll find that you can print out your drawings.

There's one thing that isn't so great here, and this is that it prints the selection handles. Really, we don't need to see these handles when a drawing is printed, so we'll now just modify the main view drawing code so that it doesn't bother to render these when it's printing. This turns out to be very simple:

while( shape = [iter nextObject]) {		if ( NSIntersectsRect( rect, [shape drawBounds])) [shape drawWithSelection:[selection containsObject:shape] && [NSGraphicsContext currentContextDrawingToScreen]]; }

This is the main loop inside our view's drawRect: method. We just add a check whether the current graphics context is drawing to the screen. If not, it must be drawing to the printer, so the objects are rendered without the handles, regardless of their selection state.

Menu item maintenance
We have seen how Cocoa automatically enables menu items that can find a target in the current context. That's pretty neat, but not always enough. For example, when we implemented Cut and Paste, we found these commands always enabled even if there was no selection to cut, or nothing on the clipboard we could paste. We'll now see how we deal with that.

Whenever a menu is displayed, the target is given a chance to overrule the normal enabling behaviour. It does this by implementing a method called validateMenuItem: which is called for each item. You can return YES to enable the item, NO to disable it. So in MyDocument, we add:

- (BOOL)		validateMenuItem:(NSMenuItem*) item {	SEL act = [item action]; if ( act == @selector(cut:) ||	    act == @selector(copy:) ||		 act == @selector(delete:)) return (self selection] count] > 0 );	else if ( act == @selector(paste:))	{		NSPasteboard* cb = [NSPasteboard generalPasteboard];		NSString* type = [cb availableTypeFromArray:[NSArray arrayWithObjects:@"wikidrawprivate", nil;

return ( type != nil ); }	else return YES; }

As here, it's a good idea to compare the action selectors to determine which action the menu item is targetting, instead of looking at the menu item strings or position. An alternative would be to use the item's tag, but that would require that you carefully set these up in IB. By using the selector, you are immune from text and positional changes you might make to the menu - as long as it remains targetted at the same action method, it will behave correctly with respect to what that method actually achieves.

Here, if the item is targetting the cut, copy or delete methods, we see if there are any items in the selection array. If so, we enable the item, otherwise we disable it. For the paste case, we peek at the pasteboard to see if it has data of type 'wikidrawprivate' available - if so we can paste, so we enable that item.

You can implement a similar method in any target of a menu command so finely control the enabling of a menu item. You can also use the opportunity to change the text of a menu item to reflect some information you have in your data model if you like.

Previous Page: Archiving


text:
Java Programming/Language Fundamentals

The previous chapter "Getting started" was a primer course in the basics of understanding how Java programming works. Throughout the chapter, we tackled a variety of concepts that included:
 * Objects and class definitions;
 * Abstract and data types;
 * Properties;
 * Methods;
 * Class-level and method-level scopes;
 * Keywords; and,
 * Access modifiers, etc.

From this point on, we will be looking into the above mentioned concepts and many more in finer detail with a deeper and richer understanding of how each one of them works. This chapter on Language fundamentals introduces the fundamental elements of the Java programming language in detail. The discussions in this chapter will use the concepts we have already gathered from our previous discussions and build upon them in a progressive manner.

The Java programming syntax
In linguistics, the word syntax (which comes from Ancient Greek σύνταξις where σύν [syn] means "together", and τάξις [táxis] means "an ordering") refers to "the process of arranging things". It defines the principles and rules for constructing phrases and sentences in natural languages.

When learning a new language, the first step one must take is to learn its programming syntax. Programming syntax is to programming languages what grammar is to spoken languages. Therefore, in order to create effective code in the Java programming language, we need to learn its syntax — its principles and rules for constructing valid code statements and expressions.

Java uses a syntax similar to the C programming language and therefore if one learns the Java programming syntax, they automatically would be able to read and write programs in similar languages — C, C++ and C#

The next step one must take when learning a new language is to learn its keywords; by combining the knowledge of keywords with an understanding of syntax rules, one can create statements, Programming Blocks, Classes, Interfaces, et al.

Use packages to avoid name collisions. To hide as much information as possible use the access modifiers properly.

Create methods that do one and if possible only one thing/task. If possible have separate method that changes the object state.

In an object oriented language, programs are run with objects; however, for ease of use and for historic reasons, Java has primitive types. Primitive Data Types only store values and have no methods. Primitive Types may be thought of as Raw Data and are usually embedded attributes inside objects or used as local variables in methods. Because primitive types are not subclasses of the object superclass, each type has a Wrapper Class which is a subclass of Object, and can thus be stored in a collection or returned as an object.

Java is a strong type checking language. There are two concepts regarding types and objects. One is the object type and the other the template/class the object was created from. When an object is created, the template/class is assigned to that object which can not be changed. Types of an object however can be changed by type casting. Types of an object is associated with the object reference that referencing the object and determines what operation can be performed on the object through that object reference. Assigning the value of one object reference to a different type of object reference is called type casting.

The most often used data structure in any language is a character string. For this reason java defines a special object that is String.

To aggregate same type java objects to an array, java has a special array object for that. Both java objects and primitive types can be aggregated to arrays.

title: Java Programming/Language Fundamentals


text:
Java Programming/Classes and Objects

Classes and Objects
An object-oriented program is built from objects. A class is a "template" that is used to create objects. The class defines the values the object can contain and the operations that can be performed on the object.

After compilation, a class is stored on the file system in a '(class-name).class' file.

The class is loaded into memory when we are about to create the first object from that class, or when we call one of its static functions.

During class loading all the class static variables are initialized. Also operations defined in a  block are executed. Once a class is loaded it stays in memory, and the class static variables won't be initialized again.

After the class is loaded into memory, objects can be created from that class. When an object is created, its member variables are initialized, but the class static variables are not.

When there are no more references to an object, the garbage collector will destroy the object and free its memory, so that the memory can be reused to hold new objects.

title: Java Programming/Classes and Objects


text:
Java Programming/Aggregate

In the previous chapters, we have discovered the array. An array stores a group of primitive types. To group objects, or to reference a group of objects, we can use Java aggregate classes. There are two main interfaces, those are  and. Implementations for those interfaces are not interchangeable.

Collection
The implementations of  interface are used for grouping simple java objects.

 * Example: We can group together all patients in a Hospital to a "patient" collection.

Map
The implementations of  interface are used to represent mapping between "key" and "value" objects. A Map represents a group of "key" objects, where each "key" object is mapped to a "value" object.

 * Example: For each patient, there is one and only one main nurse assigned to. That association can be represented by a "patient-nurse" Map.

Choice
A collection is better when you have to access all the items at once. A map is better when you have to randomly access an item regularly.

Before selecting a particular collection implementation, ask the following question: Can my collection contain the same elements, i.e. are duplicates allowed?

Can my collection contain the element?

''Should the collection maintain the order of the elements? Is the order important in any way?''

''How do you want to access an element? By index, key or just with an iterator?''

Does the collection need to be synchronized?

From a performance perspective, which one needs to be faster, updates or reads?

From a usage perspective, which operation will be more frequent, updates or reads?

Once you know your needs, you can select an existing implementation. But first decide if you need a, or a.

Note that the above associations are explicit. The objects them-self do not have any knowledge/information about that they are part in an association. But creating explicit associations between simple java objects is the main idea about using the aggregate/collection classes.

Programmeren in Java/Collections

title: Java Programming/Aggregate


text:
Java Programming/Exceptions

The ideal time to catch an error is at compile time, before you even try to run the program. However, not all errors can be detected at compile time. The rest of the problems must be handled at run time through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly.

Improved error recovery is one of the most powerful ways that you can increase the robustness of your code. Error recovery is a fundamental concern for every program you write, but it's especially important in Java, where one of the primary goals is to create program components for others to use. To create a robust system, each component must be robust. By providing a consistent error-reporting model using exceptions, Java allows components to reliably communicate problems to client code.

Flow of code execution
In Java, there are two main flows of code executions.
 * Normal main sequential code execution, the program doing what it meant to accomplish.
 * Exception handling code execution, the main program flow was interrupted by an error or some other condition that prevent the continuation of the normal main sequential code execution.

 * Exception : Exceptions are Java's way of error handling. Whenever an unexpected condition occurs, an exception can be thrown with an exception object as a parameter. It means that the normal program control flow stops and the search for a  block begins. If that is not found at the current method level the search continues at the caller method level, until a matching  block is found. If none is found the exception will be handled by the JVM, and usually the java program terminates.

 * When a "matching" block is found, that block will be executed, the exception object is passed to the block as a parameter. Then normal program execution continues after the  block. See Java exception handling syntax.

 * Exception Object : This is the object that is "thrown" as a parameter from the error, and passed to the block. Exception object encapsulates the information about the error's location and its nature.  All Exception objects must be inherited from the  . See the UML diagram below.

 * Matching rule : A thrown exception object can be caught by the keyword and specifying the exception object's class or its super-class.

 * Naming convention : It is good practice to add Exception to all exception classes. The name of the exception should be meaningful, and should represent the problem. For example,  may indicate that a customer was not found.

Programmeren in Java/Exceptions

title: Java Programming/Exceptions


text:
Java Programming/Reflection

Reflection is a new concept in Java, and did not exist in classical compiled languages like C, and C++. The idea is to discover an object's attributes and its methods programmatically.

title: Java Programming/Reflection


text: Java Programming/Libraries, extensions and frameworks


text: Template:Java Programming/OverviewTopic/Nav


text: Template:Java Programming/GettingStartedTopic/Nav


text: Template:Java Programming/LanguageFundamentalsTopic/Nav


text: Template:Java Programming/ClassesAndObjectsTopic/Nav


text: Template:Java Programming/Aggregate/Nav

title: Template:Java Programming/Aggregate/Nav


text: Template:Java Programming/ExceptionsTopic/Nav


text:
Template:Java Programming/Concurrent Programming/Topic

 * Threads and Runnables
 * Basic Synchronization
 * Client Server Programming
 * Remote Method Invocation (RMI)
 * Enterprise JavaBean Programming (EJB)
 * Java Spaces Programming (Jini)


text:
Magic: The Gathering/Highlander Format

Highland Format takes its name from a memorable line from the movie 'Highlander': There can be only one!. Only one copy of any Magic card (other than basic land) is allowed in a highlander deck. Any magic format can be converted into a highlander-type format if this rule is followed.

title: Magic: The Gathering/Highlander Format


text:
Template:Java Programming/Reflection/Topic

 * Reflection Overview
 * Dynamic Class Loading
 * Dynamic Method Invocation
 * Accessing Private Features with Reflection


text:
Java Programming/JavaBeans

Reusability comes at the core of any modern computer language's framework. It is often desirable to use components you previously built in recurring environments. In Rapid Application Development, these prove more helpful as you can drag them off a list of components and use it elsewhere in your project. Such level of reusability is added into the Java Programming language with the help of the JavaBeans architecture.

JavaBeans are the mainstream Java component model, introduced in 1996 by Sun Microsystems. JavaBeans are defined as follows:

"A JavaBean is a reusable software component that can be manipulated visually in a builder tool."

Together with the component model, Sun released a simple visual composition tool, the BeanBox. It is mostly intended for experimenting with Beans rather than offering a professional IDE. For real world applications, one should better deploy on one of the Java IDEs like Visual Age or JBuilder that support the visual composition of JavaBeans.

As we will see, JavaBeans do not essentially differ from standard Java classes, which makes the component model quite easy to use. What sets a JavaBean apart from normal Java classes is that a JavaBean follows the Oracle JavaBeans Standard (the term JavaBean or simply bean also refers to the instances of a JavaBean class). There is a set of features and conventions adopted for facilitating reuse:

 * Presence of a no argument constructor;
 * Support for persistence;
 * Properties manipulated by getter and setter methods;
 * Support for introspection;
 * Events as the mechanism of communication between beans;
 * Support for customization via property editors.

The JavaBeans standard provides a framework for creating objects to be used by GUI tools, including Java development environments. But in more common usage, a bean is a serializable class that follows the JavaBeans naming conventions for its properties. These naming standards make it easy to use Java introspection.

Implementation
To follow these standards, the bean needs one or more properties abstractions which represent different state values of an object. A property has a name (a valid Java identifier) and a type (either a reference type, a primitive type or an array type). By default, the properties of a JavaBean class are inferred by the presence of either a getter method, a setter method, or both: would be the getter method for a boolean property named. Thus, the method signature of most getters is  or.
 * A getter method which is used to obtain the value of the property from a bean. The name is usually of the form . For example, the getter method for the String property   is  . For boolean properties (those whose type is boolean), the convention is to use the naming pattern.
 * A setter method which is used to assign a value to a bean's property. A setter method is a method of the form . For the previous example, the setter could be invoked as.

As per the JavaBeans standard, getters and setters defined as described above automatically determine the properties of the class. However, by creating  classes, you can specify alternate implementations by explicitly declaring the property names and the getter and/or setter methods for each property.

Properties are often implemented with private instance variables, but this is not required.

A Simple JavaBean
This is an example of a simple JavaBean type with the properties  and.

Persistence
The requirements for an object to be a bean is to define a public parameterless constructor, so that beans can be instantiated by builder tools in an uncomplicated way (In the Point bean, the parameterless constructor is given implicitly). Secondly, one of the interfaces  or   need to be implemented. The interfaces do not prescribe the implementation of any methods, but are an approval, that the bean may be saved in persistent storage as in a file or database. In doing so, the bean can be restored after an application was shut down or transferred across networks. The ability to store state of a component in persistent storage is called persistence. Java offers a standard serialization mechanism, which makes it very easy to serialize objects. Alternatively, a component can be stored in a customized manner (e.g. in xml format) by implementing the  interface.

Properties
The properties of a bean are all private fields that are accessible and modifiable by public methods. These getter and setter methods should be marked as such by following a simple naming convention: for some property named, say,  there should be a   which returns the property value and a   which sets the property.

Introspection
In Java and J2EE programming, you can call a method on an object only if it is casted to a class or an interface that declares it. The structured definition of bean properties is very useful for comparing a single common property across several objects that are not and should not be related by inheritance.

For example, a program may contain both a bean representing a company's employees, and another containing a list of buildings that a company occupies. A programmer writing a function called  wants to write a simple way of getting the field "name" from several beans that can get the field from both Employee and Building beans, and that can be easily adapted to get the same field from other types of beans that may not be written yet.

While this could be done by rewriting both Employee and Building so that they each inherit from one class named NamedObject, or by creating a NamedObject interface, both methods have their own problems. Using inheritance is limiting, as each child class can only inherit from one parent class, which limits the number of different classes that can share properties, as well as the number of common properties that can be shared. Furthermore, using inheritance to express relationships other than a simple "is-a" relationship can be confusing, as can looking through dozens of class definitions to find where a single "dumb" getter function is implemented. Creating an interface fixes the problems caused by the multiple inheritance rule, as a class can use any number of interfaces, but it still requires every shared property to be explicitly spelled out.

The simplest, most elegant way to deal with this type of relationship is to read the bean properties using introspection. The jakarta BeanUtils package is a common way of handling objects that need to be related in this way, as it takes advantage of the regularity of JavaBean naming conventions.

or

Events
JavaBeans interact with each other by means of events. Events are notifications, a component can give to other components, that something interesting has happened. An example for an event might be a mouse click on a button or the closing of a window. Beans can be source and target of events. To be informed about an event, a bean has to register at another Bean as a listener.

The Java event model realizes the observer design pattern with the effect that the inter-component coupling is reduced. Method calls require tight coupling, as caller and receiver need to know each other at compile time, while with events all communication happens solely via interfaces.

A special kind of event are. They are used to restrict some properties to take only specific values, for example for a month integer values between 1 and 12. Every time, such a bound property is modified, notifications to all registered PropertyChangeListeners will be send.

Customization
Customization is done via Property Editors. A property editor is a tool for customizing at design time a particular property type. Property editors are activated from so-called property sheets, which display all properties of a bean. If a property is selected for customization, the property sheet finds out the type of the property, displays the appropriate property editor with the property's current value.

Additional Remarks
A big strength of the JavaBean component model is that it is designed for simplicity. Developing JavaBeans is very simple, because a lot of behavior (like the platform independence or packaging mechanism) is supported in the Java Programming Language by default. However, one can optionally equip beans with additional objects like BeanInfos or custom PropertyEditors to use the component model in a more flexible way. A second facility is that Sun designed the whole Swing GUI library according to the JavaBeans component model. Thereby Swing components can easily be composed in visual builder tools. However, JavaBeans do not realize all features of a component model. A drawback is that JavaBeans are restricted to the Java programming language, while an important goal of components is the independence of an implementation language.

Recommended readings

 * Learning JavaTM, Niemeyer, P. and Knudsen, J., 3rd Edition, 2005, O'Reilly: Sebastopol, CA. pp.751-786

title: Java Programming/JavaBeans


text:
Template:Java Programming/Libraries

Libraries, Extensions, and Frameworks

 * Math and Geometry
 * Regular Expressions
 * Security
 * Input and Output
 * Logging
 * Database Connectivity
 * Zip and Other Archives
 * XML
 * Graphical User Interfaces
 * Open Source
 * Struts
 * Spring framework

title: Template:Java Programming/Libraries


text:
Magic: The Gathering/5-Color Format

5-Color Format exists in slightly different variations in the online and offline Magic communities. 5-Color was initially a fan-created format, not supported by the DCI. The basic rules could be summarized as follows:

 * Decks must contain a minimum of 250 cards
 * Decks must have no less than 20 cards of each color
 * No more than four of each non basic land card
 * The game is played for ante, and ante cards, including Contract from Below, are legal

A full list of rules, including banned and restricted cards, is maintained at: http://www.5-color.com/

Due to the popularity of this non-sanctioned format, WotC created a similar format in the Magic online game.

title: Magic: The Gathering/5-Color Format


text:
User talk:FraterM

Thanks for experimenting with the page Errata/1931567506 on Wikibooks. Your test worked, and has been reverted or removed. Please use the sandbox for any other tests you want to do. Take a look at the welcome page if you would like to learn more about contributing to our encyclopedia. Thanks. -- Jeandré, 2006-01-29t05:39z

title: User talk:FraterM


text:
Japanese Law and Government

Contents

 * /Government/
 * /Local Government/
 * /Constitutional Law/
 * /Civil Law/
 * /Obligation Law/
 * /Property Law/
 * /Family Law/
 * /Commercial Law/
 * /Criminal Law/
 * /Immigration Law/

title: Japanese Law and Government