package org.nanopub;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.openrdf.model.URI;
import org.openrdf.rio.trig.TriGWriter;

/**
 * @author Tobias Kuhn
 */
public class CustomTrigWriter extends TriGWriter {

	public CustomTrigWriter(OutputStream out) {
		super(out);
	}

	public CustomTrigWriter(Writer writer) {
		super(writer);
	}

	protected void writeURI(URI uri) throws IOException {
		String prefix = namespaceTable.get(uri.toString());
		if (prefix != null) {
			writer.write(prefix);
			writer.write(":");
		} else {
			super.writeURI(uri);
		}
	}

}

@@ -165,16 +165,58 @@
 GWriter;
+%0Aimport org.openrdf.rio.turtle.TurtleUtil;
 %0A%0A/**%0A *
@@ -418,16 +418,27 @@
 r);%0A%09%7D%0A%0A
+%09@Override%0A
 %09protect
@@ -497,156 +497,919 @@
 ing 
-prefix = namespaceTable.get(uri.toString());%0A%09%09if (prefix != null) %7B%0A%09%09%09writer.write(prefix);%0A%09%09%09writer.write(%22:%22);%0A%09%09%7D else %7B%0A%09%09%09super.writeURI(uri
+uriString = uri.toString();%0A%0A%09%09String prefix = namespaceTable.get(uriString);%0A%09%09if (prefix != null) %7B%0A%09%09%09// Exact match: no suffix required%0A%09%09%09writer.write(prefix);%0A%09%09%09writer.write(%22:%22);%0A%09%09%09return;%0A%09%09%7D%0A%0A%09%09prefix = null;%0A%0A%09%09int splitIdxNorm = TurtleUtil.findURISplitIndex(uriString);%0A%09%09// Do also split at dots:%0A%09%09int splitIdxDot = uriString.lastIndexOf(%22.%22) + 1;%0A%09%09if (uriString.length() == splitIdxDot) splitIdxDot = -1;%0A%09%09int splitIdx = Math.max(splitIdxNorm, splitIdxDot);%0A%09%09if (splitIdx %3E 0) %7B%0A%09%09%09String namespace = uriString.substring(0, splitIdx);%0A%09%09%09prefix = namespaceTable.get(namespace);%0A%09%09%7D%0A%0A%09%09if (prefix != null) %7B%0A%09%09%09// Namespace is mapped to a prefix; write abbreviated URI%0A%09%09%09writer.write(prefix);%0A%09%09%09writer.write(%22:%22);%0A%09%09%09writer.write(uriString.substring(splitIdx));%0A%09%09%7D else %7B%0A%09%09%09// Write full URI%0A%09%09%09writer.write(%22%3C%22);%0A%09%09%09writer.write(TurtleUtil.encodeURIString(uriString));%0A%09%09%09writer.write(%22%3E%22
 );%0A%09

Make sure prefixes are split at '.' when writing TriG