📄 basexmlwriter.java
字号:
this.modelPrefixMapping = baseModel;
primeNamespace( baseModel );
addNameSpace( RDF.getURI() );
addNameSpaces(model);
jenaPrefixCount = 0;
}
static IRIFactory factory = IRIFactory.jenaImplementation();
private void writeXMLBody( Model model, PrintWriter pw, String base ) {
if (showDoctypeDeclaration.booleanValue()) generateDoctypeDeclaration( model, pw );
// try {
// TODO errors?
if (xmlBase == null) {
baseURI = (base == null || base.length() == 0) ? null : factory.create(base);
writeBody(model, pw, base, false);
} else {
baseURI = xmlBase.length() == 0 ? null : factory.create(xmlBase);
writeBody(model, pw, xmlBase, true);
}
// } catch (MalformedURIException e) {
// throw new BadURIException( e.getMessage(), e);
// }
}
protected static final Pattern predefinedEntityNames = Pattern.compile( "amp|lt|gt|apos|quot" );
public boolean isPredefinedEntityName( String name )
{ return predefinedEntityNames.matcher( name ).matches(); }
private String attributeQuoteChar ="\"";
protected String attributeQuoted( String s )
{ return attributeQuoteChar + s + attributeQuoteChar; }
protected String substitutedAttribute( String s )
{
String substituted = Util.substituteStandardEntities( s );
if (!showDoctypeDeclaration.booleanValue())
return attributeQuoted( substituted );
else
{
int split = Util.splitNamespace( substituted );
String namespace = substituted.substring( 0, split );
String prefix = modelPrefixMapping.getNsURIPrefix( namespace );
return prefix == null || isPredefinedEntityName( prefix )
? attributeQuoted( substituted )
: attributeQuoted( "&" + prefix + ";" + substituted.substring( split ) )
;
}
}
private void generateDoctypeDeclaration( Model model, PrintWriter pw )
{
String rdfns = RDF.getURI();
String rdfRDF = model.qnameFor( rdfns + "RDF" );
if ( rdfRDF == null ) {
model.setNsPrefix("rdf",rdfns);
rdfRDF = "rdf:RDF";
}
Map prefixes = model.getNsPrefixMap();
pw.print( "<!DOCTYPE " + rdfRDF +" [" );
for (Iterator it = prefixes.keySet().iterator(); it.hasNext();)
{
String prefix = (String) it.next();
if (!isPredefinedEntityName( prefix ) )
pw.print( newline + " <!ENTITY " + prefix + " '" + Util.substituteEntitiesInEntityValue((String)prefixes.get( prefix )) + "'>" );
}
pw.print( "]>" + newline );
}
private void writeXMLDeclaration(Writer out, PrintWriter pw) {
String decl = null;
if (out instanceof OutputStreamWriter) {
String javaEnc = ((OutputStreamWriter) out).getEncoding();
// System.err.println(javaEnc);
if (!(javaEnc.equals("UTF8") || javaEnc.equals("UTF-16"))) {
CharEncoding encodingInfo = CharEncoding.create(javaEnc);
String ianaEnc = encodingInfo.name();
decl = "<?xml version="+attributeQuoted("1.0")+" encoding=" + attributeQuoted(ianaEnc) + "?>";
if (!encodingInfo.isIANA())
logger.warn(encodingInfo.warningMessage()+"\n"+
" It is better to use a FileOutputStream, in place of a FileWriter.");
}
}
if (decl == null && showXmlDeclaration != null)
decl = "<?xml version="+attributeQuoted("1.0")+"?>";
if (decl != null) {
pw.println(decl);
}
}
/** Set an error handler.
* @param errHandler The new error handler to be used, or null for the default handler.
* @return the old error handler
*/
synchronized public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) {
// null means no user defined error handler.
// We implement this using defaultErrorHandler,
// but hide this fact from the user.
RDFErrorHandler rslt = errorHandler;
if (rslt == defaultErrorHandler) rslt = null;
errorHandler = errHandler == null ? defaultErrorHandler : errHandler;
return rslt;
}
static private final char ESCAPE = 'X';
static private String escapedId(String id) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < id.length(); i++) {
char ch = id.charAt(i);
if (ch != ESCAPE
&& (i == 0 ? XMLChar.isNCNameStart(ch) : XMLChar.isNCName(ch))) {
result.append( ch );
} else {
escape( result, ch );
}
}
return result.toString();
}
static final char [] hexchar = "0123456789abcdef".toCharArray();
static private void escape( StringBuffer sb, char ch) {
sb.append( ESCAPE );
int charcode = ch;
do {
sb.append( hexchar[charcode & 15] );
charcode = charcode >> 4;
} while (charcode != 0);
sb.append( ESCAPE );
}
/**
Set the writer property propName to the value obtained from propValue. Return an
Object representation of the original value.
@see com.hp.hpl.jena.rdf.model.RDFWriter#setProperty(java.lang.String, java.lang.Object)
*/
final synchronized public Object setProperty( String propName, Object propValue ) {
if (propName.equalsIgnoreCase("showXmlDeclaration")) {
return setShowXmlDeclaration(propValue);
} else if (propName.equalsIgnoreCase( "showDoctypeDeclaration" )) {
return setShowDoctypeDeclaration( propValue );
} else if (propName.equalsIgnoreCase( "minimalPrefixes" )) {
try { return new Boolean( !writingAllModelPrefixNamespaces ); }
finally { writingAllModelPrefixNamespaces = !getBoolean( propValue ); }
} else if (propName.equalsIgnoreCase("xmlbase")) {
String result = xmlBase;
xmlBase = (String) propValue;
return result;
} else if (propName.equalsIgnoreCase("tab")) {
return setTab( propValue );
} else if (propName.equalsIgnoreCase("width")) {
return setWidth(propValue);
} else if (propName.equalsIgnoreCase("longid")) {
Boolean result = new Boolean(longId);
longId = getBoolean(propValue);
return result;
} else if (propName.equalsIgnoreCase("attributeQuoteChar")) {
return setAttributeQuoteChar(propValue);
} else if (propName.equalsIgnoreCase( "allowBadURIs" )) {
Boolean result = new Boolean( !demandGoodURIs );
demandGoodURIs = !getBoolean(propValue);
return result;
} else if (propName.equalsIgnoreCase("prettyTypes")) {
return setTypes((Resource[]) propValue);
} else if (propName.equalsIgnoreCase("relativeURIs")) {
int old = relativeFlags;
relativeFlags = str2flags((String) propValue);
return flags2str(old);
} else if (propName.equalsIgnoreCase("blockRules")) {
return setBlockRules(propValue);
} else {
logger.warn("Unsupported property: " + propName);
return null;
}
}
private String setAttributeQuoteChar(Object propValue) {
String oldValue = attributeQuoteChar;
if ( "\"".equals(propValue) || "'".equals(propValue) )
attributeQuoteChar = (String)propValue;
else
logger.warn("attributeQutpeChar must be either \"\\\"\" or \', not \""+propValue+"\"" );
return oldValue;
}
private Integer setWidth(Object propValue) {
Integer oldValue = new Integer(width);
if (propValue instanceof Integer) {
width = ((Integer) propValue).intValue();
} else {
try {
width = Integer.parseInt((String) propValue);
} catch (Exception e) {
logger.warn( "Bad value for width: '" + propValue + "' [" + e.getMessage() + "]" );
}
}
return oldValue;
}
private Integer setTab(Object propValue) {
Integer result = new Integer(tabSize);
if (propValue instanceof Integer) {
tabSize = ((Integer) propValue).intValue();
} else {
try {
tabSize = Integer.parseInt((String) propValue);
} catch (Exception e) {
logger.warn( "Bad value for tab: '" + propValue + "' [" + e.getMessage() + "]" );
}
}
return result;
}
private String setShowDoctypeDeclaration( Object propValue )
{
String oldValue = showDoctypeDeclaration.toString();
showDoctypeDeclaration = getBooleanValue( propValue, Boolean.FALSE );
return oldValue;
}
private String setShowXmlDeclaration( Object propValue )
{
String oldValue = showXmlDeclaration == null ? null : showXmlDeclaration.toString();
showXmlDeclaration = getBooleanValue( propValue, null );
return oldValue;
}
/**
Answer the boolean value corresponding to o, which must either be a Boolean,
or a String parsable as a Boolean.
*/
static private boolean getBoolean( Object o )
{ return getBooleanValue( o, Boolean.FALSE ).booleanValue(); }
private static Boolean getBooleanValue( Object propValue, Boolean theDefault )
{
if (propValue == null)
return theDefault;
else if (propValue instanceof Boolean)
return (Boolean) propValue;
else if (propValue instanceof String)
return stringToBoolean( (String) propValue, theDefault );
else
throw new JenaException( "cannot treat as boolean: " + propValue );
}
private static Boolean stringToBoolean( String b, Boolean theDefault )
{
if (b.equals( "default" )) return theDefault;
if (b.equalsIgnoreCase( "true" )) return Boolean.TRUE;
if (b.equalsIgnoreCase( "false" )) return Boolean.FALSE;
throw new BadBooleanException( b );
}
Resource[] setTypes( Resource x[] ) {
logger.warn( "prettyTypes is not a property on the Basic RDF/XML writer." );
return null;
}
private Resource blockedRules[] = new Resource[]{RDFSyntax.propertyAttr};
Resource[] setBlockRules(Object o) {
Resource rslt[] = blockedRules;
unblockAll();
if (o instanceof Resource[]) {
blockedRules = (Resource[]) o;
} else {
StringTokenizer tkn = new StringTokenizer((String) o, ", ");
Vector v = new Vector();
while (tkn.hasMoreElements()) {
String frag = tkn.nextToken();
// System.err.println("Blocking " + frag);
if (frag.equals("daml:collection"))
v.add(DAML_OIL.collection);
else
v.add(new ResourceImpl(RDFSyntax.getURI() + frag));
}
blockedRules = new Resource[v.size()];
v.copyInto(blockedRules);
}
for (int i = 0; i < blockedRules.length; i++)
blockRule(blockedRules[i]);
return rslt;
}
/*
private boolean sameDocument = true;
private boolean network = false;
private boolean absolute = true;
private boolean relative = true;
private boolean parent = true;
private boolean grandparent = false;
*/
private int relativeFlags =
IRI.SAMEDOCUMENT | IRI.ABSOLUTE | IRI.CHILD | IRI.PARENT;
/**
Answer the form of the URI after relativisation according to the relativeFlags set
by properties. If the flags are 0 or the base URI is null, answer the original URI.
Throw an exception if the URI is "bad" and we demandGoodURIs.
*/
protected String relativize( String uri ) {
return relativeFlags != 0 && baseURI != null
? relativize( baseURI, uri )
: checkURI( uri );
}
/**
Answer the relative form of the URI against the base, according to the relativeFlags.
*/
private String relativize( IRI base, String uri ) {
// TODO errors?
return base.relativize( uri, relativeFlags).toString();
}
/**
Answer the argument URI, but if we demandGoodURIs and it isn't good, throw
a JenaException that encapsulates a MalformedURIException. There doesn't
appear to be a convenient URI.checkGood() kind of method, alas.
*/
private String checkURI( String uri ) {
if (demandGoodURIs) {
IRI iri = factory.create( uri );
if (iri.hasViolation(false) )
throw new BadURIException( "Only well-formed absolute URIrefs can be included in RDF/XML output: "
+ ((Violation)iri.violations(false).next()).getShortMessage());
}
return uri;
}
/**
Answer true iff prefix is a "legal" prefix to use, ie, is empty [for the default namespace]
or an NCName that does not start with "xml" and does not match the reserved-to-Jena
pattern.
*/
private boolean checkLegalPrefix( String prefix ) {
if (prefix.equals(""))
return true;
if (prefix.toLowerCase().startsWith( "xml" ))
logger.warn( "Namespace prefix '" + prefix + "' is reserved by XML." );
else if (!XMLChar.isValidNCName(prefix))
logger.warn( "'" + prefix + "' is not a legal namespace prefix." );
else if (jenaNamespace.matcher(prefix).matches())
logger.warn( "Namespace prefix '" + prefix + "' is reserved by Jena." );
else
return true;
return false;
}
static private String flags2str(int f) {
StringBuffer oldValue = new StringBuffer(64);
if ( (f&IRI.SAMEDOCUMENT)!=0 )
oldValue.append( "same-document, " );
if ( (f&IRI.NETWORK)!=0 )
oldValue.append( "network, ");
if ( (f&IRI.ABSOLUTE)!=0 )
oldValue.append("absolute, ");
if ( (f&IRI.CHILD)!=0 )
oldValue.append("relative, ");
if ((f&IRI.PARENT)!=0)
oldValue.append("parent, ");
if ((f&IRI.GRANDPARENT)!=0)
oldValue.append("grandparent, ");
if (oldValue.length() > 0)
oldValue.setLength(oldValue.length()-2);
return oldValue.toString();
}
public static int str2flags(String pv){
StringTokenizer tkn = new StringTokenizer(pv,", ");
int rslt = 0;
while ( tkn.hasMoreElements() ) {
String flag = tkn.nextToken();
if ( flag.equals("same-document") )
rslt |= IRI.SAMEDOCUMENT;
else if ( flag.equals("network") )
rslt |= IRI.NETWORK;
else if ( flag.equals("absolute") )
rslt |= IRI.ABSOLUTE;
else if ( flag.equals("relative") )
rslt |= IRI.CHILD;
else if ( flag.equals("parent") )
rslt |= IRI.PARENT;
else if ( flag.equals("grandparent") )
rslt |= IRI.GRANDPARENT;
else
logger.warn(
"Incorrect property value for relativeURIs: " + flag
);
}
return rslt;
}
}
/*
(c) Copyright 2000, 2001, 2002, 2002, 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -