Example usage for javax.xml.bind Marshaller setSchema

List of usage examples for javax.xml.bind Marshaller setSchema

Introduction

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

Prototype

public void setSchema(Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent marshal operations against.

Usage

From source file:org.echocat.jemoni.carbon.jmx.configuration.RulesMarshaller.java

@Nonnull
private static Marshaller marshallerFor(@Nonnull Configuration configuration) {
    final Marshaller marshaller;
    try {//from  w  w  w  .ja va 2  s .  co  m
        marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true);
        marshaller.setSchema(SCHEMA);
        if (NAMESPACE_PREFIX_MAPPER != null) {
            marshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", NAMESPACE_PREFIX_MAPPER);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not create marshaller to marshall " + configuration + ".", e);
    }
    return marshaller;
}

From source file:org.eclipse.smila.utils.jaxb.JaxbUtils.java

/**
 * Creates the validating marshaller.// w w  w .j a v a  2 s . co m
 * 
 * @param context
 *          the context
 * @param schema
 *          the schema
 * 
 * @return the marshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 */
public static Marshaller createValidatingMarshaller(final JAXBContext context, final Schema schema)
        throws JAXBException {
    if (schema == null) {
        throw new IllegalArgumentException("Schema is not found!");
    }
    final Marshaller marshaller = context.createMarshaller();
    marshaller.setSchema(schema);
    marshaller.setEventHandler(createValidationEventHandler());
    return marshaller;
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

protected Marshaller createMarshaller(String packageName) throws JAXBException {
    final Marshaller marshaller = getContext(packageName).createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_XML_ENCODING);

    if (!(this.getSchema() == null)) {
        marshaller.setSchema(getSchema());
    }//w w w .ja  v a  2  s  .co  m

    return marshaller;
}

From source file:org.multicore_association.measure.mem.writeback.SetResultToShim.java

/**
 * Set the value to read the existing SHIM file.
 * @return Flag for success judgements//from  ww  w.  ja va  2s.  c  om
 * @throws ShimFileFormatException
 * @throws ShimFileGenerateException
 */
private static boolean appendToExistingShim() {
    /*
     * append to existing llvm-shim
     */
    SystemConfiguration sysConf = null;

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        e.printStackTrace();
        return false;
    }

    AddressSpaceSet addrSpaceSet = sysConf.getAddressSpaceSet();
    if (addrSpaceSet == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    List<AddressSpace> addrSpaceList = addrSpaceSet.getAddressSpace();
    if (addrSpaceList == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    masterComponentMap = new HashMap<String, MasterComponent>();
    slaveComponentMap = new HashMap<String, SlaveComponent>();
    accessTypeMap = new HashMap<String, AccessType>();

    List<String> route = new ArrayList<String>();
    ComponentSet cs = sysConf.getComponentSet();
    route.add(cs.getName());

    makeRefMapFromComponentSet(cs, route);

    for (int i = 0; i < measureList.size(); i++) {
        MeasurementsCSVData data = measureList.get(i);

        route.clear();

        /*
         * search AddressSpaceName
         */
        AddressSpace addrSp = null;
        for (Iterator<AddressSpace> j = addrSpaceList.iterator(); j.hasNext();) {
            AddressSpace as = j.next();

            if (as.getName() != null && as.getName().equals(data.getAddressSpaceName())) {
                addrSp = as;
                break;
            }
        }
        if (addrSp == null) {
            System.err.println("Error: Unknown 'Address Space' name (\"" + data.getAddressSpaceName() + "\").");
            return false;
        }

        route.add(addrSp.getName());

        /*
         * search SubSpaceName
         */
        SubSpace subSp = null;
        List<SubSpace> ssList = addrSp.getSubSpace();
        for (Iterator<SubSpace> j = ssList.iterator(); j.hasNext();) {
            SubSpace ss = j.next();

            route.add(ss.getName());
            String path = createPathName(route);
            route.remove(ss.getName());
            if (path != null && path.equals(data.getSubSpaceName())) {
                subSp = ss;
                break;
            }

        }
        if (subSp == null) {
            System.err.println("Error: Unknown 'Sub Space' name (\"" + data.getSubSpaceName() + "\").");
            return false;
        }

        /*
         * search SlaveComponentRef in MasterSlaveBinding
         */
        MasterSlaveBindingSet msBindSet = null;
        msBindSet = subSp.getMasterSlaveBindingSet();
        if (msBindSet == null) {
            continue;
        }

        MasterSlaveBinding msBind = null;
        List<MasterSlaveBinding> msBindList = msBindSet.getMasterSlaveBinding();
        SlaveComponent scComp = slaveComponentMap.get(data.getSlaveComponentName());
        if (scComp == null) {
            System.err.println(
                    "Error: Unknown 'Slave Comonent' name (\"" + data.getSlaveComponentName() + "\").");
            return false;
        }
        for (Iterator<MasterSlaveBinding> j = msBindList.iterator(); j.hasNext();) {
            MasterSlaveBinding msb = j.next();
            SlaveComponent sca = (SlaveComponent) msb.getSlaveComponentRef();

            if (sca != null && sca.getId().equals(scComp.getId())) {
                msBind = msb;
                break;
            }
        }
        if (msBind == null) {
            continue;
        }

        /*
         * search MasterComponentRef in Accessor
         */
        Accessor accessor = null;
        List<Accessor> acList = msBind.getAccessor();
        MasterComponent mcComp = masterComponentMap.get(data.getMasterComponentName());
        if (mcComp == null) {
            System.err.println(
                    "Error: Unknown 'Master Comonent' name (\"" + data.getMasterComponentName() + "\").");
            return false;
        }
        for (Iterator<Accessor> j = acList.iterator(); j.hasNext();) {
            Accessor ac = j.next();
            MasterComponent mc = (MasterComponent) ac.getMasterComponentRef();

            if (mc != null && mc.getId().equals(mcComp.getId())) {
                accessor = ac;
                break;
            }
        }
        if (accessor == null) {
            continue;
        }

        /*
         * search PerformanceSet
         */
        PerformanceSet perfrmSet = null;

        if (accessor.getPerformanceSet().size() != 0) {
            perfrmSet = accessor.getPerformanceSet().get(0);
        }
        if (perfrmSet == null) {
            continue;
        }

        /*
         * search Performance
         */
        List<Performance> pfrmList = perfrmSet.getPerformance();
        AccessType atComp = accessTypeMap.get(data.getAccessTypeName());
        if (atComp == null) {
            System.err.println("Error: Unknown 'Access Type' name (\"" + data.getAccessTypeName() + "\").");
            return false;
        }
        for (Iterator<Performance> j = pfrmList.iterator(); j.hasNext();) {
            Performance pfm = j.next();
            AccessType at = (AccessType) pfm.getAccessTypeRef();

            if (at != null && at.getId().equals(atComp.getId())) {
                Latency latency = new Latency();
                Pitch pitch = new Pitch();

                latency.setBest(data.getBestLatency());
                latency.setWorst(data.getWorstLatency());
                latency.setTypical(data.getTypicalLatency());
                pitch.setBest(data.getBestPitch());
                pitch.setWorst(data.getWorstPitch());
                pitch.setTypical(data.getTypicalPitch());

                pfm.setLatency(latency);
                pfm.setPitch(pitch);
                break;
            }
        }
    }

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class.getPackage().getName());

        Marshaller marshaller = context.createMarshaller();
        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            marshaller.setSchema(schema);
        }
        QName qname = new QName("", "SystemConfiguration");

        JAXBElement<SystemConfiguration> elem = new JAXBElement<SystemConfiguration>(qname,
                SystemConfiguration.class, sysConf);

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //         marshaller.marshal(elem, new PrintStream(shimf));
        marshaller.marshal(elem, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
        System.err.println("Error: exception occurs in SHIM file generation"); //$NON-NLS-1$
        return false;
    } catch (SAXException e) {
        e.printStackTrace();
        System.err.println("Error: output SHIM file validation error"); //$NON-NLS-1$
        return false;
    }

    return true;
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

private void createFile(File mxmlFile, String processId) {
    LOGGER.debug(String.format("create file %s for process %s", mxmlFile.getName(), processId));
    try {// ww  w .  jav a 2s.c o  m
        if (mxmlFile.createNewFile()) {
            Marshaller m = jaxbContext.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,
                    "http://is.tm.tue.nl/research/processmining/WorkflowLog.xsd");
            m.setSchema(schema);
            m.marshal(createWorkflowLogTemplate(processId), mxmlFile);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

private Marshaller createMarshaller() throws JAXBException {
    Marshaller m = jaxbContext.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.setSchema(schema);
    return m;//from  ww  w . jav a2s . com
}

From source file:org.opennms.core.xml.JaxbUtils.java

public static Marshaller getMarshallerFor(final Object obj, final JAXBContext jaxbContext) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Map<Class<?>, Marshaller> marshallers = m_marshallers.get();
    if (jaxbContext == null) {
        if (marshallers == null) {
            marshallers = new WeakHashMap<Class<?>, Marshaller>();
            m_marshallers.set(marshallers);
        }/*from  w  w  w  .  j a  v a  2  s  . c  o m*/
        if (marshallers.containsKey(clazz)) {
            LOG.trace("found unmarshaller for {}", clazz);
            return marshallers.get(clazz);
        }
    }
    LOG.trace("creating unmarshaller for {}", clazz);

    try {
        final JAXBContext context;
        if (jaxbContext == null) {
            context = getContextFor(clazz);
        } else {
            context = jaxbContext;
        }
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        if (context.getClass().getName().startsWith("org.eclipse.persistence.jaxb")) {
            marshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER,
                    new EmptyNamespacePrefixMapper());
            marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, true);
        }
        final Schema schema = getValidatorFor(clazz);
        marshaller.setSchema(schema);
        if (jaxbContext == null)
            marshallers.put(clazz, marshaller);

        return marshaller;
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
    }
}

From source file:org.opentravel.schemacompiler.repository.RepositoryFileManager.java

/**
 * Saves the content of the given JAXB element the specified file location.
 * /*from www  .  j a v a  2s  .  com*/
 * @param file
 *            the file to which the JAXB contents should be saved
 * @param jaxbElement
 *            the JAXB element whose content is to be saved
 * @param addToChangeSet
 *            flag indicating whether the saved file should be added to the current change set
 * @throws RepositoryException
 *             thrown if the file cannot be saved
 */
protected void saveFile(File file, JAXBElement<?> jaxbElement, boolean addToChangeSet)
        throws RepositoryException {
    try {
        Marshaller marshaller = jaxbContext.createMarshaller();

        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {

            @Override
            public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
                return REPOSITORY_NAMESPACE.equals(namespaceUri)
                        ? SchemaDeclarations.OTA2_PROJECT_SCHEMA.getDefaultPrefix()
                        : suggestion;
            }

            @Override
            public String[] getPreDeclaredNamespaceUris() {
                return new String[] { REPOSITORY_NAMESPACE };
            }

        });
        marshaller.setSchema(repositoryValidationSchema);

        if (addToChangeSet) {
            addToChangeSet(file);
        }
        marshaller.marshal(jaxbElement, file);

    } catch (JAXBException e) {
        throw new RepositoryException("Unknown error while repository file: " + file.getName(), e);
    }
}

From source file:org.opentravel.schemacompiler.security.impl.AbstractAuthenticationProvider.java

/**
 * Overwrites the current user account file with the given list.
 * /*from ww  w  .ja v a 2s.c  o  m*/
 * @param userList  the list of all user accounts to save
 * @throws RepositoryException  thrown if the user accounts file cannot be updated for any reason
 */
protected void saveUserAccounts(List<UserInfo> userList) throws RepositoryException {
    RepositoryFileManager fileManager = repositoryManager.getFileManager();
    boolean success = false;
    fileManager.startChangeSet();

    try {
        File usersFile = new File(fileManager.getRepositoryLocation(), REPOSITORY_USERS_FILE);
        RepositoryUsers repoUsers = new RepositoryUsers();
        Marshaller marshaller = jaxbContext.createMarshaller();

        repoUsers.getUser().addAll(userList);
        fileManager.addToChangeSet(usersFile);

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
            public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
                return REPOSITORY_EXT_NAMESPACE.equals(namespaceUri) ? "r" : suggestion;
            }

            public String[] getPreDeclaredNamespaceUris() {
                return new String[] { REPOSITORY_EXT_NAMESPACE };
            }
        });
        marshaller.setSchema(validationSchema);
        marshaller.marshal(objectFactory.createRepositoryUsers(repoUsers), usersFile);

        fileManager.commitChangeSet();
        success = true;

    } catch (JAXBException e) {
        throw new RepositoryException("Error committing user updates to file system.", e);

    } finally {
        try {
            if (!success)
                fileManager.rollbackChangeSet();
        } catch (Throwable t) {
        }
    }
}

From source file:org.perfclipse.core.scenario.ScenarioManager.java

/**
 * The createXML method converts scenario model into XML representation 
 * according to PerfCake XML Schema and writes output to output stream out
 * @param model model to be converted/*from  w  ww. jav  a2s  .  co  m*/
 * @param out OutputStream to which xml will be written
 * @throws ScenarioException
 */
public void createXML(org.perfcake.model.Scenario model, OutputStream out) throws ScenarioException {
    try {
        JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        //obtain url to schema definition, which is located somewhere in PerfCakeBundle
        URL schemaUrl = SchemaScanner.getSchema();
        Schema schema = schemaFactory.newSchema(schemaUrl);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(schema);

        //add line breaks and indentation into output
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(model, out);
    } catch (JAXBException e) {
        log.error("JAXB error", e);
        throw new ScenarioException("JAXB error", e);
    } catch (MalformedURLException e) {
        log.error("Malformed url", e);
        throw new ScenarioException("Malformed url", e);
    } catch (SAXException e) {
        log.error("Cannot obtain schema definition", e);
        throw new ScenarioException("Cannot obtain schema definition", e);
    } catch (IOException e) {
        log.error("Cannot obtain XML schema file", e);
        throw new ScenarioException("Cannot obtain XML schema file", e);
    }
}