Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java

/** Private method which validates a XML document at a given location.
 *
 * @param location String representing the location where the document can be found.
 *
 * @throws IOException/* ww  w .j  a va2  s.co m*/
 * @throws SAXException
 */
// <editor-fold defaultstate="" desc="validate(String location) method.">
private void validate(String location) throws IOException, SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(SCHEMA_FACTORY);
    File schemaLocation = new File(SCHEMA_FILE);
    Schema schema = factory.newSchema(schemaLocation);
    Validator validator = schema.newValidator();

    Source source = new StreamSource(new File(location));
    validator.validate(source);
}

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

public static boolean validation(String schema_file, String xml_file) {
    Object obj = null;/*from   ww  w  .  j  ava2  s. c o m*/

    // create a JAXBContext capable of handling classes generated into
    // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance();

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file));

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error(se.toString());
        }

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        LOG.error(e.toString());
    }

    return true;

}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

private static Schema getValidatorFor(final Class<?> origClazz) {
    final Class<?> clazz = (Class<?>) (origClazz instanceof Class<?> ? origClazz : origClazz.getClass());
    LogUtils.tracef(clazz, "finding XSD for class %s", clazz);

    if (m_schemas.containsKey(clazz)) {
        return m_schemas.get(clazz);
    }// w ww  .j a va 2 s .  c o m

    final ValidateUsing schemaFileAnnotation = clazz.getAnnotation(ValidateUsing.class);
    if (schemaFileAnnotation == null || schemaFileAnnotation.value() == null) {
        return null;
    }

    final String schemaFileName = schemaFileAnnotation.value();
    InputStream schemaInputStream = null;
    try {
        final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        if (schemaInputStream == null) {
            final File schemaFile = new File(
                    System.getProperty("opennms.home") + "/share/xsds/" + schemaFileName);
            if (schemaFile.exists()) {
                LogUtils.tracef(clazz, "using file %s", schemaFile);
                schemaInputStream = new FileInputStream(schemaFile);
            }
            ;
        }
        if (schemaInputStream == null) {
            final File schemaFile = new File("target/xsds/" + schemaFileName);
            if (schemaFile.exists()) {
                LogUtils.tracef(clazz, "using file %s", schemaFile);
                schemaInputStream = new FileInputStream(schemaFile);
            }
            ;
        }
        if (schemaInputStream == null) {
            final URL schemaResource = Thread.currentThread().getContextClassLoader()
                    .getResource("xsds/" + schemaFileName);
            if (schemaResource == null) {
                LogUtils.debugf(clazz, "Unable to load resource xsds/%s from the classpath.", schemaFileName);
            } else {
                LogUtils.tracef(clazz, "using resource %s from classpath", schemaResource);
                schemaInputStream = schemaResource.openStream();
            }
        }
        if (schemaInputStream == null) {
            LogUtils.tracef(clazz, "Did not find a suitable XSD.  Skipping.");
            return null;
        }
        final Schema schema = factory.newSchema(new StreamSource(schemaInputStream));
        m_schemas.put(clazz, schema);
        return schema;
    } catch (final Throwable t) {
        LogUtils.warnf(clazz, t, "an error occurred while attempting to load %s for validation",
                schemaFileName);
        return null;
    } finally {
        IOUtils.closeQuietly(schemaInputStream);
    }
}

From source file:org.openremote.beehive.configuration.www.UsersAPI.java

private File createControllerXmlFile(java.nio.file.Path temporaryFolder, Account account) {
    File controllerXmlFile = new File(temporaryFolder.toFile(), "controller.xml");

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    try {/*  www . ja  v a 2 s. c  o m*/
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
        Document document = domImplementation.createDocument(OPENREMOTE_NAMESPACE, "openremote", null);
        document.getDocumentElement().setAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                "xsi:schemaLocation",
                "http://www.openremote.org http://www.openremote.org/schemas/controller.xsd");

        Element componentsElement = document.createElementNS(OPENREMOTE_NAMESPACE, "components");
        document.getDocumentElement().appendChild(componentsElement);
        writeSensors(document, document.getDocumentElement(), account, findHighestCommandId(account));
        writeCommands(document, document.getDocumentElement(), account);
        writeConfig(document, document.getDocumentElement(), account);

        // Document is fully built, validate against schema before writing to file
        URL xsdResource = UsersAPI.class.getResource(CONTROLLER_XSD_PATH);
        if (xsdResource == null) {
            log.error("Cannot find XSD schema ''{0}''. Disabling validation...", CONTROLLER_XSD_PATH);
        } else {
            String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(language);
            Schema schema = factory.newSchema(xsdResource);
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(document));
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Result output = new StreamResult(controllerXmlFile);
        Source input = new DOMSource(document);
        transformer.transform(input, output);
    } catch (ParserConfigurationException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (TransformerConfigurationException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (TransformerException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (SAXException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (IOException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return controllerXmlFile;
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Initializes the site components like modules, templates, actions etc.
 * //from   w w w  .  j  av a 2 s.  com
 * @throws Exception
 *           if initialization fails
 */
private void initializeSiteComponents() throws Exception {

    logger.debug("Initializing site '{}'", this);

    final Bundle bundle = bundleContext.getBundle();

    // Load i18n dictionary
    Enumeration<URL> i18nEnum = bundle.findEntries("site/i18n", "*.xml", true);
    while (i18nEnum != null && i18nEnum.hasMoreElements()) {
        i18n.addDictionary(i18nEnum.nextElement());
    }

    // Prepare schema validator
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/module.xsd");
    Schema moduleSchema = schemaFactory.newSchema(schemaUrl);

    // Set up the document builder
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(moduleSchema);
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    // Load the modules
    final Enumeration<URL> e = bundle.findEntries("site", "module.xml", true);

    if (e != null) {
        while (e.hasMoreElements()) {
            URL moduleXmlUrl = e.nextElement();
            int endIndex = moduleXmlUrl.toExternalForm().lastIndexOf('/');
            URL moduleUrl = new URL(moduleXmlUrl.toExternalForm().substring(0, endIndex));
            logger.debug("Loading module '{}' for site '{}'", moduleXmlUrl, this);

            // Load and validate the module descriptor
            ValidationErrorHandler errorHandler = new ValidationErrorHandler(moduleXmlUrl);
            docBuilder.setErrorHandler(errorHandler);
            Document moduleXml = docBuilder.parse(moduleXmlUrl.openStream());
            if (errorHandler.hasErrors()) {
                logger.error("Errors found while validating module descriptor {}. Site '{}' is not loaded",
                        moduleXml, this);
                throw new IllegalStateException("Errors found while validating module descriptor " + moduleXml);
            }

            // We need the module id even if the module initialization fails to log
            // a proper error message
            Node moduleNode = moduleXml.getFirstChild();
            String moduleId = moduleNode.getAttributes().getNamedItem("id").getNodeValue();

            Module module;
            try {
                module = ModuleImpl.fromXml(moduleNode);
                logger.debug("Module '{}' loaded for site '{}'", module, this);
            } catch (Throwable t) {
                logger.error("Error loading module '{}' of site {}", moduleId, identifier);
                if (t instanceof Exception)
                    throw (Exception) t;
                throw new Exception(t);
            }

            // If module is disabled, don't add it to the site
            if (!module.isEnabled()) {
                logger.info("Found disabled module '{}' in site '{}'", module, this);
                continue;
            }

            // Make sure there is only one module with this identifier
            if (modules.containsKey(module.getIdentifier())) {
                logger.warn("A module with id '{}' is already registered in site '{}'", module.getIdentifier(),
                        identifier);
                logger.error("Module '{}' is not registered due to conflicting identifier",
                        module.getIdentifier());
                continue;
            }

            // Check inter-module compatibility
            for (Module m : modules.values()) {

                // Check actions
                for (Action a : m.getActions()) {
                    for (Action action : module.getActions()) {
                        if (action.getIdentifier().equals(a.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines an action with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, a.getIdentifier() });
                        } else if (action.getPath().equals(a.getPath())) {
                            logger.warn("Module '{}' of site '{}' already defines an action at '{}'",
                                    new String[] { m.getIdentifier(), identifier, a.getPath() });
                            logger.error(
                                    "Module '{}' of site '{}' is not registered due to conflicting mountpoints",
                                    m.getIdentifier(), identifier);
                            continue;
                        }
                    }
                }

                // Check image styles
                for (ImageStyle s : m.getImageStyles()) {
                    for (ImageStyle style : module.getImageStyles()) {
                        if (style.getIdentifier().equals(s.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines an image style with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, s.getIdentifier() });
                        }
                    }
                }

                // Check jobs
                for (Job j : m.getJobs()) {
                    for (Job job : module.getJobs()) {
                        if (job.getIdentifier().equals(j.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines a job with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, j.getIdentifier() });
                        }
                    }
                }

            }

            addModule(module);

            // Do this as last step since we don't want to have i18n dictionaries of
            // an invalid or disabled module in the site
            String i18nPath = UrlUtils.concat(moduleUrl.getPath(), "i18n");
            i18nEnum = bundle.findEntries(i18nPath, "*.xml", true);
            while (i18nEnum != null && i18nEnum.hasMoreElements()) {
                i18n.addDictionary(i18nEnum.nextElement());
            }
        }

    } else {
        logger.debug("Site '{}' has no modules", this);
    }

    // Look for a job scheduler
    logger.debug("Signing up for a job scheduling services");
    schedulingServiceTracker = new SchedulingServiceTracker(bundleContext, this);
    schedulingServiceTracker.open();

    // Load the tests
    if (!Environment.Production.equals(environment))
        integrationTests = loadIntegrationTests();
    else
        logger.info("Skipped loading of integration tests due to environment '{}'", environment);

    siteInitialized = true;
    logger.info("Site '{}' initialized", this);
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

private boolean isMappingValid(File mappingFile) throws IOException {
    URL mappingSchema = getClass().getResource(MAPPING_SCHEMA);
    Source xmlFile = new StreamSource(mappingFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    javax.xml.validation.Schema schema = null;
    try {// w  w w  .jav a 2 s  .  com
        schema = schemaFactory.newSchema(mappingSchema);
    } catch (SAXException e) {
        fail("Exception parsing mapping schema: " + e.getMessage());
    }

    @SuppressWarnings("null")
    Validator validator = schema.newValidator();
    try {
        validator.validate(xmlFile);
        return true;
    } catch (SAXException e) {
        log.error("Mapping file validation failed", e);
        return false;
    }
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

static Schema getBwSchema() throws SAXException {
    if (SCHEMA_BWMETA == null) {
        SCHEMA_BWMETA = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(CejshBuilder.class.getResource(XSD_FILENAME));
    }/*from www. jav a  2s  .c o m*/
    return SCHEMA_BWMETA;
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples./*w ww . j ava 2s .c om*/
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}

From source file:io.aino.agents.wso2.mediator.factory.AinoMediatorFactory.java

private void validateXml(OMElement element, String schemaPath) throws SAXException, IOException {
    OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();

    StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, element.getXMLStreamReader());

    Element domElement = (Element) doomBuilder.getDocumentElement();

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(this.getClass().getResourceAsStream(schemaPath));

    Schema schema = factory.newSchema(source);

    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(domElement));
}

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  w w  .  j a va2 s.c om*/
    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;
}