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:com.springsource.hq.plugin.tcserver.serverconfig.ProfileMarshaller.java

public void marshal(Profile graph, Result result) throws JAXBException, IOException {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setSchema(profileSchema);
    marshaller.marshal(graph, result);/*w  ww  .jav  a 2  s  . c o m*/
}

From source file:com.aionemu.gameserver.dataholders.SpawnsData2.java

public synchronized boolean saveSpawn(Player admin, VisibleObject visibleObject, boolean delete)
        throws IOException {
    SpawnTemplate spawn = visibleObject.getSpawn();
    Spawn oldGroup = DataManager.SPAWNS_DATA2.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());

    File xml = new File("./data/static_data/spawns/" + getRelativePath(visibleObject));
    SpawnsData2 data = null;//from w ww.j a  v a  2s  .  c  o m
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    JAXBContext jc = null;
    boolean addGroup = false;

    try {
        schema = sf.newSchema(new File("./data/static_data/spawns/spawns.xsd"));
        jc = JAXBContext.newInstance(SpawnsData2.class);
    } catch (Exception e) {
        // ignore, if schemas are wrong then we even could not call the command;
    }

    FileInputStream fin = null;
    if (xml.exists()) {
        try {
            fin = new FileInputStream(xml);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            unmarshaller.setSchema(schema);
            data = (SpawnsData2) unmarshaller.unmarshal(fin);
        } catch (Exception e) {
            log.error(e.getMessage());
            PacketSendUtility.sendMessage(admin, "Could not load old XML file!");
            return false;
        } finally {
            if (fin != null) {
                fin.close();
            }
        }
    }

    if (oldGroup == null || oldGroup.isCustom()) {
        if (data == null) {
            data = new SpawnsData2();
        }

        oldGroup = data.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());
        if (oldGroup == null) {
            oldGroup = new Spawn(spawn.getNpcId(), spawn.getRespawnTime(), spawn.getHandlerType());
            addGroup = true;
        }
    } else {
        if (data == null) {
            data = DataManager.SPAWNS_DATA2;
        }
        // only remove from memory, will be added back later
        allSpawnMaps.get(visibleObject.getWorldId()).remove(spawn.getNpcId());
        addGroup = true;
    }

    SpawnSpotTemplate spot = new SpawnSpotTemplate(visibleObject.getX(), visibleObject.getY(),
            visibleObject.getZ(), visibleObject.getHeading(), visibleObject.getSpawn().getRandomWalk(),
            visibleObject.getSpawn().getWalkerId(), visibleObject.getSpawn().getWalkerIndex());
    boolean changeX = visibleObject.getX() != spawn.getX();
    boolean changeY = visibleObject.getY() != spawn.getY();
    boolean changeZ = visibleObject.getZ() != spawn.getZ();
    boolean changeH = visibleObject.getHeading() != spawn.getHeading();
    if (changeH && visibleObject instanceof Npc) {
        Npc npc = (Npc) visibleObject;
        if (!npc.isAtSpawnLocation() || !npc.isInState(CreatureState.NPC_IDLE) || changeX || changeY
                || changeZ) {
            // if H changed, XSD validation fails, because it may be negative; thus, reset it back
            visibleObject.setXYZH(null, null, null, spawn.getHeading());
            changeH = false;
        }
    }

    SpawnSpotTemplate oldSpot = null;
    for (SpawnSpotTemplate s : oldGroup.getSpawnSpotTemplates()) {
        if (s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()) {
            if (delete || !StringUtils.equals(s.getWalkerId(), spot.getWalkerId())) {
                oldSpot = s;
                break;
            } else {
                return false; // nothing to change
            }
        } else if (changeX && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()
                || changeY && s.getX() == spot.getX() && s.getZ() == spot.getZ()
                        && s.getHeading() == spot.getHeading()
                || changeZ && s.getX() == spot.getX() && s.getY() == spot.getY()
                        && s.getHeading() == spot.getHeading()
                || changeH && s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()) {
            oldSpot = s;
            break;
        }
    }

    if (oldSpot != null) {
        oldGroup.getSpawnSpotTemplates().remove(oldSpot);
    }
    if (!delete) {
        oldGroup.addSpawnSpot(spot);
    }
    oldGroup.setCustom(true);

    SpawnMap map = null;
    if (data.templates == null) {
        data.templates = new ArrayList<SpawnMap>();
        map = new SpawnMap(spawn.getWorldId());
        data.templates.add(map);
    } else {
        map = data.templates.get(0);
    }

    if (addGroup) {
        map.addSpawns(oldGroup);
    }

    FileOutputStream fos = null;
    try {
        xml.getParentFile().mkdir();
        fos = new FileOutputStream(xml);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(data, fos);
        DataManager.SPAWNS_DATA2.templates = data.templates;
        DataManager.SPAWNS_DATA2.afterUnmarshal(null, null);
        DataManager.SPAWNS_DATA2.clearTemplates();
        data.clearTemplates();
    } catch (Exception e) {
        log.error(e.getMessage());
        PacketSendUtility.sendMessage(admin, "Could not save XML file!");
        return false;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected String toXml(Object o) {
    try {//from   w  w  w  .  j  av  a  2 s  . c  o m
        StringWriter sw = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(o.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
        marshaller.setSchema(null);
        marshaller.marshal(o, sw);
        return sw.toString();
    } catch (JAXBException e) {
        if (logger.isTraceEnabled())
            logger.trace(e.getMessage(), e);
        if (logger.isInfoEnabled())
            logger.info(e.getMessage());
    }
    return null;
}

From source file:no.digipost.api.client.representations.XsdValidationTest.java

public <T> T marshallValidateAndUnmarshall(T element, boolean log) {
    InputStream in = null;/*  w  w  w.  j  a v  a 2s . co m*/
    try (ByteArrayOutputStream resultXml = new ByteArrayOutputStream()) {
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty("jaxb.formatted.output", true);
        marshaller.marshal(element, new StreamResult(resultXml));
        resultXml.flush();
        byte[] xml = resultXml.toByteArray();
        if (log) {
            LOG.info("Marshalled XML:\n{}", new String(xml));
        }
        in = new ByteArrayInputStream(xml);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        @SuppressWarnings("unchecked")
        T unmarshalled = (T) unmarshaller.unmarshal(in);
        return unmarshalled;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        closeQuietly(in);
    }
}

From source file:org.apache.cxf.jaxbplus.io.DataWriterImpl.java

public Marshaller createMarshaller(Object elValue, MessagePartInfo part) {
    Class<?> cls = null;//from  ww  w. ja  v a  2s  .com
    if (part != null) {
        cls = part.getTypeClass();
    }

    if (cls == null) {
        cls = null != elValue ? elValue.getClass() : null;
    }

    if (cls != null && cls.isArray() && elValue instanceof Collection) {
        Collection<?> col = (Collection<?>) elValue;
        elValue = col.toArray((Object[]) Array.newInstance(cls.getComponentType(), col.size()));
    }
    Marshaller marshaller;
    try {

        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        marshaller.setListener(databinding.getMarshallerListener());
        if (databinding.getValidationEventHandler() != null) {
            marshaller.setEventHandler(databinding.getValidationEventHandler());
        }

        final Map<String, String> nspref = databinding.getDeclaredNamespaceMappings();
        if (nspref != null) {
            JAXBUtils.setNamespaceWrapper(nspref, marshaller);
        }
        if (databinding.getMarshallerProperties() != null) {
            for (Map.Entry<String, Object> propEntry : databinding.getMarshallerProperties().entrySet()) {
                try {
                    marshaller.setProperty(propEntry.getKey(), propEntry.getValue());
                } catch (PropertyException pe) {
                    LOG.log(Level.INFO, "PropertyException setting Marshaller properties", pe);
                }
            }
        }

        marshaller.setSchema(schema);
        AttachmentMarshaller atmarsh = getAttachmentMarshaller();
        marshaller.setAttachmentMarshaller(atmarsh);

        if (schema != null && atmarsh instanceof JAXBAttachmentMarshaller) {
            //we need a special even handler for XOP attachments 
            marshaller.setEventHandler(new MtomValidationHandler(marshaller.getEventHandler(),
                    (JAXBAttachmentMarshaller) atmarsh));
        }
    } catch (JAXBException ex) {
        if (ex instanceof javax.xml.bind.MarshalException) {
            javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException) ex;
            Message faultMessage = new Message("MARSHAL_ERROR", LOG,
                    marshalEx.getLinkedException().getMessage());
            throw new Fault(faultMessage, ex);
        } else {
            throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
        }
    }
    return marshaller;
}

From source file:org.apache.nifi.authorization.FileAccessPolicyProvider.java

private void saveAuthorizations(final Authorizations authorizations) throws JAXBException {
    final Marshaller marshaller = JAXB_AUTHORIZATIONS_CONTEXT.createMarshaller();
    marshaller.setSchema(authorizationsSchema);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(authorizations, authorizationsFile);
}

From source file:org.apache.nifi.authorization.FileAuthorizer.java

private void saveTenants(final Tenants tenants) throws JAXBException {
    final Marshaller marshaller = JAXB_TENANTS_CONTEXT.createMarshaller();
    marshaller.setSchema(tenantsSchema);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(tenants, tenantsFile);
}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

/**
 * Initializes java xml bindings, builds the document and then marshalls
 * it to the writer./*  ww  w.  ja v  a 2s  .co  m*/
 * 
 * @throws InternServerException
 *             if the document can't be marshalled
 */
private void serialize(final Writer writer, final BibsonomyXML xmlDoc) throws InternServerException {
    try {
        // initialize context for java xml bindings
        final JAXBContext jc = this.getJAXBContext();

        // buildup document model
        final JAXBElement<BibsonomyXML> webserviceElement = new ObjectFactory().createBibsonomy(xmlDoc);

        // create a marshaller
        final Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (this.validateXMLOutput) {
            // validate the XML produced by the marshaller
            marshaller.setSchema(schema);
        }

        // marshal to the writer
        this.marshal(marshaller, webserviceElement, writer);
        // TODO log
        // log.debug("");
    } catch (final JAXBException e) {
        final Throwable linkedException = e.getLinkedException();
        if (present(linkedException) && linkedException.getClass() == SAXParseException.class) {
            final SAXParseException ex = (SAXParseException) linkedException;
            throw new BadRequestOrResponseException("Error while parsing XML (Line " + ex.getLineNumber()
                    + ", Column " + ex.getColumnNumber() + ": " + ex.getMessage());
        }
        throw new InternServerException(e.toString());
    }
}

From source file:org.bonitasoft.engine.io.IOUtil.java

public static byte[] marshallObjectToXML(final Object jaxbModel, final URL schemaURL)
        throws JAXBException, IOException, SAXException {
    if (jaxbModel == null) {
        return null;
    }/*from   ww  w .  j a  v a2 s .  com*/
    if (schemaURL == null) {
        throw new IllegalArgumentException("schemaURL is null");
    }
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(schemaURL);
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        final JAXBContext contextObj = JAXBContext.newInstance(jaxbModel.getClass());
        final Marshaller m = contextObj.createMarshaller();
        m.setSchema(schema);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(jaxbModel, baos);
        return baos.toByteArray();
    }
}

From source file:org.echocat.jability.configuration.ConfigurationMarshaller.java

@Nonnull
private static Marshaller marshallerFor(@Nonnull Configuration configuration) throws ConfigurationException {
    final Marshaller marshaller;
    try {//from   w  w w.  j  a v  a2  s. c  om
        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 ConfigurationException("Could not create marshaller to marshal " + configuration + ".", e);
    }
    return marshaller;
}