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:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testCheckAccessForIds() throws Exception {
    CheckAccessForIdsInputDTO input = new CheckAccessForIdsInputDTO();
    input.setPresentationType("Search");
    input.setAttributes(createUserObjAttributeDTO());
    ArrayList<String> ids = new ArrayList<String>();
    ids.add("doms_radioTVCollection:uuid:371157ee-b120-4504-bfaf-364c15a4137c");//radio TV        
    ids.add("doms_radioTVCollection:uuid:c3386ed5-9b79-47a2-a648-8de53569e630");//radio TV
    ids.add("doms_reklamefilm:uuid:35a1aa76-97a1-4f1b-b5aa-ad2a246eeeec"); //reklame
    ids.add("doms_newspaperCollection:uuid:18709dea-802c-4bd7-98e6-32ca3b285774-segment_6"); //aviser      
    input.setIds(ids);/*  www  .j  a  v  a  2s  .c  o m*/

    JAXBContext context = JAXBContext.newInstance(CheckAccessForIdsInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println(inputXML);
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://devel06:9612/licensemodule/services/").build());

    // Call with XML
    CheckAccessForIdsOutputDTO output = service.path("checkAccessForIds").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(inputXML).post(CheckAccessForIdsOutputDTO.class);
    context = JAXBContext.newInstance(CheckAccessForIdsOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    System.out.println("query:" + output.getQuery());
    System.out.println("presentationtype:" + output.getPresentationType());
    System.out.println("number of IDs:" + output.getAccessIds().size());
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testValidateAccess() throws Exception {
    // Test Validate Access
    ValidateAccessInputDTO input = new ValidateAccessInputDTO();

    ArrayList<UserObjAttributeDTO> userObjAttributes = createUserObjAttributeDTO();
    input.setAttributes(userObjAttributes);

    ArrayList<String> groups = new ArrayList<String>();
    groups.add("IndividueltForbud");
    groups.add("Klausuleret");
    input.setGroups(groups);//  ww  w  .  j a v  a2 s  .  com
    input.setPresentationType("images");

    JAXBContext context = JAXBContext.newInstance(ValidateAccessInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println("input xml:\n" + inputXML);

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());

    // Call with XML
    ValidateAccessOutputDTO output = service.path("validateAccess").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(inputXML).post(ValidateAccessOutputDTO.class);

    // Call with @XmlRootElement
    // output = service.path("validateAccess").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).entity(input).post(ValidateAccessOutputDTO.class);

    context = JAXBContext.newInstance(ValidateAccessOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    // Access depends on the licenses in the DB.
    System.out.println("access :" + output.isAccess());
}

From source file:main.java.refinement_class.Useful.java

public static void mashal(Object o, String xml_file, Class c) {

    Marshaller marshaller;//from   w  w  w.j  a va2  s .c om
    // create a JAXBContext
    JAXBContext jaxbContext;

    try {
        jaxbContext = JAXBContext.newInstance(c);

        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        marshaller.marshal(o, new FileOutputStream(xml_file));
    } catch (JAXBException e) {
        e.printStackTrace();
        LOG.error(e.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        LOG.error(e.toString());
    }
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

public static String marshallToString(Class sourceClass, Object source) {
    try {/*from  w  ww .jav a2s . c  om*/
        JAXBContext jaxbContext = JAXBContext.newInstance(sourceClass);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshaller.marshal(source, sw);
        return sw.toString();
    } catch (JAXBException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

From source file:com.kcs.core.utilities.Utility.java

public static OutputStream generate(Object jaxbElement, OutputStream output) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(jaxbElement.getClass());
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(jaxbElement, output);
    return output;
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

public static Marshaller getMarshaller(boolean isFragment, Class... docClass) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(docClass);
    Marshaller m = context.createMarshaller();
    m.setProperty(javax.xml.bind.Marshaller.JAXB_FRAGMENT, isFragment);
    return m;/*from   ww  w  .  ja  v a2  s  .  c  o  m*/
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

public static Marshaller getMarshaller(Class... docClass) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(docClass);
    Marshaller m = context.createMarshaller();
    m.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(javax.xml.bind.Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    return m;//from  w  ww.j  av a2 s . com
}

From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java

public static File saveConfiguration(File directory, Object configuration) throws Exception {
    String configurationPackage = configuration.getClass().getPackage().getName();
    JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    File configurationFile = new File(directory, "configuration.xml");
    marshaller.marshal(configuration, configurationFile);
    configurationCache.invalidate(configurationFile);
    return configurationFile;
}

From source file:main.java.refinement_class.Useful.java

public static String mashal2(Object o, Class c) {

    Marshaller marshaller;//from  w w  w  .j a  v  a  2s  .c o  m
    // create a JAXBContext
    JAXBContext jaxbContext;
    String xmlString = "";

    try {
        jaxbContext = JAXBContext.newInstance(c);
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        //  marshaller.marshal(o, new FileOutputStream(xml_file));

        StringWriter sw = new StringWriter();
        marshaller.marshal(o, sw);
        xmlString = sw.toString();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return xmlString;
}

From source file:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * This method adds a selection of {@link TNodeTemplate}- and {@link TRelationshipTemplate}-XML-Strings to a {@link TTopologyTemplate}-XML-String using JAXB.
 * After the templates have been added, the {@link TTopologyTemplate} object is re-marshalled to an XML-String.
 *
 * This method is called by the selectionHandler.jsp after several Node or RelationshipTemplates have been chosen in a dialog.
 *
 * @param topology/*from w  w  w .j av a 2s . co m*/
 *            the topology as XML string
 * @param allTemplateChoicesAsXML
 *            all possible template choices as TOSCA-XML strings containing the complete templates
 * @param selectedNodeTemplatesAsJSON
 *            the names of the selected NodeTemplates as JSONArray
 * @param selectedRelationshipTemplatesAsJSON
 *            the names of the selected RelationshipTemplates as JSONArray
 *
 * @return the complete topology XML string
 */
public static String addTemplatesToTopology(String topology, String allTemplateChoicesAsXML,
        String selectedNodeTemplatesAsJSON, String selectedRelationshipTemplatesAsJSON) {
    try {

        // initialization code for the jackson types used to convert JSON string arrays to a java.util.List
        ObjectMapper mapper = new ObjectMapper();
        TypeFactory factory = mapper.getTypeFactory();

        // convert the JSON array containing the names of the selected RelationshipTemplates to a java.util.List
        List<String> selectedRelationshipTemplates = mapper.readValue(selectedRelationshipTemplatesAsJSON,
                factory.constructCollectionType(List.class, String.class));

        // convert the topology and the choices to objects using JAXB
        TTopologyTemplate topologyTemplate = getTopologyAsJaxBObject(topology);
        List<TEntityTemplate> allTemplateChoices = getEntityTemplatesAsJaxBObject(allTemplateChoicesAsXML);

        // this distinction of cases is necessary because it is possible that only RelationshipTemplates have been selected
        if (selectedNodeTemplatesAsJSON != null) {

            // convert the JSON string array containing the names of the selected NodeTemplates to a java.util.List
            List<String> selectedNodeTemplates = mapper.readValue(selectedNodeTemplatesAsJSON,
                    factory.constructCollectionType(List.class, String.class));

            // search the selected NodeTemplate in the List of all choices by its name to receive its object which will ne added to the topology
            for (String nodeTemplateName : selectedNodeTemplates) {
                for (TEntityTemplate choice : allTemplateChoices) {
                    if (choice instanceof TNodeTemplate) {
                        TNodeTemplate nodeTemplate = (TNodeTemplate) choice;
                        // matching a name is usually unsafe because the uniqueness cannot be assured,
                        // however similar names are not possible at this location due to the implementation of the selection dialogs
                        if (nodeTemplateName.equals(nodeTemplate.getName())) {
                            // add the selected NodeTemplate to the topology
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate);

                            // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                            // Re-add it to avoid errors.
                            for (TEntityTemplate entity : topologyTemplate
                                    .getNodeTemplateOrRelationshipTemplate()) {
                                if (entity instanceof TRelationshipTemplate) {
                                    TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) entity;
                                    if (relationshipTemplate.getSourceElement().getRef() == null) {
                                        // connect to the added NodeTemplate
                                        SourceElement sourceElement = new SourceElement();
                                        sourceElement.setRef(nodeTemplate);
                                        relationshipTemplate.setSourceElement(sourceElement);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // now search and add the selected RelationshipTemplate object connecting to the inserted NodeTemplate
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TEntityTemplate toBeAdded : allTemplateChoices) {
                    if (toBeAdded instanceof TRelationshipTemplate) {
                        TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) toBeAdded;
                        if (relationshipTemplateName.equals(relationshipTemplate.getName())) {
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relationshipTemplate);
                        }
                    }
                }
            }

        } else {
            // in this case only Relationship Templates have been selected
            List<TRelationshipTemplate> allRelationshipTemplateChoices = JAXBHelper
                    .getRelationshipTemplatesAsJaxBObject(allTemplateChoicesAsXML);

            // add the target Node Template to the topology which is unique due to the implementation of the selection dialog
            topologyTemplate.getNodeTemplateOrRelationshipTemplate()
                    .add((TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                            .getTargetElement().getRef());

            // search the JAXB object of the selected RelationshipTemplate and add it to the topology
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TRelationshipTemplate choice : allRelationshipTemplateChoices) {
                    if (relationshipTemplateName.equals(choice.getName())) {
                        topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(choice);
                    }
                }
            }

            for (TEntityTemplate entityTemplate : topologyTemplate.getNodeTemplateOrRelationshipTemplate()) {
                if (entityTemplate instanceof TRelationshipTemplate) {
                    TRelationshipTemplate relationship = (TRelationshipTemplate) entityTemplate;

                    // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                    // Re-add it to avoid errors.
                    if (relationship.getSourceElement().getRef() == null) {
                        relationship.getSourceElement().setRef(
                                (TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                                        .getTargetElement().getRef());
                    }
                }
            }
        }

        // re-convert the topology from a JAXB object to an XML string and return it
        Definitions definitions = new Definitions();
        TServiceTemplate st = new TServiceTemplate();
        st.setTopologyTemplate(topologyTemplate);
        definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(st);
        JAXBContext context = JAXBContext.newInstance(Definitions.class);
        Marshaller m = context.createMarshaller();
        StringWriter stringWriter = new StringWriter();

        m.marshal(definitions, stringWriter);

        return stringWriter.toString();

    } catch (JAXBException | IOException e) {
        logger.error(e.getLocalizedMessage());
    }

    return null;
}