Chapter 4. Basic Operations

Table of Contents

Parsing Topic Maps From File
Creating Topic Maps Programmatically
Copying Topic Map Objects
Exporting XTM Files
Filtering The Output

This section describes how to perform the standard operations of reading and writing topic maps from and to files in the XTM syntax.

Parsing Topic Maps From File

The org.tm4j.topicmap.source.SerializedTopicMapSource provides a standard way to access a serialized topic map file in any syntax. When reading from a SerializedTopicMapSource, TM4J uses an instance of the TopicMapBuilder interface to parse the serialized source. Currently TM4J provides two implementations of this interface, org.tm4j.topicmap.utils.XTMBuilder which parses the input stream as XML conforming to the XTM 1.0 interchange syntax; and org.tm4j.topicmap.utils.LTMBuilder which parses the input stream as text conforming to the Ontopia Linear Topic Map (LTM) notation. The TopicMapBuilder instance to be used can be explicity specified in the constructor for the SerializedTopicMapSource or else it is determined from the file extension on the file name or base locator for the source. Sources where the file name or base locator ends with the extension ".txt" or ".ltm" will be parsed by the LTMBuilder, with all other files being parsed by the XTMBuilder.

The following code snippet shows the typical use of the TopicMapSource interface to parse a new TopicMap from a file in the XTM 1.0 interchange syntax.

Example 4.1. Parsing an XTM File

    public TopicMap readTopicMap(String topicMapFileName)
    {
	try
	{
	    File tmFile = new File(topicMapFileName);
	    FileInputStream inputStream = new FileInputStream(tmFile);
	    Locator baseLoc = m_provider.getLocatorFactory().createLocator(
		"URI", tmFile.toURL().toString());
            TopicMapSource src = new SerializedTopicMapSource(inputStream, baseLoc);
	    return m_provider.addTopicMap(src);
	}
	catch(FileNotFoundException ex)
	{
	    throw new RuntimeException("Could not read topic map file: " + topicMapFileName, ex);
	}
	catch(java.net.MalformedURLException ex)
	{
	    throw new RuntimeException("Could  not convert file name: " + topicMapFileName + " to a URL.");
	}
	catch(LocatorFactoryException ex)
	{
	    throw new RuntimeException("Could not convert file name:  " + topicMapFileName + " to a TM4J Locator.");
	}
	catch(TopicMapProviderException ex)
	{
	    throw new RuntimeException("Could not parse topic map file: ", ex);
	}
    }