Skip to content
This repository has been archived by the owner on Aug 31, 2020. It is now read-only.
KIMB-technologies edited this page Jul 10, 2018 · 5 revisions

USF Examples

Basics

import eu.kimb_technologies.usf.*;

// adding data
USFList list = new USFList();
list.add( new USFPair( new Bool( true ), new USFInteger( -1220 ) ) );
list.add( new USFString( "Hallo <name>" ) );
	// also nested data allowed

// USF export
String usf = USFParser.toUSF( list );
	// will be: [{true:-1220},"Hallo <name>"];

// USF import
Atom data = USFParser.parse( usf );

USFList l = (USFList) data;
("Hallo <name>").equals(
	((USFString) l.get(1)).getValue()
); // == true

Basic usage in classes

Example Class to Export:

import eu.kimb_technologies.usf.Atom;
import eu.kimb_technologies.usf.USFInteger;
import eu.kimb_technologies.usf.USFList;
import eu.kimb_technologies.usf.USFSaveable;

public class Position implements USFSaveable {

	private int xPos;
	
	private int yPos;

	public Position() {
		this.xPos = -1;
		this.yPos = -1;
	}
	
	public Position(int xPos, int yPos) {
		this.xPos = xPos;
		this.yPos = yPos;
	}
	
	public int getY() {
		return yPos;
	}
	
	public int getX() {
		return xPos;
	}

	@Override
	public Atom toAtom() {
		USFList list = new USFList();
		list.add( new USFInteger( this.xPos ) );
		list.add( new USFInteger( this.yPos ) );
		return list;
	}

	@Override
	public void fromAtom(Atom atom) t {
		try {
			USFList list = ((USFList) atom);	
			this.xPos = ((USFInteger) list.get(0)).getValue();
			this.yPos = ((USFInteger) list.get(1)).getValue();
		} catch( Exception e ) {
			System.out.println("Error on loading a position!");
		}
	}
	
}

Now you can export and import this way:

Position pos = new Position(12,33);

System.out.println( USFParser.toUSF( pos ) );
	// [12,33]
USFParser.saveToFile("/home/user/example.usf", pos);
	// will create file /home/user/example.usf with content [12,33]  

	// creating "default" object
Position posImport = new Position();
	// importing saved data
posImport.fromAtom( USFParser.loadFromFile("/home/user/example.usf") );

	// or just:
posImport.fromAtom( USFParser.parse("[12,33]") );

MVC Ex- & Import

If one uses the MVC-Pattern one can easily export and import the application model. All model classes should implement the USFSaveable-Interface.

Afterwards the model can be exported using the USFParser and also recreated from an export.

The implementation of the toAtom() and fromAtom() methods should add all necessary attributes to the exported Atom and recreate all from an Atom. It can call the toAtom() and fromAtom() methods from other model classes.
It cloud be necessary to process object some references in a different way, because the object identity is not preserved during ex- and import.