Example usage for javax.xml.bind JAXBContext newInstance

List of usage examples for javax.xml.bind JAXBContext newInstance

Introduction

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

Prototype

public static JAXBContext newInstance(Class<?>[] classesToBeBound, Map<String, ?> properties)
        throws JAXBException 

Source Link

Document

Create a new instance of a JAXBContext class.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(A.class, B.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    A a = new A();
    a.setFoo("Hello World");
    marshaller.marshal(a, System.out);

    B b = new B();
    b.setFoo("Hello World");
    marshaller.marshal(b, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Object value = "Hello World";

    JAXBContext jc = JAXBContext.newInstance(String.class, Bar.class);
    JAXBIntrospector introspector = jc.createJAXBIntrospector();
    Marshaller marshaller = jc.createMarshaller();
    if (null == introspector.getElementName(value)) {
        JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), Object.class, value);
        marshaller.marshal(jaxbElement, System.out);
    } else {/*ww w .j av  a2s  .  c om*/
        marshaller.marshal(value, System.out);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(BarX.class, BarY.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    BarX barX = new BarX();
    barX.setXThing("XThing");
    marshaller.marshal(barX, System.out);

    BarY barY = new BarY();
    barY.setYBlah("YBlah");
    marshaller.marshal(barY, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Foo.class, ObjectFactory.class);

    StringReader xml = new StringReader("<foo><C>Hello World</C></foo>");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Foo foo = (Foo) unmarshaller.unmarshal(xml);

    JAXBElement<?> aOrBOrCOrD = foo.aOrBOrCOrD;
    System.out.println(aOrBOrCOrD.getName().getLocalPart());
    System.out.println(aOrBOrCOrD.getDeclaredType());
    System.out.println(aOrBOrCOrD.getValue());
}

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   ww w.  j  av a  2s  .  co  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.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * This class authenticates with the Hiperium Platform using JAXBContext and the selects user's home and
 * profile to access the system functions, and finally end the session. For all this lasts functions
 * we use SOAP messages with dispatchers and not JAXBContext.
 * /*from w w w . j a v a2s .  c  o m*/
 * We need to recall, that for JAXBContext we could not add a handler to add header security parameters that need
 * to be verified in every service call in the Hiperium Platform, and for that reason, we only use JAXBContext in
 * the authentication process that do not need this header validation in the SOAP message header.
 * 
 * @param args
 */
public static void main(String[] args) {
    try {
        URL authURL = new URL(AUTH_SERVICE_URL);
        // The NAMESPACE must be http://authentication.soap.web.hiperium.com/ and must not begin
        // with http://SEI.authentication.soap.web.hiperium.com. Furthermore, the service name
        // and service port name must end WSService and WSPort respectively in order to call the service.
        QName authServiceQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSService");
        QName authPortQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSPort");
        // The parameter class must be annotated with @XmlRootElement in order to function
        JAXBContext jaxbContext = JAXBContext.newInstance(UserAuthentication.class,
                UserAuthenticationResponse.class);
        Service authService = Service.create(authURL, authServiceQName);
        // When we use JAXBContext the dispatcher mode must be PAYLOAD and NOT MESSAGE mode
        Dispatch<Object> dispatch = authService.createDispatch(authPortQName, jaxbContext,
                Service.Mode.PAYLOAD);
        UserCredentialDTO credentialsDTO = new UserCredentialDTO("andres_solorzano85@hotmail.com", "andres123");
        UserAuthentication authenticateRequest = new UserAuthentication();
        authenticateRequest.setArg0(credentialsDTO);
        UserAuthenticationResponse authenticateResponse = (UserAuthenticationResponse) dispatch
                .invoke(authenticateRequest);
        String sessionId = authenticateResponse.getReturn();
        LOGGER.debug("SESSION ID: " + sessionId);

        // Verify if session ID exists
        if (StringUtils.isNotBlank(sessionId)) {
            // Select home and profile
            URL selectHomeURL = new URL(HOME_SELECTION_SERVICE_URL);
            Service selectHomeService = Service.create(selectHomeURL,
                    new QName(AUTH_NAMESPACE, "HomeSelectionWSService"));
            selectHomeService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                    CLIENT_APPLICATION_TOKEN, AuthenticationObjectFactory._SelectHome_QNAME));
            Dispatch<SOAPMessage> selectHomeDispatch = selectHomeService.createDispatch(
                    new QName(AUTH_NAMESPACE, "HomeSelectionWSPort"), SOAPMessage.class, Service.Mode.MESSAGE);
            CommonsUtil.addSessionHeaderParms(selectHomeDispatch, sessionId);
            HomeSelectionDTO homeSelectionDTO = new HomeSelectionDTO(1L, 1L);
            SOAPMessage response = selectHomeDispatch.invoke(createSelectHomeSOAPMessage(homeSelectionDTO));
            readSOAPMessageResponse(response);

            // End Session
            URL endSessionURL = new URL(END_SESSION_SERVICE_URL);
            QName endSessionServiceQName = new QName(GENERAL_NAMESPACE, "MenuWSService");
            QName endSessionPortQName = new QName(GENERAL_NAMESPACE, "MenuWSPort");
            Service endSessionService = Service.create(endSessionURL, endSessionServiceQName);
            endSessionService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                    CLIENT_APPLICATION_TOKEN, GeneralObjectFactory._EndSession_QNAME));
            Dispatch<SOAPMessage> endSessionDispatch = endSessionService.createDispatch(endSessionPortQName,
                    SOAPMessage.class, Service.Mode.MESSAGE);
            CommonsUtil.addSessionHeaderParms(endSessionDispatch, sessionId);
            response = endSessionDispatch.invoke(createEndSessionSOAPMessage());
            readSOAPMessageResponse(response);
        }
    } catch (MalformedURLException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (JAXBException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:com.l2jserver.model.template.NPCTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    controllers.put("L2Teleporter", TeleporterController.class);
    controllers.put("L2CastleTeleporter", TeleporterController.class);
    controllers.put("L2Npc", BaseNPCController.class);
    controllers.put("L2Monster", MonsterController.class);
    controllers.put("L2FlyMonster", MonsterController.class);
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("generated/template/npc");

    System.out.println("Scaning legacy HTML files...");
    htmlScannedFiles = FileUtils.listFiles(L2J_HTML_FOLDER, new String[] { "html", "htm" }, true);

    final JAXBContext c = JAXBContext.newInstance(NPCTemplate.class, Teleports.class);

    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    {//from   ww  w .java 2  s .c o m
        System.out.println("Converting teleport templates...");
        teleportation.teleport = CollectionFactory.newList();

        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement("SELECT * FROM teleport");
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            final TeleportationTemplate template = new TeleportationTemplate();

            template.id = new TeleportationTemplateID(rs.getInt("id"), null);
            template.name = rs.getString("Description");
            TemplateCoordinate coord = new TemplateCoordinate();
            coord.x = rs.getInt("loc_x");
            coord.y = rs.getInt("loc_y");
            coord.z = rs.getInt("loc_z");
            template.point = coord;
            template.price = rs.getInt("price");
            template.item = rs.getInt("itemId");
            if (rs.getBoolean("fornoble")) {
                template.restrictions = new Restrictions();
                template.restrictions.restriction = Arrays.asList("NOBLE");
            }
            teleportation.teleport.add(template);
        }
        m.marshal(teleportation, getXMLSerializer(new FileOutputStream(new File(target, "../teleports.xml"))));
        // System.exit(0);
    }

    System.out.println("Generating template XML files...");
    // c.generateSchema(new SchemaOutputResolver() {
    // @Override
    // public Result createOutput(String namespaceUri,
    // String suggestedFileName) throws IOException {
    // // System.out.println(new File(target, suggestedFileName));
    // // return null;
    // return new StreamResult(new File(target, suggestedFileName));
    // }
    // });

    try {
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement(
                "SELECT npc.*, npcskills.level AS race " + "FROM npc " + "LEFT JOIN npcskills "
                        + "ON(npc.idTemplate = npcskills.npcid AND npcskills.skillid = ?)");
        st.setInt(1, 4416);
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            Object[] result = fillNPC(rs);
            NPCTemplate t = (NPCTemplate) result[0];
            String type = (String) result[1];

            String folder = createFolder(type);
            if (folder.isEmpty()) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../npc.xsd");
            } else {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../../npc.xsd");
            }

            final File file = new File(target, "npc/" + folder + "/" + t.getID().getID()
                    + (t.getInfo().getName() != null ? "-" + camelCase(t.getInfo().getName().getValue()) : "")
                    + ".xml");
            file.getParentFile().mkdirs();
            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.getInfo().getName().getValue() + " - " + 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.moss.appsnap.server.AppSnapServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {/*  w ww. java  2s  . co  m*/
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class, VeracityId.class);
    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppSnapServer.class);

    File[] configPaths = new File[] { new File("settings.xml"),
            new File(new File(System.getProperty("user.home")), ".appsnap-server.xml"),
            new File("/etc/appsnap-server.xml") };

    File configFile = null;

    for (File next : configPaths) {
        if (next.exists()) {
            configFile = next;
        }
    }

    if (configFile == null) {

        log.warn("No config file found.");

        for (int x = configPaths.length - 1; x >= 0; x--) {
            File next = configPaths[x];
            log.warn("Attempting to create default config file at " + next.getAbsolutePath());
            ServerConfiguration defaults = new ServerConfiguration();
            defaults.idProofRecipie(
                    new PasswordProofRecipie(new SimpleId("mr-admin-dude"), "my-super-secret-password"));
            try {
                helper.writeToFile(helper.writeToXmlString(defaults), next);
                log.warn("done");
                break;
            } catch (Exception e) {
                log.warn("Error writing file: " + e.getMessage(), e);
            }
        }
        System.exit(1);
        return;
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppSnapServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:Main.java

private static JAXBContext getContext(Class<?> clazz) throws JAXBException {
    return JAXBContext.newInstance(clazz.getPackage().getName(), clazz.getClassLoader());
}

From source file:Main.java

/**
 * Create a {@link Unmarshaller} for the given context and return it.
 * //w w w  . j  av  a  2s . co  m
 * @param jaxbContextName the context name where to look to find jaxb classes
 * @return the created {@link Unmarshaller}
 * @throws JAXBException
 */
public static Unmarshaller createUnmarshaller(final String jaxbContextName, ClassLoader cl)
        throws JAXBException {
    final JAXBContext jaxbContext = JAXBContext.newInstance(jaxbContextName, cl);
    return jaxbContext.createUnmarshaller();
}