Java Code Examples for javax.xml.bind.JAXBContext#generateSchema()

The following examples show how to use javax.xml.bind.JAXBContext#generateSchema() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JAXBSchemaGenerator.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 2
Source File: JAXBUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: SchemaMappingWriter.java    From importer-exporter with Apache License 2.0 6 votes vote down vote up
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.");
}
 
Example 4
Source File: SchemaGeneratorActionHelper.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: WebServiceConfiguration.java    From cukes with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 6
Source File: DefaultToolingXMLService.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@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);
    }
}
 
Example 7
Source File: QuerySchemaWriter.java    From importer-exporter with Apache License 2.0 6 votes vote down vote up
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.");
}
 
Example 8
Source File: SchemagenStackOverflow.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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\""));
}
 
Example 9
Source File: DevelopmentGenerateJaxbSchema.java    From settlers-remake with MIT License 5 votes vote down vote up
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!");
}
 
Example 10
Source File: DynamicSchemaTest.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@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);
}
 
Example 11
Source File: WorkflowProfilesTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: SchemagenStackOverflow.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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\""));
}
 
Example 13
Source File: SchemagenStackOverflow.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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\""));
}
 
Example 14
Source File: AminoAcidTest.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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()));
}
 
Example 15
Source File: SchemagenStackOverflow.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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\""));
}
 
Example 16
Source File: ElementTest.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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()));
}
 
Example 17
Source File: ApprovalsUtil.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 18
Source File: SchemagenStackOverflow.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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\""));
}
 
Example 19
Source File: GenerateExtensionManifestSchema.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(ExtensionManifest.class);
    SchemaOutputResolver sor = new MySchemaOutputResolver();
    jaxbContext.generateSchema(sor);
}
 
Example 20
Source File: GenerateXMLSchemaDocuments.java    From regxmllib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 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"))
        );
    }

}