Example usage for javax.xml.bind JAXBContext createMarshaller

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

Introduction

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

Prototype

public abstract Marshaller createMarshaller() throws JAXBException;

Source Link

Document

Create a Marshaller object that can be used to convert a java content tree into XML data.

Usage

From source file:ejava.projects.edmv.xml.EDmvBindingTest.java

public void setUp() throws Exception {
    JAXBContext jaxbc = JAXBContext.newInstance(Dmv.class);
    m = jaxbc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

}

From source file:com.jaspersoft.jasperserver.jaxrs.client.apiadapters.jobs.BatchJobsOperationsAdapter.java

private String buildXml(ReportJobModel reportJobModel) {
    try {/*  ww w  .j  a  v a2 s . c o m*/
        StringWriter writer = new StringWriter();
        JAXBContext jaxbContext = JAXBContext.newInstance(ReportJobModel.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(reportJobModel, writer);
        return writer.toString();
    } catch (JAXBException e) {
        log.warn("Can't marshal report job model.");
        throw new RuntimeException("Failed inFolder build report job model xml.", e);
    }
}

From source file:gov.nih.nci.cacis.sa.mirthconnect.SemanticAdapterChannelIntegrationTest.java

/**
 * This test calls out acceptSource(..) operation on SematicAdapter WS.
 * The SemanticAdapter WS is the source connector to SemanticAdapterChannel in Mirth.
 * @throws Exception exception/*from www .ja va2s  . com*/
 */
@Test
public void invokeSemanticAdapterWS() throws Exception { //NOPMD
    final JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(AcceptSourcePortType.class);
    factory.setAddress(ADDRESS);
    final AcceptSourcePortType client = (AcceptSourcePortType) factory.create();

    final InputStream sampleMessageIS = FileUtils
            .openInputStream(new File(getClass().getClassLoader().getResource("SARequestSample.xml").toURI()));

    final JAXBContext jc = JAXBContext.newInstance(CaCISRequest.class);
    final Unmarshaller unm = jc.createUnmarshaller();

    final CaCISRequest request = (CaCISRequest) unm.unmarshal(sampleMessageIS);

    final Marshaller m = jc.createMarshaller();
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    m.marshal(request, pw);
    final String reqStr = sw.toString();

    final CaCISResponse response = client.acceptSource(request);
    assertTrue(response.getStatus() == ResponseStatusType.SUCCESS);

}

From source file:net.sf.taverna.t2.maven.plugins.TavernaProfileGenerateMojo.java

/**
 * Generates the application profile file.
 *
 * @return the <code>File</code> that the application profile has been written to
 * @throws JAXBException//from  w ww. ja  va2 s.  c  o  m
 *             if the application profile cannot be created
 * @throws MojoExecutionException
 */
private File createApplicationProfile() throws JAXBException, MojoExecutionException {
    String groupId = project.getGroupId();
    String artifactId = project.getArtifactId();
    String version = maven2OsgiConverter.getVersion(project.getVersion());
    if (version.endsWith("SNAPSHOT")) {
        version = version.substring(0, version.indexOf("SNAPSHOT")) + buildNumber;
    }

    tempDirectory.mkdirs();
    File applicationProfileFile = new File(tempDirectory, APPLICATION_PROFILE_FILE);

    ApplicationProfile applicationProfile = new ApplicationProfile();
    applicationProfile.setId(groupId + "." + artifactId);
    applicationProfile.setName(project.getName());
    applicationProfile.setVersion(version);

    Updates updates = new Updates();
    updates.setUpdateSite(updateSite);
    updates.setUpdatesFile(updatesFile);
    updates.setLibDirectory(libDirectory);
    updates.setPluginSite(pluginSite);
    updates.setPluginsFile(pluginsFile);
    applicationProfile.setUpdates(updates);

    List<FrameworkConfiguration> frameworkConfiguration = applicationProfile.getFrameworkConfiguration();
    for (FrameworkConfiguration configuration : frameworkConfigurations) {
        frameworkConfiguration.add(configuration);
    }

    Set<BundleArtifact> bundleDependencies = osgiUtils.getBundleDependencies(Artifact.SCOPE_COMPILE,
            Artifact.SCOPE_RUNTIME);
    List<BundleInfo> runtimeBundles = osgiUtils.getBundles(bundleDependencies);
    if (!runtimeBundles.isEmpty()) {
        List<BundleInfo> bundles = applicationProfile.getBundle();
        for (BundleInfo bundle : runtimeBundles) {
            bundles.add(bundle);
        }
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(ApplicationProfile.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, SCHEMA_LOCATION);
    marshaller.marshal(applicationProfile, applicationProfileFile);

    return applicationProfileFile;
}

From source file:fr.fastconnect.factory.tibco.bw.maven.compile.ArchiveBuilder.java

public void save(File f) {
    try {//  w ww.java  2 s .  c o m
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(this.repository, f);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

From source file:org.kemri.wellcome.dhisreport.api.model.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;/*from   www .java 2  s .  c o m*/

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(DataValueSet.class);
        Marshaller dataValueSetMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        dataValueSetMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        dataValueSetMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        log.error(ex.getMessage());
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    String host = getUrl().getHost();
    int port = getUrl().getPort();

    HttpHost targetHost = new HttpHost(host, port, getUrl().getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        String postUrl = getUrl().toString() + DATAVALUESET_PATH;
        log.error("Post URL: " + postUrl);
        HttpPost httpPost = new HttpPost(postUrl);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext);
        httpPost.addHeader("Authorization", bs.getValue());
        httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
        httpPost.addHeader("Accept", "application/xml");

        httpPost.setEntity(new StringEntity(xmlReport.toString()));
        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Dhis2Exception(this, "Problem accessing Dhis2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

From source file:com.u2apple.tool.dao.DeviceXmlDaoJaxbImpl.java

private void flushVids() throws JAXBException, PropertyException {
    String vidFileFormat = Configuration.getProperty(Constants.VID_FILE_FORMAT);
    for (String vid : changedVids) {
        File file = new File(String.format(vidFileFormat, vid));
        JAXBContext jaxbContext = JAXBContext.newInstance(VID.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        VID v = getVid(getStaticMapFile().getVids(), vid);
        jaxbMarshaller.marshal(v, file);
    }/* ww  w.j  av  a  2 s  .co  m*/
    changedVids.clear();
}

From source file:org.motechproject.mobile.web.ivr.intellivr.IntellIVRController.java

public void init() {
    Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {/*from ww w  . ja va  2 s. c o  m*/
        Schema schema = factory.newSchema(schemaResource.getFile());
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        validator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Error initializing controller:", e);
    } catch (IOException e) {
        log.error("Error initializing controller:", e);
    } catch (ParserConfigurationException e) {
        log.error("Error initializing controller:", e);
    } catch (FactoryConfigurationError e) {
        log.error("Error initializing controller:", e);
    }
    try {
        JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.mobile.omp.manager.intellivr");
        marshaller = jaxbc.createMarshaller();
        unmarshaller = jaxbc.createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Error initializing controller:", e);
    }
}

From source file:com.floreantpos.bo.actions.DataExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    Session session = null;//from   w w w. j av a  2s.  c o  m
    Transaction transaction = null;
    FileWriter fileWriter = null;
    GenericDAO dao = new GenericDAO();

    try {
        JFileChooser fileChooser = getFileChooser();
        int option = fileChooser.showSaveDialog(com.floreantpos.util.POSUtil.getBackOfficeWindow());
        if (option != JFileChooser.APPROVE_OPTION) {
            return;
        }

        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            option = JOptionPane.showConfirmDialog(com.floreantpos.util.POSUtil.getFocusedWindow(),
                    Messages.getString("DataExportAction.1") + file.getName() + "?", //$NON-NLS-1$//$NON-NLS-2$
                    Messages.getString("DataExportAction.3"), //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION);
            if (option != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // fixMenuItemModifierGroups();

        JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();

        session = dao.createNewSession();
        transaction = session.beginTransaction();

        Elements elements = new Elements();

        //          * 2. USERS
        //          * 3. TAX
        //          * 4. MENU_CATEGORY
        //          * 5. MENU_GROUP
        //          * 6. MENU_MODIFIER
        //          * 7. MENU_MODIFIER_GROUP
        //          * 8. MENU_ITEM
        //          * 9. MENU_ITEM_SHIFT
        //          * 10. RESTAURANT
        //          * 11. USER_TYPE
        //          * 12. USER_PERMISSION
        //          * 13. SHIFT

        elements.setTaxes(TaxDAO.getInstance().findAll(session));
        elements.setMenuCategories(MenuCategoryDAO.getInstance().findAll(session));
        elements.setMenuGroups(MenuGroupDAO.getInstance().findAll(session));
        elements.setMenuModifiers(MenuModifierDAO.getInstance().findAll(session));
        elements.setMenuModifierGroups(MenuModifierGroupDAO.getInstance().findAll(session));
        elements.setMenuItems(MenuItemDAO.getInstance().findAll(session));
        elements.setMenuItemModifierGroups(MenuItemModifierGroupDAO.getInstance().findAll(session));

        //           elements.setUsers(UserDAO.getInstance().findAll(session));
        //           
        //           elements.setMenuItemShifts(MenuItemShiftDAO.getInstance().findAll(session));
        //           elements.setRestaurants(RestaurantDAO.getInstance().findAll(session));
        //           elements.setUserTypes(UserTypeDAO.getInstance().findAll(session));
        //           elements.setUserPermissions(UserPermissionDAO.getInstance().findAll(session));
        //           elements.setShifts(ShiftDAO.getInstance().findAll(session));

        m.marshal(elements, writer);

        transaction.commit();

        fileWriter = new FileWriter(file);
        fileWriter.write(writer.toString());
        fileWriter.close();

        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(),
                Messages.getString("DataExportAction.4")); //$NON-NLS-1$

    } catch (Exception e1) {
        transaction.rollback();
        PosLog.error(getClass(), e1);
        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(), e1.getMessage());
    } finally {
        IOUtils.closeQuietly(fileWriter);
        dao.closeSession(session);
    }
}

From source file:com.mgmtp.perfload.loadprofiles.ui.ctrl.ConfigController.java

public void saveActiveSettings() {
    checkState(activeSettingsFile != null, "No active settings file set.");

    Writer wr = null;/*  w  w w.  j a  v  a2 s. co m*/
    File file = new File(settingsDir, activeSettingsFile);
    file.getParentFile().mkdir();

    try {
        wr = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        JAXBContext context = JAXBContext.newInstance(Settings.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(getActiveSettings(), wr);
    } catch (JAXBException ex) {
        String msg = "Error marshalling contents to file: " + file;
        throw new LoadProfileException(msg, ex);
    } catch (IOException ex) {
        throw new LoadProfileException(ex.getMessage(), ex);
    } finally {
        Closeables.closeQuietly(wr);
    }
}