下面列出了javax.xml.bind.JAXBContext#generateSchema ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Generates an XML Schema file for the given list of classes and writes it to
* the file with the given name.
*
* @param args The first argument is expected to be the name of the file to
* write the schema to. All following arguments are expected to be fully
* qualified names of classes to include.
* @throws Exception If an exception occurs.
*/
public static void main(String[] args)
throws Exception {
checkArgument(args.length >= 2,
"Expected at least 2 arguments, got %s.",
args.length);
File outputFile = new File(args[0]);
Class<?>[] classes = new Class<?>[args.length - 1];
for (int i = 1; i < args.length; i++) {
classes[i - 1]
= JAXBSchemaGenerator.class.getClassLoader().loadClass(args[i]);
}
JAXBContext jc = JAXBContext.newInstance(classes);
jc.generateSchema(new FixedSchemaOutputResolver(outputFile));
}
public static void main(String[] args) throws Exception {
final File file = new File("src/main/resources/org/citydb/database/schema/3dcitydb-schema.xsd");
System.out.print("Generting XML schema in " + file.getAbsolutePath() + "... ");
JAXBContext ctx = JAXBContext.newInstance(SchemaMapping.class);
ctx.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
StreamResult res = new StreamResult(file);
res.setSystemId(file.toURI().toString());
return res;
}
});
System.out.println("finished.");
}
@Override
public void generateSchema(Path outputPath)
{
try
{
JAXBContext jaxbContext = getJAXBContext();
SchemaOutputResolver sor = new SchemaOutputResolver()
{
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException
{
StreamResult result = new StreamResult();
result.setSystemId(outputPath.toUri().toString());
return result;
}
};
jaxbContext.generateSchema(sor);
}
catch (JAXBException | IOException e)
{
throw new WindupException("Error generating Windup schema due to: " + e.getMessage(), e);
}
}
public static void main(String[] args) throws Exception {
Path configFile = Paths.get("src/main/resources/org/citydb/config/schema/query.xsd");
System.out.print("Generting XML schema in " + configFile.toAbsolutePath() + "... ");
JAXBContext context = JAXBContext.newInstance(QueryWrapper.class);
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
if (ConfigUtil.CITYDB_CONFIG_NAMESPACE_URI.equals(namespaceUri)) {
Files.createDirectories(configFile.getParent());
StreamResult res = new StreamResult();
res.setSystemId(configFile.toUri().toString());
return res;
} else
return null;
}
});
System.out.println("finished.");
}
@Bean
public XsdSchemaCollection schemaCollection() throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance(CalculatorRequest.class, CalculatorResponse.class);
List<ByteArrayOutputStream> outs = new ArrayList<>();
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
outs.add(out);
StreamResult result = new StreamResult(out);
result.setSystemId(suggestedFileName);
return result;
}
});
Resource[] resources = outs.stream().
map(ByteArrayOutputStream::toByteArray).
map(InMemoryResource::new).
collect(Collectors.toList()).
toArray(new Resource[]{});
return new CommonsXsdSchemaCollection(resources);
}
public String generateSchema(Class jaxbObject) throws Exception {
InputStream mainStream = null;
String schema = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(jaxbObject);
StreamSchemaOutputResolver sor = new StreamSchemaOutputResolver();
jaxbContext.generateSchema(sor);
mainStream = sor.getStream();
schema = FileTextReader.getText(mainStream);
} catch (Throwable t) {
_logger.error("Error extracting generating schema from class {}", jaxbObject, t);
//ApsSystemUtils.logThrowable(t, this, "generateSchema", "Error extracting generating schema from class " + jaxbObject);
throw new RuntimeException("Error extracting generating schema", t);
} finally {
if (null != mainStream) mainStream.close();
}
return schema;
}
public static List<DOMResult> generateJaxbSchemas(
JAXBContext context, final Map<String, DOMResult> builtIns) throws IOException {
final List<DOMResult> results = new ArrayList<>();
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String ns, String file) throws IOException {
DOMResult result = new DOMResult();
if (builtIns.containsKey(ns)) {
DOMResult dr = builtIns.get(ns);
result.setSystemId(dr.getSystemId());
results.add(dr);
return result;
}
result.setSystemId(file);
results.add(result);
return result;
}
});
return results;
}
@Test
public void schemagenStackOverflowTest() throws Exception {
// Create new instance of JAXB context
JAXBContext context = JAXBContext.newInstance(Foo.class);
context.generateSchema(new TestOutputResolver());
// Read schema content from file
String content = Files.lines(resultSchemaFile).collect(Collectors.joining(""));
System.out.println("Generated schema content:" + content);
// Check if schema was generated: check class and list object names
Assert.assertTrue(content.contains("name=\"Foo\""));
Assert.assertTrue(content.contains("name=\"fooObject\""));
}
@Test
public void schemagenStackOverflowTest() throws Exception {
// Create new instance of JAXB context
JAXBContext context = JAXBContext.newInstance(Foo.class);
context.generateSchema(new TestOutputResolver());
// Read schema content from file
String content = Files.lines(resultSchemaFile).collect(Collectors.joining(""));
System.out.println("Generated schema content:" + content);
// Check if schema was generated: check class and list object names
Assert.assertTrue(content.contains("name=\"Foo\""));
Assert.assertTrue(content.contains("name=\"fooObject\""));
}
private static String generateSchema( final Class<?> type ) throws JAXBException, IOException {
final StringWriter stringWriter = new StringWriter();
final JAXBContext jaxbContext =
JAXBContextFactory.createContext( new Class<?>[] { type }, Collections.emptyMap() );
jaxbContext.generateSchema( new SchemaOutputResolver() {
@Override
public final Result createOutput( final String namespaceURI, final String suggestedFileName )
throws IOException {
final StreamResult result = new StreamResult( stringWriter );
result.setSystemId( suggestedFileName );
return result;
}
} );
return stringWriter.toString();
}
@Test
public void generateSchema() throws JAXBException, IOException{
File outputFile = new File(System.getProperty("java.io.tmpdir"),"ElementMass.xsd");
outputFile.deleteOnExit();
JAXBContext context = JAXBContext.newInstance(ElementTable.class);
context.generateSchema(new SchemaGenerator(outputFile.toString()));
}
@Test
public void schemagenStackOverflowTest() throws Exception {
// Create new instance of JAXB context
JAXBContext context = JAXBContext.newInstance(Foo.class);
context.generateSchema(new TestOutputResolver());
// Read schema content from file
String content = Files.lines(resultSchemaFile).collect(Collectors.joining(""));
System.out.println("Generated schema content:" + content);
// Check if schema was generated: check class and list object names
Assert.assertTrue(content.contains("name=\"Foo\""));
Assert.assertTrue(content.contains("name=\"fooObject\""));
}
@Test
public void generateSchema() throws JAXBException, IOException{
JAXBContext context = JAXBContext.newInstance(AminoAcidCompositionTable.class);
File outputFile = new File(System.getProperty("java.io.tmpdir"),"AminoAcidComposition.xsd");
outputFile.deleteOnExit();
context.generateSchema(new SchemaGenerator(outputFile.toString()));
}
@Test
public void schemagenStackOverflowTest() throws Exception {
// Create new instance of JAXB context
JAXBContext context = JAXBContext.newInstance(Foo.class);
context.generateSchema(new TestOutputResolver());
// Read schema content from file
String content = Files.lines(resultSchemaFile).collect(Collectors.joining(""));
System.out.println("Generated schema content:" + content);
// Check if schema was generated: check class and list object names
Assert.assertTrue(content.contains("name=\"Foo\""));
Assert.assertTrue(content.contains("name=\"fooObject\""));
}
@Test
public void schemagenStackOverflowTest() throws Exception {
// Create new instance of JAXB context
JAXBContext context = JAXBContext.newInstance(Foo.class);
context.generateSchema(new TestOutputResolver());
// Read schema content from file
String content = Files.lines(resultSchemaFile).collect(Collectors.joining(""));
System.out.println("Generated schema content:" + content);
// Check if schema was generated: check class and list object names
Assert.assertTrue(content.contains("name=\"Foo\""));
Assert.assertTrue(content.contains("name=\"fooObject\""));
}
public void testCreateSchema() throws Exception {
JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
final Map<String, StreamResult> schemas = new HashMap<String, StreamResult>();
jctx.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
StreamResult sr = new StreamResult(new StringWriter());
sr.setSystemId(namespaceUri);
schemas.put(namespaceUri, sr);
return sr;
}
});
System.out.println(schemas.get(WorkflowProfileConsts.NS_WORKFLOW_V1).getWriter().toString());
}
@Test(expected = MarshalException.class)
public void generatesAndUsesSchema() throws JAXBException, IOException,
SAXException {
final JAXBContext context = JAXBContext.newInstance(A.class);
final DOMResult result = new DOMResult();
result.setSystemId("schema.xsd");
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri,
String suggestedFileName) {
return result;
}
});
@SuppressWarnings("deprecation")
final SchemaFactory schemaFactory = SchemaFactory
.newInstance(WellKnownNamespace.XML_SCHEMA);
final Schema schema = schemaFactory.newSchema(new DOMSource(result
.getNode()));
final Marshaller marshaller = context.createMarshaller();
marshaller.setSchema(schema);
// Works
marshaller.marshal(new A("works"), System.out);
// Fails
marshaller.marshal(new A(null), System.out);
}
public static void main(String[] args) throws JAXBException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(Presets.class);
SchemaOutputResolver sor = new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
File file = new File("src/jsettlers/mapcreator/presetloader/preset.xsd");
StreamResult result = new StreamResult(file);
result.setSystemId(file.toURI().toURL().toString());
return result;
}
};
jaxbContext.generateSchema(sor);
System.out.println("Finished!");
}
public static void main(String[] args) throws IOException, JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ExtensionManifest.class);
SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);
}
/**
* Usage is specified at {@link #USAGE}
*/
public static void main(String[] args) throws FileNotFoundException, JAXBException, IOException, InvalidEntryException, DuplicateEntryException, Exception {
if (args.length != 4
|| "-?".equals(args[0])) {
System.out.println(USAGE);
return;
}
/* NOTE: to mute logging: Logger.getLogger("").setLevel(Level.OFF); */
Class c = Class.forName(args[1]);
JAXBContext ctx = JAXBContext.newInstance(c);
File baseDir = new File(args[3]);
final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final ArrayList<Document> docs = new ArrayList<>();
ctx.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
Document doc = docBuilder.newDocument();
docs.add(doc);
Date now = new java.util.Date();
doc.appendChild(doc.createComment("Created: " + now.toString()));
doc.appendChild(doc.createComment("By: regxmllib build " + BuildVersionSingleton.getBuildVersion()));
doc.appendChild(doc.createComment("See: https://github.com/sandflow/regxmllib"));
return new DOMResult(doc, suggestedFileName);
}
});
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
for (int i = 0; i < docs.size(); i++) {
tr.transform(
new DOMSource(docs.get(i)),
new StreamResult(new File(baseDir, c.getSimpleName() + (i == 0 ? "" : "." + i) + ".xsd"))
);
}
}