Example usage for javax.xml.bind SchemaOutputResolver SchemaOutputResolver

List of usage examples for javax.xml.bind SchemaOutputResolver SchemaOutputResolver

Introduction

In this page you can find the example usage for javax.xml.bind SchemaOutputResolver SchemaOutputResolver.

Prototype

SchemaOutputResolver

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Main.class);
    jc.generateSchema(new SchemaOutputResolver() {

        @Override// ww  w .  j ava2s  .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//  w  ww.  ja v  a 2 s.  c om
        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: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 ww .j ava2  s  .  c o  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:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private void generateSchema(final OutputStream os) {
    try {/*from w  ww. j a va2s  .c  o m*/
        JAXBContext.newInstance(SpringApplicationService.class).generateSchema(new SchemaOutputResolver() {

            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName)
                    throws IOException {
                final StreamResult result = new StreamResult(os);
                result.setSystemId("");
                return result;
            }
        });
    } catch (final IOException | JAXBException e) {
        throw new RuntimeException("generateSchema() failed", e);
    }
}

From source file:com.azaptree.services.command.http.WebXmlRequestCommand.java

@Override
public void generateSchema(final OutputStream os) {
    final Optional<JAXBContext> jaxbContext = getJaxbContext();
    if (!jaxbContext.isPresent()) {
        return;// ww  w.  ja va  2s  .c  om
    }
    try {
        jaxbContext.get().generateSchema(new SchemaOutputResolver() {

            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName)
                    throws IOException {
                final StreamResult result = new StreamResult(os);
                result.setSystemId("");
                return result;
            }
        });
    } catch (final IOException e) {
        throw new RuntimeException("generateSchema() failed", e);
    }
}

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/*from  ww  w  .  j  av a2s .c o  m*/
        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.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();//www . j  a  v  a2 s.co m

    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: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 ww  . j a  v a2s . 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.artifactory.jaxb.JaxbHelper.java

public void generateSchema(final OutputStream stream, final Class<T> clazz, final String namespace) {
    try {/*w  w w .j a v a 2  s  . c  om*/
        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.niord.web.api.ApiRestService.java

/**
 * Returns the XSD for the Message class.
 * Two XSDs are produced, "schema1.xsd" and "schema2.xsd". The latter is the main schema for
 * Message and will import the former./*  w  w  w .java  2  s  . co  m*/
 * @return the XSD for the Message class
 */
@ApiOperation(value = "Returns XSD model of the Message class", tags = { "messages" })
@GET
@Path("/xsd/{schemaFile}")
@Produces("application/xml;charset=UTF-8")
@GZIP
@NoCache
public String getMessageXsd(
        @ApiParam(value = "The schema file, either schema1.xsd or schema2.xsd", example = "schema2.xsd") @PathParam("schemaFile") String schemaFile)
        throws Exception {

    if (!schemaFile.equals("schema1.xsd") && !schemaFile.equals("schema2.xsd")) {
        throw new Exception("Only 'schema1.xsd' and 'schema2.xsd' allowed");
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(MessageVo.class);

    Map<String, StringWriter> result = new HashMap<>();
    SchemaOutputResolver sor = new SchemaOutputResolver() {
        @Override
        public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
            StringWriter out = new StringWriter();
            result.put(suggestedFileName, out);
            StreamResult result = new StreamResult(out);
            result.setSystemId(app.getBaseUri() + "/rest/public/v1/xsd/" + suggestedFileName);
            return result;
        }

    };

    // Generate the schemas
    jaxbContext.generateSchema(sor);

    return result.get(schemaFile).toString();
}