Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java

private static final BaukConfiguration findConfiguration() {
    LOG.info(/*  ww  w .j av a  2s  . c om*/
            "Trying to find configuration file. First if specified as {} system property and then as {} in classpath",
            CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
    final String configFile = System.getProperty(CONFIG_FILE_PROP_NAME);
    InputStream is = null;
    if (StringUtil.isEmpty(configFile)) {
        LOG.info(
                "Was not able to find system property {}. Trying to find default configuration {} in classpath",
                CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
        is = StreamHorizonEngine.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG_FILE_NAME);
        if (is == null) {
            LOG.error("Was not able to find file {} in the classpath. Unable to start application",
                    DEFAULT_CONFIG_FILE_NAME);
            return null;
        }
        LOG.info("Found configuration file {} in classpath", DEFAULT_CONFIG_FILE_NAME);
    } else {
        LOG.info("Found system property {}={}. Will try to load it as configuration...", CONFIG_FILE_PROP_NAME,
                configFile);
        final File cFile = new File(configFile);
        try {
            if (cFile.exists() && cFile.isFile()) {
                LOG.debug("Loading config file [{}] from file system", configFile);
                is = new FileInputStream(configFile);
            } else {
                LOG.debug("Loading config file [{}] from classpath", configFile);
                is = StreamHorizonEngine.class.getClass().getResourceAsStream(configFile);
            }
            LOG.info("Successfully found configuration [{}] on file system", configFile);
        } catch (final FileNotFoundException fnfe) {
            LOG.error("Was not able to find file {}. Use full, absolute path.", configFile);
            return null;
        }
    }
    if (is == null) {
        return null;
    }
    try {
        LOG.debug("Trying to load configuration from xml file");
        final JAXBContext jaxbContext = JAXBContext.newInstance(BaukConfiguration.class);
        final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(StreamHorizonEngine.class.getResource("/bauk_config.xsd"));
        jaxbUnmarshaller.setSchema(schema);
        final BaukConfiguration config = (BaukConfiguration) jaxbUnmarshaller.unmarshal(is);
        LOG.info("Successfully loaded configuration");
        return config;
    } catch (final Exception exc) {
        LOG.error("Exception while loading configuration", exc);
        exc.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.denimgroup.threadfix.importer.impl.upload.SSVLChannelImporter.java

@Nonnull
@Override/*from w w  w.  ja v a2 s .  c om*/
public ScanCheckResultBean checkFile() {

    boolean valid = false;
    String[] schemaList = new String[] { "ssvl.xsd", "ssvl_v0.3.xsd" };

    for (String schemaFilePath : schemaList) {

        try {
            URL schemaFile = ResourceUtils.getResourceAsUrl(schemaFilePath);

            if (schemaFile == null) {
                throw new IllegalStateException("ssvl.xsd file not available from ClassLoader. Fix that.");
            }

            if (inputFileName == null) {
                throw new IllegalStateException("inputFileName was null, unable to load scan file.");
            }

            Source xmlFile = new StreamSource(new File(inputFileName));
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);

            valid = true;
            log.info(xmlFile.getSystemId() + " is valid");
            break;

        } catch (MalformedURLException e) {
            log.error("Code contained an incorrect path to the XSD file.", e);
        } catch (SAXException e) {
            log.warn("SAX Exception encountered, ", e);
        } catch (IOException e) {
            log.warn("IOException encountered, ", e);
        }
    }

    if (valid) {
        return testSAXInput(new SSVLChannelSAXValidator());
    } else {
        return new ScanCheckResultBean(ScanImportStatus.FAILED_XSD);
    }
}

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 {//from w w w .  j av  a2 s.  co  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.
 * //w  ww.j a va2s . 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 {/*from w w w .ja  v  a  2 s.c  o m*/
        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));
    }//  ww w  . ja v a2s.c o  m
    return SCHEMA_BWMETA;
}

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

/**
 * Standard test for XSD examples./*from  ww  w .ja  va  2 s  .  c  o m*/
 * 
 * @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;/*w w w . j a v a2s  . 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;
}