fix spotbugs issues
use JDKs Base64
forbidden-apis fixes
git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1881117 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java b/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java
index 86f4c01..0d26b03 100644
--- a/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java
+++ b/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java
@@ -16,84 +16,70 @@
package org.apache.xmlbeans.impl.repackage;
import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
-public class EditBuildScript
-{
+public class EditBuildScript {
//
// usgae: edit buildfile token new-value
//
- public static void main ( String[] args )
- throws Exception
- {
- if (args.length != 3)
- throw new IllegalArgumentException( "Wrong number of arguments" );
+ public static void main(String[] args) throws Exception {
+ if (args.length != 3) {
+ throw new IllegalArgumentException("Wrong number of arguments");
+ }
- args[ 0 ] = args[ 0 ].replace( '/', File.separatorChar );
+ args[0] = args[0].replace('/', File.separatorChar);
- File buildFile = new File( args[ 0 ] );
+ File buildFile = new File(args[0]);
- StringBuffer sb = readFile( buildFile );
+ StringBuffer sb = readFile(buildFile);
- String tokenStr = "<property name=\"" + args[ 1 ] + "\" value=\"";
-
- int i = sb.indexOf( tokenStr );
+ String tokenStr = "<property name=\"" + args[1] + "\" value=\"";
- if (i < 0)
- throw new IllegalArgumentException( "Can't find token: " + tokenStr );
+ int i = sb.indexOf(tokenStr);
+
+ if (i < 0) {
+ throw new IllegalArgumentException("Can't find token: " + tokenStr);
+ }
int j = i + tokenStr.length();
- while ( sb.charAt( j ) != '"' )
+ while (sb.charAt(j) != '"') {
j++;
+ }
- sb.replace( i + tokenStr.length(), j, args[ 2 ] );
+ sb.replace(i + tokenStr.length(), j, args[2]);
- writeFile( buildFile, sb );
+ writeFile(buildFile, sb);
}
-
- static StringBuffer readFile ( File f )
- throws IOException
- {
- InputStream in = new FileInputStream( f );
- Reader r = new InputStreamReader( in );
- StringWriter w = new StringWriter();
- copy( r, w );
-
- w.close();
- r.close();
- in.close();
-
- return w.getBuffer();
+ static StringBuffer readFile(File f) throws IOException {
+ try (Reader r = Files.newBufferedReader(f.toPath(), StandardCharsets.ISO_8859_1);
+ StringWriter w = new StringWriter()) {
+ copy(r, w);
+ return w.getBuffer();
+ }
}
-
- static void writeFile ( File f, StringBuffer chars )
- throws IOException
- {
- OutputStream out = new FileOutputStream( f );
- Writer w = new OutputStreamWriter( out );
- Reader r = new StringReader( chars.toString() );
- copy( r, w );
-
- r.close();
- w.close();
- out.close();
+ static void writeFile(File f, StringBuffer chars) throws IOException {
+ try (Writer w = Files.newBufferedWriter(f.toPath(), StandardCharsets.ISO_8859_1);
+ Reader r = new StringReader(chars.toString())) {
+ copy(r, w);
+ }
}
-
- static void copy ( Reader r, Writer w ) throws IOException
- {
- char[] buffer = new char [ 1024 * 16 ];
- for ( ; ; )
- {
- int n = r.read( buffer, 0, buffer.length );
+ static void copy(Reader r, Writer w) throws IOException {
+ char[] buffer = new char[1024 * 16];
- if (n < 0)
+ for (; ; ) {
+ int n = r.read(buffer, 0, buffer.length);
+
+ if (n < 0) {
break;
+ }
- w.write( buffer, 0, n );
+ w.write(buffer, 0, n);
}
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/repackage/Repackage.java b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackage.java
index 8c1c1c5..2bb8a1f 100644
--- a/src/main/java/org/apache/xmlbeans/impl/repackage/Repackage.java
+++ b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackage.java
@@ -16,347 +16,327 @@
package org.apache.xmlbeans.impl.repackage;
import java.io.*;
-import java.util.*;
-import java.util.regex.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
-public class Repackage
-{
- public static void main ( String[] args ) throws Exception
- {
+public class Repackage {
+
+ private final File _sourceBase;
+ private final File _targetBase;
+
+ private List<List<String>> _fromPackages;
+ private List<List<String>> _toPackages;
+
+ private Pattern _packagePattern;
+
+ private final Repackager _repackager;
+
+ private Map<String, String> _movedDirs;
+ private List<String> _moveAlongFiles;
+ private int _skippedFiles;
+
+ public static void main(String[] args) throws Exception {
new Repackage(args).repackage();
}
-
- private Repackage(String[] args)
- {
+
+ private Repackage(String[] args) {
String sourceDir = null;
String targetDir = null;
String repackageSpec = null;
boolean failure = false;
-
- for (int i = 0; i < args.length; i++)
- {
- if (args[i].equals("-repackage") && i + 1 < args.length)
+
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].equals("-repackage") && i + 1 < args.length) {
repackageSpec = args[++i];
- else if (args[i].equals("-f") && i + 1 < args.length)
+ } else if (args[i].equals("-f") && i + 1 < args.length) {
sourceDir = args[++i];
- else if (args[i].equals("-t") && i + 1 < args.length)
+ } else if (args[i].equals("-t") && i + 1 < args.length) {
targetDir = args[++i];
- else
+ } else {
failure = true;
+ }
}
-
- if (failure || repackageSpec == null || (sourceDir == null ^ targetDir == null))
+
+ if (failure || repackageSpec == null || (sourceDir == null ^ targetDir == null)) {
throw new RuntimeException("Usage: repackage -repackage [spec] [ -f [sourcedir] -t [targetdir] ]");
-
+ }
+
_repackager = new Repackager(repackageSpec);
- if (sourceDir==null || targetDir==null)
- return;
-
- _sourceBase = new File(sourceDir);
- _targetBase = new File(targetDir);
+ if (sourceDir == null || targetDir == null) {
+ _sourceBase = _targetBase = null;
+ } else {
+ _sourceBase = new File(sourceDir);
+ _targetBase = new File(targetDir);
+ }
}
-
-
- public void repackage () throws Exception
- {
- if (_sourceBase==null || _targetBase==null)
- { // read from system.in, write on system.out
- System.out.println( _repackager.repackage(readInputStream(System.in)).toString() );
+
+
+ public void repackage() throws Exception {
+ if (_sourceBase == null || _targetBase == null) {
+ // read from system.in, write on system.out
+ System.out.println(_repackager.repackage(readInputStream(System.in)).toString());
return;
}
_fromPackages = _repackager.getFromPackages();
_toPackages = _repackager.getToPackages();
-
- _packagePattern =
- Pattern.compile( "^\\s*package\\s+((?:\\w|\\.)*)\\s*;", Pattern.MULTILINE );
-
- _moveAlongFiles = new ArrayList();
- _movedDirs = new HashMap();
-
+
+ _packagePattern = Pattern.compile("^\\s*package\\s+((?:\\w|\\.)*)\\s*;", Pattern.MULTILINE);
+
+ _moveAlongFiles = new ArrayList<>();
+ _movedDirs = new HashMap<>();
+
// System.out.println( "Deleting repackage dir ..." );
// recursiveDelete( _targetBase );
-
- _targetBase.mkdirs();
-
- ArrayList files = new ArrayList();
- fillFiles( files, _sourceBase );
-
- System.out.println( "Repackaging " + files.size() + " files ..." );
+ _targetBase.mkdirs();
+
+ List<File> files = new ArrayList<>();
+
+ fillFiles(files, _sourceBase);
+
+ System.out.println("Repackaging " + files.size() + " files ...");
int prefixLength = _sourceBase.getCanonicalPath().length();
- for ( int i = 0 ; i < files.size() ; i++ )
- {
- File from = (File) files.get( i );
+ for (File from : files) {
- String name = from.getCanonicalPath().substring( prefixLength + 1 );
+ String name = from.getCanonicalPath().substring(prefixLength + 1);
- repackageFile( name );
+ repackageFile(name);
}
-
+
finishMovingFiles();
-
- if (_skippedFiles > 0)
+
+ if (_skippedFiles > 0) {
System.out.println("Skipped " + _skippedFiles + " unmodified files.");
- }
-
- private boolean fileIsUnchanged(String name)
- {
- File sourceFile = new File( _sourceBase, name );
- File targetFile = new File( _targetBase, name );
- return (sourceFile.lastModified() < targetFile.lastModified());
+ }
}
- public void repackageFile ( String name )
- throws IOException
- {
- if (name.endsWith( ".java" ))
- repackageJavaFile( name );
- else if (name.endsWith( ".xsdconfig" ) ||
- name.endsWith( ".xml" ) ||
- name.endsWith( ".g" ) )
- repackageNonJavaFile( name );
- else if (name.startsWith( "bin" + File.separatorChar ))
- repackageNonJavaFile( name );
- else
- moveAlongWithJavaFiles( name );
+ public void repackageFile(String name)
+ throws IOException {
+ if (name.endsWith(".java")) {
+ repackageJavaFile(name);
+ } else if (name.endsWith(".xsdconfig") ||
+ name.endsWith(".xml") ||
+ name.endsWith(".g")) {
+ repackageNonJavaFile(name);
+ } else if (name.startsWith("bin" + File.separatorChar)) {
+ repackageNonJavaFile(name);
+ } else {
+ moveAlongWithJavaFiles(name);
+ }
}
- public void moveAlongWithJavaFiles( String name )
- {
+ public void moveAlongWithJavaFiles(String name) {
_moveAlongFiles.add(name);
}
-
- public void finishMovingFiles ( )
- throws IOException
- {
- for ( Iterator i = _moveAlongFiles.iterator(); i.hasNext(); )
- {
- String name = (String) i.next();
- String toName = name;
-
- String srcDir = Repackager.dirForPath( name );
- String toDir = (String) _movedDirs.get( srcDir );
-
- if (toDir != null)
- toName = new File( toDir, new File( name ).getName() ).toString();
- if (name.endsWith( ".html" ))
+ public void finishMovingFiles()
+ throws IOException {
+ for (String name : _moveAlongFiles) {
+ String srcDir = Repackager.dirForPath(name);
+ String toDir = _movedDirs.get(srcDir);
+
+ String toName = (toDir == null) ? name : new File(toDir, new File(name).getName()).toString();
+
+ if (name.endsWith(".html")) {
repackageNonJavaFile(name, toName);
- else
+ } else {
justMoveNonJavaFile(name, toName);
+ }
}
}
public void repackageNonJavaFile(String name)
- throws IOException
- {
- File sourceFile = new File( _sourceBase, name );
- File targetFile = new File( _targetBase, name );
-
- if (sourceFile.lastModified() < targetFile.lastModified())
+ throws IOException {
+ File sourceFile = new File(_sourceBase, name);
+ File targetFile = new File(_targetBase, name);
+
+ if (sourceFile.lastModified() < targetFile.lastModified()) {
_skippedFiles += 1;
- else
- writeFile( targetFile, _repackager.repackage( readFile( sourceFile ) ) );
+ } else {
+ writeFile(targetFile, _repackager.repackage(readFile(sourceFile)));
+ }
}
-
- public void repackageNonJavaFile ( String sourceName, String targetName )
- throws IOException
- {
- File sourceFile = new File( _sourceBase, sourceName );
- File targetFile = new File( _targetBase, targetName );
-
- if (sourceFile.lastModified() < targetFile.lastModified())
+
+ public void repackageNonJavaFile(String sourceName, String targetName)
+ throws IOException {
+ File sourceFile = new File(_sourceBase, sourceName);
+ File targetFile = new File(_targetBase, targetName);
+
+ if (sourceFile.lastModified() < targetFile.lastModified()) {
_skippedFiles += 1;
- else
- writeFile( targetFile, _repackager.repackage( readFile( sourceFile ) ) );
+ } else {
+ writeFile(targetFile, _repackager.repackage(readFile(sourceFile)));
+ }
}
-
- public void justMoveNonJavaFile ( String sourceName, String targetName )
- throws IOException
- {
- File sourceFile = new File( _sourceBase, sourceName );
- File targetFile = new File( _targetBase, targetName );
-
- if (sourceFile.lastModified() < targetFile.lastModified())
+
+ public void justMoveNonJavaFile(String sourceName, String targetName)
+ throws IOException {
+ File sourceFile = new File(_sourceBase, sourceName);
+ File targetFile = new File(_targetBase, targetName);
+
+ if (sourceFile.lastModified() < targetFile.lastModified()) {
_skippedFiles += 1;
- else
- copyFile( sourceFile, targetFile );
+ } else {
+ copyFile(sourceFile, targetFile);
+ }
}
-
- public void repackageJavaFile ( String name )
- throws IOException
- {
+
+ public void repackageJavaFile(String name)
+ throws IOException {
File sourceFile = new File(_sourceBase, name);
StringBuffer sb = readFile(sourceFile);
- Matcher packageMatcher = _packagePattern.matcher( sb );
+ Matcher packageMatcher = _packagePattern.matcher(sb);
- if (packageMatcher.find())
- {
- String pkg = packageMatcher.group( 1 );
- int pkgStart = packageMatcher.start( 1 );
- int pkgEnd = packageMatcher.end( 1 );
-
- if (packageMatcher.find())
- throw new RuntimeException( "Two package specifications found: " + name );
+ if (packageMatcher.find()) {
+ String pkg = packageMatcher.group(1);
+ int pkgStart = packageMatcher.start(1);
+ int pkgEnd = packageMatcher.end(1);
- List filePath = Repackager.splitPath( name, File.separatorChar );
- String srcDir = Repackager.dirForPath( name );
-
+ if (packageMatcher.find()) {
+ throw new RuntimeException("Two package specifications found: " + name);
+ }
+
+ List<String> filePath = Repackager.splitPath(name, File.separatorChar);
+ String srcDir = Repackager.dirForPath(name);
+
// Sort the repackage spec so that longer from's are first to match
// longest package first
- for ( ; ; )
- {
+ for (; ; ) {
boolean swapped = false;
- for ( int i = 1 ; i < filePath.size() ; i++ )
- {
- String spec1 = (String) filePath.get( i - 1 );
- String spec2 = (String) filePath.get( i );
+ for (int i = 1; i < filePath.size(); i++) {
+ String spec1 = filePath.get(i - 1);
+ String spec2 = filePath.get(i);
- if (spec1.indexOf( ':' ) < spec2.indexOf( ':' ))
- {
- filePath.set( i - 1, spec2 );
- filePath.set( i, spec1 );
+ if (spec1.indexOf(':') < spec2.indexOf(':')) {
+ filePath.set(i - 1, spec2);
+ filePath.set(i, spec1);
swapped = true;
}
}
- if (!swapped)
+ if (!swapped) {
break;
+ }
}
- List pkgPath = Repackager.splitPath( pkg, '.' );
+ List<String> pkgPath = Repackager.splitPath(pkg, '.');
int f = filePath.size() - 2;
- if (f<0 || (filePath.size()-1)< pkgPath.size())
+ if (f < 0 || (filePath.size() - 1) < pkgPath.size()) {
throw new RuntimeException("Package spec differs from file path: " + name);
+ }
- for ( int i = pkgPath.size() - 1 ; i >= 0 ; i-- )
- {
- if (!pkgPath.get( i ).equals( filePath.get( f ) ))
- throw new RuntimeException( "Package spec differs from file path: " + name );
+ for (int i = pkgPath.size() - 1; i >= 0; i--) {
+ if (!pkgPath.get(i).equals(filePath.get(f))) {
+ throw new RuntimeException("Package spec differs from file path: " + name);
+ }
f--;
}
- List changeTo = null;
- List changeFrom = null;
-
- from:
- for ( int i = 0 ; i < _fromPackages.size() ; i ++ )
- {
- List from = (List) _fromPackages.get( i );
+ List<String> changeTo = null;
+ List<String> changeFrom = null;
- if (from.size() <= pkgPath.size())
- {
- for ( int j = 0 ; j < from.size() ; j++ )
- if (!from.get( j ).equals( pkgPath.get( j )))
+ from:
+ for (int i = 0; i < _fromPackages.size(); i++) {
+ List<String> from = _fromPackages.get(i);
+
+ if (from.size() <= pkgPath.size()) {
+ for (int j = 0; j < from.size(); j++) {
+ if (!from.get(j).equals(pkgPath.get(j))) {
continue from;
+ }
+ }
changeFrom = from;
- changeTo = (List) _toPackages.get( i );
+ changeTo = _toPackages.get(i);
break;
}
}
- if (changeTo != null)
- {
+ if (changeTo != null) {
String newPkg = "";
String newName = "";
- for ( int i = 0 ; i < changeTo.size() ; i++ )
- {
- if (i > 0)
- {
+ for (int i = 0; i < changeTo.size(); i++) {
+ if (i > 0) {
newPkg += ".";
newName += File.separatorChar;
}
-
- newPkg += changeTo.get( i );
- newName += changeTo.get( i );
- }
-
- for ( int i = filePath.size() - pkgPath.size() - 2 ; i >= 0 ; i-- )
- newName = (String) filePath.get( i ) + File.separatorChar + newName;
- for ( int i = changeFrom.size() ; i < pkgPath.size() ; i++ )
- {
- newName += File.separatorChar + (String) pkgPath.get( i );
- newPkg += '.' + (String) pkgPath.get( i );
+ newPkg += changeTo.get(i);
+ newName += changeTo.get(i);
}
- newName += File.separatorChar + (String) filePath.get( filePath.size() - 1 );
+ for (int i = filePath.size() - pkgPath.size() - 2; i >= 0; i--) {
+ newName = filePath.get(i) + File.separatorChar + newName;
+ }
- sb.replace( pkgStart, pkgEnd, newPkg );
+ for (int i = changeFrom.size(); i < pkgPath.size(); i++) {
+ newName += File.separatorChar + pkgPath.get(i);
+ newPkg += '.' + pkgPath.get(i);
+ }
+
+ newName += File.separatorChar + filePath.get(filePath.size() - 1);
+
+ sb.replace(pkgStart, pkgEnd, newPkg);
name = newName;
- String newDir = Repackager.dirForPath( name );
-
- if (!srcDir.equals(newDir))
- {
+ String newDir = Repackager.dirForPath(name);
+
+ if (!srcDir.equals(newDir)) {
_movedDirs.put(srcDir, newDir);
}
}
}
-
+
File targetFile = new File(_targetBase, name); // new name
-
- if (sourceFile.lastModified() < targetFile.lastModified())
- {
+
+ if (sourceFile.lastModified() < targetFile.lastModified()) {
_skippedFiles += 1;
return;
}
- writeFile( new File( _targetBase, name ), _repackager.repackage( sb ) );
+ writeFile(new File(_targetBase, name), _repackager.repackage(sb));
}
- void writeFile ( File f, StringBuffer chars )
- throws IOException
- {
+ void writeFile(File f, StringBuffer chars) throws IOException {
f.getParentFile().mkdirs();
-
- OutputStream out = new FileOutputStream( f );
- Writer w = new OutputStreamWriter( out );
- Reader r = new StringReader( chars.toString() );
- copy( r, w );
-
- r.close();
- w.close();
- out.close();
- }
-
- StringBuffer readFile ( File f )
- throws IOException
- {
- InputStream in = new FileInputStream( f );
- Reader r = new InputStreamReader( in );
- StringWriter w = new StringWriter();
-
- copy( r, w );
-
- w.close();
- r.close();
- in.close();
-
- return w.getBuffer();
+ try (Writer w = Files.newBufferedWriter(f.toPath(), StandardCharsets.ISO_8859_1);
+ Reader r = new StringReader(chars.toString())) {
+ copy(r, w);
+ }
}
- StringBuffer readInputStream ( InputStream is )
- throws IOException
- {
- Reader r = new InputStreamReader( is );
+ StringBuffer readFile(File f) throws IOException {
+ try (Reader r = Files.newBufferedReader(f.toPath(), StandardCharsets.ISO_8859_1);
+ StringWriter w = new StringWriter()) {
+ copy(r, w);
+ return w.getBuffer();
+ }
+ }
+
+ StringBuffer readInputStream(InputStream is) throws IOException {
+ Reader r = new InputStreamReader(is);
StringWriter w = new StringWriter();
- copy( r, w );
+ copy(r, w);
w.close();
r.close();
@@ -364,99 +344,88 @@
return w.getBuffer();
}
- public static void copyFile ( File from, File to ) throws IOException
- {
+ public static void copyFile(File from, File to) throws IOException {
to.getParentFile().mkdirs();
-
- FileInputStream in = new FileInputStream( from );
- FileOutputStream out = new FileOutputStream( to );
- copy( in, out );
-
+ FileInputStream in = new FileInputStream(from);
+ FileOutputStream out = new FileOutputStream(to);
+
+ copy(in, out);
+
out.close();
in.close();
}
-
- public static void copy ( InputStream in, OutputStream out ) throws IOException
- {
- byte[] buffer = new byte [ 1024 * 16 ];
- for ( ; ; )
- {
- int n = in.read( buffer, 0, buffer.length );
+ public static void copy(InputStream in, OutputStream out) throws IOException {
+ byte[] buffer = new byte[1024 * 16];
- if (n < 0)
+ for (; ; ) {
+ int n = in.read(buffer, 0, buffer.length);
+
+ if (n < 0) {
break;
+ }
- out.write( buffer, 0, n );
+ out.write(buffer, 0, n);
}
}
-
- public static void copy ( Reader r, Writer w ) throws IOException
- {
- char[] buffer = new char [ 1024 * 16 ];
- for ( ; ; )
- {
- int n = r.read( buffer, 0, buffer.length );
+ public static void copy(Reader r, Writer w) throws IOException {
+ char[] buffer = new char[1024 * 16];
- if (n < 0)
+ for (; ; ) {
+ int n = r.read(buffer, 0, buffer.length);
+
+ if (n < 0) {
break;
+ }
- w.write( buffer, 0, n );
+ w.write(buffer, 0, n);
}
}
-
- public void fillFiles ( ArrayList files, File file ) throws IOException
- {
- if (!file.isDirectory())
- {
- files.add( file );
+
+ public void fillFiles(List<File> files, File file) {
+ if (!file.isDirectory()) {
+ files.add(file);
return;
}
// Exclude the build directory
- if (file.getName().equals( "build" ))
+ if (file.getName().equals("build")) {
return;
-
+ }
+
// Exclude CVS directories
- if (file.getName().equals( "CVS" ))
+ if (file.getName().equals("CVS")) {
return;
+ }
String[] entries = file.list();
-
- for ( int i = 0 ; i < entries.length ; i++ )
- fillFiles( files, new File( file, entries[ i ] ) );
+ if (entries == null) {
+ throw new RuntimeException("Directory can't be accessed: " + file.toString());
+ }
+ for (String entry : entries) {
+ fillFiles(files, new File(file, entry));
+ }
}
- public void recursiveDelete ( File file ) throws IOException
- {
- if (!file.exists())
+ public void recursiveDelete(File file) {
+ if (!file.exists()) {
return;
+ }
- if (file.isDirectory())
- {
+ if (file.isDirectory()) {
String[] entries = file.list();
+ if (entries == null) {
+ throw new RuntimeException("Directory can't be accessed: " + file.toString());
+ }
- for ( int i = 0 ; i < entries.length ; i++ )
- recursiveDelete( new File( file, entries[ i ] ) );
+ for (String entry : entries) {
+ recursiveDelete(new File(file, entry));
+ }
}
file.delete();
}
-
- private File _sourceBase;
- private File _targetBase;
-
- private List _fromPackages;
- private List _toPackages;
-
- private Pattern _packagePattern;
-
- private Repackager _repackager;
-
- private Map _movedDirs;
- private List _moveAlongFiles;
- private int _skippedFiles;
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java
index 5bf921a..93518e0 100644
--- a/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java
+++ b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java
@@ -15,122 +15,116 @@
package org.apache.xmlbeans.impl.repackage;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
-public class Repackager
-{
- public Repackager ( String repackageSpecs )
- {
- _fromPackages = new ArrayList();
- _toPackages = new ArrayList();
-
- List repackages = splitPath( repackageSpecs, ';' );
+public class Repackager {
+
+ private final List<List<String>> _fromPackages = new ArrayList<>();
+ private final List<List<String>> _toPackages = new ArrayList<>();
+
+ private Matcher[] _fromMatchers;
+ private String[] _toPackageNames;
+
+ public Repackager(String repackageSpecs) {
+ List<String> repackages = splitPath(repackageSpecs, ';');
// Sort the repackage spec so that longer from's are first to match
// longest package first
-
- for ( ; ; )
- {
+
+ for (; ; ) {
boolean swapped = false;
- for ( int i = 1 ; i < repackages.size() ; i++ )
- {
- String spec1 = (String) repackages.get( i - 1 );
- String spec2 = (String) repackages.get( i );
-
- if (spec1.indexOf( ':' ) < spec2.indexOf( ':' ))
- {
- repackages.set( i - 1, spec2 );
- repackages.set( i, spec1 );
-
+ for (int i = 1; i < repackages.size(); i++) {
+ String spec1 = repackages.get(i - 1);
+ String spec2 = repackages.get(i);
+
+ if (spec1.indexOf(':') < spec2.indexOf(':')) {
+ repackages.set(i - 1, spec2);
+ repackages.set(i, spec1);
+
swapped = true;
}
}
- if (!swapped)
+ if (!swapped) {
break;
+ }
}
- for ( int i = 0 ; i < repackages.size() ; i++ )
- {
- String spec = (String) repackages.get( i );
-
- int j = spec.indexOf( ':' );
+ for (String repackage : repackages) {
- if (j < 0 || spec.indexOf( ':', j + 1 ) >= 0)
- throw new RuntimeException( "Illegal repackage specification: " + spec );
+ int j = repackage.indexOf(':');
- String from = spec.substring( 0, j );
- String to = spec.substring( j + 1 );
+ if (j < 0 || repackage.indexOf(':', j + 1) >= 0) {
+ throw new RuntimeException("Illegal repackage specification: " + repackage);
+ }
- _fromPackages.add( Repackager.splitPath( from, '.' ) );
- _toPackages.add( Repackager.splitPath( to, '.' ) );
+ String from = repackage.substring(0, j);
+ String to = repackage.substring(j + 1);
+
+ _fromPackages.add(Repackager.splitPath(from, '.'));
+ _toPackages.add(Repackager.splitPath(to, '.'));
}
- _fromMatchers = new Matcher [ _fromPackages.size() * 2 ];
- _toPackageNames = new String [ _fromPackages.size() * 2 ];
+ _fromMatchers = new Matcher[_fromPackages.size() * 2];
+ _toPackageNames = new String[_fromPackages.size() * 2];
- addPatterns( '.', 0 );
- addPatterns( '/', _fromPackages.size() );
+ addPatterns('.', 0);
+ addPatterns('/', _fromPackages.size());
}
- void addPatterns ( char sep, int off )
- {
- for ( int i = 0 ; i < _fromPackages.size() ; i++ )
- {
- List from = (List) _fromPackages.get( i );
- List to = (List) _toPackages.get( i );
+ void addPatterns(char sep, int off) {
+ for (int i = 0; i < _fromPackages.size(); i++) {
+ List<String> from = _fromPackages.get(i);
+ List<String> to = _toPackages.get(i);
String pattern = "";
-
- for ( int j = 0 ; j < from.size() ; j++ )
- {
- if (j > 0)
+
+ for (int j = 0; j < from.size(); j++) {
+ if (j > 0) {
pattern += "\\" + sep;
+ }
- pattern += from.get( j );
+ pattern += from.get(j);
}
-
+
String toPackage = "";
-
- for ( int j = 0 ; j < to.size() ; j++ )
- {
- if (j > 0)
- toPackage += sep;
- toPackage += to.get( j );
+ for (int j = 0; j < to.size(); j++) {
+ if (j > 0) {
+ toPackage += sep;
+ }
+
+ toPackage += to.get(j);
}
- _fromMatchers[ off + i ] = Pattern.compile( pattern ).matcher( "" );
- _toPackageNames[ off + i ] = toPackage;
+ _fromMatchers[off + i] = Pattern.compile(pattern).matcher("");
+ _toPackageNames[off + i] = toPackage;
}
}
- public StringBuffer repackage ( StringBuffer sb )
- {
+ public StringBuffer repackage(StringBuffer sb) {
StringBuffer result = null;
- for ( int i = 0 ; i < _fromMatchers.length ; i++ )
- {
- Matcher m = (Matcher) _fromMatchers[ i ];
-
- m.reset( sb );
-
- for ( boolean found = m.find() ; found ; found = m.find() )
- {
- if (result == null)
- result = new StringBuffer();
+ for (int i = 0; i < _fromMatchers.length; i++) {
+ Matcher m = _fromMatchers[i];
- m.appendReplacement( result, _toPackageNames[ i ] );
+ m.reset(sb);
+
+ for (boolean found = m.find(); found; found = m.find()) {
+ if (result == null) {
+ result = new StringBuffer();
+ }
+
+ m.appendReplacement(result, _toPackageNames[i]);
}
- if (result != null)
- {
- m.appendTail( result );
+ if (result != null) {
+ m.appendTail(result);
sb = result;
result = null;
}
@@ -139,46 +133,37 @@
return sb;
}
- public List getFromPackages ( )
- {
+ public List<List<String>> getFromPackages() {
return _fromPackages;
}
- public List getToPackages ( )
- {
+ public List<List<String>> getToPackages() {
return _toPackages;
}
-
- public static ArrayList splitPath ( String path, char separator )
- {
- ArrayList components = new ArrayList();
-
- for ( ; ; )
- {
- int i = path.indexOf( separator );
- if (i < 0)
+ public static List<String> splitPath(String path, char separator) {
+ ArrayList<String> components = new ArrayList<>();
+
+ for (; ; ) {
+ int i = path.indexOf(separator);
+
+ if (i < 0) {
break;
+ }
- components.add( path.substring( 0, i ) );
-
- path = path.substring( i + 1 );
+ components.add(path.substring(0, i));
+
+ path = path.substring(i + 1);
}
- if (path.length() > 0)
- components.add( path );
+ if (path.length() > 0) {
+ components.add(path);
+ }
return components;
}
-
- public static String dirForPath ( String path )
- {
+
+ public static String dirForPath(String path) {
return new File(path).getParent();
}
-
- private List _fromPackages;
- private List _toPackages;
-
- private Matcher[] _fromMatchers;
- private String[] _toPackageNames;
}
\ No newline at end of file
diff --git a/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java b/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java
index 831ec01..1bd4d4f 100644
--- a/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java
@@ -19,12 +19,11 @@
import org.apache.xmlbeans.GDateBuilder;
import org.apache.xmlbeans.GDuration;
import org.apache.xmlbeans.XmlCalendar;
-import org.apache.xmlbeans.impl.common.XMLChar;
-import org.apache.xmlbeans.impl.util.XsTypeConverter;
-import org.apache.xmlbeans.impl.util.Base64;
-import org.apache.xmlbeans.impl.util.HexBin;
import org.apache.xmlbeans.impl.common.InvalidLexicalValueException;
+import org.apache.xmlbeans.impl.common.XMLChar;
import org.apache.xmlbeans.impl.common.XmlWhitespace;
+import org.apache.xmlbeans.impl.util.HexBin;
+import org.apache.xmlbeans.impl.util.XsTypeConverter;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
@@ -35,6 +34,8 @@
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
import java.util.Date;
/**
@@ -42,37 +43,33 @@
* Date: Nov 17, 2003
*/
public class XMLStreamReaderExtImpl
- implements XMLStreamReaderExt
-{
+ implements XMLStreamReaderExt {
private final XMLStreamReader _xmlStream;
private final CharSeqTrimWS _charSeq;
private String _defaultValue;
- public XMLStreamReaderExtImpl(XMLStreamReader xmlStream)
- {
- if (xmlStream==null)
+ public XMLStreamReaderExtImpl(XMLStreamReader xmlStream) {
+ if (xmlStream == null) {
throw new IllegalArgumentException();
+ }
_xmlStream = xmlStream;
_charSeq = new CharSeqTrimWS(this);
}
- public XMLStreamReader getUnderlyingXmlStream()
- {
+ public XMLStreamReader getUnderlyingXmlStream() {
return _xmlStream;
}
// XMLStreamReaderExt methods
public String getStringValue()
- throws XMLStreamException
- {
+ throws XMLStreamException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE);
return _charSeq.toString();
}
public String getStringValue(int wsStyle)
- throws XMLStreamException
- {
+ throws XMLStreamException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE);
//REVIEW zieg 2004-01-11 - we should write a collapse method
//that takes a CharSequence to void creating this extra String object
@@ -80,641 +77,468 @@
}
public boolean getBooleanValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexBoolean(_charSeq);
- }
- catch(InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public byte getByteValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexByte(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public short getShortValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexShort(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public int getIntValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexInt(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public long getLongValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexLong(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public BigInteger getBigIntegerValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexInteger(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public BigDecimal getBigDecimalValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexDecimal(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public float getFloatValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexFloat(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public double getDoubleValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexDouble(_charSeq);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public InputStream getHexBinaryValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
String text = _charSeq.toString();
- byte[] buf = HexBin.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1));
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation());
+ }
}
public InputStream getBase64Value()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
String text = _charSeq.toString();
- byte[] buf = Base64.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = Base64.getDecoder().decode(text.getBytes());
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation());
+ }
}
public XmlCalendar getCalendarValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return new GDateBuilder(_charSeq).getCalendar();
- }
- catch( IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public Date getDateValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return new GDateBuilder(_charSeq).getDate();
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public GDate getGDateValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexGDate(_charSeq);
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public GDuration getGDurationValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return new GDuration(_charSeq);
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
public QName getQNameValue()
- throws XMLStreamException, InvalidLexicalValueException
- {
+ throws XMLStreamException, InvalidLexicalValueException {
_charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexQName(_charSeq, _xmlStream.getNamespaceContext());
- }
- catch(InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation());
}
}
- public String getAttributeStringValue(int index) throws XMLStreamException
- {
+ public String getAttributeStringValue(int index) throws XMLStreamException {
return _xmlStream.getAttributeValue(index);
}
- public String getAttributeStringValue(int index, int wsStyle) throws XMLStreamException
- {
+ public String getAttributeStringValue(int index, int wsStyle) throws XMLStreamException {
return XmlWhitespace.collapse(_xmlStream.getAttributeValue(index), wsStyle);
}
- public boolean getAttributeBooleanValue(int index) throws XMLStreamException
- {
- try
- {
+ public boolean getAttributeBooleanValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexBoolean(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public byte getAttributeByteValue(int index) throws XMLStreamException
- {
- try
- {
+ public byte getAttributeByteValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexByte(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public short getAttributeShortValue(int index) throws XMLStreamException
- {
- try
- {
+ public short getAttributeShortValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexShort(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public int getAttributeIntValue(int index) throws XMLStreamException
- {
- try
- {
+ public int getAttributeIntValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexInt(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public long getAttributeLongValue(int index) throws XMLStreamException
- {
- try
- {
+ public long getAttributeLongValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexLong(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public BigInteger getAttributeBigIntegerValue(int index) throws XMLStreamException
- {
- try
- {
+ public BigInteger getAttributeBigIntegerValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexInteger(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public BigDecimal getAttributeBigDecimalValue(int index) throws XMLStreamException
- {
- try
- {
+ public BigDecimal getAttributeBigDecimalValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexDecimal(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public float getAttributeFloatValue(int index) throws XMLStreamException
- {
- try
- {
+ public float getAttributeFloatValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexFloat(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public double getAttributeDoubleValue(int index) throws XMLStreamException
- {
- try
- {
+ public double getAttributeDoubleValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexDouble(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public InputStream getAttributeHexBinaryValue(int index) throws XMLStreamException
- {
+ public InputStream getAttributeHexBinaryValue(int index) throws XMLStreamException {
String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString();
- byte[] buf = HexBin.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1));
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation());
+ }
}
- public InputStream getAttributeBase64Value(int index) throws XMLStreamException
- {
+ public InputStream getAttributeBase64Value(int index) throws XMLStreamException {
String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString();
- byte[] buf = Base64.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = Base64.getDecoder().decode(text.getBytes());
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation());
+ }
}
- public XmlCalendar getAttributeCalendarValue(int index) throws XMLStreamException
- {
- try
- {
+ public XmlCalendar getAttributeCalendarValue(int index) throws XMLStreamException {
+ try {
return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)).
getCalendar();
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public Date getAttributeDateValue(int index) throws XMLStreamException
- {
- try
- {
+ public Date getAttributeDateValue(int index) throws XMLStreamException {
+ try {
return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM))
.getDate();
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public GDate getAttributeGDateValue(int index) throws XMLStreamException
- {
- try
- {
+ public GDate getAttributeGDateValue(int index) throws XMLStreamException {
+ try {
return new GDate(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public GDuration getAttributeGDurationValue(int index) throws XMLStreamException
- {
- try
- {
+ public GDuration getAttributeGDurationValue(int index) throws XMLStreamException {
+ try {
return new GDuration(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public QName getAttributeQNameValue(int index) throws XMLStreamException
- {
- try
- {
+ public QName getAttributeQNameValue(int index) throws XMLStreamException {
+ try {
return XsTypeConverter.lexQName(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM),
_xmlStream.getNamespaceContext());
- }
- catch(InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation());
}
}
- public String getAttributeStringValue(String uri, String local) throws XMLStreamException
- {
+ public String getAttributeStringValue(String uri, String local) throws XMLStreamException {
return _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_PRESERVE).toString();
}
- public String getAttributeStringValue(String uri, String local, int wsStyle) throws XMLStreamException
- {
+ public String getAttributeStringValue(String uri, String local, int wsStyle) throws XMLStreamException {
return XmlWhitespace.collapse(_xmlStream.getAttributeValue(uri, local), wsStyle);
}
- public boolean getAttributeBooleanValue(String uri, String local) throws XMLStreamException
- {
+ public boolean getAttributeBooleanValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexBoolean(cs);
- }
- catch(InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public byte getAttributeByteValue(String uri, String local) throws XMLStreamException
- {
+ public byte getAttributeByteValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexByte(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public short getAttributeShortValue(String uri, String local) throws XMLStreamException
- {
+ public short getAttributeShortValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexShort(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public int getAttributeIntValue(String uri, String local) throws XMLStreamException
- {
+ public int getAttributeIntValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexInt(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public long getAttributeLongValue(String uri, String local) throws XMLStreamException
- {
+ public long getAttributeLongValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexLong(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public BigInteger getAttributeBigIntegerValue(String uri, String local) throws XMLStreamException
- {
+ public BigInteger getAttributeBigIntegerValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexInteger(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public BigDecimal getAttributeBigDecimalValue(String uri, String local) throws XMLStreamException
- {
+ public BigDecimal getAttributeBigDecimalValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexDecimal(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public float getAttributeFloatValue(String uri, String local) throws XMLStreamException
- {
+ public float getAttributeFloatValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexFloat(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public double getAttributeDoubleValue(String uri, String local) throws XMLStreamException
- {
+ public double getAttributeDoubleValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexDouble(cs);
- }
- catch(NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public InputStream getAttributeHexBinaryValue(String uri, String local) throws XMLStreamException
- {
+ public InputStream getAttributeHexBinaryValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
String text = cs.toString();
- byte[] buf = HexBin.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1));
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation());
+ }
}
- public InputStream getAttributeBase64Value(String uri, String local) throws XMLStreamException
- {
+ public InputStream getAttributeBase64Value(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
String text = cs.toString();
- byte[] buf = Base64.decode(text.getBytes());
- if (buf!=null)
+ byte[] buf = Base64.getDecoder().decode(text.getBytes());
+ if (buf != null) {
return new ByteArrayInputStream(buf);
- else
+ } else {
throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation());
+ }
}
- public XmlCalendar getAttributeCalendarValue(String uri, String local) throws XMLStreamException
- {
+ public XmlCalendar getAttributeCalendarValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return new GDateBuilder(cs).getCalendar();
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public Date getAttributeDateValue(String uri, String local) throws XMLStreamException
- {
- try
- {
+ public Date getAttributeDateValue(String uri, String local) throws XMLStreamException {
+ try {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
return new GDateBuilder(cs).getDate();
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public GDate getAttributeGDateValue(String uri, String local) throws XMLStreamException
- {
- try
- {
+ public GDate getAttributeGDateValue(String uri, String local) throws XMLStreamException {
+ try {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
return new GDate(cs);
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public GDuration getAttributeGDurationValue(String uri, String local) throws XMLStreamException
- {
- try
- {
+ public GDuration getAttributeGDurationValue(String uri, String local) throws XMLStreamException {
+ try {
return new GDuration(_charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM));
- }
- catch(IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException(e, _charSeq.getLocation());
}
}
- public QName getAttributeQNameValue(String uri, String local) throws XMLStreamException
- {
+ public QName getAttributeQNameValue(String uri, String local) throws XMLStreamException {
CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM);
- try
- {
+ try {
return XsTypeConverter.lexQName(cs, _xmlStream.getNamespaceContext());
- }
- catch (InvalidLexicalValueException e)
- {
+ } catch (InvalidLexicalValueException e) {
throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation());
}
}
- public void setDefaultValue(String defaultValue) throws XMLStreamException
- {
+ public void setDefaultValue(String defaultValue) throws XMLStreamException {
_defaultValue = defaultValue;
}
@@ -723,8 +547,7 @@
* Used for int, short, byte
*/
private static class CharSeqTrimWS
- implements CharSequence
- {
+ implements CharSequence {
final static int XMLWHITESPACE_PRESERVE = 1;
final static int XMLWHITESPACE_TRIM = 2;
@@ -739,156 +562,155 @@
private final ExtLocation _location;
private boolean _hasText;
- CharSeqTrimWS(XMLStreamReaderExtImpl xmlSteam)
- {
+ CharSeqTrimWS(XMLStreamReaderExtImpl xmlSteam) {
_xmlSteam = xmlSteam;
_location = new ExtLocation();
}
void reload(int style)
- throws XMLStreamException
- {
+ throws XMLStreamException {
_toStringValue = null;
_location.reset();
_hasText = false;
fillBuffer();
- if (style==XMLWHITESPACE_PRESERVE)
- {
+ if (style == XMLWHITESPACE_PRESERVE) {
_nonWSStart = 0;
_nonWSEnd = _length;
// takes defaultValue only if there wasn't any text
- if (!_hasText && _xmlSteam._defaultValue!=null)
- {
+ if (!_hasText && _xmlSteam._defaultValue != null) {
_length = 0;
fillBufferFromString(_xmlSteam._defaultValue);
}
- }
- else if (style==XMLWHITESPACE_TRIM)
- {
- for (_nonWSStart=0; _nonWSStart<_length; _nonWSStart++)
- if (!XMLChar.isSpace(_buf[_nonWSStart]))
+ } else if (style == XMLWHITESPACE_TRIM) {
+ for (_nonWSStart = 0; _nonWSStart < _length; _nonWSStart++) {
+ if (!XMLChar.isSpace(_buf[_nonWSStart])) {
break;
- for (_nonWSEnd=_length; _nonWSEnd>_nonWSStart; _nonWSEnd--)
- if (!XMLChar.isSpace(_buf[_nonWSEnd-1]))
+ }
+ }
+ for (_nonWSEnd = _length; _nonWSEnd > _nonWSStart; _nonWSEnd--) {
+ if (!XMLChar.isSpace(_buf[_nonWSEnd - 1])) {
break;
+ }
+ }
// takes defaultValue if length after triming is 0
- if (length()==0 && _xmlSteam._defaultValue!=null)
- {
+ if (length() == 0 && _xmlSteam._defaultValue != null) {
_length = 0;
fillBufferFromString(_xmlSteam._defaultValue);
//apply whispace rule on the default value
- for (_nonWSStart=0; _nonWSStart<_length; _nonWSStart++)
- if (!XMLChar.isSpace(_buf[_nonWSStart]))
+ for (_nonWSStart = 0; _nonWSStart < _length; _nonWSStart++) {
+ if (!XMLChar.isSpace(_buf[_nonWSStart])) {
break;
- for (_nonWSEnd=_length; _nonWSEnd>_nonWSStart; _nonWSEnd--)
- if (!XMLChar.isSpace(_buf[_nonWSEnd-1]))
+ }
+ }
+ for (_nonWSEnd = _length; _nonWSEnd > _nonWSStart; _nonWSEnd--) {
+ if (!XMLChar.isSpace(_buf[_nonWSEnd - 1])) {
break;
+ }
+ }
}
}
_xmlSteam._defaultValue = null;
}
private void fillBuffer()
- throws XMLStreamException
- {
+ throws XMLStreamException {
_length = 0;
- if (_xmlSteam.getEventType() == XMLStreamReader.START_DOCUMENT)
+ if (_xmlSteam.getEventType() == XMLStreamReader.START_DOCUMENT) {
_xmlSteam.next();
- if (_xmlSteam.isStartElement())
+ }
+ if (_xmlSteam.isStartElement()) {
_xmlSteam.next();
+ }
int depth = 0;
String error = null;
int eventType = _xmlSteam.getEventType();
loop:
- while(true)
- {
- switch(eventType)
- {
- case XMLStreamReader.CDATA:
- case XMLStreamReader.CHARACTERS:
- case XMLStreamReader.SPACE:
- _location.set(_xmlSteam.getLocation());
+ while (true) {
+ switch (eventType) {
+ case XMLStreamReader.CDATA:
+ case XMLStreamReader.CHARACTERS:
+ case XMLStreamReader.SPACE:
+ _location.set(_xmlSteam.getLocation());
- if (depth==0)
- addTextToBuffer();
+ if (depth == 0) {
+ addTextToBuffer();
+ }
- break;
+ break;
- case XMLStreamReader.ATTRIBUTE:
- case XMLStreamReader.COMMENT:
- case XMLStreamReader.DTD:
- case XMLStreamReader.ENTITY_DECLARATION:
- case XMLStreamReader.NAMESPACE:
- case XMLStreamReader.NOTATION_DECLARATION:
- case XMLStreamReader.PROCESSING_INSTRUCTION:
- case XMLStreamReader.START_DOCUMENT:
- // ignore
- break;
+ case XMLStreamReader.ATTRIBUTE:
+ case XMLStreamReader.COMMENT:
+ case XMLStreamReader.DTD:
+ case XMLStreamReader.ENTITY_DECLARATION:
+ case XMLStreamReader.NAMESPACE:
+ case XMLStreamReader.NOTATION_DECLARATION:
+ case XMLStreamReader.PROCESSING_INSTRUCTION:
+ case XMLStreamReader.START_DOCUMENT:
+ // ignore
+ break;
- case XMLStreamReader.END_DOCUMENT:
- _location.set(_xmlSteam.getLocation());
+ case XMLStreamReader.END_DOCUMENT:
+ _location.set(_xmlSteam.getLocation());
- break loop;
-
- case XMLStreamReader.END_ELEMENT:
- _location.set(_xmlSteam.getLocation());
- depth--;
- if (depth<0)
break loop;
- break;
- case XMLStreamReader.ENTITY_REFERENCE:
- _location.set(_xmlSteam.getLocation());
+ case XMLStreamReader.END_ELEMENT:
+ _location.set(_xmlSteam.getLocation());
+ depth--;
+ if (depth < 0) {
+ break loop;
+ }
+ break;
- addEntityToBuffer();
- break;
+ case XMLStreamReader.ENTITY_REFERENCE:
+ _location.set(_xmlSteam.getLocation());
- case XMLStreamReader.START_ELEMENT:
- depth++;
- error = "Unexpected element '" + _xmlSteam.getName() + "' in text content.";
- _location.set(_xmlSteam.getLocation());
+ addEntityToBuffer();
+ break;
- break;
+ case XMLStreamReader.START_ELEMENT:
+ depth++;
+ error = "Unexpected element '" + _xmlSteam.getName() + "' in text content.";
+ _location.set(_xmlSteam.getLocation());
+
+ break;
}
eventType = _xmlSteam.next();
}
- if (error!=null)
+ if (error != null) {
throw new XMLStreamException(error);
+ }
}
- private void ensureBufferLength(int lengthToAdd)
- {
- if (_length + lengthToAdd>_buf.length)
- {
+ private void ensureBufferLength(int lengthToAdd) {
+ if (_length + lengthToAdd > _buf.length) {
char[] newBuf = new char[_length + lengthToAdd];
- if (_length>0)
+ if (_length > 0) {
System.arraycopy(_buf, 0, newBuf, 0, _length);
+ }
_buf = newBuf;
}
}
- private void fillBufferFromString(CharSequence value)
- {
+ private void fillBufferFromString(CharSequence value) {
int textLength = value.length();
ensureBufferLength(textLength);
- for (int i=0; i<textLength; i++)
- {
+ for (int i = 0; i < textLength; i++) {
_buf[i] = value.charAt(i);
}
_length = textLength;
}
- private void addTextToBuffer()
- {
+ private void addTextToBuffer() {
_hasText = true;
int textLength = _xmlSteam.getTextLength();
ensureBufferLength(textLength);
@@ -919,8 +741,7 @@
//}
}
- private void addEntityToBuffer()
- {
+ private void addEntityToBuffer() {
String text = _xmlSteam.getText();
int textLength = text.length();
@@ -931,112 +752,111 @@
}
CharSequence reloadAtt(int index, int style)
- throws XMLStreamException
- {
+ throws XMLStreamException {
_location.reset();
_location.set(_xmlSteam.getLocation());
String value = _xmlSteam.getAttributeValue(index);
- if (value==null && _xmlSteam._defaultValue!=null)
+ if (value == null && _xmlSteam._defaultValue != null) {
value = _xmlSteam._defaultValue;
+ }
_xmlSteam._defaultValue = null;
int length = value.length();
- if (style==XMLWHITESPACE_PRESERVE)
- {
+ if (style == XMLWHITESPACE_PRESERVE) {
return value;
- }
- else if (style==XMLWHITESPACE_TRIM)
- {
+ } else if (style == XMLWHITESPACE_TRIM) {
int nonWSStart, nonWSEnd;
- for (nonWSStart=0; nonWSStart<length; nonWSStart++)
- if (!XMLChar.isSpace(value.charAt(nonWSStart)))
+ for (nonWSStart = 0; nonWSStart < length; nonWSStart++) {
+ if (!XMLChar.isSpace(value.charAt(nonWSStart))) {
break;
- for (nonWSEnd=length; nonWSEnd>nonWSStart; nonWSEnd--)
- if (!XMLChar.isSpace(value.charAt(nonWSEnd-1)))
+ }
+ }
+ for (nonWSEnd = length; nonWSEnd > nonWSStart; nonWSEnd--) {
+ if (!XMLChar.isSpace(value.charAt(nonWSEnd - 1))) {
break;
- if (nonWSStart==0 && nonWSEnd==length)
+ }
+ }
+ if (nonWSStart == 0 && nonWSEnd == length) {
return value;
- else
+ } else {
return value.subSequence(nonWSStart, nonWSEnd);
+ }
}
throw new IllegalStateException("unknown style");
}
CharSequence reloadAtt(String uri, String local, int style)
- throws XMLStreamException
- {
+ throws XMLStreamException {
_location.reset();
_location.set(_xmlSteam.getLocation());
String value = _xmlSteam.getAttributeValue(uri, local);
- if (value==null && _xmlSteam._defaultValue!=null)
+ if (value == null && _xmlSteam._defaultValue != null) {
value = _xmlSteam._defaultValue;
+ }
_xmlSteam._defaultValue = null;
int length = value.length();
- if (style==XMLWHITESPACE_PRESERVE)
- {
+ if (style == XMLWHITESPACE_PRESERVE) {
return value;
- }
- else if (style==XMLWHITESPACE_TRIM)
- {
- for (_nonWSStart=0; _nonWSStart<length; _nonWSStart++)
- if (!XMLChar.isSpace(value.charAt(_nonWSStart)))
+ } else if (style == XMLWHITESPACE_TRIM) {
+ for (_nonWSStart = 0; _nonWSStart < length; _nonWSStart++) {
+ if (!XMLChar.isSpace(value.charAt(_nonWSStart))) {
break;
- for (_nonWSEnd=length; _nonWSEnd>_nonWSStart; _nonWSEnd--)
- if (!XMLChar.isSpace(value.charAt(_nonWSEnd-1)))
+ }
+ }
+ for (_nonWSEnd = length; _nonWSEnd > _nonWSStart; _nonWSEnd--) {
+ if (!XMLChar.isSpace(value.charAt(_nonWSEnd - 1))) {
break;
- if (_nonWSStart==0 && _nonWSEnd==length)
+ }
+ }
+ if (_nonWSStart == 0 && _nonWSEnd == length) {
return value;
- else
+ } else {
return value.subSequence(_nonWSStart, _nonWSEnd);
+ }
}
throw new IllegalStateException("unknown style");
}
- Location getLocation()
- {
+ Location getLocation() {
ExtLocation loc = new ExtLocation();
loc.set(_location);
return loc;
}
- public int length()
- {
+ public int length() {
return _nonWSEnd - _nonWSStart;
}
- public char charAt(int index)
- {
+ public char charAt(int index) {
// for each char, this has to be fast, using assert instead of if throw
- assert (index<_nonWSEnd-_nonWSStart && -1<index) :
+ assert (index < _nonWSEnd - _nonWSStart && -1 < index) :
"Index " + index + " must be >-1 and <" + (_nonWSEnd - _nonWSStart);
return _buf[_nonWSStart + index];
}
- public CharSequence subSequence(int start, int end)
- {
+ public CharSequence subSequence(int start, int end) {
return new String(_buf, _nonWSStart + start, end - start);
}
- public String toString()
- {
- if (_toStringValue!=null)
+ public String toString() {
+ if (_toStringValue != null) {
return _toStringValue;
+ }
_toStringValue = new String(_buf, _nonWSStart, _nonWSEnd - _nonWSStart);
return _toStringValue;
}
- private static class ExtLocation implements Location
- {
+ private static class ExtLocation implements Location {
private int _line;
private int _col;
private int _off;
@@ -1044,55 +864,54 @@
private String _sid;
private boolean _isSet;
- ExtLocation()
- {
+ ExtLocation() {
_isSet = false;
}
- public int getLineNumber()
- {
- if (_isSet)
+ public int getLineNumber() {
+ if (_isSet) {
return _line;
- else
+ } else {
throw new IllegalStateException();
+ }
}
- public int getColumnNumber()
- {
- if (_isSet)
+ public int getColumnNumber() {
+ if (_isSet) {
return _col;
- else
+ } else {
throw new IllegalStateException();
+ }
}
- public int getCharacterOffset()
- {
- if (_isSet)
+ public int getCharacterOffset() {
+ if (_isSet) {
return _off;
- else
+ } else {
throw new IllegalStateException();
+ }
}
- public String getPublicId()
- {
- if (_isSet)
+ public String getPublicId() {
+ if (_isSet) {
return _pid;
- else
+ } else {
throw new IllegalStateException();
+ }
}
- public String getSystemId()
- {
- if (_isSet)
+ public String getSystemId() {
+ if (_isSet) {
return _sid;
- else
+ } else {
throw new IllegalStateException();
+ }
}
- void set(Location loc)
- {
- if (_isSet)
+ void set(Location loc) {
+ if (_isSet) {
return;
+ }
_isSet = true;
_line = loc.getLineNumber();
@@ -1102,8 +921,7 @@
_sid = loc.getSystemId();
}
- void reset()
- {
+ void reset() {
_isSet = false;
}
}
@@ -1111,231 +929,186 @@
// XMLStreamReader methods
public Object getProperty(String s)
- throws IllegalArgumentException
- {
+ throws IllegalArgumentException {
return _xmlStream.getProperty(s);
}
public int next()
- throws XMLStreamException
- {
+ throws XMLStreamException {
return _xmlStream.next();
}
public void require(int i, String s, String s1)
- throws XMLStreamException
- {
+ throws XMLStreamException {
_xmlStream.require(i, s, s1);
}
- public String getElementText() throws XMLStreamException
- {
+ public String getElementText() throws XMLStreamException {
return _xmlStream.getElementText();
}
- public int nextTag() throws XMLStreamException
- {
+ public int nextTag() throws XMLStreamException {
return _xmlStream.nextTag();
}
- public boolean hasNext() throws XMLStreamException
- {
+ public boolean hasNext() throws XMLStreamException {
return _xmlStream.hasNext();
}
- public void close() throws XMLStreamException
- {
+ public void close() throws XMLStreamException {
_xmlStream.close();
}
- public String getNamespaceURI(String s)
- {
+ public String getNamespaceURI(String s) {
return _xmlStream.getNamespaceURI(s);
}
- public boolean isStartElement()
- {
+ public boolean isStartElement() {
return _xmlStream.isStartElement();
}
- public boolean isEndElement()
- {
+ public boolean isEndElement() {
return _xmlStream.isEndElement();
}
- public boolean isCharacters()
- {
+ public boolean isCharacters() {
return _xmlStream.isCharacters();
}
- public boolean isWhiteSpace()
- {
+ public boolean isWhiteSpace() {
return _xmlStream.isWhiteSpace();
}
- public String getAttributeValue(String s, String s1)
- {
+ public String getAttributeValue(String s, String s1) {
return _xmlStream.getAttributeValue(s, s1);
}
- public int getAttributeCount()
- {
+ public int getAttributeCount() {
return _xmlStream.getAttributeCount();
}
- public QName getAttributeName(int i)
- {
+ public QName getAttributeName(int i) {
return _xmlStream.getAttributeName(i);
}
- public String getAttributeNamespace(int i)
- {
+ public String getAttributeNamespace(int i) {
return _xmlStream.getAttributeNamespace(i);
}
- public String getAttributeLocalName(int i)
- {
+ public String getAttributeLocalName(int i) {
return _xmlStream.getAttributeLocalName(i);
}
- public String getAttributePrefix(int i)
- {
+ public String getAttributePrefix(int i) {
return _xmlStream.getAttributePrefix(i);
}
- public String getAttributeType(int i)
- {
+ public String getAttributeType(int i) {
return _xmlStream.getAttributeType(i);
}
- public String getAttributeValue(int i)
- {
+ public String getAttributeValue(int i) {
return _xmlStream.getAttributeValue(i);
}
- public boolean isAttributeSpecified(int i)
- {
+ public boolean isAttributeSpecified(int i) {
return _xmlStream.isAttributeSpecified(i);
}
- public int getNamespaceCount()
- {
+ public int getNamespaceCount() {
return _xmlStream.getNamespaceCount();
}
- public String getNamespacePrefix(int i)
- {
+ public String getNamespacePrefix(int i) {
return _xmlStream.getNamespacePrefix(i);
}
- public String getNamespaceURI(int i)
- {
+ public String getNamespaceURI(int i) {
return _xmlStream.getNamespaceURI(i);
}
- public NamespaceContext getNamespaceContext()
- {
+ public NamespaceContext getNamespaceContext() {
return _xmlStream.getNamespaceContext();
}
- public int getEventType()
- {
+ public int getEventType() {
return _xmlStream.getEventType();
}
- public String getText()
- {
+ public String getText() {
return _xmlStream.getText();
}
- public char[] getTextCharacters()
- {
+ public char[] getTextCharacters() {
return _xmlStream.getTextCharacters();
}
public int getTextCharacters(int i, char[] chars, int i1, int i2)
- throws XMLStreamException
- {
+ throws XMLStreamException {
return _xmlStream.getTextCharacters(i, chars, i1, i2);
}
- public int getTextStart()
- {
+ public int getTextStart() {
return _xmlStream.getTextStart();
}
- public int getTextLength()
- {
+ public int getTextLength() {
return _xmlStream.getTextLength();
}
- public String getEncoding()
- {
+ public String getEncoding() {
return _xmlStream.getEncoding();
}
- public boolean hasText()
- {
+ public boolean hasText() {
return _xmlStream.hasText();
}
- public Location getLocation()
- {
+ public Location getLocation() {
return _xmlStream.getLocation();
}
- public QName getName()
- {
+ public QName getName() {
return _xmlStream.getName();
}
- public String getLocalName()
- {
+ public String getLocalName() {
return _xmlStream.getLocalName();
}
- public boolean hasName()
- {
+ public boolean hasName() {
return _xmlStream.hasName();
}
- public String getNamespaceURI()
- {
+ public String getNamespaceURI() {
return _xmlStream.getNamespaceURI();
}
- public String getPrefix()
- {
+ public String getPrefix() {
return _xmlStream.getPrefix();
}
- public String getVersion()
- {
+ public String getVersion() {
return _xmlStream.getVersion();
}
- public boolean isStandalone()
- {
+ public boolean isStandalone() {
return _xmlStream.isStandalone();
}
- public boolean standaloneSet()
- {
+ public boolean standaloneSet() {
return _xmlStream.standaloneSet();
}
- public String getCharacterEncodingScheme()
- {
+ public String getCharacterEncodingScheme() {
return _xmlStream.getCharacterEncodingScheme();
}
- public String getPITarget()
- {
+ public String getPITarget() {
return _xmlStream.getPITarget();
}
- public String getPIData()
- {
+ public String getPIData() {
return _xmlStream.getPIData();
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
index 8b1b5fb..6107010 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
@@ -32,6 +32,7 @@
import javax.xml.namespace.QName;
import java.io.*;
import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -406,8 +407,8 @@
copy(in, out);
} catch (IOException e) {
// ok
- }
}
+ }
private InputStream getHolder() {
InputStream is = SchemaTypeSystemImpl.class.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE);
@@ -825,7 +826,7 @@
// get 128 random bits (that'll be 32 hex digits)
byte[] bytes = new byte[128 / 8];
nextBytes(bytes);
- nameForSystem = "s" + new String(HexBin.encode(bytes));
+ nameForSystem = "s" + new String(HexBin.encode(bytes), StandardCharsets.ISO_8859_1);
}
_name = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN.replace('/', '.') + ".system." + nameForSystem;
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
index f464200..55c292d 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
@@ -15,45 +15,28 @@
package org.apache.xmlbeans.impl.schema;
-import org.apache.xmlbeans.XmlErrorCodes;
+import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.QNameHelper;
import org.apache.xmlbeans.impl.common.ResolverUtil;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaComponent;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaIdentityConstraint;
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.SystemProperties;
-import org.apache.xmlbeans.XmlError;
-import org.apache.xmlbeans.XmlBeans;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.BindingConfig;
+import org.apache.xmlbeans.impl.util.HexBin;
import org.apache.xmlbeans.impl.values.XmlStringImpl;
import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
-import org.apache.xmlbeans.impl.util.HexBin;
-
-import java.util.*;
-import java.net.URISyntaxException;
-import java.net.URI;
-import java.net.URL;
-import java.io.File;
-
-
-import javax.xml.namespace.QName;
-
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import org.xml.sax.EntityResolver;
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+
/**
* This class represents the state of the SchemaTypeSystemCompiler as it's
* going.
*/
-public class StscState
-{
+public class StscState {
private String _givenStsName;
private Collection _errorListener;
private SchemaTypeSystemImpl _target;
@@ -62,7 +45,7 @@
private boolean _doingDownloads;
private byte[] _digest = null;
private boolean _noDigest = false;
-
+
// EXPERIMENTAL: recovery from compilation errors and partial type systems
private boolean _allowPartial = false;
private int _recoveredErrors = 0;
@@ -72,38 +55,37 @@
private Map _containers = new LinkedHashMap();
private SchemaDependencies _dependencies;
- private Map _redefinedGlobalTypes = new LinkedHashMap();
- private Map _redefinedModelGroups = new LinkedHashMap();
- private Map _redefinedAttributeGroups = new LinkedHashMap();
+ private Map _redefinedGlobalTypes = new LinkedHashMap();
+ private Map _redefinedModelGroups = new LinkedHashMap();
+ private Map _redefinedAttributeGroups = new LinkedHashMap();
- private Map _globalTypes = new LinkedHashMap();
- private Map _globalElements = new LinkedHashMap();
- private Map _globalAttributes = new LinkedHashMap();
- private Map _modelGroups = new LinkedHashMap();
- private Map _attributeGroups = new LinkedHashMap();
- private Map _documentTypes = new LinkedHashMap();
- private Map _attributeTypes = new LinkedHashMap();
- private Map _typesByClassname = new LinkedHashMap();
- private Map _misspelledNames = new HashMap();
- private Set _processingGroups = new LinkedHashSet();
- private Map _idConstraints = new LinkedHashMap();
- private Set _namespaces = new HashSet();
- private List _annotations = new ArrayList();
+ private Map _globalTypes = new LinkedHashMap();
+ private Map _globalElements = new LinkedHashMap();
+ private Map _globalAttributes = new LinkedHashMap();
+ private Map _modelGroups = new LinkedHashMap();
+ private Map _attributeGroups = new LinkedHashMap();
+ private Map _documentTypes = new LinkedHashMap();
+ private Map _attributeTypes = new LinkedHashMap();
+ private Map _typesByClassname = new LinkedHashMap();
+ private Map _misspelledNames = new HashMap();
+ private Set _processingGroups = new LinkedHashSet();
+ private Map _idConstraints = new LinkedHashMap();
+ private Set _namespaces = new HashSet();
+ private List _annotations = new ArrayList();
private boolean _noUpa;
private boolean _noPvr;
private boolean _noAnn;
private boolean _mdefAll;
- private Set _mdefNamespaces = buildDefaultMdefNamespaces();
+ private Set _mdefNamespaces = buildDefaultMdefNamespaces();
private EntityResolver _entityResolver;
private File _schemasDir;
- private static Set buildDefaultMdefNamespaces()
- {
+ private static Set buildDefaultMdefNamespaces() {
// namespaces which are known to appear in WSDLs redundantly
return new HashSet(
- Arrays.asList( new String[] {
- "http://www.openuri.org/2002/04/soap/conversation/",
- }));
+ Arrays.asList(new String[]{
+ "http://www.openuri.org/2002/04/soap/conversation/",
+ }));
}
/**
@@ -115,22 +97,18 @@
/**
* Only constructed via StscState.start().
*/
- private StscState()
- {
+ private StscState() {
}
/**
* Initializer for incremental compilation
*/
- public void initFromTypeSystem(SchemaTypeSystemImpl system, Set newNamespaces)
- {
+ public void initFromTypeSystem(SchemaTypeSystemImpl system, Set newNamespaces) {
// setGivenTypeSystemName(system.getName().substring(14));
SchemaContainer[] containers = system.containers();
- for (int i = 0; i < containers.length; i++)
- {
- if (!newNamespaces.contains(containers[i].getNamespace()))
- {
+ for (int i = 0; i < containers.length; i++) {
+ if (!newNamespaces.contains(containers[i].getNamespace())) {
// Copy data from the given container
addContainer(containers[i]);
}
@@ -140,10 +118,10 @@
/* CONTAINERS ================================================================*/
- void addNewContainer(String namespace)
- {
- if (_containers.containsKey(namespace))
+ void addNewContainer(String namespace) {
+ if (_containers.containsKey(namespace)) {
return;
+ }
SchemaContainer container = new SchemaContainer(namespace);
container.setTypeSystem(sts());
@@ -151,91 +129,82 @@
_containers.put(namespace, container);
}
- private void addContainer(SchemaContainer container)
- {
+ private void addContainer(SchemaContainer container) {
_containers.put(container.getNamespace(), container);
List redefModelGroups = container.redefinedModelGroups();
- for (int i = 0; i < redefModelGroups.size(); i++)
- {
+ for (int i = 0; i < redefModelGroups.size(); i++) {
QName name = ((SchemaModelGroup) redefModelGroups.get(i)).getName();
_redefinedModelGroups.put(name, redefModelGroups.get(i));
}
List redefAttrGroups = container.redefinedAttributeGroups();
- for (int i = 0; i < redefAttrGroups.size(); i++)
- {
+ for (int i = 0; i < redefAttrGroups.size(); i++) {
QName name = ((SchemaAttributeGroup) redefAttrGroups.get(i)).getName();
_redefinedAttributeGroups.put(name, redefAttrGroups.get(i));
}
List redefTypes = container.redefinedGlobalTypes();
- for (int i = 0; i < redefTypes.size(); i++)
- {
+ for (int i = 0; i < redefTypes.size(); i++) {
QName name = ((SchemaType) redefTypes.get(i)).getName();
_redefinedGlobalTypes.put(name, redefTypes.get(i));
}
List globalElems = container.globalElements();
- for (int i = 0; i < globalElems.size(); i++)
- {
+ for (int i = 0; i < globalElems.size(); i++) {
QName name = ((SchemaGlobalElement) globalElems.get(i)).getName();
_globalElements.put(name, globalElems.get(i));
}
List globalAtts = container.globalAttributes();
- for (int i = 0; i < globalAtts.size(); i++)
- {
+ for (int i = 0; i < globalAtts.size(); i++) {
QName name = ((SchemaGlobalAttribute) globalAtts.get(i)).getName();
_globalAttributes.put(name, globalAtts.get(i));
}
List modelGroups = container.modelGroups();
- for (int i = 0; i < modelGroups.size(); i++)
- {
+ for (int i = 0; i < modelGroups.size(); i++) {
QName name = ((SchemaModelGroup) modelGroups.get(i)).getName();
_modelGroups.put(name, modelGroups.get(i));
}
List attrGroups = container.attributeGroups();
- for (int i = 0; i < attrGroups.size(); i++)
- {
+ for (int i = 0; i < attrGroups.size(); i++) {
QName name = ((SchemaAttributeGroup) attrGroups.get(i)).getName();
_attributeGroups.put(name, attrGroups.get(i));
}
List globalTypes = container.globalTypes();
- for (int i = 0; i < globalTypes.size(); i++)
- {
+ for (int i = 0; i < globalTypes.size(); i++) {
SchemaType t = (SchemaType) globalTypes.get(i);
QName name = t.getName();
_globalTypes.put(name, t);
- if (t.getFullJavaName() != null)
+ if (t.getFullJavaName() != null) {
addClassname(t.getFullJavaName(), t);
+ }
}
List documentTypes = container.documentTypes();
- for (int i = 0; i < documentTypes.size(); i++)
- {
+ for (int i = 0; i < documentTypes.size(); i++) {
SchemaType t = (SchemaType) documentTypes.get(i);
QName name = t.getProperties()[0].getName();
_documentTypes.put(name, t);
- if (t.getFullJavaName() != null)
+ if (t.getFullJavaName() != null) {
addClassname(t.getFullJavaName(), t);
+ }
}
List attributeTypes = container.attributeTypes();
- for (int i = 0; i < attributeTypes.size(); i++)
- {
+ for (int i = 0; i < attributeTypes.size(); i++) {
SchemaType t = (SchemaType) attributeTypes.get(i);
QName name = t.getProperties()[0].getName();
_attributeTypes.put(name, t);
- if (t.getFullJavaName() != null)
+ if (t.getFullJavaName() != null) {
addClassname(t.getFullJavaName(), t);
+ }
}
List identityConstraints = container.identityConstraints();
- for (int i = 0; i < identityConstraints.size(); i++)
- {
+ for (int i = 0; i < identityConstraints.size(); i++) {
QName name = ((SchemaIdentityConstraint) identityConstraints.get(i)).getName();
_idConstraints.put(name, identityConstraints.get(i));
}
@@ -245,40 +214,33 @@
container.unsetImmutable();
}
- SchemaContainer getContainer(String namespace)
- {
+ SchemaContainer getContainer(String namespace) {
return (SchemaContainer) _containers.get(namespace);
}
- Map getContainerMap()
- {
+ Map getContainerMap() {
return Collections.unmodifiableMap(_containers);
}
/* DEPENDENCIES ================================================================*/
- void registerDependency(String sourceNs, String targetNs)
- {
+ void registerDependency(String sourceNs, String targetNs) {
_dependencies.registerDependency(sourceNs, targetNs);
}
- void registerContribution(String ns, String fileUrl)
- {
+ void registerContribution(String ns, String fileUrl) {
_dependencies.registerContribution(ns, fileUrl);
}
- SchemaDependencies getDependencies()
- {
+ SchemaDependencies getDependencies() {
return _dependencies;
}
- void setDependencies(SchemaDependencies deps)
- {
+ void setDependencies(SchemaDependencies deps) {
_dependencies = deps;
}
- boolean isFileProcessed(String url)
- {
+ boolean isFileProcessed(String url) {
return _dependencies.isFileRepresented(url);
}
@@ -286,54 +248,57 @@
/**
* Initializer for schematypepath
*/
- public void setImportingTypeLoader(SchemaTypeLoader loader)
- {
+ public void setImportingTypeLoader(SchemaTypeLoader loader) {
_importingLoader = loader;
}
/**
* Initializer for error handling.
*/
- public void setErrorListener(Collection errorListener)
- { _errorListener = errorListener; }
+ public void setErrorListener(Collection errorListener) {
+ _errorListener = errorListener;
+ }
/**
* Passes an error on to the current error listener.
* KHK: remove this
*/
- public void error(String message, int code, XmlObject loc)
- { addError(_errorListener, message, code, loc); }
+ public void error(String message, int code, XmlObject loc) {
+ addError(_errorListener, message, code, loc);
+ }
/**
* Passes an error on to the current error listener.
*/
- public void error(String code, Object[] args, XmlObject loc)
- { addError(_errorListener, code, args, loc); }
-
+ public void error(String code, Object[] args, XmlObject loc) {
+ addError(_errorListener, code, args, loc);
+ }
+
/**
* Passes a recovered error on to the current error listener.
*/
- public void recover(String code, Object[] args, XmlObject loc)
- { addError(_errorListener, code, args, loc); _recoveredErrors++; }
-
+ public void recover(String code, Object[] args, XmlObject loc) {
+ addError(_errorListener, code, args, loc);
+ _recoveredErrors++;
+ }
+
/**
* Passes an error on to the current error listener.
*/
- public void warning(String message, int code, XmlObject loc)
- {
+ public void warning(String message, int code, XmlObject loc) {
addWarning(_errorListener, message, code, loc);
}
/**
* Passes an error on to the current error listener.
*/
- public void warning(String code, Object[] args, XmlObject loc)
- {
+ public void warning(String code, Object[] args, XmlObject loc) {
// it's OK for XMLSchema.xsd itself to have reserved type names
if (code == XmlErrorCodes.RESERVED_TYPE_NAME &&
loc.documentProperties().getSourceName() != null &&
- loc.documentProperties().getSourceName().indexOf("XMLSchema.xsd") > 0)
+ loc.documentProperties().getSourceName().indexOf("XMLSchema.xsd") > 0) {
return;
+ }
addWarning(_errorListener, code, args, loc);
}
@@ -341,18 +306,19 @@
/**
* Passes a warning on to the current error listener.
*/
- public void info(String message)
- { addInfo(_errorListener, message); }
+ public void info(String message) {
+ addInfo(_errorListener, message);
+ }
/**
* Passes a warning on to the current error listener.
*/
- public void info(String code, Object[] args)
- { addInfo(_errorListener, code, args); }
+ public void info(String code, Object[] args) {
+ addInfo(_errorListener, code, args);
+ }
// KHK: remove this
- public static void addError(Collection errorListener, String message, int code, XmlObject location)
- {
+ public static void addError(Collection errorListener, String message, int code, XmlObject location) {
XmlError err =
XmlError.forObject(
message,
@@ -361,19 +327,17 @@
errorListener.add(err);
}
- public static void addError(Collection errorListener, String code, Object[] args, XmlObject location)
- {
+ public static void addError(Collection errorListener, String code, Object[] args, XmlObject location) {
XmlError err =
XmlError.forObject(
- code,
- args,
- XmlError.SEVERITY_ERROR,
- location);
+ code,
+ args,
+ XmlError.SEVERITY_ERROR,
+ location);
errorListener.add(err);
}
-
- public static void addError(Collection errorListener, String code, Object[] args, File location)
- {
+
+ public static void addError(Collection errorListener, String code, Object[] args, File location) {
XmlError err =
XmlError.forLocation(
code,
@@ -383,30 +347,27 @@
errorListener.add(err);
}
- public static void addError(Collection errorListener, String code, Object[] args, URL location)
- {
+ public static void addError(Collection errorListener, String code, Object[] args, URL location) {
XmlError err =
XmlError.forLocation(
- code,
- args,
- XmlError.SEVERITY_ERROR,
- location.toString(), 0, 0, 0);
+ code,
+ args,
+ XmlError.SEVERITY_ERROR,
+ location.toString(), 0, 0, 0);
errorListener.add(err);
}
// KHK: remove this
- public static void addWarning(Collection errorListener, String message, int code, XmlObject location)
- {
+ public static void addWarning(Collection errorListener, String message, int code, XmlObject location) {
XmlError err =
XmlError.forObject(
- message,
- XmlError.SEVERITY_WARNING,
- location);
+ message,
+ XmlError.SEVERITY_WARNING,
+ location);
errorListener.add(err);
}
- public static void addWarning(Collection errorListener, String code, Object[] args, XmlObject location)
- {
+ public static void addWarning(Collection errorListener, String code, Object[] args, XmlObject location) {
XmlError err =
XmlError.forObject(
code,
@@ -416,62 +377,65 @@
errorListener.add(err);
}
- public static void addInfo(Collection errorListener, String message)
- {
+ public static void addInfo(Collection errorListener, String message) {
XmlError err = XmlError.forMessage(message, XmlError.SEVERITY_INFO);
errorListener.add(err);
}
- public static void addInfo(Collection errorListener, String code, Object[] args)
- {
+ public static void addInfo(Collection errorListener, String code, Object[] args) {
XmlError err = XmlError.forMessage(code, args, XmlError.SEVERITY_INFO);
errorListener.add(err);
}
- public void setGivenTypeSystemName(String name)
- { _givenStsName = name; }
+ public void setGivenTypeSystemName(String name) {
+ _givenStsName = name;
+ }
/**
* Initializer for references to the SchemaTypeLoader
*/
- public void setTargetSchemaTypeSystem(SchemaTypeSystemImpl target)
- { _target = target; }
+ public void setTargetSchemaTypeSystem(SchemaTypeSystemImpl target) {
+ _target = target;
+ }
/**
* Accumulates a schema digest...
*/
- public void addSchemaDigest(byte[] digest)
- {
- if (_noDigest)
+ public void addSchemaDigest(byte[] digest) {
+ if (_noDigest) {
return;
+ }
- if (digest == null)
- {
+ if (digest == null) {
_noDigest = true;
_digest = null;
return;
}
- if (_digest == null)
- _digest = new byte[128/8]; // 128 bits.
+ if (_digest == null) {
+ _digest = new byte[128 / 8]; // 128 bits.
+ }
int len = _digest.length;
- if (digest.length < len)
+ if (digest.length < len) {
len = digest.length;
- for (int i = 0; i < len; i++)
+ }
+ for (int i = 0; i < len; i++) {
_digest[i] ^= digest[i];
+ }
}
/**
* The SchemaTypeSystem which we're building types on behalf of.
*/
- public SchemaTypeSystemImpl sts()
- {
- if (_target != null)
+ public SchemaTypeSystemImpl sts() {
+ if (_target != null) {
return _target;
+ }
String name = _givenStsName;
- if (name == null && _digest != null)
- name = "s" + new String(HexBin.encode(_digest));
+ if (name == null && _digest != null) {
+ name = "s" + new String(HexBin.encode(_digest), StandardCharsets.ISO_8859_1);
+ }
_target = new SchemaTypeSystemImpl(name);
return _target;
@@ -480,29 +444,26 @@
/**
* True if the given URI is a local file
*/
- public boolean shouldDownloadURI(String uriString)
- {
- if (_doingDownloads)
+ public boolean shouldDownloadURI(String uriString) {
+ if (_doingDownloads) {
return true;
+ }
- if (uriString == null)
+ if (uriString == null) {
return false;
+ }
- try
- {
+ try {
URI uri = new URI(uriString);
if (uri.getScheme().equalsIgnoreCase("jar") ||
- uri.getScheme().equalsIgnoreCase("zip"))
- {
+ uri.getScheme().equalsIgnoreCase("zip")) {
// It may be local or not, depending on the embedded URI
String s = uri.getSchemeSpecificPart();
int i = s.lastIndexOf('!');
return shouldDownloadURI(i > 0 ? s.substring(0, i) : s);
}
return uri.getScheme().equalsIgnoreCase("file");
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
return false;
}
}
@@ -510,46 +471,43 @@
/**
* Initializer for compatMap.
*/
- public void setOptions(XmlOptions options)
- {
- if (options == null)
- {
+ public void setOptions(XmlOptions options) {
+ if (options == null) {
return; // defaults are all false.
}
_allowPartial = options.hasOption("COMPILE_PARTIAL_TYPESYSTEM");
-
- _compatMap = (Map)options.get(XmlOptions.COMPILE_SUBSTITUTE_NAMES);
+
+ _compatMap = (Map) options.get(XmlOptions.COMPILE_SUBSTITUTE_NAMES);
_noUpa = options.hasOption(XmlOptions.COMPILE_NO_UPA_RULE) ? true :
- !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true"));
+ !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true"));
_noPvr = options.hasOption(XmlOptions.COMPILE_NO_PVR_RULE) ? true :
- !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true"));
+ !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true"));
_noAnn = options.hasOption(XmlOptions.COMPILE_NO_ANNOTATIONS) ? true :
!"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true"));
_doingDownloads = options.hasOption(XmlOptions.COMPILE_DOWNLOAD_URLS) ? true :
- "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false"));
- _entityResolver = (EntityResolver)options.get(XmlOptions.ENTITY_RESOLVER);
+ "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false"));
+ _entityResolver = (EntityResolver) options.get(XmlOptions.ENTITY_RESOLVER);
- if (_entityResolver == null)
+ if (_entityResolver == null) {
_entityResolver = ResolverUtil.getGlobalEntityResolver();
+ }
- if (_entityResolver != null)
+ if (_entityResolver != null) {
_doingDownloads = true;
-
- if (options.hasOption(XmlOptions.COMPILE_MDEF_NAMESPACES))
- {
- _mdefNamespaces.addAll((Collection)options.get(XmlOptions.COMPILE_MDEF_NAMESPACES));
-
+ }
+
+ if (options.hasOption(XmlOptions.COMPILE_MDEF_NAMESPACES)) {
+ _mdefNamespaces.addAll((Collection) options.get(XmlOptions.COMPILE_MDEF_NAMESPACES));
+
String local = "##local";
String any = "##any";
-
- if (_mdefNamespaces.contains(local))
- {
+
+ if (_mdefNamespaces.contains(local)) {
_mdefNamespaces.remove(local);
_mdefNamespaces.add("");
}
- if (_mdefNamespaces.contains(any))
- {
+ if (_mdefNamespaces.contains(any)) {
_mdefNamespaces.remove(any);
_mdefAll = true;
}
@@ -559,71 +517,67 @@
/**
* May return null if there is no custom entity resolver.
*/
- public EntityResolver getEntityResolver()
- {
+ public EntityResolver getEntityResolver() {
return _entityResolver;
}
/**
* True if no unique particle attribution option is set
*/
- public boolean noUpa()
- {
+ public boolean noUpa() {
return _noUpa;
}
/**
* True if no particle valid (restriciton) option is set
*/
- public boolean noPvr()
- {
+ public boolean noPvr() {
return _noPvr;
}
/**
* True if annotations should be skipped
*/
- public boolean noAnn()
- {
+ public boolean noAnn() {
return _noAnn;
}
-
+
/**
* True if a partial SchemaTypeSystem should be produced
*/
// EXPERIMENTAL
- public boolean allowPartial()
- {
+ public boolean allowPartial() {
return _allowPartial;
}
-
+
/**
* Get count of recovered errors. Not for public.
- */
+ */
// EXPERIMENTAL
- public int getRecovered()
- {
+ public int getRecovered() {
return _recoveredErrors;
}
-
+
/**
* Intercepts XML names and translates them
* through the compat map, if any.
- *
+ * <p>
* Also looks for a default namespace for global definitions.
*/
- private QName compatName(QName name, String chameleonNamespace)
- {
+ private QName compatName(QName name, String chameleonNamespace) {
// first check for a chameleonNamespace namespace
- if (name.getNamespaceURI().length() == 0 && chameleonNamespace != null && chameleonNamespace.length() > 0)
+ if (name.getNamespaceURI().length() == 0 && chameleonNamespace != null && chameleonNamespace.length() > 0) {
name = new QName(chameleonNamespace, name.getLocalPart());
+ }
- if (_compatMap == null)
+ if (_compatMap == null) {
return name;
+ }
- QName subst = (QName)_compatMap.get(name);
- if (subst == null)
+ QName subst = (QName) _compatMap.get(name);
+ if (subst == null) {
return name;
+ }
return subst;
}
@@ -631,173 +585,152 @@
* Initializer for the schema config object.
*/
public void setBindingConfig(BindingConfig config)
- throws IllegalArgumentException
- {
+ throws IllegalArgumentException {
_config = config;
}
public BindingConfig getBindingConfig()
- throws IllegalArgumentException
- {
+ throws IllegalArgumentException {
return _config;
}
/**
* Looks up package override for a namespace URI
*/
- public String getPackageOverride(String namespace)
- {
- if (_config == null)
+ public String getPackageOverride(String namespace) {
+ if (_config == null) {
return null;
+ }
return _config.lookupPackageForNamespace(namespace);
}
/**
* Looks up package override for a namespace URI
*/
- public String getJavaPrefix(String namespace)
- {
- if (_config == null)
+ public String getJavaPrefix(String namespace) {
+ if (_config == null) {
return null;
+ }
return _config.lookupPrefixForNamespace(namespace);
}
/**
* Looks up package override for a namespace URI
*/
- public String getJavaSuffix(String namespace)
- {
- if (_config == null)
+ public String getJavaSuffix(String namespace) {
+ if (_config == null) {
return null;
+ }
return _config.lookupSuffixForNamespace(namespace);
}
/**
* Looks up configured java name for the given qname.
*/
- public String getJavaname(QName qname, int kind)
- {
- if (_config == null)
+ public String getJavaname(QName qname, int kind) {
+ if (_config == null) {
return null;
+ }
return _config.lookupJavanameForQName(qname, kind);
}
/* SPELLINGS ======================================================*/
- private static String crunchName(QName name)
- {
+ private static String crunchName(QName name) {
// lowercase, and drop namespace.
return name.getLocalPart().toLowerCase();
}
- void addSpelling(QName name, SchemaComponent comp)
- {
+ void addSpelling(QName name, SchemaComponent comp) {
_misspelledNames.put(crunchName(name), comp);
}
- SchemaComponent findSpelling(QName name)
- {
- return (SchemaComponent)_misspelledNames.get(crunchName(name));
+ SchemaComponent findSpelling(QName name) {
+ return (SchemaComponent) _misspelledNames.get(crunchName(name));
}
/* NAMESPACES ======================================================*/
- void addNamespace(String targetNamespace)
- {
+ void addNamespace(String targetNamespace) {
_namespaces.add(targetNamespace);
}
- String[] getNamespaces()
- {
- return (String[])_namespaces.toArray(new String[_namespaces.size()]);
+ String[] getNamespaces() {
+ return (String[]) _namespaces.toArray(new String[_namespaces.size()]);
}
- boolean linkerDefinesNamespace(String namespace)
- {
+ boolean linkerDefinesNamespace(String namespace) {
return _importingLoader.isNamespaceDefined(namespace);
}
/* TYPES ==========================================================*/
- SchemaTypeImpl findGlobalType(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaTypeImpl findGlobalType(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaTypeImpl result = (SchemaTypeImpl)_globalTypes.get(name);
+ SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaTypeImpl)_importingLoader.findType(name);
+ if (result == null) {
+ result = (SchemaTypeImpl) _importingLoader.findType(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- SchemaTypeImpl findRedefinedGlobalType(QName name, String chameleonNamespace, SchemaTypeImpl redefinedBy)
- {
+ SchemaTypeImpl findRedefinedGlobalType(QName name, String chameleonNamespace, SchemaTypeImpl redefinedBy) {
QName redefinedName = redefinedBy.getName();
name = compatName(name, chameleonNamespace);
- if (name.equals(redefinedName))
- {
- return (SchemaTypeImpl)_redefinedGlobalTypes.get(redefinedBy);
+ if (name.equals(redefinedName)) {
+ return (SchemaTypeImpl) _redefinedGlobalTypes.get(redefinedBy);
// BUGBUG: should also link against _importingLoader.findRedefinedType
}
- SchemaTypeImpl result = (SchemaTypeImpl)_globalTypes.get(name);
- if (result == null)
- result = (SchemaTypeImpl)_importingLoader.findType(name);
+ SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name);
+ if (result == null) {
+ result = (SchemaTypeImpl) _importingLoader.findType(name);
+ }
// no dependency is needed here, necause it's intra-namespace
return result;
}
- void addGlobalType(SchemaTypeImpl type, SchemaTypeImpl redefined)
- {
- if (type != null)
- {
+ void addGlobalType(SchemaTypeImpl type, SchemaTypeImpl redefined) {
+ if (type != null) {
QName name = type.getName();
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == type.getContainer();
- if (redefined != null)
- {
- if (_redefinedGlobalTypes.containsKey(redefined))
- {
+ if (redefined != null) {
+ if (_redefinedGlobalTypes.containsKey(redefined)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName() } ,
- type.getParseObject());
+ new Object[]{"global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName()},
+ type.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName() } ,
+ new Object[]{"global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName()},
type.getParseObject());
}
}
- }
- else
- {
+ } else {
_redefinedGlobalTypes.put(redefined, type);
container.addRedefinedType(type.getRef());
}
- }
- else
- {
- if (_globalTypes.containsKey(name))
- {
+ } else {
+ if (_globalTypes.containsKey(name)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName() },
- type.getParseObject());
+ new Object[]{"global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName()},
+ type.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName() },
+ new Object[]{"global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName()},
type.getParseObject());
}
}
- }
- else
- {
+ } else {
_globalTypes.put(name, type);
container.addGlobalType(type.getRef());
addSpelling(name, type);
@@ -806,52 +739,48 @@
}
}
- private boolean ignoreMdef(QName name)
- {
+ private boolean ignoreMdef(QName name) {
return _mdefNamespaces.contains(name.getNamespaceURI());
}
- SchemaType[] globalTypes()
- { return (SchemaType[])_globalTypes.values().toArray(new SchemaType[_globalTypes.size()]); }
+ SchemaType[] globalTypes() {
+ return (SchemaType[]) _globalTypes.values().toArray(new SchemaType[_globalTypes.size()]);
+ }
- SchemaType[] redefinedGlobalTypes()
- { return (SchemaType[])_redefinedGlobalTypes.values().toArray(new SchemaType[_redefinedGlobalTypes.size()]); }
+ SchemaType[] redefinedGlobalTypes() {
+ return (SchemaType[]) _redefinedGlobalTypes.values().toArray(new SchemaType[_redefinedGlobalTypes.size()]);
+ }
/* DOCUMENT TYPES =================================================*/
- SchemaTypeImpl findDocumentType(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaTypeImpl findDocumentType(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaTypeImpl result = (SchemaTypeImpl)_documentTypes.get(name);
+ SchemaTypeImpl result = (SchemaTypeImpl) _documentTypes.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaTypeImpl)_importingLoader.findDocumentType(name);
+ if (result == null) {
+ result = (SchemaTypeImpl) _importingLoader.findDocumentType(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- void addDocumentType(SchemaTypeImpl type, QName name)
- {
- if (_documentTypes.containsKey(name))
- {
+ void addDocumentType(SchemaTypeImpl type, QName name) {
+ if (_documentTypes.containsKey(name)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName() },
- type.getParseObject());
- } else {
+ new Object[]{"global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName()},
+ type.getParseObject());
+ } else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName() },
+ new Object[]{"global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName()},
type.getParseObject());
}
}
- }
- else
- {
+ } else {
_documentTypes.put(name, type);
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == type.getContainer();
@@ -859,44 +788,40 @@
}
}
- SchemaType[] documentTypes()
- { return (SchemaType[])_documentTypes.values().toArray(new SchemaType[_documentTypes.size()]); }
+ SchemaType[] documentTypes() {
+ return (SchemaType[]) _documentTypes.values().toArray(new SchemaType[_documentTypes.size()]);
+ }
/* ATTRIBUTE TYPES =================================================*/
- SchemaTypeImpl findAttributeType(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaTypeImpl findAttributeType(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaTypeImpl result = (SchemaTypeImpl)_attributeTypes.get(name);
+ SchemaTypeImpl result = (SchemaTypeImpl) _attributeTypes.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaTypeImpl)_importingLoader.findAttributeType(name);
+ if (result == null) {
+ result = (SchemaTypeImpl) _importingLoader.findAttributeType(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- void addAttributeType(SchemaTypeImpl type, QName name)
- {
- if (_attributeTypes.containsKey(name))
- {
+ void addAttributeType(SchemaTypeImpl type, QName name) {
+ if (_attributeTypes.containsKey(name)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName() },
+ new Object[]{"global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName()},
type.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName() },
+ new Object[]{"global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName()},
type.getParseObject());
}
}
- }
- else
- {
+ } else {
_attributeTypes.put(name, type);
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == type.getContainer();
@@ -904,30 +829,28 @@
}
}
- SchemaType[] attributeTypes()
- { return (SchemaType[])_attributeTypes.values().toArray(new SchemaType[_attributeTypes.size()]); }
+ SchemaType[] attributeTypes() {
+ return (SchemaType[]) _attributeTypes.values().toArray(new SchemaType[_attributeTypes.size()]);
+ }
/* ATTRIBUTES =====================================================*/
- SchemaGlobalAttributeImpl findGlobalAttribute(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaGlobalAttributeImpl findGlobalAttribute(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaGlobalAttributeImpl result = (SchemaGlobalAttributeImpl)_globalAttributes.get(name);
+ SchemaGlobalAttributeImpl result = (SchemaGlobalAttributeImpl) _globalAttributes.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaGlobalAttributeImpl)_importingLoader.findAttribute(name);
+ if (result == null) {
+ result = (SchemaGlobalAttributeImpl) _importingLoader.findAttribute(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- void addGlobalAttribute(SchemaGlobalAttributeImpl attribute)
- {
- if (attribute != null)
- {
+ void addGlobalAttribute(SchemaGlobalAttributeImpl attribute) {
+ if (attribute != null) {
QName name = attribute.getName();
_globalAttributes.put(name, attribute);
addSpelling(name, attribute);
@@ -937,30 +860,28 @@
}
}
- SchemaGlobalAttribute[] globalAttributes()
- { return (SchemaGlobalAttribute[])_globalAttributes.values().toArray(new SchemaGlobalAttribute[_globalAttributes.size()]); }
+ SchemaGlobalAttribute[] globalAttributes() {
+ return (SchemaGlobalAttribute[]) _globalAttributes.values().toArray(new SchemaGlobalAttribute[_globalAttributes.size()]);
+ }
/* ELEMENTS =======================================================*/
- SchemaGlobalElementImpl findGlobalElement(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaGlobalElementImpl findGlobalElement(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaGlobalElementImpl result = (SchemaGlobalElementImpl)_globalElements.get(name);
+ SchemaGlobalElementImpl result = (SchemaGlobalElementImpl) _globalElements.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaGlobalElementImpl)_importingLoader.findElement(name);
+ if (result == null) {
+ result = (SchemaGlobalElementImpl) _importingLoader.findElement(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- void addGlobalElement(SchemaGlobalElementImpl element)
- {
- if (element != null)
- {
+ void addGlobalElement(SchemaGlobalElementImpl element) {
+ if (element != null) {
QName name = element.getName();
_globalElements.put(name, element);
SchemaContainer container = getContainer(name.getNamespaceURI());
@@ -970,88 +891,76 @@
}
}
- SchemaGlobalElement[] globalElements()
- { return (SchemaGlobalElement[])_globalElements.values().toArray(new SchemaGlobalElement[_globalElements.size()]); }
+ SchemaGlobalElement[] globalElements() {
+ return (SchemaGlobalElement[]) _globalElements.values().toArray(new SchemaGlobalElement[_globalElements.size()]);
+ }
/* ATTRIBUTE GROUPS ===============================================*/
- SchemaAttributeGroupImpl findAttributeGroup(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaAttributeGroupImpl findAttributeGroup(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl)_attributeGroups.get(name);
+ SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaAttributeGroupImpl)_importingLoader.findAttributeGroup(name);
+ if (result == null) {
+ result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- SchemaAttributeGroupImpl findRedefinedAttributeGroup(QName name, String chameleonNamespace, SchemaAttributeGroupImpl redefinedBy)
- {
+ SchemaAttributeGroupImpl findRedefinedAttributeGroup(QName name, String chameleonNamespace, SchemaAttributeGroupImpl redefinedBy) {
QName redefinitionFor = redefinedBy.getName();
name = compatName(name, chameleonNamespace);
- if (name.equals(redefinitionFor))
- {
- return (SchemaAttributeGroupImpl)_redefinedAttributeGroups.get(redefinedBy);
+ if (name.equals(redefinitionFor)) {
+ return (SchemaAttributeGroupImpl) _redefinedAttributeGroups.get(redefinedBy);
// BUGBUG: should also link against _importingLoader.findRedefinedAttributeGroup
}
- SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl)_attributeGroups.get(name);
- if (result == null)
- result = (SchemaAttributeGroupImpl)_importingLoader.findAttributeGroup(name);
+ SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name);
+ if (result == null) {
+ result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name);
+ }
return result;
}
- void addAttributeGroup(SchemaAttributeGroupImpl attributeGroup, SchemaAttributeGroupImpl redefined)
- {
- if (attributeGroup != null)
- {
+ void addAttributeGroup(SchemaAttributeGroupImpl attributeGroup, SchemaAttributeGroupImpl redefined) {
+ if (attributeGroup != null) {
QName name = attributeGroup.getName();
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == attributeGroup.getContainer();
- if (redefined != null)
- {
- if (_redefinedAttributeGroups.containsKey(redefined))
- {
+ if (redefined != null) {
+ if (_redefinedAttributeGroups.containsKey(redefined)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName() },
+ new Object[]{"attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName()},
attributeGroup.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName() },
+ new Object[]{"attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName()},
attributeGroup.getParseObject());
}
}
- }
- else
- {
+ } else {
_redefinedAttributeGroups.put(redefined, attributeGroup);
container.addRedefinedAttributeGroup(attributeGroup.getRef());
}
- }
- else
- {
- if (_attributeGroups.containsKey( name ))
- {
+ } else {
+ if (_attributeGroups.containsKey(name)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName() },
+ new Object[]{"attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName()},
attributeGroup.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName() },
+ new Object[]{"attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName()},
attributeGroup.getParseObject());
}
}
- }
- else
- {
+ } else {
_attributeGroups.put(attributeGroup.getName(), attributeGroup);
addSpelling(attributeGroup.getName(), attributeGroup);
container.addAttributeGroup(attributeGroup.getRef());
@@ -1060,91 +969,80 @@
}
}
- SchemaAttributeGroup[] attributeGroups()
- { return (SchemaAttributeGroup[])_attributeGroups.values().toArray(new SchemaAttributeGroup[_attributeGroups.size()]); }
+ SchemaAttributeGroup[] attributeGroups() {
+ return (SchemaAttributeGroup[]) _attributeGroups.values().toArray(new SchemaAttributeGroup[_attributeGroups.size()]);
+ }
- SchemaAttributeGroup[] redefinedAttributeGroups()
- { return (SchemaAttributeGroup[])_redefinedAttributeGroups.values().toArray(new SchemaAttributeGroup[_redefinedAttributeGroups.size()]); }
+ SchemaAttributeGroup[] redefinedAttributeGroups() {
+ return (SchemaAttributeGroup[]) _redefinedAttributeGroups.values().toArray(new SchemaAttributeGroup[_redefinedAttributeGroups.size()]);
+ }
/* MODEL GROUPS ===================================================*/
- SchemaModelGroupImpl findModelGroup(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaModelGroupImpl findModelGroup(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- SchemaModelGroupImpl result = (SchemaModelGroupImpl)_modelGroups.get(name);
+ SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name);
boolean foundOnLoader = false;
- if (result == null)
- {
- result = (SchemaModelGroupImpl)_importingLoader.findModelGroup(name);
+ if (result == null) {
+ result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name);
foundOnLoader = result != null;
}
- if (!foundOnLoader && sourceNamespace != null)
+ if (!foundOnLoader && sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
+ }
return result;
}
- SchemaModelGroupImpl findRedefinedModelGroup(QName name, String chameleonNamespace, SchemaModelGroupImpl redefinedBy)
- {
+ SchemaModelGroupImpl findRedefinedModelGroup(QName name, String chameleonNamespace, SchemaModelGroupImpl redefinedBy) {
QName redefinitionFor = redefinedBy.getName();
name = compatName(name, chameleonNamespace);
- if (name.equals(redefinitionFor))
- {
- return (SchemaModelGroupImpl)_redefinedModelGroups.get(redefinedBy);
+ if (name.equals(redefinitionFor)) {
+ return (SchemaModelGroupImpl) _redefinedModelGroups.get(redefinedBy);
// BUGBUG: should also link against _importingLoader.findRedefinedModelGroup
}
- SchemaModelGroupImpl result = (SchemaModelGroupImpl)_modelGroups.get(name);
- if (result == null)
- result = (SchemaModelGroupImpl)_importingLoader.findModelGroup(name);
+ SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name);
+ if (result == null) {
+ result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name);
+ }
return result;
}
- void addModelGroup(SchemaModelGroupImpl modelGroup, SchemaModelGroupImpl redefined)
- {
- if (modelGroup != null)
- {
+ void addModelGroup(SchemaModelGroupImpl modelGroup, SchemaModelGroupImpl redefined) {
+ if (modelGroup != null) {
QName name = modelGroup.getName();
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == modelGroup.getContainer();
- if (redefined != null)
- {
- if (_redefinedModelGroups.containsKey(redefined))
- {
+ if (redefined != null) {
+ if (_redefinedModelGroups.containsKey(redefined)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName() },
- modelGroup.getParseObject());
+ new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()},
+ modelGroup.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName() },
+ new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()},
modelGroup.getParseObject());
}
}
- }
- else
- {
+ } else {
_redefinedModelGroups.put(redefined, modelGroup);
container.addRedefinedModelGroup(modelGroup.getRef());
}
- }
- else
- {
- if (_modelGroups.containsKey(name))
- {
+ } else {
+ if (_modelGroups.containsKey(name)) {
if (!ignoreMdef(name)) {
if (_mdefAll) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName() },
- modelGroup.getParseObject());
+ new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName()},
+ modelGroup.getParseObject());
} else {
error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName() },
+ new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName()},
modelGroup.getParseObject());
}
}
- }
- else
- {
+ } else {
_modelGroups.put(modelGroup.getName(), modelGroup);
addSpelling(modelGroup.getName(), modelGroup);
container.addModelGroup(modelGroup.getRef());
@@ -1153,38 +1051,36 @@
}
}
- SchemaModelGroup[] modelGroups()
- { return (SchemaModelGroup[])_modelGroups.values().toArray(new SchemaModelGroup[_modelGroups.size()]); }
+ SchemaModelGroup[] modelGroups() {
+ return (SchemaModelGroup[]) _modelGroups.values().toArray(new SchemaModelGroup[_modelGroups.size()]);
+ }
- SchemaModelGroup[] redefinedModelGroups()
- { return (SchemaModelGroup[])_redefinedModelGroups.values().toArray(new SchemaModelGroup[_redefinedModelGroups.size()]); }
+ SchemaModelGroup[] redefinedModelGroups() {
+ return (SchemaModelGroup[]) _redefinedModelGroups.values().toArray(new SchemaModelGroup[_redefinedModelGroups.size()]);
+ }
/* IDENTITY CONSTRAINTS ===========================================*/
- SchemaIdentityConstraintImpl findIdConstraint(QName name, String chameleonNamespace, String sourceNamespace)
- {
+ SchemaIdentityConstraintImpl findIdConstraint(QName name, String chameleonNamespace, String sourceNamespace) {
name = compatName(name, chameleonNamespace);
- if (sourceNamespace != null)
+ if (sourceNamespace != null) {
registerDependency(sourceNamespace, name.getNamespaceURI());
- return (SchemaIdentityConstraintImpl)_idConstraints.get(name);
+ }
+ return (SchemaIdentityConstraintImpl) _idConstraints.get(name);
}
- void addIdConstraint(SchemaIdentityConstraintImpl idc)
- {
- if (idc != null)
- {
+ void addIdConstraint(SchemaIdentityConstraintImpl idc) {
+ if (idc != null) {
QName name = idc.getName();
SchemaContainer container = getContainer(name.getNamespaceURI());
assert container != null && container == idc.getContainer();
- if (_idConstraints.containsKey(name))
- {
- if (!ignoreMdef(name))
+ if (_idConstraints.containsKey(name)) {
+ if (!ignoreMdef(name)) {
warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE,
- new Object[] { "identity constraint", QNameHelper.pretty(name), ((SchemaComponent) _idConstraints.get(name)).getSourceName() },
+ new Object[]{"identity constraint", QNameHelper.pretty(name), ((SchemaComponent) _idConstraints.get(name)).getSourceName()},
idc.getParseObject());
- }
- else
- {
+ }
+ } else {
_idConstraints.put(name, idc);
addSpelling(idc.getName(), idc);
container.addIdentityConstraint(idc.getRef());
@@ -1192,15 +1088,14 @@
}
}
- SchemaIdentityConstraintImpl[] idConstraints()
- { return (SchemaIdentityConstraintImpl[])_idConstraints.values().toArray(new SchemaIdentityConstraintImpl[_idConstraints.size()]); }
+ SchemaIdentityConstraintImpl[] idConstraints() {
+ return (SchemaIdentityConstraintImpl[]) _idConstraints.values().toArray(new SchemaIdentityConstraintImpl[_idConstraints.size()]);
+ }
/* ANNOTATIONS ===========================================*/
- void addAnnotation(SchemaAnnotationImpl ann, String targetNamespace)
- {
- if (ann != null)
- {
+ void addAnnotation(SchemaAnnotationImpl ann, String targetNamespace) {
+ if (ann != null) {
SchemaContainer container = getContainer(targetNamespace);
assert container != null && container == ann.getContainer();
_annotations.add(ann);
@@ -1208,59 +1103,56 @@
}
}
- List annotations()
- { return _annotations; }
+ List annotations() {
+ return _annotations;
+ }
/* RECURSION AVOIDANCE ============================================*/
- boolean isProcessing(Object obj)
- {
+ boolean isProcessing(Object obj) {
return _processingGroups.contains(obj);
}
- void startProcessing(Object obj)
- {
- assert(!_processingGroups.contains(obj));
+ void startProcessing(Object obj) {
+ assert (!_processingGroups.contains(obj));
_processingGroups.add(obj);
}
- void finishProcessing(Object obj)
- {
- assert(_processingGroups.contains(obj));
+ void finishProcessing(Object obj) {
+ assert (_processingGroups.contains(obj));
_processingGroups.remove(obj);
}
- Object[] getCurrentProcessing()
- {
+ Object[] getCurrentProcessing() {
return _processingGroups.toArray();
}
/* JAVAIZATION ====================================================*/
- Map typesByClassname()
- { return Collections.unmodifiableMap(_typesByClassname); }
+ Map typesByClassname() {
+ return Collections.unmodifiableMap(_typesByClassname);
+ }
- void addClassname(String classname, SchemaType type)
- { _typesByClassname.put(classname, type); }
-
+ void addClassname(String classname, SchemaType type) {
+ _typesByClassname.put(classname, type);
+ }
/**
* Stack management if (heaven help us) we ever need to do
* nested compilation of schema type system.
*/
- private static final class StscStack
- {
+ private static final class StscStack {
StscState current;
ArrayList stack = new ArrayList();
- final StscState push()
- {
+
+ final StscState push() {
stack.add(current);
current = new StscState();
return current;
}
- final void pop()
- {
- current = (StscState)stack.get(stack.size() - 1);
+
+ final void pop() {
+ current = (StscState) stack.get(stack.size() - 1);
stack.remove(stack.size() - 1);
}
}
@@ -1271,30 +1163,27 @@
tl_stscStack.remove();
}
- public static StscState start()
- {
+ public static StscState start() {
StscStack stscStack = (StscStack) tl_stscStack.get();
- if (stscStack==null)
- {
+ if (stscStack == null) {
stscStack = new StscStack();
tl_stscStack.set(stscStack);
}
return stscStack.push();
}
- public static StscState get()
- {
+ public static StscState get() {
return ((StscStack) tl_stscStack.get()).current;
}
- public static void end()
- {
+ public static void end() {
StscStack stscStack = (StscStack) tl_stscStack.get();
stscStack.pop();
- if (stscStack.stack.size()==0)
+ if (stscStack.stack.size() == 0) {
tl_stscStack.set(null); // this is required to release all the references in this classloader
- // which will enable class unloading and avoid OOM in PermGen
+ }
+ // which will enable class unloading and avoid OOM in PermGen
}
private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve");
@@ -1305,30 +1194,28 @@
static final SchemaType.Ref[] EMPTY_STREF_ARRAY = new SchemaType.Ref[0];
private final static XmlValueRef[] FACETS_NONE = new XmlValueRef[]
- { null, null, null, null, null, null, null, null, null,
- null, null, null };
+ {null, null, null, null, null, null, null, null, null,
+ null, null, null};
private final static boolean[] FIXED_FACETS_NONE = new boolean[]
- { false, false, false, false, false, false, false, false, false,
- false, false, false };
+ {false, false, false, false, false, false, false, false, false,
+ false, false, false};
private final static XmlValueRef[] FACETS_WS_COLLAPSE = new XmlValueRef[]
- { null, null, null, null, null, null, null, null, null,
- build_wsstring(SchemaType.WS_COLLAPSE), null, null };
+ {null, null, null, null, null, null, null, null, null,
+ build_wsstring(SchemaType.WS_COLLAPSE), null, null};
private final static boolean[] FIXED_FACETS_WS = new boolean[]
- { false, false, false, false, false, false, false, false, false,
- true, false, false };
+ {false, false, false, false, false, false, false, false, false,
+ true, false, false};
final static XmlValueRef[] FACETS_UNION = FACETS_NONE;
final static boolean[] FIXED_FACETS_UNION = FIXED_FACETS_NONE;
final static XmlValueRef[] FACETS_LIST = FACETS_WS_COLLAPSE;
final static boolean[] FIXED_FACETS_LIST = FIXED_FACETS_WS;
- static XmlValueRef build_wsstring(int wsr)
- {
- switch (wsr)
- {
+ static XmlValueRef build_wsstring(int wsr) {
+ switch (wsr) {
case SchemaType.WS_PRESERVE:
return XMLSTR_PRESERVE;
case SchemaType.WS_REPLACE:
@@ -1339,37 +1226,33 @@
return null;
}
- static XmlValueRef buildString(String str)
- {
- if (str == null)
+ static XmlValueRef buildString(String str) {
+ if (str == null) {
return null;
+ }
- try
- {
+ try {
XmlStringImpl i = new XmlStringImpl();
i.set(str);
i.setImmutable();
return new XmlValueRef(i);
- }
- catch (XmlValueOutOfRangeException e)
- {
+ } catch (XmlValueOutOfRangeException e) {
return null;
}
}
- public void notFoundError(QName itemName, int code, XmlObject loc, boolean recovered)
- {
+ public void notFoundError(QName itemName, int code, XmlObject loc, boolean recovered) {
String expected;
String expectedName = QNameHelper.pretty(itemName);
String found = null;
String foundName = null;
String sourceName = null;
-
- if (recovered)
- _recoveredErrors++;
- switch (code)
- {
+ if (recovered) {
+ _recoveredErrors++;
+ }
+
+ switch (code) {
case SchemaType.TYPE:
expected = "type";
break;
@@ -1389,31 +1272,28 @@
expected = "identity constraint";
break;
default:
- assert(false);
+ assert (false);
expected = "definition";
break;
}
SchemaComponent foundComponent = findSpelling(itemName);
QName name;
- if (foundComponent != null)
- {
+ if (foundComponent != null) {
name = foundComponent.getName();
- if (name != null)
- {
- switch (foundComponent.getComponentType())
- {
+ if (name != null) {
+ switch (foundComponent.getComponentType()) {
case SchemaComponent.TYPE:
found = "type";
- sourceName = ((SchemaType)foundComponent).getSourceName();
+ sourceName = ((SchemaType) foundComponent).getSourceName();
break;
case SchemaComponent.ELEMENT:
found = "element";
- sourceName = ((SchemaGlobalElement)foundComponent).getSourceName();
+ sourceName = ((SchemaGlobalElement) foundComponent).getSourceName();
break;
case SchemaComponent.ATTRIBUTE:
found = "attribute";
- sourceName = ((SchemaGlobalAttribute)foundComponent).getSourceName();
+ sourceName = ((SchemaGlobalAttribute) foundComponent).getSourceName();
break;
case SchemaComponent.ATTRIBUTE_GROUP:
found = "attribute group";
@@ -1423,28 +1303,24 @@
break;
}
- if (sourceName != null)
- {
+ if (sourceName != null) {
sourceName = sourceName.substring(sourceName.lastIndexOf('/') + 1);
}
- if (!name.equals(itemName))
- {
+ if (!name.equals(itemName)) {
foundName = QNameHelper.pretty(name);
}
}
}
- if (found == null)
- {
+ if (found == null) {
// error with no help
error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE,
- new Object[] { expected, expectedName }, loc);
- }
- else {
+ new Object[]{expected, expectedName}, loc);
+ } else {
// error with help
error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE$HELP,
- new Object[] {
+ new Object[]{
expected,
expectedName,
found,
@@ -1461,12 +1337,11 @@
/**
* Produces the "sourceName" (to be used within the schema project
* source file copies) from the URI of the original source.
- *
+ * <p>
* Returns null if none.
*/
- public String sourceNameForUri(String uri)
- {
- return (String)_sourceForUri.get(uri);
+ public String sourceNameForUri(String uri) {
+ return (String) _sourceForUri.get(uri);
}
/**
@@ -1474,95 +1349,90 @@
* been read to "sourceName" local names that have been used
* to tag the types.
*/
- public Map sourceCopyMap()
- {
+ public Map sourceCopyMap() {
return Collections.unmodifiableMap(_sourceForUri);
}
/**
* The base URI to use for nice filenames when saving sources.
*/
- public void setBaseUri(URI uri)
- {
+ public void setBaseUri(URI uri) {
_baseURI = uri;
}
private final static String PROJECT_URL_PREFIX = "project://local";
- public String relativize(String uri)
- {
+ public String relativize(String uri) {
return relativize(uri, false);
}
- public String computeSavedFilename(String uri)
- {
+ public String computeSavedFilename(String uri) {
return relativize(uri, true);
}
- private String relativize(String uri, boolean forSavedFilename)
- {
- if (uri == null)
+ private String relativize(String uri, boolean forSavedFilename) {
+ if (uri == null) {
return null;
+ }
// deal with things that do not look like absolute uris
- if (uri.startsWith("/"))
- {
+ if (uri.startsWith("/")) {
uri = PROJECT_URL_PREFIX + uri.replace('\\', '/');
- }
- else
- {
+ } else {
// looks like a URL?
int colon = uri.indexOf(':');
- if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$"))
+ if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$")) {
uri = PROJECT_URL_PREFIX + "/" + uri.replace('\\', '/');
+ }
}
// now relativize against that...
- if (_baseURI != null)
- {
- try
- {
+ if (_baseURI != null) {
+ try {
URI relative = _baseURI.relativize(new URI(uri));
- if (!relative.isAbsolute())
+ if (!relative.isAbsolute()) {
return relative.toString();
- else
+ } else {
uri = relative.toString();
- }
- catch (URISyntaxException e)
- {
+ }
+ } catch (URISyntaxException e) {
}
}
- if (!forSavedFilename)
+ if (!forSavedFilename) {
return uri;
+ }
int lastslash = uri.lastIndexOf('/');
String dir = QNameHelper.hexsafe(lastslash == -1 ? "" : uri.substring(0, lastslash));
int question = uri.indexOf('?', lastslash + 1);
- if (question == -1)
+ if (question == -1) {
return dir + "/" + uri.substring(lastslash + 1);
+ }
String query = QNameHelper.hexsafe(question == -1 ? "" : uri.substring(question));
// if encoded query part is longer than 64 characters, just drop it
- if (query.startsWith(QNameHelper.URI_SHA1_PREFIX))
+ if (query.startsWith(QNameHelper.URI_SHA1_PREFIX)) {
return dir + "/" + uri.substring(lastslash + 1, question);
- else
+ } else {
return dir + "/" + uri.substring(lastslash + 1, question) + query;
+ }
}
/**
* Notes another URI that has been consumed during compilation
* (this is the URI that is in the document .NAME property)
*/
- public void addSourceUri(String uri, String nameToUse)
- {
- if (uri == null)
+ public void addSourceUri(String uri, String nameToUse) {
+ if (uri == null) {
return;
+ }
- if (nameToUse == null)
+ if (nameToUse == null) {
nameToUse = computeSavedFilename(uri);
+ }
_sourceForUri.put(uri, nameToUse);
}
@@ -1570,16 +1440,14 @@
/**
* Returns the error listener being filled in during this compilation
*/
- public Collection getErrorListener()
- {
+ public Collection getErrorListener() {
return _errorListener;
}
/**
* Returns the schema type loader to use for processing s4s
*/
- public SchemaTypeLoader getS4SLoader()
- {
+ public SchemaTypeLoader getS4SLoader() {
return _s4sloader;
}
@@ -1587,13 +1455,11 @@
URI _baseURI = URI.create(PROJECT_URL_PREFIX + "/");
SchemaTypeLoader _s4sloader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader());
- public File getSchemasDir()
- {
+ public File getSchemasDir() {
return _schemasDir;
}
- public void setSchemasDir(File _schemasDir)
- {
+ public void setSchemasDir(File _schemasDir) {
this._schemasDir = _schemasDir;
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
index f7757ba..3aa4205 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
@@ -15,30 +15,21 @@
package org.apache.xmlbeans.impl.tool;
-import java.util.*;
-import java.util.zip.ZipFile;
-import java.util.zip.ZipEntry;
-import java.io.*;
-import java.math.BigInteger;
-
-
+import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.QNameHelper;
import org.apache.xmlbeans.impl.util.HexBin;
-import org.apache.xmlbeans.QNameSet;
-import org.apache.xmlbeans.SchemaLocalAttribute;
-import org.apache.xmlbeans.SchemaParticle;
-import org.apache.xmlbeans.SchemaProperty;
-import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.soap.SOAPArrayType;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import javax.xml.namespace.QName;
-public class XsbDumper
-{
- public static void printUsage()
- {
+import javax.xml.namespace.QName;
+import java.io.*;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+public class XsbDumper {
+ public static void printUsage() {
System.out.println("Prints the contents of an XSB file in human-readable form.");
System.out.println("An XSB file contains schema meta information needed to ");
System.out.println("perform tasks such as binding and validation.");
@@ -47,110 +38,118 @@
System.out.println();
}
- public static void main(String[] args)
- {
+ public static void main(String[] args) {
if (args.length == 0) {
printUsage();
System.exit(0);
return;
}
- for (int i = 0; i < args.length; i++)
- {
+ for (int i = 0; i < args.length; i++) {
dump(new File(args[i]), true);
}
}
- private static void dump(File file, boolean force)
- {
- if (file.isDirectory())
- {
+ private static void dump(File file, boolean force) {
+ if (file.isDirectory()) {
File[] files = file.listFiles(
- new FileFilter()
- {
- public boolean accept(File file)
- { return file.isDirectory() || file.isFile() && file.getName().endsWith(".xsb"); }
+ new FileFilter() {
+ public boolean accept(File file) {
+ return file.isDirectory() || file.isFile() && file.getName().endsWith(".xsb");
+ }
}
);
- for (int i = 0; i < files.length; i++)
- {
+ for (int i = 0; i < files.length; i++) {
dump(files[i], false);
}
- }
- else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip"))
- {
+ } else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) {
dumpZip(file);
- }
- else if (force || file.getName().endsWith(".xsb"))
- {
- try
- {
+ } else if (force || file.getName().endsWith(".xsb")) {
+ try {
System.out.println(file.toString());
dump(new FileInputStream(file), " ");
System.out.println();
- }
- catch (FileNotFoundException e)
- {
+ } catch (FileNotFoundException e) {
System.out.println(e.toString());
}
}
}
- public static void dumpZip(File file)
- {
- try
- {
+ public static void dumpZip(File file) {
+ try {
ZipFile zipFile = new ZipFile(file);
Enumeration e = zipFile.entries();
- while (e.hasMoreElements())
- {
- ZipEntry entry = (ZipEntry)e.nextElement();
- if (entry.getName().endsWith(".xsb"))
- {
+ while (e.hasMoreElements()) {
+ ZipEntry entry = (ZipEntry) e.nextElement();
+ if (entry.getName().endsWith(".xsb")) {
System.out.println(entry.getName());
dump(zipFile.getInputStream(entry), " ");
System.out.println();
}
}
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
System.out.println(e.toString());
}
}
- public static void dump(InputStream input)
- {
+ public static void dump(InputStream input) {
dump(input, "", System.out);
}
- public static void dump(InputStream input, String indent)
- {
+ public static void dump(InputStream input, String indent) {
dump(input, indent, System.out);
}
- public static void dump(InputStream input, String indent, PrintStream output)
- {
+ public static void dump(InputStream input, String indent, PrintStream output) {
XsbDumper dumper = new XsbDumper(input, indent, output);
dumper.dumpAll();
}
- private XsbDumper(InputStream stream, String indent, PrintStream ostream)
- {
+ private XsbDumper(InputStream stream, String indent, PrintStream ostream) {
_input = new DataInputStream(stream);
_indent = indent;
_out = ostream;
}
- void flush() { _out.flush(); }
- void emit(String str) { _out.println(_indent + str); flush(); }
- void emit() { _out.println(); flush(); }
- void error(Exception e) { _out.println(e.toString()); flush(); IllegalStateException e2 = new IllegalStateException( e.getMessage() ); e2.initCause( e ); throw e2; }
- void error(String str) { _out.println(str); flush(); IllegalStateException e2 = new IllegalStateException( str ); throw e2; }
+ void flush() {
+ _out.flush();
+ }
+
+ void emit(String str) {
+ _out.println(_indent + str);
+ flush();
+ }
+
+ void emit() {
+ _out.println();
+ flush();
+ }
+
+ void error(Exception e) {
+ _out.println(e.toString());
+ flush();
+ IllegalStateException e2 = new IllegalStateException(e.getMessage());
+ e2.initCause(e);
+ throw e2;
+ }
+
+ void error(String str) {
+ _out.println(str);
+ flush();
+ IllegalStateException e2 = new IllegalStateException(str);
+ throw e2;
+ }
+
private String _indent;
private PrintStream _out;
- void indent() { _indent += " "; }
- void outdent() { _indent = _indent.substring(0, _indent.length() - 2); }
+
+ void indent() {
+ _indent += " ";
+ }
+
+ void outdent() {
+ _indent = _indent.substring(0, _indent.length() - 2);
+ }
public static final int DATA_BABE = 0xDA7ABABE;
public static final int MAJOR_VERSION = 2;
@@ -164,17 +163,22 @@
public static final int FILETYPE_SCHEMAMODELGROUP = 6;
public static final int FILETYPE_SCHEMAATTRIBUTEGROUP = 7;
- static String filetypeString(int code)
- {
- switch (code)
- {
- case FILETYPE_SCHEMAINDEX: return "FILETYPE_SCHEMAINDEX";
- case FILETYPE_SCHEMATYPE: return "FILETYPE_SCHEMATYPE";
- case FILETYPE_SCHEMAELEMENT: return "FILETYPE_SCHEMAELEMENT";
- case FILETYPE_SCHEMAATTRIBUTE: return "FILETYPE_SCHEMAATTRIBUTE";
- case FILETYPE_SCHEMAPOINTER: return "FILETYPE_SCHEMAPOINTER";
- case FILETYPE_SCHEMAMODELGROUP: return "FILETYPE_SCHEMAMODELGROUP";
- case FILETYPE_SCHEMAATTRIBUTEGROUP: return "FILETYPE_SCHEMAATTRIBUTEGROUP";
+ static String filetypeString(int code) {
+ switch (code) {
+ case FILETYPE_SCHEMAINDEX:
+ return "FILETYPE_SCHEMAINDEX";
+ case FILETYPE_SCHEMATYPE:
+ return "FILETYPE_SCHEMATYPE";
+ case FILETYPE_SCHEMAELEMENT:
+ return "FILETYPE_SCHEMAELEMENT";
+ case FILETYPE_SCHEMAATTRIBUTE:
+ return "FILETYPE_SCHEMAATTRIBUTE";
+ case FILETYPE_SCHEMAPOINTER:
+ return "FILETYPE_SCHEMAPOINTER";
+ case FILETYPE_SCHEMAMODELGROUP:
+ return "FILETYPE_SCHEMAMODELGROUP";
+ case FILETYPE_SCHEMAATTRIBUTEGROUP:
+ return "FILETYPE_SCHEMAATTRIBUTEGROUP";
default:
return "Unknown FILETYPE (" + code + ")";
}
@@ -190,19 +194,38 @@
public static final int FLAG_PART_FINALEXT = 256;
public static final int FLAG_PART_FINALREST = 512;
- static String particleflagsString(int flags)
- {
+ static String particleflagsString(int flags) {
StringBuilder result = new StringBuilder();
- if ((flags & FLAG_PART_SKIPPABLE) != 0) result.append("FLAG_PART_SKIPPABLE | ");
- if ((flags & FLAG_PART_FIXED) != 0) result.append("FLAG_PART_FIXED | ");
- if ((flags & FLAG_PART_NILLABLE) != 0) result.append("FLAG_PART_NILLABLE | ");
- if ((flags & FLAG_PART_BLOCKEXT) != 0) result.append("FLAG_PART_BLOCKEXT | ");
- if ((flags & FLAG_PART_BLOCKREST) != 0) result.append("FLAG_PART_BLOCKREST | ");
- if ((flags & FLAG_PART_BLOCKSUBST) != 0) result.append("FLAG_PART_BLOCKSUBST | ");
- if ((flags & FLAG_PART_ABSTRACT) != 0) result.append("FLAG_PART_ABSTRACT | ");
- if ((flags & FLAG_PART_FINALEXT) != 0) result.append("FLAG_PART_FINALEXT | ");
- if ((flags & FLAG_PART_FINALREST) != 0) result.append("FLAG_PART_FINALREST | ");
- if (result.length() == 0) result.append("0 | ");
+ if ((flags & FLAG_PART_SKIPPABLE) != 0) {
+ result.append("FLAG_PART_SKIPPABLE | ");
+ }
+ if ((flags & FLAG_PART_FIXED) != 0) {
+ result.append("FLAG_PART_FIXED | ");
+ }
+ if ((flags & FLAG_PART_NILLABLE) != 0) {
+ result.append("FLAG_PART_NILLABLE | ");
+ }
+ if ((flags & FLAG_PART_BLOCKEXT) != 0) {
+ result.append("FLAG_PART_BLOCKEXT | ");
+ }
+ if ((flags & FLAG_PART_BLOCKREST) != 0) {
+ result.append("FLAG_PART_BLOCKREST | ");
+ }
+ if ((flags & FLAG_PART_BLOCKSUBST) != 0) {
+ result.append("FLAG_PART_BLOCKSUBST | ");
+ }
+ if ((flags & FLAG_PART_ABSTRACT) != 0) {
+ result.append("FLAG_PART_ABSTRACT | ");
+ }
+ if ((flags & FLAG_PART_FINALEXT) != 0) {
+ result.append("FLAG_PART_FINALEXT | ");
+ }
+ if ((flags & FLAG_PART_FINALREST) != 0) {
+ result.append("FLAG_PART_FINALREST | ");
+ }
+ if (result.length() == 0) {
+ result.append("0 | ");
+ }
return result.substring(0, result.length() - 3);
}
@@ -211,14 +234,23 @@
public static final int FLAG_PROP_JAVAOPTIONAL = 4;
public static final int FLAG_PROP_JAVAARRAY = 8;
- static String propertyflagsString(int flags)
- {
+ static String propertyflagsString(int flags) {
StringBuilder result = new StringBuilder();
- if ((flags & FLAG_PROP_ISATTR) != 0) result.append("FLAG_PROP_ISATTR | ");
- if ((flags & FLAG_PROP_JAVASINGLETON) != 0) result.append("FLAG_PROP_JAVASINGLETON | ");
- if ((flags & FLAG_PROP_JAVAOPTIONAL) != 0) result.append("FLAG_PROP_JAVAOPTIONAL | ");
- if ((flags & FLAG_PROP_JAVAARRAY) != 0) result.append("FLAG_PROP_JAVAARRAY | ");
- if (result.length() == 0) result.append("0 | ");
+ if ((flags & FLAG_PROP_ISATTR) != 0) {
+ result.append("FLAG_PROP_ISATTR | ");
+ }
+ if ((flags & FLAG_PROP_JAVASINGLETON) != 0) {
+ result.append("FLAG_PROP_JAVASINGLETON | ");
+ }
+ if ((flags & FLAG_PROP_JAVAOPTIONAL) != 0) {
+ result.append("FLAG_PROP_JAVAOPTIONAL | ");
+ }
+ if ((flags & FLAG_PROP_JAVAARRAY) != 0) {
+ result.append("FLAG_PROP_JAVAARRAY | ");
+ }
+ if (result.length() == 0) {
+ result.append("0 | ");
+ }
return result.substring(0, result.length() - 3);
}
@@ -227,72 +259,111 @@
public static final int FIELD_LOCALATTR = 2;
public static final int FIELD_LOCALELT = 3;
- static String containerfieldTypeString(int code)
- {
- switch (code)
- {
- case FIELD_NONE: return "FIELD_NONE";
- case FIELD_GLOBAL: return "FIELD_GLOBAL";
- case FIELD_LOCALATTR: return "FIELD_LOCALATTR";
- case FIELD_LOCALELT: return "FIELD_LOCALELT";
+ static String containerfieldTypeString(int code) {
+ switch (code) {
+ case FIELD_NONE:
+ return "FIELD_NONE";
+ case FIELD_GLOBAL:
+ return "FIELD_GLOBAL";
+ case FIELD_LOCALATTR:
+ return "FIELD_LOCALATTR";
+ case FIELD_LOCALELT:
+ return "FIELD_LOCALELT";
default:
return "Unknown container field type (" + code + ")";
}
}
// type flags
- static final int FLAG_SIMPLE_TYPE = 0x1;
- static final int FLAG_DOCUMENT_TYPE = 0x2;
- static final int FLAG_ORDERED = 0x4;
- static final int FLAG_BOUNDED = 0x8;
- static final int FLAG_FINITE = 0x10;
- static final int FLAG_NUMERIC = 0x20;
- static final int FLAG_STRINGENUM = 0x40;
- static final int FLAG_UNION_OF_LISTS = 0x80;
- static final int FLAG_HAS_PATTERN = 0x100;
+ static final int FLAG_SIMPLE_TYPE = 0x1;
+ static final int FLAG_DOCUMENT_TYPE = 0x2;
+ static final int FLAG_ORDERED = 0x4;
+ static final int FLAG_BOUNDED = 0x8;
+ static final int FLAG_FINITE = 0x10;
+ static final int FLAG_NUMERIC = 0x20;
+ static final int FLAG_STRINGENUM = 0x40;
+ static final int FLAG_UNION_OF_LISTS = 0x80;
+ static final int FLAG_HAS_PATTERN = 0x100;
static final int FLAG_ORDER_SENSITIVE = 0x200;
- static final int FLAG_TOTAL_ORDER = 0x400;
- static final int FLAG_COMPILED = 0x800;
- static final int FLAG_BLOCK_EXT = 0x1000;
- static final int FLAG_BLOCK_REST = 0x2000;
- static final int FLAG_FINAL_EXT = 0x4000;
- static final int FLAG_FINAL_REST = 0x8000;
- static final int FLAG_FINAL_UNION = 0x10000;
- static final int FLAG_FINAL_LIST = 0x20000;
- static final int FLAG_ABSTRACT = 0x40000;
- static final int FLAG_ATTRIBUTE_TYPE = 0x80000;
+ static final int FLAG_TOTAL_ORDER = 0x400;
+ static final int FLAG_COMPILED = 0x800;
+ static final int FLAG_BLOCK_EXT = 0x1000;
+ static final int FLAG_BLOCK_REST = 0x2000;
+ static final int FLAG_FINAL_EXT = 0x4000;
+ static final int FLAG_FINAL_REST = 0x8000;
+ static final int FLAG_FINAL_UNION = 0x10000;
+ static final int FLAG_FINAL_LIST = 0x20000;
+ static final int FLAG_ABSTRACT = 0x40000;
+ static final int FLAG_ATTRIBUTE_TYPE = 0x80000;
- static String typeflagsString(int flags)
- {
+ static String typeflagsString(int flags) {
StringBuilder result = new StringBuilder();
- if ((flags & FLAG_SIMPLE_TYPE) != 0) result.append("FLAG_SIMPLE_TYPE | ");
- if ((flags & FLAG_DOCUMENT_TYPE) != 0) result.append("FLAG_DOCUMENT_TYPE | ");
- if ((flags & FLAG_ATTRIBUTE_TYPE) != 0) result.append("FLAG_ATTRIBUTE_TYPE | ");
- if ((flags & FLAG_ORDERED) != 0) result.append("FLAG_ORDERED | ");
- if ((flags & FLAG_BOUNDED) != 0) result.append("FLAG_BOUNDED | ");
- if ((flags & FLAG_FINITE) != 0) result.append("FLAG_FINITE | ");
- if ((flags & FLAG_NUMERIC) != 0) result.append("FLAG_NUMERIC | ");
- if ((flags & FLAG_STRINGENUM) != 0) result.append("FLAG_STRINGENUM | ");
- if ((flags & FLAG_UNION_OF_LISTS) != 0) result.append("FLAG_UNION_OF_LISTS | ");
- if ((flags & FLAG_HAS_PATTERN) != 0) result.append("FLAG_HAS_PATTERN | ");
- if ((flags & FLAG_TOTAL_ORDER) != 0) result.append("FLAG_TOTAL_ORDER | ");
- if ((flags & FLAG_COMPILED) != 0) result.append("FLAG_COMPILED | ");
- if ((flags & FLAG_BLOCK_EXT) != 0) result.append("FLAG_BLOCK_EXT | ");
- if ((flags & FLAG_BLOCK_REST) != 0) result.append("FLAG_BLOCK_REST | ");
- if ((flags & FLAG_FINAL_EXT) != 0) result.append("FLAG_FINAL_EXT | ");
- if ((flags & FLAG_FINAL_REST) != 0) result.append("FLAG_FINAL_REST | ");
- if ((flags & FLAG_FINAL_UNION) != 0) result.append("FLAG_FINAL_UNION | ");
- if ((flags & FLAG_FINAL_LIST) != 0) result.append("FLAG_FINAL_LIST | ");
- if ((flags & FLAG_ABSTRACT) != 0) result.append("FLAG_ABSTRACT | ");
- if (result.length() == 0) result.append("0 | ");
+ if ((flags & FLAG_SIMPLE_TYPE) != 0) {
+ result.append("FLAG_SIMPLE_TYPE | ");
+ }
+ if ((flags & FLAG_DOCUMENT_TYPE) != 0) {
+ result.append("FLAG_DOCUMENT_TYPE | ");
+ }
+ if ((flags & FLAG_ATTRIBUTE_TYPE) != 0) {
+ result.append("FLAG_ATTRIBUTE_TYPE | ");
+ }
+ if ((flags & FLAG_ORDERED) != 0) {
+ result.append("FLAG_ORDERED | ");
+ }
+ if ((flags & FLAG_BOUNDED) != 0) {
+ result.append("FLAG_BOUNDED | ");
+ }
+ if ((flags & FLAG_FINITE) != 0) {
+ result.append("FLAG_FINITE | ");
+ }
+ if ((flags & FLAG_NUMERIC) != 0) {
+ result.append("FLAG_NUMERIC | ");
+ }
+ if ((flags & FLAG_STRINGENUM) != 0) {
+ result.append("FLAG_STRINGENUM | ");
+ }
+ if ((flags & FLAG_UNION_OF_LISTS) != 0) {
+ result.append("FLAG_UNION_OF_LISTS | ");
+ }
+ if ((flags & FLAG_HAS_PATTERN) != 0) {
+ result.append("FLAG_HAS_PATTERN | ");
+ }
+ if ((flags & FLAG_TOTAL_ORDER) != 0) {
+ result.append("FLAG_TOTAL_ORDER | ");
+ }
+ if ((flags & FLAG_COMPILED) != 0) {
+ result.append("FLAG_COMPILED | ");
+ }
+ if ((flags & FLAG_BLOCK_EXT) != 0) {
+ result.append("FLAG_BLOCK_EXT | ");
+ }
+ if ((flags & FLAG_BLOCK_REST) != 0) {
+ result.append("FLAG_BLOCK_REST | ");
+ }
+ if ((flags & FLAG_FINAL_EXT) != 0) {
+ result.append("FLAG_FINAL_EXT | ");
+ }
+ if ((flags & FLAG_FINAL_REST) != 0) {
+ result.append("FLAG_FINAL_REST | ");
+ }
+ if ((flags & FLAG_FINAL_UNION) != 0) {
+ result.append("FLAG_FINAL_UNION | ");
+ }
+ if ((flags & FLAG_FINAL_LIST) != 0) {
+ result.append("FLAG_FINAL_LIST | ");
+ }
+ if ((flags & FLAG_ABSTRACT) != 0) {
+ result.append("FLAG_ABSTRACT | ");
+ }
+ if (result.length() == 0) {
+ result.append("0 | ");
+ }
return result.substring(0, result.length() - 3);
}
- void dumpAll()
- {
+ void dumpAll() {
int filetype = dumpHeader();
- switch (filetype)
- {
+ switch (filetype) {
case FILETYPE_SCHEMAINDEX:
dumpIndexData();
return;
@@ -318,33 +389,30 @@
readEnd();
}
- static String hex32String(int i)
- {
+ static String hex32String(int i) {
return Integer.toHexString(i);
}
- protected int dumpHeader()
- {
+ protected int dumpHeader() {
int magic = readInt();
emit("Magic cookie: " + hex32String(magic));
- if (magic != DATA_BABE)
- {
+ if (magic != DATA_BABE) {
emit("Wrong magic cookie.");
return 0;
}
_majorver = readShort();
_minorver = readShort();
- if (atLeast(2, 18, 0))
+ if (atLeast(2, 18, 0)) {
_releaseno = readShort();
+ }
emit("Major version: " + _majorver);
emit("Minor version: " + _minorver);
emit("Release number: " + _releaseno);
- if (_majorver != MAJOR_VERSION || _minorver > MINOR_VERSION)
- {
+ if (_majorver != MAJOR_VERSION || _minorver > MINOR_VERSION) {
emit("Incompatible version.");
return 0;
}
@@ -358,19 +426,16 @@
return actualfiletype;
}
- void dumpPointerData()
- {
+ void dumpPointerData() {
emit("Type system: " + readString());
}
- protected void dumpIndexData()
- {
+ protected void dumpIndexData() {
// has a handle pool (count, handle/type, handle/type...)
int size = readShort();
emit("Handle pool (" + size + "):");
indent();
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
String handle = readString();
int code = readShort();
emit(handle + " (" + filetypeString(code) + ")");
@@ -404,45 +469,42 @@
dumpStringArray("Defined namespaces");
// version 15 stuff for redefines
- if (atLeast(2, 15, 0))
- {
+ if (atLeast(2, 15, 0)) {
dumpQNameMap("Redefined global types");
dumpQNameMap("Redfined model groups");
dumpQNameMap("Redfined attribute groups");
}
// version 19 annotations
- if (atLeast(2, 19, 0))
+ if (atLeast(2, 19, 0)) {
dumpAnnotations();
+ }
readEnd();
}
- class StringPool
- {
+ class StringPool {
private List intsToStrings = new ArrayList();
private Map stringsToInts = new HashMap();
- StringPool()
- {
+ StringPool() {
intsToStrings.add(null);
}
- String stringForCode(int code)
- {
- if (code == 0)
+ String stringForCode(int code) {
+ if (code == 0) {
return null;
- return (String)intsToStrings.get(code);
+ }
+ return (String) intsToStrings.get(code);
}
- int codeForString(String str)
- {
- if (str == null)
+ int codeForString(String str) {
+ if (str == null) {
return 0;
- Integer result = (Integer)stringsToInts.get(str);
- if (result == null)
- {
+ }
+ Integer result = (Integer) stringsToInts.get(str);
+ if (result == null) {
result = new Integer(intsToStrings.size());
intsToStrings.add(str);
stringsToInts.put(str, result);
@@ -450,28 +512,25 @@
return result.intValue();
}
- void readFrom(DataInputStream input)
- {
- if (intsToStrings.size() != 1 || stringsToInts.size() != 0)
+ void readFrom(DataInputStream input) {
+ if (intsToStrings.size() != 1 || stringsToInts.size() != 0) {
throw new IllegalStateException();
+ }
- try
- {
+ try {
int size = input.readShort();
emit("String pool (" + size + "):");
indent();
- for (int i = 1; i < size; i++)
- {
+ for (int i = 1; i < size; i++) {
String str = input.readUTF();
int code = codeForString(str);
- if (code != i)
+ if (code != i) {
throw new IllegalStateException();
+ }
emit(code + " = \"" + str + "\"");
}
outdent();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
emit(e.toString());
}
}
@@ -481,237 +540,218 @@
DataInputStream _input;
StringPool _stringPool;
- int readShort()
- {
- try
- {
+ int readShort() {
+ try {
return _input.readUnsignedShort();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
error(e);
return 0;
}
}
- int readInt()
- {
- try
- {
+ int readInt() {
+ try {
return _input.readInt();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
error(e);
return 0;
}
}
- String readString()
- {
+ String readString() {
return _stringPool.stringForCode(readShort());
}
- QName readQName()
- {
+ QName readQName() {
String namespace = readString();
String localname = readString();
- if (localname == null)
+ if (localname == null) {
return null;
+ }
return new QName(namespace, localname);
}
- String readHandle()
- {
+ String readHandle() {
return readString();
}
- String readType()
- {
+ String readType() {
return readHandle();
}
- static String qnameString(QName qname)
- {
- if (qname == null)
+ static String qnameString(QName qname) {
+ if (qname == null) {
return "(null)";
- if (qname.getNamespaceURI() != null)
+ }
+ if (qname.getNamespaceURI() != null) {
return qname.getLocalPart() + "@" + qname.getNamespaceURI();
- else
+ } else {
return qname.getLocalPart();
+ }
}
- static String qnameSetString(QNameSet set)
- {
+ static String qnameSetString(QNameSet set) {
return set.toString();
}
- void dumpQNameMap(String fieldname)
- {
+ void dumpQNameMap(String fieldname) {
int size = readShort();
emit(fieldname + " (" + size + "):");
indent();
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
emit(qnameString(readQName()) + " = " + readHandle());
}
outdent();
}
- void dumpTypeArray(String fieldname)
- {
+ void dumpTypeArray(String fieldname) {
int size = readShort();
emit(fieldname + " (" + size + "):");
indent();
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
emit(i + " = " + readType());
}
outdent();
}
- void dumpClassnameIndex(String fieldname)
- {
+ void dumpClassnameIndex(String fieldname) {
int size = readShort();
emit(fieldname + " (" + size + "):");
indent();
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
emit(readString() + " = " + readType());
}
outdent();
}
- void dumpStringArray(String fieldname)
- {
+ void dumpStringArray(String fieldname) {
int size = readShort();
emit(fieldname + " (" + size + "):");
indent();
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
emit(readString());
}
outdent();
}
- void readEnd()
- {
- try
- {
+ void readEnd() {
+ try {
_input.close();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
// oh, well.
}
_input = null;
_stringPool = null;
}
- static String particleTypeString(int spt)
- {
- switch (spt)
- {
- case SchemaParticle.ALL: return "ALL";
- case SchemaParticle.CHOICE: return "CHOICE";
- case SchemaParticle.ELEMENT: return "ELEMENT";
- case SchemaParticle.SEQUENCE: return "SEQUENCE";
- case SchemaParticle.WILDCARD: return "WILDCARD";
+ static String particleTypeString(int spt) {
+ switch (spt) {
+ case SchemaParticle.ALL:
+ return "ALL";
+ case SchemaParticle.CHOICE:
+ return "CHOICE";
+ case SchemaParticle.ELEMENT:
+ return "ELEMENT";
+ case SchemaParticle.SEQUENCE:
+ return "SEQUENCE";
+ case SchemaParticle.WILDCARD:
+ return "WILDCARD";
default:
return "Unknown particle type (" + spt + ")";
}
}
- static String bigIntegerString(BigInteger bigint)
- {
- if (bigint == null)
+ static String bigIntegerString(BigInteger bigint) {
+ if (bigint == null) {
return "(null)";
+ }
return bigint.toString();
}
- static String wcprocessString(int code)
- {
- switch (code)
- {
- case SchemaParticle.STRICT: return "STRICT";
- case SchemaParticle.SKIP: return "SKIP";
- case SchemaParticle.LAX: return "LAX";
- case 0: return "NOT_WILDCARD";
+ static String wcprocessString(int code) {
+ switch (code) {
+ case SchemaParticle.STRICT:
+ return "STRICT";
+ case SchemaParticle.SKIP:
+ return "SKIP";
+ case SchemaParticle.LAX:
+ return "LAX";
+ case 0:
+ return "NOT_WILDCARD";
default:
return "Unknown process type (" + code + ")";
}
}
- void dumpAnnotation()
- {
- if (!atLeast(2, 19, 0))
+ void dumpAnnotation() {
+ if (!atLeast(2, 19, 0)) {
return; // no annotations in this version of the file
+ }
int n = readInt();
- if (n == -1)
+ if (n == -1) {
return; // no annotation present
+ }
emit("Annotation");
boolean empty = true;
indent();
- if (n > 0)
- {
+ if (n > 0) {
emit("Attributes (" + n + "):");
indent();
- for (int i = 0; i < n; i++)
- {
- if (atLeast(2, 24, 0))
+ for (int i = 0; i < n; i++) {
+ if (atLeast(2, 24, 0)) {
emit("Name: " + qnameString(readQName()) +
- ", Value: " + readString() +
- ", ValueURI: " + readString());
- else
+ ", Value: " + readString() +
+ ", ValueURI: " + readString());
+ } else {
emit("Name: " + qnameString(readQName()) +
- ", Value: " + readString());
+ ", Value: " + readString());
+ }
}
outdent();
empty = false;
}
n = readInt();
- if (n > 0)
- {
+ if (n > 0) {
emit("Documentation elements (" + n + "):");
indent();
- for (int i = 0; i < n; i++)
+ for (int i = 0; i < n; i++) {
emit(readString());
+ }
outdent();
empty = false;
}
n = readInt();
- if (n > 0)
- {
+ if (n > 0) {
emit("Appinfo elements (" + n + "):");
indent();
- for (int i = 0; i < n; i++)
+ for (int i = 0; i < n; i++) {
emit(readString());
+ }
outdent();
empty = false;
}
- if (empty)
+ if (empty) {
emit("<empty>");
+ }
outdent();
}
- void dumpAnnotations()
- {
+ void dumpAnnotations() {
int n = readInt();
- if (n > 0)
- {
+ if (n > 0) {
emit("Top-level annotations (" + n + "):");
indent();
- for (int i = 0; i < n; i++)
+ for (int i = 0; i < n; i++) {
dumpAnnotation();
+ }
outdent();
}
}
- void dumpParticleData(boolean global)
- {
+ void dumpParticleData(boolean global) {
int particleType = readShort();
emit(particleTypeString(particleType) + ":");
indent();
@@ -723,8 +763,7 @@
emit("Transition: " + qnameSetString(readQNameSet()));
- switch (particleType)
- {
+ switch (particleType) {
case SchemaParticle.WILDCARD:
emit("Wildcard set: " + qnameSetString(readQNameSet()));
emit("Wildcard process: " + wcprocessString(readShort()));
@@ -734,19 +773,19 @@
emit("Name: " + qnameString(readQName()));
emit("Type: " + readType());
emit("Default: " + readString());
- if (atLeast(2, 16, 0))
+ if (atLeast(2, 16, 0)) {
emit("Default value: " + readXmlValueObject());
+ }
emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType()));
dumpAnnotation();
- if (global)
- {
- if (atLeast(2, 17, 0))
+ if (global) {
+ if (atLeast(2, 17, 0)) {
emit("Substitution group ref: " + readHandle());
+ }
int substGroupCount = readShort();
emit("Substitution group members (" + substGroupCount + ")");
indent();
- for (int i = 0; i < substGroupCount; i++)
- {
+ for (int i = 0; i < substGroupCount; i++) {
emit(qnameString(readQName()));
}
outdent();
@@ -754,13 +793,13 @@
int count = readShort();
emit("Identity constraints (" + count + "):");
indent();
- for (int i = 0; i < count; i++)
- {
+ for (int i = 0; i < count; i++) {
emit(readHandle());
}
outdent();
- if (global)
+ if (global) {
emit("Filename: " + readString());
+ }
break;
case SchemaParticle.ALL:
@@ -775,86 +814,98 @@
outdent();
}
- void dumpParticleArray(String fieldname)
- {
+ void dumpParticleArray(String fieldname) {
int count = readShort();
emit(fieldname + "(" + count + "):");
indent();
- for (int i = 0; i < count; i++)
+ for (int i = 0; i < count; i++) {
dumpParticleData(false);
+ }
outdent();
}
- static String complexVarietyString(int code)
- {
- switch (code)
- {
- case SchemaType.EMPTY_CONTENT: return "EMPTY_CONTENT";
- case SchemaType.SIMPLE_CONTENT: return "SIMPLE_CONTENT";
- case SchemaType.ELEMENT_CONTENT: return "ELEMENT_CONTENT";
- case SchemaType.MIXED_CONTENT: return "MIXED_CONTENT";
+ static String complexVarietyString(int code) {
+ switch (code) {
+ case SchemaType.EMPTY_CONTENT:
+ return "EMPTY_CONTENT";
+ case SchemaType.SIMPLE_CONTENT:
+ return "SIMPLE_CONTENT";
+ case SchemaType.ELEMENT_CONTENT:
+ return "ELEMENT_CONTENT";
+ case SchemaType.MIXED_CONTENT:
+ return "MIXED_CONTENT";
default:
return "Unknown complex variety (" + code + ")";
}
}
- static String simpleVarietyString(int code)
- {
- switch (code)
- {
- case SchemaType.ATOMIC: return "ATOMIC";
- case SchemaType.LIST: return "LIST";
- case SchemaType.UNION: return "UNION";
+ static String simpleVarietyString(int code) {
+ switch (code) {
+ case SchemaType.ATOMIC:
+ return "ATOMIC";
+ case SchemaType.LIST:
+ return "LIST";
+ case SchemaType.UNION:
+ return "UNION";
default:
return "Unknown simple variety (" + code + ")";
}
}
- String facetCodeString(int code)
- {
- switch (code)
- {
- case SchemaType.FACET_LENGTH: return "FACET_LENGTH";
- case SchemaType.FACET_MIN_LENGTH: return "FACET_MIN_LENGTH";
- case SchemaType.FACET_MAX_LENGTH: return "FACET_MAX_LENGTH";
- case SchemaType.FACET_MIN_EXCLUSIVE: return "FACET_MIN_EXCLUSIVE";
- case SchemaType.FACET_MIN_INCLUSIVE: return "FACET_MIN_INCLUSIVE";
- case SchemaType.FACET_MAX_INCLUSIVE: return "FACET_MAX_INCLUSIVE";
- case SchemaType.FACET_MAX_EXCLUSIVE: return "FACET_MAX_EXCLUSIVE";
- case SchemaType.FACET_TOTAL_DIGITS: return "FACET_TOTAL_DIGITS";
- case SchemaType.FACET_FRACTION_DIGITS: return "FACET_FRACTION_DIGITS";
+ String facetCodeString(int code) {
+ switch (code) {
+ case SchemaType.FACET_LENGTH:
+ return "FACET_LENGTH";
+ case SchemaType.FACET_MIN_LENGTH:
+ return "FACET_MIN_LENGTH";
+ case SchemaType.FACET_MAX_LENGTH:
+ return "FACET_MAX_LENGTH";
+ case SchemaType.FACET_MIN_EXCLUSIVE:
+ return "FACET_MIN_EXCLUSIVE";
+ case SchemaType.FACET_MIN_INCLUSIVE:
+ return "FACET_MIN_INCLUSIVE";
+ case SchemaType.FACET_MAX_INCLUSIVE:
+ return "FACET_MAX_INCLUSIVE";
+ case SchemaType.FACET_MAX_EXCLUSIVE:
+ return "FACET_MAX_EXCLUSIVE";
+ case SchemaType.FACET_TOTAL_DIGITS:
+ return "FACET_TOTAL_DIGITS";
+ case SchemaType.FACET_FRACTION_DIGITS:
+ return "FACET_FRACTION_DIGITS";
default:
return "Unknown facet code (" + code + ")";
}
}
- String whitespaceCodeString(int code)
- {
- switch (code)
- {
- case SchemaType.WS_COLLAPSE: return "WS_COLLAPSE";
- case SchemaType.WS_PRESERVE: return "WS_PRESERVE";
- case SchemaType.WS_REPLACE: return "WS_REPLACE";
- case SchemaType.WS_UNSPECIFIED: return "WS_UNSPECIFIED";
+ String whitespaceCodeString(int code) {
+ switch (code) {
+ case SchemaType.WS_COLLAPSE:
+ return "WS_COLLAPSE";
+ case SchemaType.WS_PRESERVE:
+ return "WS_PRESERVE";
+ case SchemaType.WS_REPLACE:
+ return "WS_REPLACE";
+ case SchemaType.WS_UNSPECIFIED:
+ return "WS_UNSPECIFIED";
default:
return "Unknown whitespace code (" + code + ")";
}
}
- String derivationTypeString(int code)
- {
- switch (code)
- {
- case SchemaType.DT_NOT_DERIVED: return "DT_NOT_DERIVED";
- case SchemaType.DT_RESTRICTION: return "DT_RESTRICTION";
- case SchemaType.DT_EXTENSION: return "DT_EXTENSION";
+ String derivationTypeString(int code) {
+ switch (code) {
+ case SchemaType.DT_NOT_DERIVED:
+ return "DT_NOT_DERIVED";
+ case SchemaType.DT_RESTRICTION:
+ return "DT_RESTRICTION";
+ case SchemaType.DT_EXTENSION:
+ return "DT_EXTENSION";
default:
return "Unknown derivation code (" + code + ")";
}
}
- void dumpTypeFileData()
- {
+ void dumpTypeFileData() {
emit("Name: " + qnameString(readQName()));
emit("Outer type: " + readType());
emit("Depth: " + readShort());
@@ -866,8 +917,7 @@
indent();
int containerfieldtype = readShort();
emit("Reftype: " + containerfieldTypeString(containerfieldtype));
- switch (containerfieldtype)
- {
+ switch (containerfieldtype) {
case FIELD_GLOBAL:
emit("Handle: " + readHandle());
break;
@@ -892,19 +942,20 @@
boolean isComplexType = ((flags & FLAG_SIMPLE_TYPE) == 0);
int complexVariety = SchemaType.NOT_COMPLEX_TYPE;
- if (isComplexType)
- {
+ if (isComplexType) {
complexVariety = readShort();
emit("Complex variety: " + complexVarietyString(complexVariety));
- if (atLeast(2, 23, 0))
+ if (atLeast(2, 23, 0)) {
emit("Content based on type: " + readType());
+ }
int attrCount = readShort();
emit("Attribute model (" + attrCount + "):");
indent();
- for (int i = 0; i < attrCount; i++)
+ for (int i = 0; i < attrCount; i++) {
dumpAttributeData(false);
+ }
emit("Wildcard set: " + qnameSetString(readQNameSet()));
emit("Wildcard process: " + wcprocessString(readShort()));
@@ -914,14 +965,12 @@
int attrPropCount = readShort();
emit("Attribute properties (" + attrPropCount + "):");
indent();
- for (int i = 0; i < attrPropCount; i++)
- {
+ for (int i = 0; i < attrPropCount; i++) {
dumpPropertyData();
}
outdent();
- if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT)
- {
+ if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) {
emit("IsAll: " + readShort());
// Content model tree
@@ -931,16 +980,14 @@
int elemPropCount = readShort();
emit("Element properties (" + elemPropCount + "):");
indent();
- for (int i = 0; i < elemPropCount; i++)
- {
+ for (int i = 0; i < elemPropCount; i++) {
dumpPropertyData();
}
outdent();
}
}
- if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT)
- {
+ if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) {
int simpleVariety = readShort();
emit("Simple type variety: " + simpleVarietyString(simpleVariety));
@@ -949,8 +996,7 @@
int facetCount = readShort();
emit("Facets (" + facetCount + "):");
indent();
- for (int i = 0; i < facetCount; i++)
- {
+ for (int i = 0; i < facetCount; i++) {
emit(facetCodeString(readShort()));
emit("Value: " + readXmlValueObject());
emit("Fixed: " + readShort());
@@ -962,8 +1008,7 @@
int patternCount = readShort();
emit("Patterns (" + patternCount + "):");
indent();
- for (int i = 0; i < patternCount; i++)
- {
+ for (int i = 0; i < patternCount; i++) {
emit(readString());
}
outdent();
@@ -971,27 +1016,23 @@
int enumCount = readShort();
emit("Enumeration values (" + enumCount + "):");
indent();
- for (int i = 0; i < enumCount; i++)
- {
+ for (int i = 0; i < enumCount; i++) {
emit(readXmlValueObject());
}
outdent();
emit("Base enum type: " + readType());
- if (isStringEnum)
- {
+ if (isStringEnum) {
int seCount = readShort();
emit("String enum entries (" + seCount + "):");
indent();
- for (int i = 0; i < seCount; i++)
- {
+ for (int i = 0; i < seCount; i++) {
emit("\"" + readString() + "\" -> " + readShort() + " = " + readString());
}
outdent();
}
- switch (simpleVariety)
- {
+ switch (simpleVariety) {
case SchemaType.ATOMIC:
emit("Primitive type: " + readType());
emit("Decimal size: " + readInt());
@@ -1013,130 +1054,151 @@
emit("Filename: " + readString());
}
- static String attruseCodeString(int code)
- {
- switch (code)
- {
- case SchemaLocalAttribute.OPTIONAL: return "OPTIONAL";
- case SchemaLocalAttribute.REQUIRED: return "REQUIRED";
- case SchemaLocalAttribute.PROHIBITED: return "PROHIBITED";
+ static String attruseCodeString(int code) {
+ switch (code) {
+ case SchemaLocalAttribute.OPTIONAL:
+ return "OPTIONAL";
+ case SchemaLocalAttribute.REQUIRED:
+ return "REQUIRED";
+ case SchemaLocalAttribute.PROHIBITED:
+ return "PROHIBITED";
default:
return "Unknown use code (" + code + ")";
}
}
- void dumpAttributeData(boolean global)
- {
+ void dumpAttributeData(boolean global) {
emit("Name: " + qnameString(readQName()));
emit("Type: " + readType());
emit("Use: " + attruseCodeString(readShort()));
emit("Default: " + readString());
- if (atLeast(2, 16, 0))
+ if (atLeast(2, 16, 0)) {
emit("Default value: " + readXmlValueObject());
+ }
emit("Fixed: " + readShort());
emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType()));
dumpAnnotation();
- if (global)
+ if (global) {
emit("Filename: " + readString());
+ }
}
private static final XmlOptions prettyOptions =
new XmlOptions().setSavePrettyPrint();
- void dumpXml()
- {
+ void dumpXml() {
String xml = readString();
- try
- {
- emit( XmlObject.Factory.parse( xml ).xmlText( prettyOptions ) );
- }
- catch ( XmlException x )
- {
- emit( "!!!!!! BAD XML !!!!!" );
- emit( xml );
+ try {
+ emit(XmlObject.Factory.parse(xml).xmlText(prettyOptions));
+ } catch (XmlException x) {
+ emit("!!!!!! BAD XML !!!!!");
+ emit(xml);
}
}
- void dumpModelGroupData()
- {
+ void dumpModelGroupData() {
emit("Name: " + qnameString(readQName()));
emit("Target namespace: " + readString());
emit("Chameleon: " + readShort());
- if (atLeast(2, 22, 0))
+ if (atLeast(2, 22, 0)) {
emit("Element form default: " + readString());
- if (atLeast(2, 22, 0))
+ }
+ if (atLeast(2, 22, 0)) {
emit("Attribute form default: " + readString());
- if (atLeast(2, 15, 0))
+ }
+ if (atLeast(2, 15, 0)) {
emit("Redefine: " + readShort());
+ }
emit("Model Group Xml: ");
dumpXml();
dumpAnnotation();
- if (atLeast(2, 21, 0))
+ if (atLeast(2, 21, 0)) {
emit("Filename: " + readString());
+ }
}
- void dumpAttributeGroupData()
- {
+ void dumpAttributeGroupData() {
emit("Name: " + qnameString(readQName()));
emit("Target namespace: " + readString());
emit("Chameleon: " + readShort());
- if (atLeast(2, 22, 0))
+ if (atLeast(2, 22, 0)) {
emit("Form default: " + readString());
- if (atLeast(2, 15, 0))
+ }
+ if (atLeast(2, 15, 0)) {
emit("Redefine: " + readShort());
+ }
emit("Attribute Group Xml: ");
dumpXml();
dumpAnnotation();
- if (atLeast(2, 21, 0))
+ if (atLeast(2, 21, 0)) {
emit("Filename: " + readString());
+ }
}
- static String alwaysString(int code)
- {
- switch (code)
- {
- case SchemaProperty.CONSISTENTLY: return "CONSISTENTLY";
- case SchemaProperty.NEVER: return "NEVER";
- case SchemaProperty.VARIABLE: return "VARIABLE";
+ static String alwaysString(int code) {
+ switch (code) {
+ case SchemaProperty.CONSISTENTLY:
+ return "CONSISTENTLY";
+ case SchemaProperty.NEVER:
+ return "NEVER";
+ case SchemaProperty.VARIABLE:
+ return "VARIABLE";
default:
return "Unknown frequency code (" + code + ")";
}
}
- static String jtcString(int code)
- {
- switch (code)
- {
- case SchemaProperty.XML_OBJECT: return "XML_OBJECT";
- case SchemaProperty.JAVA_BOOLEAN: return "JAVA_BOOLEAN";
- case SchemaProperty.JAVA_FLOAT: return "JAVA_FLOAT";
- case SchemaProperty.JAVA_DOUBLE: return "JAVA_DOUBLE";
- case SchemaProperty.JAVA_BYTE: return "JAVA_BYTE";
- case SchemaProperty.JAVA_SHORT: return "JAVA_SHORT";
- case SchemaProperty.JAVA_INT: return "JAVA_INT";
- case SchemaProperty.JAVA_LONG: return "JAVA_LONG";
+ static String jtcString(int code) {
+ switch (code) {
+ case SchemaProperty.XML_OBJECT:
+ return "XML_OBJECT";
+ case SchemaProperty.JAVA_BOOLEAN:
+ return "JAVA_BOOLEAN";
+ case SchemaProperty.JAVA_FLOAT:
+ return "JAVA_FLOAT";
+ case SchemaProperty.JAVA_DOUBLE:
+ return "JAVA_DOUBLE";
+ case SchemaProperty.JAVA_BYTE:
+ return "JAVA_BYTE";
+ case SchemaProperty.JAVA_SHORT:
+ return "JAVA_SHORT";
+ case SchemaProperty.JAVA_INT:
+ return "JAVA_INT";
+ case SchemaProperty.JAVA_LONG:
+ return "JAVA_LONG";
- case SchemaProperty.JAVA_BIG_DECIMAL: return "JAVA_BIG_DECIMAL";
- case SchemaProperty.JAVA_BIG_INTEGER: return "JAVA_BIG_INTEGER";
- case SchemaProperty.JAVA_STRING: return "JAVA_STRING";
- case SchemaProperty.JAVA_BYTE_ARRAY: return "JAVA_BYTE_ARRAY";
- case SchemaProperty.JAVA_GDATE: return "JAVA_GDATE";
- case SchemaProperty.JAVA_GDURATION: return "JAVA_GDURATION";
- case SchemaProperty.JAVA_DATE: return "JAVA_DATE";
- case SchemaProperty.JAVA_QNAME: return "JAVA_QNAME";
- case SchemaProperty.JAVA_CALENDAR: return "JAVA_CALENDAR";
- case SchemaProperty.JAVA_LIST: return "JAVA_LIST";
+ case SchemaProperty.JAVA_BIG_DECIMAL:
+ return "JAVA_BIG_DECIMAL";
+ case SchemaProperty.JAVA_BIG_INTEGER:
+ return "JAVA_BIG_INTEGER";
+ case SchemaProperty.JAVA_STRING:
+ return "JAVA_STRING";
+ case SchemaProperty.JAVA_BYTE_ARRAY:
+ return "JAVA_BYTE_ARRAY";
+ case SchemaProperty.JAVA_GDATE:
+ return "JAVA_GDATE";
+ case SchemaProperty.JAVA_GDURATION:
+ return "JAVA_GDURATION";
+ case SchemaProperty.JAVA_DATE:
+ return "JAVA_DATE";
+ case SchemaProperty.JAVA_QNAME:
+ return "JAVA_QNAME";
+ case SchemaProperty.JAVA_CALENDAR:
+ return "JAVA_CALENDAR";
+ case SchemaProperty.JAVA_LIST:
+ return "JAVA_LIST";
- case SchemaProperty.JAVA_ENUM: return "JAVA_ENUM";
- case SchemaProperty.JAVA_OBJECT: return "JAVA_OBJECT";
+ case SchemaProperty.JAVA_ENUM:
+ return "JAVA_ENUM";
+ case SchemaProperty.JAVA_OBJECT:
+ return "JAVA_OBJECT";
default:
return "Unknown java type code (" + code + ")";
}
}
- void dumpPropertyData()
- {
+ void dumpPropertyData() {
emit("Property");
indent();
emit("Name: " + qnameString(readQName()));
@@ -1153,32 +1215,33 @@
emit("Java prop name: " + readString());
emit("Java type code: " + jtcString(readShort()));
emit("Type for java signature: " + readType());
- if (atMost(2, 19, 0))
+ if (atMost(2, 19, 0)) {
emit("Java setter delimiter: " + qnameSetString(readQNameSet()));
- if (atLeast(2, 16, 0))
+ }
+ if (atLeast(2, 16, 0)) {
emit("Default value: " + readXmlValueObject());
- if (((propflags & FLAG_PROP_ISATTR) == 0) && atLeast(2, 17, 0))
- {
+ }
+ if (((propflags & FLAG_PROP_ISATTR) == 0) && atLeast(2, 17, 0)) {
int size = readShort();
emit("Accepted substitutions (" + size + "):");
- for (int i = 0 ; i < size ; i++)
+ for (int i = 0; i < size; i++) {
emit(" Accepted name " + readQName());
+ }
}
outdent();
}
- String readXmlValueObject()
- {
+ String readXmlValueObject() {
String type = readType();
- if (type == null)
+ if (type == null) {
return "null";
+ }
int btc = readShort();
String value;
- switch (btc)
- {
+ switch (btc) {
default:
- assert(false);
+ assert (false);
case 0:
value = "nil";
break;
@@ -1201,13 +1264,13 @@
break;
case SchemaType.BTC_BASE_64_BINARY:
- case SchemaType.BTC_HEX_BINARY:
- {
- value = new String(HexBin.encode(readByteArray()));
- if (value.length() > 19)
- value = value.subSequence(0, 16) + "...";
- break;
+ case SchemaType.BTC_HEX_BINARY: {
+ value = new String(HexBin.encode(readByteArray()), StandardCharsets.ISO_8859_1);
+ if (value.length() > 19) {
+ value = value.subSequence(0, 16) + "...";
}
+ break;
+ }
case SchemaType.BTC_QNAME:
case SchemaType.BTC_NOTATION:
@@ -1219,121 +1282,124 @@
value = Double.toString(readDouble());
break;
}
- return value + " (" + type + ": " + btc +")";
+ return value + " (" + type + ": " + btc + ")";
}
- double readDouble()
- {
- try
- {
+ double readDouble() {
+ try {
return _input.readDouble();
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
error(e);
return 0.0;
}
}
- String SOAPArrayTypeString(SOAPArrayType t)
- {
- if (t == null)
+ String SOAPArrayTypeString(SOAPArrayType t) {
+ if (t == null) {
return "null";
+ }
return QNameHelper.pretty(t.getQName()) + t.soap11DimensionString();
}
- SOAPArrayType readSOAPArrayType()
- {
+ SOAPArrayType readSOAPArrayType() {
QName qName = readQName();
String dimensions = readString();
- if (qName == null)
+ if (qName == null) {
return null;
+ }
return new SOAPArrayType(qName, dimensions);
}
- QNameSet readQNameSet()
- {
+ QNameSet readQNameSet() {
int flag = readShort();
Set uriSet = new HashSet();
int uriCount = readShort();
- for (int i = 0; i < uriCount; i++)
+ for (int i = 0; i < uriCount; i++) {
uriSet.add(readString());
+ }
Set qnameSet1 = new HashSet();
int qncount1 = readShort();
- for (int i = 0; i < qncount1; i++)
+ for (int i = 0; i < qncount1; i++) {
qnameSet1.add(readQName());
+ }
Set qnameSet2 = new HashSet();
int qncount2 = readShort();
- for (int i = 0; i < qncount2; i++)
+ for (int i = 0; i < qncount2; i++) {
qnameSet2.add(readQName());
+ }
- if (flag == 1)
+ if (flag == 1) {
return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2);
- else
+ } else {
return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1);
+ }
}
- byte[] readByteArray()
- {
- try
- {
+ byte[] readByteArray() {
+ try {
int len = _input.readShort();
byte[] result = new byte[len];
_input.readFully(result);
return result;
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
error(e);
return null;
}
}
- BigInteger readBigInteger()
- {
+ BigInteger readBigInteger() {
byte[] result = readByteArray();
- if (result.length == 0)
+ if (result.length == 0) {
return null;
- if (result.length == 1 && result[0] == 0)
+ }
+ if (result.length == 1 && result[0] == 0) {
return BigInteger.ZERO;
- if (result.length == 1 && result[0] == 1)
+ }
+ if (result.length == 1 && result[0] == 1) {
return BigInteger.ONE;
+ }
return new BigInteger(result);
}
- static final byte[] SINGLE_ZERO_BYTE = new byte[] { (byte)0 };
+ static final byte[] SINGLE_ZERO_BYTE = new byte[]{(byte) 0};
private int _majorver;
private int _minorver;
private int _releaseno;
- protected boolean atLeast(int majorver, int minorver, int releaseno)
- {
- if (_majorver > majorver)
+ protected boolean atLeast(int majorver, int minorver, int releaseno) {
+ if (_majorver > majorver) {
return true;
- if (_majorver < majorver)
+ }
+ if (_majorver < majorver) {
return false;
- if (_minorver > minorver)
+ }
+ if (_minorver > minorver) {
return true;
- if (_minorver < minorver)
+ }
+ if (_minorver < minorver) {
return false;
+ }
return (_releaseno >= releaseno);
}
- protected boolean atMost(int majorver, int minorver, int releaseno)
- {
- if (_majorver > majorver)
+ protected boolean atMost(int majorver, int minorver, int releaseno) {
+ if (_majorver > majorver) {
return false;
- if (_majorver < majorver)
+ }
+ if (_majorver < majorver) {
return true;
- if (_minorver > minorver)
+ }
+ if (_minorver > minorver) {
return false;
- if (_minorver < minorver)
+ }
+ if (_minorver < minorver) {
return true;
+ }
return (_releaseno <= releaseno);
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/util/Base64.java b/src/main/java/org/apache/xmlbeans/impl/util/Base64.java
deleted file mode 100644
index a12b02a..0000000
--- a/src/main/java/org/apache/xmlbeans/impl/util/Base64.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/* Copyright 2004 The Apache Software Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.xmlbeans.impl.util;
-
-import java.io.UnsupportedEncodingException;
-/**
- * This class provides encode/decode for RFC 2045 Base64 as
- * defined by RFC 2045, N. Freed and N. Borenstein.
- * RFC 2045: Multipurpose Internet Mail Extensions (MIME)
- * Part One: Format of Internet Message Bodies. Reference
- * 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
- * This class is used by XML Schema binary format validation
- *
- * This implementation does not encode/decode streaming
- * data. You need the data that you will encode/decode
- * already on a byte arrray.
- *
- * @author Jeffrey Rodriguez
- * @author Sandy Gao
- * @version $Id$
- */
-public final class Base64 {
-
- static private final int BASELENGTH = 255;
- static private final int LOOKUPLENGTH = 64;
- static private final int TWENTYFOURBITGROUP = 24;
- static private final int EIGHTBIT = 8;
- static private final int SIXTEENBIT = 16;
- //static private final int SIXBIT = 6;
- static private final int FOURBYTE = 4;
- static private final int SIGN = -128;
- static private final byte PAD = ( byte ) '=';
- static private final boolean fDebug = false;
- static private byte [] base64Alphabet = new byte[BASELENGTH];
- static private byte [] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
-
- static {
-
- for (int i = 0; i<BASELENGTH; i++) {
- base64Alphabet[i] = -1;
- }
- for (int i = 'Z'; i >= 'A'; i--) {
- base64Alphabet[i] = (byte) (i-'A');
- }
- for (int i = 'z'; i>= 'a'; i--) {
- base64Alphabet[i] = (byte) ( i-'a' + 26);
- }
-
- for (int i = '9'; i >= '0'; i--) {
- base64Alphabet[i] = (byte) (i-'0' + 52);
- }
-
- base64Alphabet['+'] = 62;
- base64Alphabet['/'] = 63;
-
- for (int i = 0; i<=25; i++)
- lookUpBase64Alphabet[i] = (byte) ('A'+i );
-
- for (int i = 26, j = 0; i<=51; i++, j++)
- lookUpBase64Alphabet[i] = (byte) ('a'+ j );
-
- for (int i = 52, j = 0; i<=61; i++, j++)
- lookUpBase64Alphabet[i] = (byte) ('0' + j );
- lookUpBase64Alphabet[62] = (byte) '+';
- lookUpBase64Alphabet[63] = (byte) '/';
-
- }
-
- protected static boolean isWhiteSpace(byte octect) {
- return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
- }
-
- protected static boolean isPad(byte octect) {
- return (octect == PAD);
- }
-
- protected static boolean isData(byte octect) {
- return (base64Alphabet[octect] != -1);
- }
-
- protected static boolean isBase64(byte octect) {
- return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
- }
-
- /**
- * Encodes hex octects into Base64
- *
- * @param binaryData Array containing binaryData
- * @return Encoded Base64 array
- */
- public static byte[] encode(byte[] binaryData) {
-
- if (binaryData == null)
- return null;
-
- int lengthDataBits = binaryData.length*EIGHTBIT;
- int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP;
- int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP;
- byte encodedData[] = null;
-
- if (fewerThan24bits != 0) //data not divisible by 24 bit
- encodedData = new byte[ (numberTriplets + 1 )*4 ];
- else // 16 or 8 bit
- encodedData = new byte[ numberTriplets*4 ];
-
- byte k=0, l=0, b1=0,b2=0,b3=0;
-
- int encodedIndex = 0;
- int dataIndex = 0;
- int i = 0;
- if (fDebug) {
- System.out.println("number of triplets = " + numberTriplets );
- }
- for (i = 0; i<numberTriplets; i++) {
-
- dataIndex = i*3;
- b1 = binaryData[dataIndex];
- b2 = binaryData[dataIndex + 1];
- b3 = binaryData[dataIndex + 2];
-
- if (fDebug) {
- System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 );
- }
-
- l = (byte)(b2 & 0x0f);
- k = (byte)(b1 & 0x03);
-
- encodedIndex = i*4;
- byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
-
- byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
- byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
-
- encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ];
- if (fDebug) {
- System.out.println( "val2 = " + val2 );
- System.out.println( "k4 = " + (k<<4));
- System.out.println( "vak = " + (val2 | (k<<4)));
- }
-
- encodedData[encodedIndex+1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
- encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
- encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ];
- }
-
- // form integral number of 6-bit groups
- dataIndex = i*3;
- encodedIndex = i*4;
- if (fewerThan24bits == EIGHTBIT) {
- b1 = binaryData[dataIndex];
- k = (byte) ( b1 &0x03 );
- if (fDebug) {
- System.out.println("b1=" + b1);
- System.out.println("b1<<2 = " + (b1>>2) );
- }
- byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
- encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ];
- encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ];
- encodedData[encodedIndex + 2] = PAD;
- encodedData[encodedIndex + 3] = PAD;
- } else if (fewerThan24bits == SIXTEENBIT) {
-
- b1 = binaryData[dataIndex];
- b2 = binaryData[dataIndex +1 ];
- l = ( byte ) ( b2 &0x0f );
- k = ( byte ) ( b1 &0x03 );
-
- byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
- byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
-
- encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ];
- encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
- encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ];
- encodedData[encodedIndex + 3] = PAD;
- }
-
- return encodedData;
- }
-
- /**
- * Decodes Base64 data into octects
- *
- * @param base64Data Byte array containing Base64 data
- * @return Array containind decoded data.
- */
- public static byte[] decode(byte[] base64Data) {
-
- if (base64Data == null)
- return null;
-
- // remove white spaces
- base64Data = removeWhiteSpace(base64Data);
-
- if (base64Data.length%FOURBYTE != 0) {
- return null;//should be divisible by four
- }
-
- int numberQuadruple = (base64Data.length/FOURBYTE );
-
- if (numberQuadruple == 0)
- return new byte[0];
-
- byte decodedData[] = null;
- byte b1=0,b2=0,b3=0, b4=0;//, marker0=0, marker1=0;
- byte d1=0,d2=0,d3=0,d4=0;
-
- // Throw away anything not in normalizedBase64Data
- // Adjust size
- int i = 0;
- int encodedIndex = 0;
- int dataIndex = 0;
- decodedData = new byte[ (numberQuadruple)*3];
-
- for (; i<numberQuadruple-1; i++) {
-
- if (!isData( (d1 = base64Data[dataIndex++]) )||
- !isData( (d2 = base64Data[dataIndex++]) )||
- !isData( (d3 = base64Data[dataIndex++]) )||
- !isData( (d4 = base64Data[dataIndex++]) ))
- return null;//if found "no data" just return null
-
- b1 = base64Alphabet[d1];
- b2 = base64Alphabet[d2];
- b3 = base64Alphabet[d3];
- b4 = base64Alphabet[d4];
-
- decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ;
- decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
- decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
- }
-
- if (!isData( (d1 = base64Data[dataIndex++]) ) ||
- !isData( (d2 = base64Data[dataIndex++]) )) {
- return null;//if found "no data" just return null
- }
-
- b1 = base64Alphabet[d1];
- b2 = base64Alphabet[d2];
-
- d3 = base64Data[dataIndex++];
- d4 = base64Data[dataIndex++];
- if (!isData( (d3 ) ) ||
- !isData( (d4 ) )) {//Check if they are PAD characters
- if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad]
- if ((b2 & 0xf) != 0)//last 4 bits should be zero
- return null;
- byte[] tmp = new byte[ i*3 + 1 ];
- System.arraycopy( decodedData, 0, tmp, 0, i*3 );
- tmp[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ;
- return tmp;
- } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad]
- b3 = base64Alphabet[ d3 ];
- if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
- return null;
- byte[] tmp = new byte[ i*3 + 2 ];
- System.arraycopy( decodedData, 0, tmp, 0, i*3 );
- tmp[encodedIndex++] = (byte)( b1 <<2 | b2>>4 );
- tmp[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
- return tmp;
- } else {
- return null;//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
- }
- } else { //No PAD e.g 3cQl
- b3 = base64Alphabet[ d3 ];
- b4 = base64Alphabet[ d4 ];
- decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ;
- decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
- decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
-
- }
-
- return decodedData;
- }
-
-// /**
-// * Decodes Base64 data into octects
-// *
-// * @param base64Data String containing Base64 data
-// * @return string containing decoded data.
-// */
-// public static String decode(String base64Data) {
-// if (base64Data == null)
-// return null;
-//
-// byte[] decoded = null;
-// try {
-// decoded = decode(base64Data.getBytes("utf-8"));
-// }
-// catch(UnsupportedEncodingException e) {
-// }
-// finally {
-// return decoded == null ? null : new String(decoded);
-// }
-// }
-//
-// /**
-// * Encodes octects (using utf-8) into Base64 data
-// *
-// * @param binaryData String containing Hex data
-// * @return string containing decoded data.
-// */
-// public static String encode(String binaryData) {
-// if (binaryData == null)
-// return null;
-//
-// byte[] encoded = null;
-// try {
-// encoded = encode(binaryData.getBytes("utf-8"));
-// }
-// catch(UnsupportedEncodingException e) {}
-// finally {
-// return encoded == null ? null : new String(encoded);
-// }
-// }
-
- /**
- * remove WhiteSpace from MIME containing encoded Base64 data.
- *
- * @param data the byte array of base64 data (with WS)
- * @return the byte array of base64 data (without WS)
- */
- protected static byte[] removeWhiteSpace(byte[] data) {
- if (data == null)
- return null;
-
- // count characters that's not whitespace
- int newSize = 0;
- int len = data.length;
- for (int i = 0; i < len; i++) {
- if (!isWhiteSpace(data[i]))
- newSize++;
- }
-
- // if no whitespace, just return the input array
- if (newSize == len)
- return data;
-
- // create the array to return
- byte[] newArray = new byte[newSize];
-
- int j = 0;
- for (int i = 0; i < len; i++) {
- if (!isWhiteSpace(data[i]))
- newArray[j++] = data[i];
- }
- return newArray;
- }
-}
diff --git a/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java b/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java
index bd72bd8..60d607e 100644
--- a/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java
+++ b/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java
@@ -15,39 +15,40 @@
package org.apache.xmlbeans.impl.util;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+
/**
* format validation
- *
+ * <p>
* This class encodes/decodes hexadecimal data
- * @author Jeffrey Rodriguez
- * @version $Id$
*/
-public final class HexBin {
- static private final int BASELENGTH = 255;
- static private final int LOOKUPLENGTH = 16;
- static private byte [] hexNumberTable = new byte[BASELENGTH];
- static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH];
+public final class HexBin {
+ static private final int BASELENGTH = 255;
+ static private final int LOOKUPLENGTH = 16;
+ static private byte[] hexNumberTable = new byte[BASELENGTH];
+ static private byte[] lookUpHexAlphabet = new byte[LOOKUPLENGTH];
static {
- for (int i = 0; i<BASELENGTH; i++ ) {
+ for (int i = 0; i < BASELENGTH; i++) {
hexNumberTable[i] = -1;
}
- for ( int i = '9'; i >= '0'; i--) {
- hexNumberTable[i] = (byte) (i-'0');
+ for (int i = '9'; i >= '0'; i--) {
+ hexNumberTable[i] = (byte) (i - '0');
}
- for ( int i = 'F'; i>= 'A'; i--) {
- hexNumberTable[i] = (byte) ( i-'A' + 10 );
+ for (int i = 'F'; i >= 'A'; i--) {
+ hexNumberTable[i] = (byte) (i - 'A' + 10);
}
- for ( int i = 'f'; i>= 'a'; i--) {
- hexNumberTable[i] = (byte) ( i-'a' + 10 );
+ for (int i = 'f'; i >= 'a'; i--) {
+ hexNumberTable[i] = (byte) (i - 'a' + 10);
}
- for(int i = 0; i<10; i++ )
- lookUpHexAlphabet[i] = (byte) ('0'+i );
- for(int i = 10; i<=15; i++ )
- lookUpHexAlphabet[i] = (byte) ('A'+i -10);
+ for (int i = 0; i < 10; i++) {
+ lookUpHexAlphabet[i] = (byte) ('0' + i);
+ }
+ for (int i = 10; i <= 15; i++) {
+ lookUpHexAlphabet[i] = (byte) ('A' + i - 10);
+ }
}
/**
@@ -63,19 +64,18 @@
/**
* Converts bytes to a hex string
*/
- static public String bytesToString(byte[] binaryData)
- {
- if (binaryData == null)
+ static public String bytesToString(byte[] binaryData) {
+ if (binaryData == null) {
return null;
- return new String(encode(binaryData));
+ }
+ return new String(encode(binaryData), StandardCharsets.ISO_8859_1);
}
/**
* Converts a hex string to a byte array.
*/
- static public byte[] stringToBytes(String hexEncoded)
- {
- return decode(hexEncoded.getBytes());
+ static public byte[] stringToBytes(String hexEncoded) {
+ return decode(hexEncoded.getBytes(StandardCharsets.ISO_8859_1));
}
/**
@@ -85,32 +85,35 @@
* @return return encode binary array
*/
static public byte[] encode(byte[] binaryData) {
- if (binaryData == null)
+ if (binaryData == null) {
return null;
- int lengthData = binaryData.length;
+ }
+ int lengthData = binaryData.length;
int lengthEncode = lengthData * 2;
byte[] encodedData = new byte[lengthEncode];
- for( int i = 0; i<lengthData; i++ ){
- encodedData[i*2] = lookUpHexAlphabet[(binaryData[i] >> 4) & 0xf];
- encodedData[i*2+1] = lookUpHexAlphabet[ binaryData[i] & 0xf];
+ for (int i = 0; i < lengthData; i++) {
+ encodedData[i * 2] = lookUpHexAlphabet[(binaryData[i] >> 4) & 0xf];
+ encodedData[i * 2 + 1] = lookUpHexAlphabet[binaryData[i] & 0xf];
}
return encodedData;
}
static public byte[] decode(byte[] binaryData) {
- if (binaryData == null)
+ if (binaryData == null) {
return null;
- int lengthData = binaryData.length;
- if (lengthData % 2 != 0)
+ }
+ int lengthData = binaryData.length;
+ if (lengthData % 2 != 0) {
return null;
+ }
int lengthDecode = lengthData / 2;
byte[] decodedData = new byte[lengthDecode];
- for( int i = 0; i<lengthDecode; i++ ){
- if (!isHex(binaryData[i*2]) || !isHex(binaryData[i*2+1])) {
+ for (int i = 0; i < lengthDecode; i++) {
+ if (!isHex(binaryData[i * 2]) || !isHex(binaryData[i * 2 + 1])) {
return null;
}
- decodedData[i] = (byte)((hexNumberTable[binaryData[i*2]] << 4) | hexNumberTable[binaryData[i*2+1]]);
+ decodedData[i] = (byte) ((hexNumberTable[binaryData[i * 2]] << 4) | hexNumberTable[binaryData[i * 2 + 1]]);
}
return decodedData;
}
@@ -122,16 +125,12 @@
* @return string containing decoded data.
*/
public static String decode(String binaryData) {
- if (binaryData == null)
+ if (binaryData == null) {
return null;
+ }
- byte[] decoded = null;
- try {
- decoded = decode(binaryData.getBytes("utf-8"));
- }
- catch(UnsupportedEncodingException e) {
- }
- return decoded == null ? null : new String(decoded);
+ byte[] decoded = decode(binaryData.getBytes(StandardCharsets.ISO_8859_1));
+ return decoded == null ? null : new String(decoded, StandardCharsets.UTF_8);
}
/**
@@ -141,15 +140,12 @@
* @return string containing decoded data.
*/
public static String encode(String binaryData) {
- if (binaryData == null)
+ if (binaryData == null) {
return null;
-
- byte[] encoded = null;
- try {
- encoded = encode(binaryData.getBytes("utf-8"));
}
- catch(UnsupportedEncodingException e) {}
- return encoded == null ? null : new String(encoded);
+
+ byte[] encoded = encode(binaryData.getBytes(StandardCharsets.UTF_8));
+ return encoded == null ? null : new String(encoded, StandardCharsets.ISO_8859_1);
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java b/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java
index e2075be..1de4d85 100644
--- a/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java
@@ -15,25 +15,19 @@
package org.apache.xmlbeans.impl.util;
-import org.apache.xmlbeans.GDate;
-import org.apache.xmlbeans.GDateBuilder;
-import org.apache.xmlbeans.GDateSpecification;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.XmlCalendar;
-import org.apache.xmlbeans.XmlError;
+import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.InvalidLexicalValueException;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.net.URI;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
-import java.net.URI;
-public final class XsTypeConverter
-{
+public final class XsTypeConverter {
private static final String POS_INF_LEX = "INF";
private static final String NEG_INF_LEX = "-INF";
private static final String NAN_LEX = "NaN";
@@ -43,13 +37,12 @@
private static final BigDecimal DECIMAL__ZERO = new BigDecimal(0.0);
// See Section 2.4.3 of FRC2396 http://www.ietf.org/rfc/rfc2396.txt
- private static final String[] URI_CHARS_TO_BE_REPLACED = {" " , "{" , "}" , "|" , "\\" , "^" , "[" , "]" , "`" };
- private static final String[] URI_CHARS_REPLACED_WITH = {"%20", "%7b", "%7d", "%7c", "%5c", "%5e", "%5b", "%5d", "%60"};
+ private static final String[] URI_CHARS_TO_BE_REPLACED = {" ", "{", "}", "|", "\\", "^", "[", "]", "`"};
+ private static final String[] URI_CHARS_REPLACED_WITH = {"%20", "%7b", "%7d", "%7c", "%5c", "%5e", "%5b", "%5d", "%60"};
// ======================== float ========================
public static float lexFloat(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
final String v = cs.toString();
try {
//current jdk impl of parseFloat calls trim() on the string.
@@ -58,27 +51,31 @@
if (cs.length() > 0) {
char ch = cs.charAt(cs.length() - 1);
if (ch == 'f' || ch == 'F') {
- if (cs.charAt(cs.length() - 2) != 'N')
+ if (cs.charAt(cs.length() - 2) != 'N') {
throw new NumberFormatException("Invalid char '" + ch + "' in float.");
+ }
}
}
return Float.parseFloat(v);
- }
- catch (NumberFormatException e) {
- if (v.equals(POS_INF_LEX)) return Float.POSITIVE_INFINITY;
- if (v.equals(NEG_INF_LEX)) return Float.NEGATIVE_INFINITY;
- if (v.equals(NAN_LEX)) return Float.NaN;
+ } catch (NumberFormatException e) {
+ if (v.equals(POS_INF_LEX)) {
+ return Float.POSITIVE_INFINITY;
+ }
+ if (v.equals(NEG_INF_LEX)) {
+ return Float.NEGATIVE_INFINITY;
+ }
+ if (v.equals(NAN_LEX)) {
+ return Float.NaN;
+ }
throw e;
}
}
- public static float lexFloat(CharSequence cs, Collection errors)
- {
+ public static float lexFloat(CharSequence cs, Collection errors) {
try {
return lexFloat(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid float: " + cs;
errors.add(XmlError.forMessage(msg));
@@ -86,23 +83,22 @@
}
}
- public static String printFloat(float value)
- {
- if (value == Float.POSITIVE_INFINITY)
+ public static String printFloat(float value) {
+ if (value == Float.POSITIVE_INFINITY) {
return POS_INF_LEX;
- else if (value == Float.NEGATIVE_INFINITY)
+ } else if (value == Float.NEGATIVE_INFINITY) {
return NEG_INF_LEX;
- else if (Float.isNaN(value))
+ } else if (Float.isNaN(value)) {
return NAN_LEX;
- else
+ } else {
return Float.toString(value);
+ }
}
// ======================== double ========================
public static double lexDouble(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
final String v = cs.toString();
try {
@@ -111,26 +107,30 @@
//so no need to do a collapse pass through the string.
if (cs.length() > 0) {
char ch = cs.charAt(cs.length() - 1);
- if (ch == 'd' || ch == 'D')
+ if (ch == 'd' || ch == 'D') {
throw new NumberFormatException("Invalid char '" + ch + "' in double.");
+ }
}
return Double.parseDouble(v);
- }
- catch (NumberFormatException e) {
- if (v.equals(POS_INF_LEX)) return Double.POSITIVE_INFINITY;
- if (v.equals(NEG_INF_LEX)) return Double.NEGATIVE_INFINITY;
- if (v.equals(NAN_LEX)) return Double.NaN;
+ } catch (NumberFormatException e) {
+ if (v.equals(POS_INF_LEX)) {
+ return Double.POSITIVE_INFINITY;
+ }
+ if (v.equals(NEG_INF_LEX)) {
+ return Double.NEGATIVE_INFINITY;
+ }
+ if (v.equals(NAN_LEX)) {
+ return Double.NaN;
+ }
throw e;
}
}
- public static double lexDouble(CharSequence cs, Collection errors)
- {
+ public static double lexDouble(CharSequence cs, Collection errors) {
try {
return lexDouble(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid double: " + cs;
errors.add(XmlError.forMessage(msg));
@@ -138,23 +138,22 @@
}
}
- public static String printDouble(double value)
- {
- if (value == Double.POSITIVE_INFINITY)
+ public static String printDouble(double value) {
+ if (value == Double.POSITIVE_INFINITY) {
return POS_INF_LEX;
- else if (value == Double.NEGATIVE_INFINITY)
+ } else if (value == Double.NEGATIVE_INFINITY) {
return NEG_INF_LEX;
- else if (Double.isNaN(value))
+ } else if (Double.isNaN(value)) {
return NAN_LEX;
- else
+ } else {
return Double.toString(value);
+ }
}
// ======================== decimal ========================
public static BigDecimal lexDecimal(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
final String v = cs.toString();
//TODO: review this
@@ -166,67 +165,50 @@
return new BigDecimal(trimTrailingZeros(v));
}
- public static BigDecimal lexDecimal(CharSequence cs, Collection errors)
- {
- try {
- return lexDecimal(cs);
- }
- catch (NumberFormatException e) {
- String msg = "invalid long: " + cs;
- errors.add(XmlError.forMessage(msg));
- return DECIMAL__ZERO;
- }
- }
-
- private static final char[] CH_ZEROS = new char[] {'0', '0', '0', '0', '0', '0', '0', '0',
+ private static final char[] CH_ZEROS = new char[]{'0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
- public static String printDecimal(BigDecimal value)
- {
+ public static String printDecimal(BigDecimal value) {
// We can't simply use value.toString() here, because in JDK1.5 that returns an
// exponent String and exponents are not allowed in XMLSchema decimal values
// The following code comes from Apache Harmony
String intStr = value.unscaledValue().toString();
int scale = value.scale();
- if ((scale == 0) || ((value.longValue() == 0) && (scale < 0)))
+ if ((scale == 0) || ((value.longValue() == 0) && (scale < 0))) {
return intStr;
+ }
int begin = (value.signum() < 0) ? 1 : 0;
int delta = scale;
// We take space for all digits, plus a possible decimal point, plus 'scale'
StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale));
- if (begin == 1)
- {
- // If the number is negative, we insert a '-' character at front
+ if (begin == 1) {
+ // If the number is negative, we insert a '-' character at front
result.append('-');
}
- if (scale > 0)
- {
+ if (scale > 0) {
delta -= (intStr.length() - begin);
- if (delta >= 0)
- {
+ if (delta >= 0) {
result.append("0."); //$NON-NLS-1$
// To append zeros after the decimal point
- for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length)
+ for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) {
result.append(CH_ZEROS);
+ }
result.append(CH_ZEROS, 0, delta);
result.append(intStr.substring(begin));
- }
- else
- {
+ } else {
delta = begin - delta;
result.append(intStr.substring(begin, delta));
result.append('.');
result.append(intStr.substring(delta));
}
- }
- else
- {// (scale <= 0)
+ } else {// (scale <= 0)
result.append(intStr.substring(begin));
// To append trailing zeros
- for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length)
+ for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) {
result.append(CH_ZEROS);
+ }
result.append(CH_ZEROS, 0, -delta);
}
return result.toString();
@@ -234,11 +216,11 @@
// ======================== integer ========================
public static BigInteger lexInteger(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
if (cs.length() > 1) {
- if (cs.charAt(0) == '+' && cs.charAt(1) == '-')
+ if (cs.charAt(0) == '+' && cs.charAt(1) == '-') {
throw new NumberFormatException("Illegal char sequence '+-'");
+ }
}
final String v = cs.toString();
@@ -247,132 +229,116 @@
return new BigInteger(trimInitialPlus(v));
}
- public static BigInteger lexInteger(CharSequence cs, Collection errors)
- {
+ public static BigInteger lexInteger(CharSequence cs, Collection errors) {
try {
return lexInteger(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid long: " + cs;
errors.add(XmlError.forMessage(msg));
return BigInteger.ZERO;
}
}
- public static String printInteger(BigInteger value)
- {
+ public static String printInteger(BigInteger value) {
return value.toString();
}
// ======================== long ========================
public static long lexLong(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
final String v = cs.toString();
return Long.parseLong(trimInitialPlus(v));
}
- public static long lexLong(CharSequence cs, Collection errors)
- {
+ public static long lexLong(CharSequence cs, Collection errors) {
try {
return lexLong(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid long: " + cs;
errors.add(XmlError.forMessage(msg));
return 0L;
}
}
- public static String printLong(long value)
- {
+ public static String printLong(long value) {
return Long.toString(value);
}
// ======================== short ========================
public static short lexShort(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
return parseShort(cs);
}
- public static short lexShort(CharSequence cs, Collection errors)
- {
+ public static short lexShort(CharSequence cs, Collection errors) {
try {
return lexShort(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid short: " + cs;
errors.add(XmlError.forMessage(msg));
return 0;
}
}
- public static String printShort(short value)
- {
+ public static String printShort(short value) {
return Short.toString(value);
}
// ======================== int ========================
public static int lexInt(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
return parseInt(cs);
}
- public static int lexInt(CharSequence cs, Collection errors)
- {
+ public static int lexInt(CharSequence cs, Collection errors) {
try {
return lexInt(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid int:" + cs;
errors.add(XmlError.forMessage(msg));
return 0;
}
}
- public static String printInt(int value)
- {
+ public static String printInt(int value) {
return Integer.toString(value);
}
// ======================== byte ========================
public static byte lexByte(CharSequence cs)
- throws NumberFormatException
- {
+ throws NumberFormatException {
return parseByte(cs);
}
- public static byte lexByte(CharSequence cs, Collection errors)
- {
+ public static byte lexByte(CharSequence cs, Collection errors) {
try {
return lexByte(cs);
- }
- catch (NumberFormatException e) {
+ } catch (NumberFormatException e) {
String msg = "invalid byte: " + cs;
errors.add(XmlError.forMessage(msg));
return 0;
}
}
- public static String printByte(byte value)
- {
+ public static String printByte(byte value) {
return Byte.toString(value);
}
// ======================== boolean ========================
- public static boolean lexBoolean(CharSequence v)
- {
+ public static boolean lexBoolean(CharSequence v) {
switch (v.length()) {
case 1: // "0" or "1"
final char c = v.charAt(0);
- if ('0' == c) return false;
- if ('1' == c) return true;
+ if ('0' == c) {
+ return false;
+ }
+ if ('1' == c) {
+ return true;
+ }
break;
case 4: //"true"
if ('t' == v.charAt(0) &&
@@ -398,55 +364,38 @@
throw new InvalidLexicalValueException(msg);
}
- public static boolean lexBoolean(CharSequence value, Collection errors)
- {
+ public static boolean lexBoolean(CharSequence value, Collection<XmlError> errors) {
try {
return lexBoolean(value);
- }
- catch (InvalidLexicalValueException e) {
+ } catch (InvalidLexicalValueException e) {
errors.add(XmlError.forMessage(e.getMessage()));
return false;
}
}
- public static String printBoolean(boolean value)
- {
+ public static String printBoolean(boolean value) {
return (value ? "true" : "false");
}
// ======================== string ========================
- public static String lexString(CharSequence cs, Collection errors)
- {
- final String v = cs.toString();
-
- return v;
- }
-
-
- public static String lexString(CharSequence lexical_value)
- {
- return lexical_value.toString();
- }
-
- public static String printString(String value)
- {
+ public static String printString(String value) {
return value;
}
// ======================== QName ========================
- public static QName lexQName(CharSequence charSeq, NamespaceContext nscontext)
- {
+ public static QName lexQName(CharSequence charSeq, NamespaceContext nscontext) {
String prefix, localname;
int firstcolon;
boolean hasFirstCollon = false;
- for (firstcolon = 0; firstcolon < charSeq.length(); firstcolon++)
+ for (firstcolon = 0; firstcolon < charSeq.length(); firstcolon++) {
if (charSeq.charAt(firstcolon) == NAMESPACE_SEP) {
hasFirstCollon = true;
break;
}
+ }
if (hasFirstCollon) {
prefix = charSeq.subSequence(0, firstcolon).toString();
@@ -462,8 +411,9 @@
String uri = nscontext.getNamespaceURI(prefix);
if (uri == null) {
- if (prefix != null && prefix.length() > 0)
+ if (prefix != null && prefix.length() > 0) {
throw new InvalidLexicalValueException("Can't resolve prefix: " + prefix);
+ }
uri = "";
}
@@ -472,12 +422,10 @@
}
public static QName lexQName(String xsd_qname, Collection errors,
- NamespaceContext nscontext)
- {
+ NamespaceContext nscontext) {
try {
return lexQName(xsd_qname, nscontext);
- }
- catch (InvalidLexicalValueException e) {
+ } catch (InvalidLexicalValueException e) {
errors.add(XmlError.forMessage(e.getMessage()));
final int idx = xsd_qname.indexOf(NAMESPACE_SEP);
return new QName(null, xsd_qname.substring(idx));
@@ -485,8 +433,7 @@
}
public static String printQName(QName qname, NamespaceContext nsContext,
- Collection errors)
- {
+ Collection errors) {
final String uri = qname.getNamespaceURI();
assert uri != null; //qname is not allowed to have null uri values
final String prefix;
@@ -494,7 +441,7 @@
prefix = nsContext.getPrefix(uri);
if (prefix == null) {
String msg = "NamespaceContext does not provide" +
- " prefix for namespaceURI " + uri;
+ " prefix for namespaceURI " + uri;
errors.add(XmlError.forMessage(msg));
}
} else {
@@ -506,8 +453,7 @@
public static String getQNameString(String uri,
String localpart,
- String prefix)
- {
+ String prefix) {
if (prefix != null &&
uri != null &&
uri.length() > 0 &&
@@ -519,107 +465,68 @@
}
// ======================== GDate ========================
- public static GDate lexGDate(CharSequence charSeq)
- {
+ public static GDate lexGDate(CharSequence charSeq) {
return new GDate(charSeq);
}
- public static GDate lexGDate(String xsd_gdate, Collection errors)
- {
+ public static GDate lexGDate(String xsd_gdate, Collection errors) {
try {
return lexGDate(xsd_gdate);
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
errors.add(XmlError.forMessage(e.getMessage()));
return new GDateBuilder().toGDate();
}
}
- public static String printGDate(GDate gdate, Collection errors)
- {
+ public static String printGDate(GDate gdate, Collection errors) {
return gdate.toString();
}
// ======================== dateTime ========================
- public static XmlCalendar lexDateTime(CharSequence v)
- {
+ public static XmlCalendar lexDateTime(CharSequence v) {
GDateSpecification value = getGDateValue(v, SchemaType.BTC_DATE_TIME);
return value.getCalendar();
}
- public static String printDateTime(Calendar c)
- {
+ public static String printDateTime(Calendar c) {
return printDateTime(c, SchemaType.BTC_DATE_TIME);
}
- public static String printTime(Calendar c)
- {
+ public static String printTime(Calendar c) {
return printDateTime(c, SchemaType.BTC_TIME);
}
- public static String printDate(Calendar c)
- {
+ public static String printDate(Calendar c) {
return printDateTime(c, SchemaType.BTC_DATE);
}
- public static String printDate(Date d)
- {
+ public static String printDate(Date d) {
GDateSpecification value = getGDateValue(d, SchemaType.BTC_DATE);
return value.toString();
}
- public static String printDateTime(Calendar c, int type_code)
- {
+ public static String printDateTime(Calendar c, int type_code) {
GDateSpecification value = getGDateValue(c, type_code);
return value.toString();
}
- public static String printDateTime(Date c)
- {
+ public static String printDateTime(Date c) {
GDateSpecification value = getGDateValue(c, SchemaType.BTC_DATE_TIME);
return value.toString();
}
// ======================== hexBinary ========================
- public static CharSequence printHexBinary(byte[] val)
- {
+ public static CharSequence printHexBinary(byte[] val) {
return HexBin.bytesToString(val);
}
- public static byte[] lexHexBinary(CharSequence lexical_value)
- {
- byte[] buf = HexBin.decode(lexical_value.toString().getBytes());
- if (buf != null)
- return buf;
- else
- throw new InvalidLexicalValueException("invalid hexBinary value");
- }
-
-
- // ======================== base64binary ========================
- public static CharSequence printBase64Binary(byte[] val)
- {
- final byte[] bytes = Base64.encode(val);
- return new String(bytes);
- }
-
- public static byte[] lexBase64Binary(CharSequence lexical_value)
- {
- byte[] buf = Base64.decode(lexical_value.toString().getBytes());
- if (buf != null)
- return buf;
- else
- throw new InvalidLexicalValueException("invalid base64Binary value");
- }
-
// date utils
public static GDateSpecification getGDateValue(Date d,
- int builtin_type_code)
- {
+ int builtin_type_code) {
GDateBuilder gDateBuilder = new GDateBuilder(d);
gDateBuilder.setBuiltinTypeCode(builtin_type_code);
GDate value = gDateBuilder.toGDate();
@@ -628,8 +535,7 @@
public static GDateSpecification getGDateValue(Calendar c,
- int builtin_type_code)
- {
+ int builtin_type_code) {
GDateBuilder gDateBuilder = new GDateBuilder(c);
gDateBuilder.setBuiltinTypeCode(builtin_type_code);
GDate value = gDateBuilder.toGDate();
@@ -637,16 +543,14 @@
}
public static GDateSpecification getGDateValue(CharSequence v,
- int builtin_type_code)
- {
+ int builtin_type_code) {
GDateBuilder gDateBuilder = new GDateBuilder(v);
gDateBuilder.setBuiltinTypeCode(builtin_type_code);
GDate value = gDateBuilder.toGDate();
return value;
}
- private static String trimInitialPlus(String xml)
- {
+ private static String trimInitialPlus(String xml) {
if (xml.length() > 0 && xml.charAt(0) == '+') {
return xml.substring(1);
} else {
@@ -654,11 +558,9 @@
}
}
- private static String trimTrailingZeros(String xsd_decimal)
- {
+ private static String trimTrailingZeros(String xsd_decimal) {
final int last_char_idx = xsd_decimal.length() - 1;
- if (xsd_decimal.charAt(last_char_idx) == '0')
- {
+ if (xsd_decimal.charAt(last_char_idx) == '0') {
final int last_point = xsd_decimal.lastIndexOf('.');
if (last_point >= 0) {
//find last trailing zero
@@ -674,27 +576,24 @@
return xsd_decimal;
}
- private static int parseInt(CharSequence cs)
- {
+ private static int parseInt(CharSequence cs) {
return parseIntXsdNumber(cs, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
- private static short parseShort(CharSequence cs)
- {
- return (short)parseIntXsdNumber(cs, Short.MIN_VALUE, Short.MAX_VALUE);
+ private static short parseShort(CharSequence cs) {
+ return (short) parseIntXsdNumber(cs, Short.MIN_VALUE, Short.MAX_VALUE);
}
- private static byte parseByte(CharSequence cs)
- {
- return (byte)parseIntXsdNumber(cs, Byte.MIN_VALUE, Byte.MAX_VALUE);
+ private static byte parseByte(CharSequence cs) {
+ return (byte) parseIntXsdNumber(cs, Byte.MIN_VALUE, Byte.MAX_VALUE);
}
- private static int parseIntXsdNumber(CharSequence ch, int min_value, int max_value)
- {
+ private static int parseIntXsdNumber(CharSequence ch, int min_value, int max_value) {
// int parser on a CharSequence
int length = ch.length();
- if (length < 1)
+ if (length < 1) {
throw new NumberFormatException("For input string: \"" + ch.toString() + "\"");
+ }
int sign = 1;
int result = 0;
@@ -722,11 +621,13 @@
c = ch.charAt(i + start);
int v = Character.digit(c, 10);
- if (v < 0)
+ if (v < 0) {
throw new NumberFormatException("For input string: \"" + ch.toString() + "\"");
+ }
- if (result < limit || (result==limit && v > limit2))
+ if (result < limit || (result == limit && v > limit2)) {
throw new NumberFormatException("For input string: \"" + ch.toString() + "\"");
+ }
result = result * 10 - v;
}
@@ -735,20 +636,16 @@
}
// ======================== anyURI ========================
- public static CharSequence printAnyURI(CharSequence val)
- {
- return val;
- }
/**
* Checkes the regular expression of URI, defined by RFC2369 http://www.ietf.org/rfc/rfc2396.txt Appendix B.
* Note: The whitespace normalization rule collapse must be applied priot to calling this method.
+ *
* @param lexical_value the lexical value
* @return same input value if input value is in the lexical space
* @throws InvalidLexicalValueException
*/
- public static CharSequence lexAnyURI(CharSequence lexical_value)
- {
+ public static CharSequence lexAnyURI(CharSequence lexical_value) {
/* // Reg exp from RFC2396, but it's too forgiving for XQTS
Pattern p = Pattern.compile("^([^:/?#]+:)?(//[^/?#]*)?([^?#]*)(\\?[^#]*)?(#.*)?");
Matcher m = p.matcher(lexical_value);
@@ -766,22 +663,17 @@
// Per XMLSchema spec allow spaces inside URIs
StringBuilder s = new StringBuilder(lexical_value.toString());
- for (int ic = 0; ic<URI_CHARS_TO_BE_REPLACED.length; ic++)
- {
+ for (int ic = 0; ic < URI_CHARS_TO_BE_REPLACED.length; ic++) {
int i = 0;
- while ((i = s.indexOf(URI_CHARS_TO_BE_REPLACED[ic], i)) >= 0)
- {
+ while ((i = s.indexOf(URI_CHARS_TO_BE_REPLACED[ic], i)) >= 0) {
s.replace(i, i + 1, URI_CHARS_REPLACED_WITH[ic]);
i += 3;
}
}
- try
- {
+ try {
URI.create(s.toString());
- }
- catch (IllegalArgumentException e)
- {
+ } catch (IllegalArgumentException e) {
throw new InvalidLexicalValueException("invalid anyURI value: " + lexical_value, e);
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
index afa165f..331fa60 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
@@ -15,91 +15,79 @@
package org.apache.xmlbeans.impl.values;
+import org.apache.xmlbeans.SchemaType;
+import org.apache.xmlbeans.XmlBase64Binary;
+import org.apache.xmlbeans.XmlErrorCodes;
+import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.ValidationContext;
import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem;
-import org.apache.xmlbeans.impl.util.Base64;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlErrorCodes;
-import org.apache.xmlbeans.XmlBase64Binary;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.impl.common.ValidationContext;
-import org.apache.xmlbeans.impl.common.QNameHelper;
-
+import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
-import java.io.UnsupportedEncodingException;
+import java.util.Base64;
-public abstract class JavaBase64Holder extends XmlObjectBase
-{
- public SchemaType schemaType()
- { return BuiltinSchemaTypeSystem.ST_BASE_64_BINARY; }
+public abstract class JavaBase64Holder extends XmlObjectBase {
+ public SchemaType schemaType() {
+ return BuiltinSchemaTypeSystem.ST_BASE_64_BINARY;
+ }
protected byte[] _value;
// SIMPLE VALUE ACCESSORS BELOW -------------------------------------------
// gets raw text value
- protected String compute_text(NamespaceManager nsm)
- {
- return new String(Base64.encode(_value));
+ protected String compute_text(NamespaceManager nsm) {
+ return Base64.getEncoder().encodeToString(_value);
}
- protected void set_text(String s)
- {
+
+ protected void set_text(String s) {
_hashcached = false;
- if (_validateOnSet())
+ if (_validateOnSet()) {
_value = validateLexical(s, schemaType(), _voorVc);
- else
+ } else {
_value = lex(s, _voorVc);
+ }
}
- protected void set_nil()
- {
+
+ protected void set_nil() {
_hashcached = false;
_value = null;
}
- public static byte[] lex(String v, ValidationContext c)
- {
- byte[] vBytes = null;
- try
- {
- vBytes = v.getBytes("UTF-8");
- }
- catch(UnsupportedEncodingException uee)
- {
- // should never happen - UTF-8 is always supported
- }
- final byte[] bytes = Base64.decode(vBytes);
-
- if (bytes == null)
- {
+ public static byte[] lex(String v, ValidationContext c) {
+ try {
+ byte[] vBytes = v.getBytes(StandardCharsets.UTF_8);
+ return Base64.getDecoder().decode(vBytes);
+ } catch (IllegalArgumentException e) {
// TODO - get a decent error with line numbers and such here
- c.invalid(XmlErrorCodes.BASE64BINARY, new Object[] { "not encoded properly" });
+ c.invalid(XmlErrorCodes.BASE64BINARY, new Object[]{"not encoded properly"});
+ return null;
}
-
- return bytes;
}
- public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context)
- {
+ public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) {
final byte[] bytes = lex(v, context);
- if (bytes == null) return null;
+ if (bytes == null) {
+ return null;
+ }
- if (!sType.matchPatternFacet(v))
- {
+ if (!sType.matchPatternFacet(v)) {
context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID$NO_VALUE,
- new Object[] { "base 64", QNameHelper.readable(sType) });
+ new Object[]{"base 64", QNameHelper.readable(sType)});
return null;
}
return bytes;
}
- public byte[] getByteArrayValue()
- {
+ public byte[] getByteArrayValue() {
check_dated();
- if (_value == null)
+ if (_value == null) {
return null;
+ }
byte[] result = new byte[_value.length];
System.arraycopy(_value, 0, result, 0, _value.length);
@@ -107,16 +95,14 @@
}
// setters
- protected void set_ByteArray(byte[] ba)
- {
+ protected void set_ByteArray(byte[] ba) {
_hashcached = false;
_value = new byte[ba.length];
System.arraycopy(ba, 0, _value, 0, ba.length);
}
// comparators
- protected boolean equal_to(XmlObject i)
- {
+ protected boolean equal_to(XmlObject i) {
byte[] ival = ((XmlBase64Binary) i).getByteArrayValue();
return Arrays.equals(_value, ival);
}
@@ -125,29 +111,27 @@
protected boolean _hashcached = false;
protected int hashcode = 0;
protected static MessageDigest md5;
- static
- {
- try
- {
+
+ static {
+ try {
md5 = MessageDigest.getInstance("MD5");
- }
- catch( NoSuchAlgorithmException e )
- {
+ } catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Cannot find MD5 hash Algorithm");
}
}
- protected int value_hash_code()
- {
- if( _hashcached )
+ protected int value_hash_code() {
+ if (_hashcached) {
return hashcode;
+ }
_hashcached = true;
- if( _value == null )
+ if (_value == null) {
return hashcode = 0;
+ }
byte[] res = md5.digest(_value);
- return hashcode = res[0]<<24 + res[1]<<16 + res[2]<<8 + res[3];
+ return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3];
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
index a0c026d..6e7c5e2 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
@@ -15,92 +15,80 @@
package org.apache.xmlbeans.impl.values;
-import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem;
-
-import org.apache.xmlbeans.impl.util.HexBin;
-import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.XmlErrorCodes;
import org.apache.xmlbeans.XmlHexBinary;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.impl.common.ValidationContext;
+import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.ValidationContext;
+import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem;
+import org.apache.xmlbeans.impl.util.HexBin;
-import java.security.NoSuchAlgorithmException;
+import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
-import java.io.UnsupportedEncodingException;
-public abstract class JavaHexBinaryHolder extends XmlObjectBase
-{
- public SchemaType schemaType()
- { return BuiltinSchemaTypeSystem.ST_HEX_BINARY; }
+public abstract class JavaHexBinaryHolder extends XmlObjectBase {
+ public SchemaType schemaType() {
+ return BuiltinSchemaTypeSystem.ST_HEX_BINARY;
+ }
protected byte[] _value;
// SIMPLE VALUE ACCESSORS BELOW -------------------------------------------
// gets raw text value
- protected String compute_text(NamespaceManager nsm)
- {
- return new String(HexBin.encode(_value));
+ protected String compute_text(NamespaceManager nsm) {
+ return new String(HexBin.encode(_value), StandardCharsets.ISO_8859_1);
}
- protected void set_text(String s)
- {
+
+ protected void set_text(String s) {
_hashcached = false;
- if (_validateOnSet())
+ if (_validateOnSet()) {
_value = validateLexical(s, schemaType(), _voorVc);
- else
+ } else {
_value = lex(s, _voorVc);
+ }
}
- protected void set_nil()
- {
+
+ protected void set_nil() {
_hashcached = false;
_value = null;
}
- public static byte[] lex(String v, ValidationContext context)
- {
- byte[] vBytes = null;
- try
- {
- vBytes = v.getBytes("UTF-8");
- }
- catch(UnsupportedEncodingException uee)
- {
- // should never happen - UTF-8 is always supported
- }
+ public static byte[] lex(String v, ValidationContext context) {
+ byte[] vBytes = v.getBytes(StandardCharsets.ISO_8859_1);
byte[] bytes = HexBin.decode(vBytes);
- if (bytes == null)
- {
+ if (bytes == null) {
// TODO - get a decent error with line numbers and such here
- context.invalid(XmlErrorCodes.HEXBINARY, new Object[] { "not encoded properly" });
+ context.invalid(XmlErrorCodes.HEXBINARY, new Object[]{"not encoded properly"});
}
return bytes;
}
- public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context)
- {
+ public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) {
byte[] bytes = lex(v, context);
- if (bytes == null)
+ if (bytes == null) {
return null;
+ }
- if (!sType.matchPatternFacet(v))
- {
- context.invalid( "Hex encoded data does not match pattern for " + QNameHelper.readable(sType));
+ if (!sType.matchPatternFacet(v)) {
+ context.invalid("Hex encoded data does not match pattern for " + QNameHelper.readable(sType));
return null;
}
return bytes;
}
- public byte[] getByteArrayValue()
- {
+ public byte[] getByteArrayValue() {
check_dated();
- if (_value == null)
+ if (_value == null) {
return null;
+ }
byte[] result = new byte[_value.length];
System.arraycopy(_value, 0, result, 0, _value.length);
@@ -108,16 +96,14 @@
}
// setters
- protected void set_ByteArray(byte[] ba)
- {
+ protected void set_ByteArray(byte[] ba) {
_hashcached = false;
_value = new byte[ba.length];
System.arraycopy(ba, 0, _value, 0, ba.length);
}
// comparators
- protected boolean equal_to(XmlObject i)
- {
+ protected boolean equal_to(XmlObject i) {
byte[] ival = ((XmlHexBinary) i).getByteArrayValue();
return Arrays.equals(_value, ival);
}
@@ -126,30 +112,28 @@
protected boolean _hashcached = false;
protected int hashcode = 0;
protected static MessageDigest md5;
- static
- {
- try
- {
+
+ static {
+ try {
md5 = MessageDigest.getInstance("MD5");
- }
- catch( NoSuchAlgorithmException e )
- {
+ } catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Cannot find MD5 hash Algorithm");
}
}
- protected int value_hash_code()
- {
- if( _hashcached )
+ protected int value_hash_code() {
+ if (_hashcached) {
return hashcode;
+ }
_hashcached = true;
- if( _value == null )
+ if (_value == null) {
return hashcode = 0;
+ }
byte[] res = md5.digest(_value);
- return hashcode = res[0]<<24 + res[1]<<16 + res[2]<<8 + res[3];
+ return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3];
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java b/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java
index bf80809..a842dbe 100644
--- a/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java
+++ b/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java
@@ -17,67 +17,34 @@
/*
* TODO:
-* Comment on enumerations?
-* Comment on facets?
-* Have a verbose option?
-* Have a sample data option, would create valid instance with sample data?
-* Add the pattern facet; this is tricky, considering the relationship with length
-*/
+ * Comment on enumerations?
+ * Comment on facets?
+ * Have a verbose option?
+ * Have a sample data option, would create valid instance with sample data?
+ * Add the pattern facet; this is tricky, considering the relationship with length
+ */
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.SchemaParticle;
-import org.apache.xmlbeans.SchemaLocalElement;
-import org.apache.xmlbeans.SchemaProperty;
-import org.apache.xmlbeans.GDuration;
-import org.apache.xmlbeans.GDurationBuilder;
-import org.apache.xmlbeans.GDate;
-import org.apache.xmlbeans.GDateBuilder;
-import org.apache.xmlbeans.XmlAnySimpleType;
-import org.apache.xmlbeans.SimpleValue;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlInteger;
-import org.apache.xmlbeans.XmlDate;
-import org.apache.xmlbeans.XmlDateTime;
-import org.apache.xmlbeans.XmlTime;
-import org.apache.xmlbeans.XmlGYear;
-import org.apache.xmlbeans.XmlGYearMonth;
-import org.apache.xmlbeans.XmlGMonth;
-import org.apache.xmlbeans.XmlGMonthDay;
-import org.apache.xmlbeans.XmlGDay;
-import org.apache.xmlbeans.XmlDecimal;
-import org.apache.xmlbeans.XmlDuration;
-import org.apache.xmlbeans.soap.SchemaWSDLArrayType;
-import org.apache.xmlbeans.soap.SOAPArrayType;
-import org.apache.xmlbeans.impl.util.Base64;
+import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.util.HexBin;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Random;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Arrays;
+import org.apache.xmlbeans.soap.SOAPArrayType;
+import org.apache.xmlbeans.soap.SchemaWSDLArrayType;
import javax.xml.namespace.QName;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
-public class SampleXmlUtil
-{
+public class SampleXmlUtil {
private boolean _soapEnc;
private static final int MAX_ELEMENTS = 1000;
private int _nElements;
- private SampleXmlUtil(boolean soapEnc)
- {
+ private SampleXmlUtil(boolean soapEnc) {
_soapEnc = soapEnc;
}
- public static String createSampleForType(SchemaType sType)
- {
+ public static String createSampleForType(SchemaType sType) {
XmlObject object = XmlObject.Factory.newInstance();
XmlCursor cursor = object.newCursor();
// Skip the document node
@@ -106,144 +73,127 @@
* After:
* <theElement><lots of stuff/>^</theElement>
*/
- private void createSampleForType(SchemaType stype, XmlCursor xmlc)
- {
- if (_typeStack.contains( stype ))
+ private void createSampleForType(SchemaType stype, XmlCursor xmlc) {
+ if (_typeStack.contains(stype)) {
return;
+ }
- _typeStack.add( stype );
-
- try
- {
- if (stype.isSimpleType() || stype.isURType())
- {
+ _typeStack.add(stype);
+
+ try {
+ if (stype.isSimpleType() || stype.isURType()) {
processSimpleType(stype, xmlc);
return;
}
-
+
// complex Type
// <theElement>^</theElement>
processAttributes(stype, xmlc);
-
+
// <theElement attri1="string">^</theElement>
- switch (stype.getContentType())
- {
- case SchemaType.NOT_COMPLEX_TYPE :
- case SchemaType.EMPTY_CONTENT :
+ switch (stype.getContentType()) {
+ case SchemaType.NOT_COMPLEX_TYPE:
+ case SchemaType.EMPTY_CONTENT:
// noop
break;
- case SchemaType.SIMPLE_CONTENT :
- {
- processSimpleType(stype, xmlc);
- }
- break;
- case SchemaType.MIXED_CONTENT :
+ case SchemaType.SIMPLE_CONTENT: {
+ processSimpleType(stype, xmlc);
+ }
+ break;
+ case SchemaType.MIXED_CONTENT:
xmlc.insertChars(pick(WORDS) + " ");
- if (stype.getContentModel() != null)
- {
+ if (stype.getContentModel() != null) {
processParticle(stype.getContentModel(), xmlc, true);
}
xmlc.insertChars(pick(WORDS));
break;
- case SchemaType.ELEMENT_CONTENT :
- if (stype.getContentModel() != null)
- {
+ case SchemaType.ELEMENT_CONTENT:
+ if (stype.getContentModel() != null) {
processParticle(stype.getContentModel(), xmlc, false);
}
break;
}
- }
- finally
- {
- _typeStack.remove( _typeStack.size() - 1 );
+ } finally {
+ _typeStack.remove(_typeStack.size() - 1);
}
}
- private void processSimpleType(SchemaType stype, XmlCursor xmlc)
- {
+ private void processSimpleType(SchemaType stype, XmlCursor xmlc) {
String sample = sampleDataForSimpleType(stype);
xmlc.insertChars(sample);
}
-
- private String sampleDataForSimpleType(SchemaType sType)
- {
- if (XmlObject.type.equals(sType))
+
+ private String sampleDataForSimpleType(SchemaType sType) {
+ if (XmlObject.type.equals(sType)) {
return "anyType";
-
- if (XmlAnySimpleType.type.equals(sType))
+ }
+
+ if (XmlAnySimpleType.type.equals(sType)) {
return "anySimpleType";
-
- if (sType.getSimpleVariety() == SchemaType.LIST)
- {
+ }
+
+ if (sType.getSimpleVariety() == SchemaType.LIST) {
SchemaType itemType = sType.getListItemType();
StringBuilder sb = new StringBuilder();
int length = pickLength(sType);
- if (length > 0)
+ if (length > 0) {
sb.append(sampleDataForSimpleType(itemType));
- for (int i = 1; i < length; i += 1)
- {
+ }
+ for (int i = 1; i < length; i += 1) {
sb.append(' ');
sb.append(sampleDataForSimpleType(itemType));
}
- return sb.toString();
+ return sb.toString();
}
-
- if (sType.getSimpleVariety() == SchemaType.UNION)
- {
+
+ if (sType.getSimpleVariety() == SchemaType.UNION) {
SchemaType[] possibleTypes = sType.getUnionConstituentTypes();
- if (possibleTypes.length == 0)
+ if (possibleTypes.length == 0) {
return "";
+ }
return sampleDataForSimpleType(possibleTypes[pick(possibleTypes.length)]);
}
-
+
XmlAnySimpleType[] enumValues = sType.getEnumerationValues();
- if (enumValues != null && enumValues.length > 0)
- {
+ if (enumValues != null && enumValues.length > 0) {
return enumValues[pick(enumValues.length)].getStringValue();
}
-
- switch (sType.getPrimitiveType().getBuiltinTypeCode())
- {
+
+ switch (sType.getPrimitiveType().getBuiltinTypeCode()) {
default:
case SchemaType.BTC_NOT_BUILTIN:
return "";
-
+
case SchemaType.BTC_ANY_TYPE:
case SchemaType.BTC_ANY_SIMPLE:
return "anything";
-
+
case SchemaType.BTC_BOOLEAN:
return pick(2) == 0 ? "true" : "false";
-
- case SchemaType.BTC_BASE_64_BINARY:
- {
- String result = null;
- try
- { result = new String(Base64.encode(formatToLength(pick(WORDS), sType).getBytes("utf-8"))); }
- catch (java.io.UnsupportedEncodingException e)
- { /* Can't possibly happen */ }
- return result;
+
+ case SchemaType.BTC_BASE_64_BINARY: {
+ byte[] v = formatToLength(pick(WORDS), sType).getBytes(StandardCharsets.UTF_8);
+ return Base64.getEncoder().encodeToString(v);
}
-
+
case SchemaType.BTC_HEX_BINARY:
return HexBin.encode(formatToLength(pick(WORDS), sType));
-
+
case SchemaType.BTC_ANY_URI:
return formatToLength("http://www." + pick(DNS1) + "." + pick(DNS2) + "/" + pick(WORDS) + "/" + pick(WORDS), sType);
-
+
case SchemaType.BTC_QNAME:
return formatToLength("qname", sType);
-
+
case SchemaType.BTC_NOTATION:
return formatToLength("notation", sType);
-
+
case SchemaType.BTC_FLOAT:
return "1.5E2";
case SchemaType.BTC_DOUBLE:
return "1.051732E7";
case SchemaType.BTC_DECIMAL:
- switch (closestBuiltin(sType).getBuiltinTypeCode())
- {
+ switch (closestBuiltin(sType).getBuiltinTypeCode()) {
case SchemaType.BTC_SHORT:
return formatDecimal("1", sType);
case SchemaType.BTC_UNSIGNED_SHORT:
@@ -274,32 +224,30 @@
case SchemaType.BTC_DECIMAL:
return formatDecimal("1000.00", sType);
}
-
- case SchemaType.BTC_STRING:
- {
- String result;
- switch (closestBuiltin(sType).getBuiltinTypeCode())
- {
- case SchemaType.BTC_STRING:
- case SchemaType.BTC_NORMALIZED_STRING:
- result = "string";
- break;
-
- case SchemaType.BTC_TOKEN:
- result = "token";
- break;
-
- default:
- result = "string";
- break;
- }
-
- return formatToLength(result, sType);
+
+ case SchemaType.BTC_STRING: {
+ String result;
+ switch (closestBuiltin(sType).getBuiltinTypeCode()) {
+ case SchemaType.BTC_STRING:
+ case SchemaType.BTC_NORMALIZED_STRING:
+ result = "string";
+ break;
+
+ case SchemaType.BTC_TOKEN:
+ result = "token";
+ break;
+
+ default:
+ result = "string";
+ break;
}
+ return formatToLength(result, sType);
+ }
+
case SchemaType.BTC_DURATION:
return formatDuration(sType);
-
+
case SchemaType.BTC_DATE_TIME:
case SchemaType.BTC_TIME:
case SchemaType.BTC_DATE:
@@ -311,100 +259,102 @@
return formatDate(sType);
}
}
-
+
// a bit from the Aenid
public static final String[] WORDS = new String[]
- {
- "ipsa", "iovis", "rapidum", "iaculata", "e", "nubibus", "ignem",
- "disiecitque", "rates", "evertitque", "aequora", "ventis",
- "illum", "exspirantem", "transfixo", "pectore", "flammas",
- "turbine", "corripuit", "scopuloque", "infixit", "acuto",
- "ast", "ego", "quae", "divum", "incedo", "regina", "iovisque",
- "et", "soror", "et", "coniunx", "una", "cum", "gente", "tot", "annos",
- "bella", "gero", "et", "quisquam", "numen", "iunonis", "adorat",
- "praeterea", "aut", "supplex", "aris", "imponet", "honorem",
- "talia", "flammato", "secum", "dea", "corde", "volutans",
- "nimborum", "in", "patriam", "loca", "feta", "furentibus", "austris",
- "aeoliam", "venit", "hic", "vasto", "rex", "aeolus", "antro",
- "luctantis", "ventos", "tempestatesque", "sonoras",
- "imperio", "premit", "ac", "vinclis", "et", "carcere", "frenat",
- "illi", "indignantes", "magno", "cum", "murmure", "montis",
- "circum", "claustra", "fremunt", "celsa", "sedet", "aeolus", "arce",
- "sceptra", "tenens", "mollitque", "animos", "et", "temperat", "iras",
- "ni", "faciat", "maria", "ac", "terras", "caelumque", "profundum",
- "quippe", "ferant", "rapidi", "secum", "verrantque", "per", "auras",
- "sed", "pater", "omnipotens", "speluncis", "abdidit", "atris",
- "hoc", "metuens", "molemque", "et", "montis", "insuper", "altos",
- "imposuit", "regemque", "dedit", "qui", "foedere", "certo",
- "et", "premere", "et", "laxas", "sciret", "dare", "iussus", "habenas",
- };
-
-
-
- private static final String[] DNS1 = new String[] { "corp", "your", "my", "sample", "company", "test", "any" };
- private static final String[] DNS2 = new String[] { "com", "org", "com", "gov", "org", "com", "org", "com", "edu" };
-
- private int pick(int n)
- {
+ {
+ "ipsa", "iovis", "rapidum", "iaculata", "e", "nubibus", "ignem",
+ "disiecitque", "rates", "evertitque", "aequora", "ventis",
+ "illum", "exspirantem", "transfixo", "pectore", "flammas",
+ "turbine", "corripuit", "scopuloque", "infixit", "acuto",
+ "ast", "ego", "quae", "divum", "incedo", "regina", "iovisque",
+ "et", "soror", "et", "coniunx", "una", "cum", "gente", "tot", "annos",
+ "bella", "gero", "et", "quisquam", "numen", "iunonis", "adorat",
+ "praeterea", "aut", "supplex", "aris", "imponet", "honorem",
+ "talia", "flammato", "secum", "dea", "corde", "volutans",
+ "nimborum", "in", "patriam", "loca", "feta", "furentibus", "austris",
+ "aeoliam", "venit", "hic", "vasto", "rex", "aeolus", "antro",
+ "luctantis", "ventos", "tempestatesque", "sonoras",
+ "imperio", "premit", "ac", "vinclis", "et", "carcere", "frenat",
+ "illi", "indignantes", "magno", "cum", "murmure", "montis",
+ "circum", "claustra", "fremunt", "celsa", "sedet", "aeolus", "arce",
+ "sceptra", "tenens", "mollitque", "animos", "et", "temperat", "iras",
+ "ni", "faciat", "maria", "ac", "terras", "caelumque", "profundum",
+ "quippe", "ferant", "rapidi", "secum", "verrantque", "per", "auras",
+ "sed", "pater", "omnipotens", "speluncis", "abdidit", "atris",
+ "hoc", "metuens", "molemque", "et", "montis", "insuper", "altos",
+ "imposuit", "regemque", "dedit", "qui", "foedere", "certo",
+ "et", "premere", "et", "laxas", "sciret", "dare", "iussus", "habenas",
+ };
+
+
+ private static final String[] DNS1 = new String[]{"corp", "your", "my", "sample", "company", "test", "any"};
+ private static final String[] DNS2 = new String[]{"com", "org", "com", "gov", "org", "com", "org", "com", "edu"};
+
+ private int pick(int n) {
return _picker.nextInt(n);
}
-
- private String pick(String[] a)
- {
+
+ private String pick(String[] a) {
return a[pick(a.length)];
}
-
- private String pick(String[] a, int count)
- {
- if (count <= 0)
+
+ private String pick(String[] a, int count) {
+ if (count <= 0) {
return "";
-
+ }
+
int i = pick(a.length);
StringBuilder sb = new StringBuilder(a[i]);
- while (count-- > 0)
- {
+ while (count-- > 0) {
i += 1;
- if (i >= a.length)
+ if (i >= a.length) {
i = 0;
+ }
sb.append(' ');
sb.append(a[i]);
}
return sb.toString();
}
-
- private String pickDigits(int digits)
- {
+
+ private String pickDigits(int digits) {
StringBuilder sb = new StringBuilder();
- while (digits-- > 0)
+ while (digits-- > 0) {
sb.append(Integer.toString(pick(10)));
+ }
return sb.toString();
}
- private int pickLength(SchemaType sType)
- {
+ private int pickLength(SchemaType sType) {
XmlInteger length = (XmlInteger) sType.getFacet(SchemaType.FACET_LENGTH);
- if (length != null)
+ if (length != null) {
return length.getBigIntegerValue().intValue();
- XmlInteger min = (XmlInteger) sType.getFacet(SchemaType.FACET_MIN_LENGTH);
- XmlInteger max = (XmlInteger) sType.getFacet(SchemaType.FACET_MAX_LENGTH);
+ }
+ XmlInteger min = (XmlInteger) sType.getFacet(SchemaType.FACET_MIN_LENGTH);
+ XmlInteger max = (XmlInteger) sType.getFacet(SchemaType.FACET_MAX_LENGTH);
int minInt, maxInt;
- if (min == null)
+ if (min == null) {
minInt = 0;
- else
+ } else {
minInt = min.getBigIntegerValue().intValue();
- if (max == null)
+ }
+ if (max == null) {
maxInt = Integer.MAX_VALUE;
- else
+ } else {
maxInt = max.getBigIntegerValue().intValue();
+ }
// We try to keep the length of the array within reasonable limits,
// at least 1 item and at most 3 if possible
- if (minInt == 0 && maxInt >= 1)
+ if (minInt == 0 && maxInt >= 1) {
minInt = 1;
- if (maxInt > minInt + 2)
+ }
+ if (maxInt > minInt + 2) {
maxInt = minInt + 2;
- if (maxInt < minInt)
+ }
+ if (maxInt < minInt) {
maxInt = minInt;
- return minInt + pick(maxInt-minInt);
+ }
+ return minInt + pick(maxInt - minInt);
}
/**
@@ -412,38 +362,36 @@
* - append the source string to itself as necessary to pass the minLength;
* - truncate the result of previous step, if necessary, to keep it within minLength.
*/
- private String formatToLength(String s, SchemaType sType)
- {
+ private String formatToLength(String s, SchemaType sType) {
String result = s;
- try
- {
- SimpleValue min = (SimpleValue)sType.getFacet(SchemaType.FACET_LENGTH);
- if (min == null)
- min = (SimpleValue)sType.getFacet(SchemaType.FACET_MIN_LENGTH);
- if (min != null)
- {
+ try {
+ SimpleValue min = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH);
+ if (min == null) {
+ min = (SimpleValue) sType.getFacet(SchemaType.FACET_MIN_LENGTH);
+ }
+ if (min != null) {
int len = min.getIntValue();
- while (result.length() < len)
+ while (result.length() < len) {
result = result + result;
+ }
}
- SimpleValue max = (SimpleValue)sType.getFacet(SchemaType.FACET_LENGTH);
- if (max == null)
- max = (SimpleValue)sType.getFacet(SchemaType.FACET_MAX_LENGTH);
- if (max != null)
- {
+ SimpleValue max = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH);
+ if (max == null) {
+ max = (SimpleValue) sType.getFacet(SchemaType.FACET_MAX_LENGTH);
+ }
+ if (max != null) {
int len = max.getIntValue();
- if (result.length() > len)
+ if (result.length() > len) {
result = result.substring(0, len);
+ }
}
- }
- catch (Exception e) // intValue can be out of range
+ } catch (Exception e) // intValue can be out of range
{
}
return result;
}
- private String formatDecimal(String start, SchemaType sType)
- {
+ private String formatDecimal(String start, SchemaType sType) {
BigDecimal result = new BigDecimal(start);
XmlDecimal xmlD;
xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
@@ -452,43 +400,37 @@
BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
boolean minInclusive = true, maxInclusive = true;
xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (xmlD != null)
- {
+ if (xmlD != null) {
BigDecimal minExcl = xmlD.getBigDecimalValue();
- if (min == null || min.compareTo(minExcl) < 0)
- {
+ if (min == null || min.compareTo(minExcl) < 0) {
min = minExcl;
minInclusive = false;
}
}
xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (xmlD != null)
- {
+ if (xmlD != null) {
BigDecimal maxExcl = xmlD.getBigDecimalValue();
- if (max == null || max.compareTo(maxExcl) > 0)
- {
+ if (max == null || max.compareTo(maxExcl) > 0) {
max = maxExcl;
maxInclusive = false;
}
}
xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
int totalDigits = -1;
- if (xmlD != null)
- {
+ if (xmlD != null) {
totalDigits = xmlD.getBigDecimalValue().intValue();
StringBuilder sb = new StringBuilder(totalDigits);
- for (int i = 0; i < totalDigits; i++)
+ for (int i = 0; i < totalDigits; i++) {
sb.append('9');
+ }
BigDecimal digitsLimit = new BigDecimal(sb.toString());
- if (max != null && max.compareTo(digitsLimit) > 0)
- {
+ if (max != null && max.compareTo(digitsLimit) > 0) {
max = digitsLimit;
maxInclusive = true;
}
digitsLimit = digitsLimit.negate();
- if (min != null && min.compareTo(digitsLimit) < 0)
- {
+ if (min != null && min.compareTo(digitsLimit) < 0) {
min = digitsLimit;
minInclusive = true;
}
@@ -503,45 +445,39 @@
xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
int fractionDigits = -1;
BigDecimal increment;
- if (xmlD == null)
+ if (xmlD == null) {
increment = new BigDecimal(1);
- else
- {
+ } else {
fractionDigits = xmlD.getBigDecimalValue().intValue();
- if (fractionDigits > 0)
- {
+ if (fractionDigits > 0) {
StringBuilder sb = new StringBuilder("0.");
- for (int i = 1; i < fractionDigits; i++)
+ for (int i = 1; i < fractionDigits; i++) {
sb.append('0');
+ }
sb.append('1');
increment = new BigDecimal(sb.toString());
- }
- else
+ } else {
increment = new BigDecimal(1.0);
+ }
}
- if (minOk && maxOk)
- {
- // OK
- }
- else if (minOk && !maxOk)
- {
+ if (minOk && maxOk) {
+ // OK
+ } else if (minOk && !maxOk) {
// TOO BIG
- if (maxInclusive)
+ if (maxInclusive) {
result = max;
- else
+ } else {
result = max.subtract(increment);
- }
- else if (!minOk && maxOk)
- {
+ }
+ } else if (!minOk && maxOk) {
// TOO SMALL
- if (minInclusive)
+ if (minInclusive) {
result = min;
- else
+ } else {
result = min.add(increment);
- }
- else
- {
+ }
+ } else {
// MIN > MAX!!
}
@@ -549,42 +485,48 @@
// Adjust the scale according to the totalDigits and fractionDigits
int digits = 0;
BigDecimal ONE = new BigDecimal(BigInteger.ONE);
- for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
+ for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) {
n = n.movePointLeft(1);
+ }
- if (fractionDigits > 0)
- if (totalDigits >= 0)
+ if (fractionDigits > 0) {
+ if (totalDigits >= 0) {
result = result.setScale(Math.max(fractionDigits, totalDigits - digits));
- else
+ } else {
result = result.setScale(fractionDigits);
- else if (fractionDigits == 0)
+ }
+ } else if (fractionDigits == 0) {
result = result.setScale(0);
+ }
return result.toString();
}
- private String formatDuration(SchemaType sType)
- {
+ private String formatDuration(SchemaType sType) {
XmlDuration d =
(XmlDuration) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
GDuration minInclusive = null;
- if (d != null)
+ if (d != null) {
minInclusive = d.getGDurationValue();
+ }
d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
GDuration maxInclusive = null;
- if (d != null)
+ if (d != null) {
maxInclusive = d.getGDurationValue();
+ }
d = (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
GDuration minExclusive = null;
- if (d != null)
+ if (d != null) {
minExclusive = d.getGDurationValue();
+ }
d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
GDuration maxExclusive = null;
- if (d != null)
+ if (d != null) {
maxExclusive = d.getGDurationValue();
+ }
GDurationBuilder gdurb = new GDurationBuilder();
BigInteger min, max;
@@ -599,287 +541,339 @@
// Minutes
// Seconds
// Fractions
- if (minInclusive != null)
- {
- if (gdurb.getYear() < minInclusive.getYear())
+ if (minInclusive != null) {
+ if (gdurb.getYear() < minInclusive.getYear()) {
gdurb.setYear(minInclusive.getYear());
- if (gdurb.getMonth() < minInclusive.getMonth())
+ }
+ if (gdurb.getMonth() < minInclusive.getMonth()) {
gdurb.setMonth(minInclusive.getMonth());
- if (gdurb.getDay() < minInclusive.getDay())
+ }
+ if (gdurb.getDay() < minInclusive.getDay()) {
gdurb.setDay(minInclusive.getDay());
- if (gdurb.getHour() < minInclusive.getHour())
+ }
+ if (gdurb.getHour() < minInclusive.getHour()) {
gdurb.setHour(minInclusive.getHour());
- if (gdurb.getMinute() < minInclusive.getMinute())
+ }
+ if (gdurb.getMinute() < minInclusive.getMinute()) {
gdurb.setMinute(minInclusive.getMinute());
- if (gdurb.getSecond() < minInclusive.getSecond())
+ }
+ if (gdurb.getSecond() < minInclusive.getSecond()) {
gdurb.setSecond(minInclusive.getSecond());
- if (gdurb.getFraction().compareTo(minInclusive.getFraction()) < 0)
+ }
+ if (gdurb.getFraction().compareTo(minInclusive.getFraction()) < 0) {
gdurb.setFraction(minInclusive.getFraction());
+ }
}
- if (maxInclusive != null)
- {
- if (gdurb.getYear() > maxInclusive.getYear())
+ if (maxInclusive != null) {
+ if (gdurb.getYear() > maxInclusive.getYear()) {
gdurb.setYear(maxInclusive.getYear());
- if (gdurb.getMonth() > maxInclusive.getMonth())
+ }
+ if (gdurb.getMonth() > maxInclusive.getMonth()) {
gdurb.setMonth(maxInclusive.getMonth());
- if (gdurb.getDay() > maxInclusive.getDay())
+ }
+ if (gdurb.getDay() > maxInclusive.getDay()) {
gdurb.setDay(maxInclusive.getDay());
- if (gdurb.getHour() > maxInclusive.getHour())
+ }
+ if (gdurb.getHour() > maxInclusive.getHour()) {
gdurb.setHour(maxInclusive.getHour());
- if (gdurb.getMinute() > maxInclusive.getMinute())
+ }
+ if (gdurb.getMinute() > maxInclusive.getMinute()) {
gdurb.setMinute(maxInclusive.getMinute());
- if (gdurb.getSecond() > maxInclusive.getSecond())
+ }
+ if (gdurb.getSecond() > maxInclusive.getSecond()) {
gdurb.setSecond(maxInclusive.getSecond());
- if (gdurb.getFraction().compareTo(maxInclusive.getFraction()) > 0)
+ }
+ if (gdurb.getFraction().compareTo(maxInclusive.getFraction()) > 0) {
gdurb.setFraction(maxInclusive.getFraction());
+ }
}
- if (minExclusive != null)
- {
- if (gdurb.getYear() <= minExclusive.getYear())
- gdurb.setYear(minExclusive.getYear()+1);
- if (gdurb.getMonth() <= minExclusive.getMonth())
- gdurb.setMonth(minExclusive.getMonth()+1);
- if (gdurb.getDay() <= minExclusive.getDay())
- gdurb.setDay(minExclusive.getDay()+1);
- if (gdurb.getHour() <= minExclusive.getHour())
- gdurb.setHour(minExclusive.getHour()+1);
- if (gdurb.getMinute() <= minExclusive.getMinute())
- gdurb.setMinute(minExclusive.getMinute()+1);
- if (gdurb.getSecond() <= minExclusive.getSecond())
- gdurb.setSecond(minExclusive.getSecond()+1);
- if (gdurb.getFraction().compareTo(minExclusive.getFraction()) <= 0)
+ if (minExclusive != null) {
+ if (gdurb.getYear() <= minExclusive.getYear()) {
+ gdurb.setYear(minExclusive.getYear() + 1);
+ }
+ if (gdurb.getMonth() <= minExclusive.getMonth()) {
+ gdurb.setMonth(minExclusive.getMonth() + 1);
+ }
+ if (gdurb.getDay() <= minExclusive.getDay()) {
+ gdurb.setDay(minExclusive.getDay() + 1);
+ }
+ if (gdurb.getHour() <= minExclusive.getHour()) {
+ gdurb.setHour(minExclusive.getHour() + 1);
+ }
+ if (gdurb.getMinute() <= minExclusive.getMinute()) {
+ gdurb.setMinute(minExclusive.getMinute() + 1);
+ }
+ if (gdurb.getSecond() <= minExclusive.getSecond()) {
+ gdurb.setSecond(minExclusive.getSecond() + 1);
+ }
+ if (gdurb.getFraction().compareTo(minExclusive.getFraction()) <= 0) {
gdurb.setFraction(minExclusive.getFraction().add(new BigDecimal(0.001)));
+ }
}
- if (maxExclusive != null)
- {
- if (gdurb.getYear() > maxExclusive.getYear())
+ if (maxExclusive != null) {
+ if (gdurb.getYear() > maxExclusive.getYear()) {
gdurb.setYear(maxExclusive.getYear());
- if (gdurb.getMonth() > maxExclusive.getMonth())
+ }
+ if (gdurb.getMonth() > maxExclusive.getMonth()) {
gdurb.setMonth(maxExclusive.getMonth());
- if (gdurb.getDay() > maxExclusive.getDay())
+ }
+ if (gdurb.getDay() > maxExclusive.getDay()) {
gdurb.setDay(maxExclusive.getDay());
- if (gdurb.getHour() > maxExclusive.getHour())
+ }
+ if (gdurb.getHour() > maxExclusive.getHour()) {
gdurb.setHour(maxExclusive.getHour());
- if (gdurb.getMinute() > maxExclusive.getMinute())
+ }
+ if (gdurb.getMinute() > maxExclusive.getMinute()) {
gdurb.setMinute(maxExclusive.getMinute());
- if (gdurb.getSecond() > maxExclusive.getSecond())
+ }
+ if (gdurb.getSecond() > maxExclusive.getSecond()) {
gdurb.setSecond(maxExclusive.getSecond());
- if (gdurb.getFraction().compareTo(maxExclusive.getFraction()) > 0)
+ }
+ if (gdurb.getFraction().compareTo(maxExclusive.getFraction()) > 0) {
gdurb.setFraction(maxExclusive.getFraction());
+ }
}
gdurb.normalize();
return gdurb.toString();
}
- private String formatDate(SchemaType sType)
- {
+ private String formatDate(SchemaType sType) {
GDateBuilder gdateb = new GDateBuilder(new Date(1000L * pick(365 * 24 * 60 * 60) + (30L + pick(20)) * 365 * 24 * 60 * 60 * 1000));
GDate min = null, max = null;
GDate temp;
// Find the min and the max according to the type
- switch (sType.getPrimitiveType().getBuiltinTypeCode())
- {
- case SchemaType.BTC_DATE_TIME:
- {
+ switch (sType.getPrimitiveType().getBuiltinTypeCode()) {
+ case SchemaType.BTC_DATE_TIME: {
XmlDateTime x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_TIME:
- {
+ case SchemaType.BTC_TIME: {
XmlTime x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_DATE:
- {
+ case SchemaType.BTC_DATE: {
XmlDate x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_G_YEAR_MONTH:
- {
+ case SchemaType.BTC_G_YEAR_MONTH: {
XmlGYearMonth x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_G_YEAR:
- {
+ case SchemaType.BTC_G_YEAR: {
XmlGYear x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_G_MONTH_DAY:
- {
+ case SchemaType.BTC_G_MONTH_DAY: {
XmlGMonthDay x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_G_DAY:
- {
+ case SchemaType.BTC_G_DAY: {
XmlGDay x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
- case SchemaType.BTC_G_MONTH:
- {
+ case SchemaType.BTC_G_MONTH: {
XmlGMonth x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
- if (x != null)
+ if (x != null) {
min = x.getGDateValue();
+ }
x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
- if (x != null)
- if (min == null || min.compareToGDate(x.getGDateValue()) <= 0)
+ if (x != null) {
+ if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) {
min = x.getGDateValue();
+ }
+ }
x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
- if (x != null)
+ if (x != null) {
max = x.getGDateValue();
+ }
x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
- if (x != null)
- if (max == null || max.compareToGDate(x.getGDateValue()) >= 0)
+ if (x != null) {
+ if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) {
max = x.getGDateValue();
+ }
+ }
break;
}
}
- if (min != null && max == null)
- {
- if (min.compareToGDate(gdateb) >= 0)
- {
+ if (min != null && max == null) {
+ if (min.compareToGDate(gdateb) >= 0) {
// Reset the date to min + (1-8) hours
Calendar c = gdateb.getCalendar();
c.add(Calendar.HOUR_OF_DAY, pick(8));
gdateb = new GDateBuilder(c);
}
- }
- else if (min == null && max != null)
- {
- if (max.compareToGDate(gdateb) <= 0)
- {
+ } else if (min == null && max != null) {
+ if (max.compareToGDate(gdateb) <= 0) {
// Reset the date to max - (1-8) hours
Calendar c = gdateb.getCalendar();
- c.add(Calendar.HOUR_OF_DAY, 0-pick(8));
+ c.add(Calendar.HOUR_OF_DAY, 0 - pick(8));
gdateb = new GDateBuilder(c);
}
- }
- else if (min != null && max != null)
- {
- if (min.compareToGDate(gdateb) >= 0 || max.compareToGDate(gdateb) <= 0)
- {
+ } else if (min != null && max != null) {
+ if (min.compareToGDate(gdateb) >= 0 || max.compareToGDate(gdateb) <= 0) {
// Find a date between the two
Calendar c = min.getCalendar();
Calendar cmax = max.getCalendar();
c.add(Calendar.HOUR_OF_DAY, 1);
- if (c.after(cmax))
- {
+ if (c.after(cmax)) {
c.add(Calendar.HOUR_OF_DAY, -1);
c.add(Calendar.MINUTE, 1);
- if (c.after(cmax))
- {
+ if (c.after(cmax)) {
c.add(Calendar.MINUTE, -1);
c.add(Calendar.SECOND, 1);
- if (c.after(cmax))
- {
+ if (c.after(cmax)) {
c.add(Calendar.SECOND, -1);
c.add(Calendar.MILLISECOND, 1);
- if (c.after(cmax))
+ if (c.after(cmax)) {
c.add(Calendar.MILLISECOND, -1);
+ }
}
}
}
@@ -888,35 +882,32 @@
}
gdateb.setBuiltinTypeCode(sType.getPrimitiveType().getBuiltinTypeCode());
- if (pick(2) == 0)
+ if (pick(2) == 0) {
gdateb.clearTimeZone();
+ }
return gdateb.toString();
}
- private SchemaType closestBuiltin(SchemaType sType)
- {
- while (!sType.isBuiltinType())
+ private SchemaType closestBuiltin(SchemaType sType) {
+ while (!sType.isBuiltinType()) {
sType = sType.getBaseType();
+ }
return sType;
}
/**
* Cracks a combined QName of the form URL:localname
*/
- public static QName crackQName(String qName)
- {
+ public static QName crackQName(String qName) {
String ns;
String name;
- int index = qName.lastIndexOf( ':' );
- if (index >= 0)
- {
- ns = qName.substring( 0, index );
- name = qName.substring( index + 1);
- }
- else
- {
- ns = "";
+ int index = qName.lastIndexOf(':');
+ if (index >= 0) {
+ ns = qName.substring(0, index);
+ name = qName.substring(index + 1);
+ } else {
+ ns = "";
name = qName;
}
@@ -931,66 +922,61 @@
* After this call:
* <<outer><foo/><bar/>som text<etc/>^</outer>
*/
- private void processParticle(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processParticle(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
int loop = determineMinMaxForSample(sp, xmlc);
- while (loop-- > 0)
- {
- switch (sp.getParticleType())
- {
- case (SchemaParticle.ELEMENT) :
+ while (loop-- > 0) {
+ switch (sp.getParticleType()) {
+ case (SchemaParticle.ELEMENT):
processElement(sp, xmlc, mixed);
break;
- case (SchemaParticle.SEQUENCE) :
+ case (SchemaParticle.SEQUENCE):
processSequence(sp, xmlc, mixed);
break;
- case (SchemaParticle.CHOICE) :
+ case (SchemaParticle.CHOICE):
processChoice(sp, xmlc, mixed);
break;
- case (SchemaParticle.ALL) :
+ case (SchemaParticle.ALL):
processAll(sp, xmlc, mixed);
break;
- case (SchemaParticle.WILDCARD) :
+ case (SchemaParticle.WILDCARD):
processWildCard(sp, xmlc, mixed);
break;
- default :
+ default:
// throw new Exception("No Match on Schema Particle Type: " + String.valueOf(sp.getParticleType()));
}
}
}
- private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc)
- {
+ private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc) {
int minOccurs = sp.getIntMinOccurs();
int maxOccurs = sp.getIntMaxOccurs();
-
- if (minOccurs == maxOccurs)
+
+ if (minOccurs == maxOccurs) {
return minOccurs;
-
+ }
+
int result = minOccurs;
- if (result == 0 && _nElements < MAX_ELEMENTS)
+ if (result == 0 && _nElements < MAX_ELEMENTS) {
result = 1;
-
- if (sp.getParticleType() != SchemaParticle.ELEMENT)
+ }
+
+ if (sp.getParticleType() != SchemaParticle.ELEMENT) {
return result;
-
+ }
+
// it probably only makes sense to put comments in front of individual elements that repeat
-
- if (sp.getMaxOccurs() == null)
- {
+
+ if (sp.getMaxOccurs() == null) {
// xmlc.insertComment("The next " + getItemNameOrType(sp, xmlc) + " may be repeated " + minOccurs + " or more times");
- if (minOccurs == 0)
+ if (minOccurs == 0) {
xmlc.insertComment("Zero or more repetitions:");
- else
+ } else {
xmlc.insertComment(minOccurs + " or more repetitions:");
- }
- else if (sp.getIntMaxOccurs() > 1)
- {
+ }
+ } else if (sp.getIntMaxOccurs() > 1) {
xmlc.insertComment(minOccurs + " to " + String.valueOf(sp.getMaxOccurs()) + " repetitions:");
- }
- else
- {
+ } else {
xmlc.insertComment("Optional:");
}
return result;
@@ -999,29 +985,25 @@
/*
Return a name for the element or the particle type to use in the comment for minoccurs, max occurs
*/
- private String getItemNameOrType(SchemaParticle sp, XmlCursor xmlc)
- {
+ private String getItemNameOrType(SchemaParticle sp, XmlCursor xmlc) {
String elementOrTypeName = null;
- if (sp.getParticleType() == SchemaParticle.ELEMENT)
- {
+ if (sp.getParticleType() == SchemaParticle.ELEMENT) {
elementOrTypeName = "Element (" + sp.getName().getLocalPart() + ")";
- }
- else
- {
+ } else {
elementOrTypeName = printParticleType(sp.getParticleType());
}
return elementOrTypeName;
}
- private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
// cast as schema local element
SchemaLocalElement element = (SchemaLocalElement) sp;
/// ^ -> <elemenname></elem>^
- if (_soapEnc)
+ if (_soapEnc) {
xmlc.insertElement(element.getName().getLocalPart()); // soap encoded? drop namespaces.
- else
+ } else {
xmlc.insertElement(element.getName().getLocalPart(), element.getName().getNamespaceURI());
+ }
_nElements++;
/// -> <elem>^</elem>
xmlc.toPrevToken();
@@ -1033,66 +1015,58 @@
}
- private void moveToken(int numToMove, XmlCursor xmlc)
- {
- for (int i = 0; i < Math.abs(numToMove); i++)
- {
- if (numToMove < 0)
- {
+ private void moveToken(int numToMove, XmlCursor xmlc) {
+ for (int i = 0; i < Math.abs(numToMove); i++) {
+ if (numToMove < 0) {
xmlc.toPrevToken();
- }
- else
- {
+ } else {
xmlc.toNextToken();
}
}
}
-
- private static final String formatQName(XmlCursor xmlc, QName qName)
- {
+
+ private static final String formatQName(XmlCursor xmlc, QName qName) {
XmlCursor parent = xmlc.newCursor();
parent.toParent();
String prefix = parent.prefixForNamespace(qName.getNamespaceURI());
parent.dispose();
String name;
- if (prefix == null || prefix.length() == 0)
+ if (prefix == null || prefix.length() == 0) {
name = qName.getLocalPart();
- else
+ } else {
name = prefix + ":" + qName.getLocalPart();
+ }
return name;
}
-
- private static final QName HREF = new QName("href");
- private static final QName ID = new QName("id");
- private static final QName XSI_TYPE = new QName("http://www.w3.org/2001/XMLSchema-instance", "type");
+
+ private static final QName HREF = new QName("href");
+ private static final QName ID = new QName("id");
+ private static final QName XSI_TYPE = new QName("http://www.w3.org/2001/XMLSchema-instance", "type");
private static final QName ENC_ARRAYTYPE = new QName("http://schemas.xmlsoap.org/soap/encoding/", "arrayType");
private static final QName ENC_OFFSET = new QName("http://schemas.xmlsoap.org/soap/encoding/", "offset");
-
- private static final Set SKIPPED_SOAP_ATTRS = new HashSet(Arrays.asList(new QName[] { HREF, ID, ENC_OFFSET}));
- private void processAttributes(SchemaType stype, XmlCursor xmlc)
- {
- if (_soapEnc)
- {
+
+ private static final Set SKIPPED_SOAP_ATTRS = new HashSet(Arrays.asList(new QName[]{HREF, ID, ENC_OFFSET}));
+
+ private void processAttributes(SchemaType stype, XmlCursor xmlc) {
+ if (_soapEnc) {
QName typeName = stype.getName();
- if (typeName != null)
- {
+ if (typeName != null) {
xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName));
}
}
-
+
SchemaProperty[] attrProps = stype.getAttributeProperties();
- for (int i = 0; i < attrProps.length; i++)
- {
+ for (int i = 0; i < attrProps.length; i++) {
SchemaProperty attr = attrProps[i];
- if (_soapEnc)
- {
- if (SKIPPED_SOAP_ATTRS.contains(attr.getName()))
+ if (_soapEnc) {
+ if (SKIPPED_SOAP_ATTRS.contains(attr.getName())) {
continue;
- if (ENC_ARRAYTYPE.equals(attr.getName()))
- {
- SOAPArrayType arrayType = ((SchemaWSDLArrayType)stype.getAttributeModel().getAttribute(attr.getName())).getWSDLArrayType();
- if (arrayType != null)
+ }
+ if (ENC_ARRAYTYPE.equals(attr.getName())) {
+ SOAPArrayType arrayType = ((SchemaWSDLArrayType) stype.getAttributeModel().getAttribute(attr.getName())).getWSDLArrayType();
+ if (arrayType != null) {
xmlc.insertAttributeWithValue(attr.getName(), formatQName(xmlc, arrayType.getQName()) + arrayType.soap11DimensionString());
+ }
continue;
}
}
@@ -1102,43 +1076,38 @@
}
}
- private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
SchemaParticle[] spc = sp.getParticleChildren();
- for (int i=0; i < spc.length; i++)
- {
+ for (int i = 0; i < spc.length; i++) {
/// <parent>maybestuff^</parent>
processParticle(spc[i], xmlc, mixed);
//<parent>maybestuff...morestuff^</parent>
- if (mixed && i < spc.length-1)
+ if (mixed && i < spc.length - 1) {
xmlc.insertChars(pick(WORDS));
+ }
}
}
- private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
SchemaParticle[] spc = sp.getParticleChildren();
xmlc.insertComment("You have a CHOICE of the next " + String.valueOf(spc.length) + " items at this level");
- for (int i=0; i < spc.length; i++)
- {
+ for (int i = 0; i < spc.length; i++) {
processParticle(spc[i], xmlc, mixed);
}
}
- private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
SchemaParticle[] spc = sp.getParticleChildren();
// xmlc.insertComment("You may enter the following " + String.valueOf(spc.length) + " items in any order");
- for (int i=0; i < spc.length; i++)
- {
+ for (int i = 0; i < spc.length; i++) {
processParticle(spc[i], xmlc, mixed);
- if (mixed && i < spc.length-1)
+ if (mixed && i < spc.length - 1) {
xmlc.insertChars(pick(WORDS));
+ }
}
}
- private void processWildCard(SchemaParticle sp, XmlCursor xmlc, boolean mixed)
- {
+ private void processWildCard(SchemaParticle sp, XmlCursor xmlc, boolean mixed) {
xmlc.insertComment("You may enter ANY elements at this point");
xmlc.insertElement("AnyElement");
}
@@ -1146,38 +1115,36 @@
/**
* This method will get the base type for the schema type
*/
-
- private static QName getClosestName(SchemaType sType)
- {
- while (sType.getName() == null)
+
+ private static QName getClosestName(SchemaType sType) {
+ while (sType.getName() == null) {
sType = sType.getBaseType();
+ }
return sType.getName();
}
- private String printParticleType(int particleType)
- {
+ private String printParticleType(int particleType) {
StringBuilder returnParticleType = new StringBuilder();
returnParticleType.append("Schema Particle Type: ");
- switch (particleType)
- {
- case SchemaParticle.ALL :
+ switch (particleType) {
+ case SchemaParticle.ALL:
returnParticleType.append("ALL\n");
break;
- case SchemaParticle.CHOICE :
+ case SchemaParticle.CHOICE:
returnParticleType.append("CHOICE\n");
break;
- case SchemaParticle.ELEMENT :
+ case SchemaParticle.ELEMENT:
returnParticleType.append("ELEMENT\n");
break;
- case SchemaParticle.SEQUENCE :
+ case SchemaParticle.SEQUENCE:
returnParticleType.append("SEQUENCE\n");
break;
- case SchemaParticle.WILDCARD :
+ case SchemaParticle.WILDCARD:
returnParticleType.append("WILDCARD\n");
break;
- default :
+ default:
returnParticleType.append("Schema Particle Type Unknown");
break;
}
diff --git a/src/test/java/misc/checkin/HexBinTest.java b/src/test/java/misc/checkin/HexBinTest.java
new file mode 100644
index 0000000..c41ccef
--- /dev/null
+++ b/src/test/java/misc/checkin/HexBinTest.java
@@ -0,0 +1,56 @@
+/* Copyright 2004 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package misc.checkin;
+
+import net.sf.saxon.trans.XPathException;
+import net.sf.saxon.value.HexBinaryValue;
+import org.apache.xmlbeans.impl.util.HexBin;
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
+import static org.junit.Assert.assertEquals;
+
+public class HexBinTest {
+
+ @Test
+ public void testSurrogate() throws Exception {
+ String exp = "ABC\ud83c\udf09123";
+ String enc = HexBin.encode(exp);
+ String dec = HexBin.decode(enc);
+ assertEquals(exp, dec);
+ }
+
+ @Test
+ public void knownValue() throws XPathException {
+ // I've looked for comparison values but the following definition seems to be wrong,
+ // because Saxon also returns the same encoded value
+ // see http://books.xmlschemata.org/relaxng/ch19-77143.html
+ // "Relax NG" by Eric van der Vlist
+
+ String in = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>a";
+
+ String exp = "3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e61";
+ String enc = HexBin.encode(in);
+
+ HexBinaryValue val = new HexBinaryValue(enc);
+ String saxIn = new String(val.getBinaryValue(), StandardCharsets.UTF_8);
+
+ assertEquals(exp, enc.toLowerCase(Locale.ROOT));
+ assertEquals(in, saxIn);
+ }
+}