List of usage examples for javax.xml.bind JAXBContext generateSchema
public void generateSchema(SchemaOutputResolver outputResolver) throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Main.class); jc.generateSchema(new SchemaOutputResolver() { @Override//from w w w . j av a2s . c o m public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { System.out.println(suggestedFileName); return new StreamResult(suggestedFileName); } }); }
From source file:com.l2jserver.model.template.SkillTemplateConverter.java
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException { Class.forName("com.mysql.jdbc.Driver"); final File target = new File("data/templates"); final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class); final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); System.out.println("Generating template XML files..."); c.generateSchema(new SchemaOutputResolver() { @Override/*from w ww . j a va 2 s.c o m*/ public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { return new StreamResult(new File(target, suggestedFileName)); } }); try { final Unmarshaller u = c.createUnmarshaller(); final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill"); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd"); Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" }, true); for (final File legacyFile : files) { LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile); for (final LegacySkill legacySkill : list.skills) { SkillTemplate t = fillSkill(legacySkill); final File file = new File(target, "skill/" + t.id.getID() + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml"); templates.add(t); try { m.marshal(t, getXMLSerializer(new FileOutputStream(file))); } catch (MarshalException e) { System.err.println( "Could not generate XML template file for " + t.getName() + " - " + t.getID()); file.delete(); } } } System.out.println("Generated " + templates.size() + " templates"); System.gc(); System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory())); System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory())); System.out.println("Used: " + FileUtils.byteCountToDisplaySize( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory())); } finally { conn.close(); } }
From source file:com.betfair.cougar.marshalling.impl.databinding.xml.XMLUtils.java
public static Schema getSchema(JAXBContext context) { Result result = new ResultImplementation(); SchemaOutputResolver outputResolver = new SchemaOutputResolverImpl(result); File tempFile = null;//from www .java2 s . c o m try { context.generateSchema(outputResolver); String schemaFile = result.getSystemId(); if (schemaFile != null) { tempFile = new File(URI.create(schemaFile)); String content = FileUtils.readFileToString(tempFile); // JAXB nicely generates a schema with element refs, unfortunately it also adds the nillable attribute to the // referencing element, which is invalid, it has to go on the target. this string manipulation is to move the // nillable attribute to the correct place, preserving it's value. Map<String, Boolean> referenceElementsWithNillable = new HashMap<>(); BufferedReader br = new BufferedReader(new StringReader(content)); String line; while ((line = br.readLine()) != null) { if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) { // we've got a reference element with nillable set int refStartIndex = line.indexOf(" ref=\"") + 6; int refEndIndex = line.indexOf("\"", refStartIndex); int nillableStartIndex = line.indexOf(" nillable=\"") + 11; int nillableEndIndex = line.indexOf("\"", nillableStartIndex); String ref = line.substring(refStartIndex, refEndIndex); if (ref.startsWith("tns:")) { ref = ref.substring(4); } String nillable = line.substring(nillableStartIndex, nillableEndIndex); referenceElementsWithNillable.put(ref, Boolean.valueOf(nillable)); } } // if we got some hits, then we need to rewrite this schema if (!referenceElementsWithNillable.isEmpty()) { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new StringReader(content)); while ((line = br.readLine()) != null) { // these we need to remove the nillable section from if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) { int nillableStartIndex = line.indexOf(" nillable=\""); int nillableEndIndex = line.indexOf("\"", nillableStartIndex + 11); line = line.substring(0, nillableStartIndex) + line.substring(nillableEndIndex + 1); } else if (line.contains("<xs:element name=\"")) { for (String key : referenceElementsWithNillable.keySet()) { // this we need to add the nillable back to String elementTagWithName = "<xs:element name=\"" + key + "\""; if (line.contains(elementTagWithName)) { int endOfElementName = line.indexOf(elementTagWithName) + elementTagWithName.length(); line = line.substring(0, endOfElementName) + " nillable=\"" + referenceElementsWithNillable.get(key) + "\"" + line.substring(endOfElementName); break; } } } sb.append(line).append("\n"); } content = sb.toString(); } SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); return sf.newSchema(new StreamSource(new StringReader(content))); } } catch (IOException e) { throw new PanicInTheCougar(e); } catch (SAXException e) { throw new PanicInTheCougar(e); } finally { if (tempFile != null) tempFile.delete(); } return null; }
From source file:test.com.azaptree.services.spring.application.SpringApplicationServiceTest.java
@Test public void testGenerateXSD() throws JAXBException, IOException { final JAXBContext jc = JAXBContext .newInstance(com.azaptree.services.spring.application.config.SpringApplicationService.class); jc.generateSchema(new SchemaOutputResolver() { @Override/*w w w . ja va 2s . c om*/ public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { File file = new File("target", suggestedFileName); StreamResult result = new StreamResult(file); result.setSystemId(file.toURI().toURL().toString()); return result; } }); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); jc.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { StreamResult result = new StreamResult(bos); result.setSystemId(""); return result; } }); System.out.println(bos.toString()); }
From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java
@Test public void generateXmlSchema() throws Exception { JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class, org.javelin.sws.ext.bind.jaxb.context3a.MyClassJ3.class); final List<DOMResult> results = new LinkedList<DOMResult>(); ctx.generateSchema(new SchemaOutputResolver() { @Override// w w w . j a v a 2 s .co m public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { log.info("file: {}, namespace: {}", suggestedFileName, namespaceUri); DOMResult result = new DOMResult(); results.add(result); result.setSystemId(suggestedFileName); return result; } }); for (DOMResult dr : results) { log.info("=== {} ===", dr.getSystemId()); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform( new javax.xml.transform.dom.DOMSource(dr.getNode()), new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out))); } }
From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfilesTest.java
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//from w w w . j a v a2 s .c om 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()); }
From source file:org.javelin.sws.ext.bind.internal.model.ClassHierarchyTest.java
@Test public void handleXmlAccessTypePropertyWithBase() throws Exception { // f3, f4, p1, p2, p3, p4 - properties and annotated fields System.out.println("\nD2"); JAXBContext context = JAXBContext.newInstance(D2.class); context.createMarshaller().marshal(new JAXBElement<D2>(new QName("", "r"), D2.class, new D2()), System.out); System.out.println();/*from ww w.ja v a2 s . c om*/ final List<DOMResult> results = new LinkedList<DOMResult>(); context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { DOMResult result = new DOMResult(); results.add(result); result.setSystemId(suggestedFileName); return result; } }); for (DOMResult dr : results) { javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform( new javax.xml.transform.dom.DOMSource(dr.getNode()), new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out))); } JAXBContext ctx = SweJaxbContextFactory.createContext(new Class[] { D2.class }, null); Map<Class<?>, TypedPattern<?>> patterns = (Map<Class<?>, TypedPattern<?>>) ReflectionTestUtils.getField(ctx, "patterns"); ComplexTypePattern<D2> pattern = (ComplexTypePattern<D2>) patterns.get(D2.class); Map<QName, PropertyMetadata<D2, ?>> elements = (Map<QName, PropertyMetadata<D2, ?>>) ReflectionTestUtils .getField(pattern, "elements"); assertThat(elements.size(), equalTo(8)); assertTrue(elements.containsKey(new QName("", "f3"))); assertTrue(elements.containsKey(new QName("", "f4"))); assertTrue(elements.containsKey(new QName("", "fd3"))); assertTrue(elements.containsKey(new QName("", "fd4"))); assertTrue(elements.containsKey(new QName("", "p1"))); assertTrue(elements.containsKey(new QName("", "p2"))); assertTrue(elements.containsKey(new QName("", "p3"))); assertTrue(elements.containsKey(new QName("", "p4"))); }
From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java
/** * * * @param scenario/*w w w . j a v a2s . c o m*/ */ public File generateScenarioXml(Scenario scenario) { scenario = populateScenario(scenario); File base = new File(scriptSystemPath + File.separator + Cfg.RESOURCE_PATH); File saveDir = new File(base, String.valueOf(scenario.getId())); try { if (!saveDir.exists() && saveDir.getParentFile().exists()) { saveDir.mkdir(); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss"); String baseName = "scenario_" + scenario.getId() + "_export_" + fmt.format(new Date()); String conflict = "VERSION_CONFLICT"; File scenarioXml = new File(saveDir, baseName + ".xml"); File scenarioXmlConflict = new File(saveDir, baseName + "_" + conflict + ".xml"); File scenarioXsd = new File(saveDir, baseName + ".xsd"); File scenarioXsdConflict = new File(saveDir, baseName + "_" + conflict + ".xsd"); File scenarioMain = new File(scriptSystemPath, "reference_schema.xsd"); File scenarioMainConflict = new File(saveDir, baseName + "_" + "REFERENCE_SCHEMA.xsd"); JAXBContext jaxbContext = JAXBContext.newInstance(Scenario.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(scenario, scenarioXml); SchemaOutputResolver sor = new CustomOutputResolver(saveDir, baseName + ".xsd"); jaxbContext.generateSchema(sor); if (!scenarioMain.exists()) { LOGGER.error("REFERENCE SCHEMA IS MISSING: " + scenarioMain); } if (!scenarioXsd.exists()) { LOGGER.error("GENERATED XSD IS MISSING: " + scenarioXsd); } if (!scenarioXml.exists()) { LOGGER.error("GENERATED XML IS MISSING: " + scenarioXml); } if (scenarioMain.exists() && scenarioXsd.exists() && scenarioXml.exists()) { String referenceMD5 = calculateMD5FromFile(scenarioMain); String newMD5 = calculateMD5FromFile(scenarioXsd); File export = null; boolean falseMD5 = !referenceMD5.equals(newMD5); File conflictReadme = new File(saveDir, conflict + "_README.txt"); if (falseMD5) { FileUtils.moveFile(scenarioXml, scenarioXmlConflict); FileUtils.moveFile(scenarioXsd, scenarioXsdConflict); FileUtils.copyFile(scenarioMain, scenarioMainConflict); scenarioXml = scenarioXmlConflict; scenarioXsd = scenarioXsdConflict; export = new File(saveDir, "scenario_" + scenario.getId() + "_export_" + conflict + ".zip"); String readme = Cfg.inst().getProp(DEF_LANGUAGE, "MISC.XSD_XML_CONFLICT") + "\n" + scenarioMainConflict.getName(); if (conflictReadme.exists()) { conflictReadme.delete(); } if (!conflictReadme.exists()) { conflictReadme.createNewFile(); } PrintWriter out = new PrintWriter(conflictReadme); out.println(readme); out.flush(); out.close(); } else { export = new File(saveDir, "scenario_" + scenario.getId() + "_export.zip"); } ArrayList<File> exportFiles = new ArrayList<File>(); if (scenarioXml.exists()) { exportFiles.add(scenarioXml); } if (scenarioXsd.exists()) { exportFiles.add(scenarioXsd); } if (falseMD5 && conflictReadme.exists() && scenarioMainConflict.exists()) { exportFiles.add(conflictReadme); exportFiles.add(scenarioMainConflict); } if (export.exists()) { export.delete(); } return zip(exportFiles, export); } } catch (Exception e) { LOGGER.error("EXPORT XSD/XML FAILED!", e); } return null; }
From source file:org.artifactory.jaxb.JaxbHelper.java
public void generateSchema(final OutputStream stream, final Class<T> clazz, final String namespace) { try {/* www .j a va 2s .co m*/ JAXBContext context = JAXBContext.newInstance(clazz); context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { StreamResult result = new StreamResult(stream); result.setSystemId(namespace); return result; } }); } catch (Exception e) { throw new RuntimeException("Failed to write object to stream.", e); } }
From source file:org.dspace.rest.common.TestJAXBSchema.java
@Test public void testFullSchema() throws Exception { StringWriter writer = new StringWriter(); TestSchemaOutputResolver resolver = new TestSchemaOutputResolver(writer); JAXBContext context = JAXBContext.newInstance(Bitstream.class, CheckSum.class, Collection.class, Community.class, DSpaceObject.class, Item.class, MetadataEntry.class, ResourcePolicy.class, Status.class); context.generateSchema(resolver); String res = "org/dspace/rest/common/expected_xsd0.xsd"; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(res); String expected = IOUtils.toString(is, "UTF-8"); // System.err.println(writer.toString()); assertEquals("JAXB schema", expected, writer.toString()); }