Validate the parsed gateway configuration file.

@param configDoc the XmlObject representing the gateway-config document
19957
private void validateGatewayConfig(GatewayConfigDocument configDoc, List<String> preProcessErrors) {
        List<XmlError> errorList = new ArrayList<>();
        for (String preProcessError : preProcessErrors) {
            errorList.add(XmlError.forMessage(preProcessError, XmlError.SEVERITY_ERROR));
        }
        if (errorList.isEmpty()) {
            XmlOptions validationOptions = new XmlOptions();
            validationOptions.setLoadLineNumbers();
            validationOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT);
            validationOptions.setErrorListener(errorList);
            boolean valid = configDoc.validate(validationOptions);
            if (valid) {
                // Perform custom validations that aren't expressed in the XSD
                GatewayConfigDocument.GatewayConfig config = configDoc.getGatewayConfig();

                ServiceType[] services = config.getServiceArray();
                if (services != null && services.length > 0) {
                    List<String> serviceNames = new ArrayList<>();
                    for (ServiceType service : services) {
                        String name = service.getName();
                        if (name == null || name.length() == 0) {
                            errorList.add(XmlError.forMessage("All services must have unique non-empty names",
                                    XmlError.SEVERITY_ERROR));
                        } else if (serviceNames.indexOf(name) >= 0) {
                            errorList.add(XmlError
                                    .forMessage("Service name must be unique. More than one service named '" + name + "'",
                                            XmlError.SEVERITY_ERROR));
                        } else {
                            serviceNames.add(name);
                        }
                    }
                }

                SecurityType[] security = config.getSecurityArray();
                if (security != null && security.length > 1) {
                    errorList.add(XmlError.forMessage("Multiple <security> elements found; only one allowed",
                            XmlError.SEVERITY_ERROR));
                }
                ServiceDefaultsType[] serviceDefaults = config.getServiceDefaultsArray();
                if (serviceDefaults != null && serviceDefaults.length > 1) {
                    errorList.add(XmlError.forMessage("Multiple <service-defaults> elements found; only one allowed",
                            XmlError.SEVERITY_ERROR));
                }
                ClusterType[] clusterConfigs = config.getClusterArray();
                if (clusterConfigs != null && clusterConfigs.length > 1) {
                    errorList.add(XmlError.forMessage("Multiple <cluster> elements found; only one allowed",
                            XmlError.SEVERITY_ERROR));
                }
            }
        }

        // Report all validation errors
        if (errorList.size() > 0) {
            String validationError = "Validation errors in gateway configuration file";
            LOGGER.error(validationError);
            for (XmlError error : errorList) {
                int line = error.getLine();
                if (line != -1) {
                    int column = error.getColumn();
                    if (column == -1) {
                        LOGGER.error("  Line: " + line);
                    } else {
                        LOGGER.error("  Line: " + line + " Column: " + column);
                    }
                }
                LOGGER.error("  " + error.getMessage().replaceAll("@" + GatewayConfigNamespace.CURRENT_NS, ""));
                if (error.getMessage().contains("notify-options") || error.getMessage().contains("notify")) {
                    validationError = "Could not start because of references to APNs in the configuration."
                     + " APNs is not supported in this version of the gateway, but will be added in a future release.";
                    LOGGER.error(validationError);

                }
                if (error.getMessage().contains("DataRateString")) {
                    // Yeah, it's crude, but customers are going to keep tripping over cases like 100KB/s being invalid otherwise
                    // Example output:
                    // ERROR - Validation errors in gateway configuration file
                    // ERROR -   Line: 12 Column: 36
                    // ERROR -   string value '1m' does not match pattern for DataRateString in namespace http://xmlns.kaazing
                    // .com/2012/08/gateway
                    // ERROR -   (permitted data rate units are B/s, kB/s, KiB/s, kB/s, MB/s, and MiB/s)
                    // ERROR -   <xml-fragment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
                    LOGGER.error("  " + "(permitted data rate units are B/s, kB/s, KiB/s, kB/s, MB/s, and MiB/s)");
                }
                if (error.getCursorLocation() != null) {
                    LOGGER.error("  " + error.getCursorLocation().xmlText());
                }
            }
            throw new GatewayConfigParserException(validationError);
        }
    }
471121
protected boolean postValidateXML(final ContentSpec contentSpec, final KeyValueNode<String> keyValueNode,
            final String wrappedElement, String parentElement) {
        String fixedWrappedElement = DocBookUtilities.escapeForXML(wrappedElement);

        // Get the docbook DTD
        final String docbookFileName;
        final XMLValidator.ValidationMethod validationMethod;
        final byte[] docbookSchema;
        if (contentSpec.getFormat().equalsIgnoreCase(CommonConstants.DOCBOOK_50_TITLE)) {
            final BlobConstantWrapper docbookRng = blobConstantProvider.getBlobConstant(serverEntities.getDocBook50RNGBlobConstantId());
            docbookFileName = docbookRng.getName();
            validationMethod = XMLValidator.ValidationMethod.RELAXNG;
            docbookSchema = docbookRng.getValue();
            // Further wrap the element for docbook 5.0
            if (CommonConstants.CS_TITLE_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                fixedWrappedElement = DocBookUtilities.addDocBook50Namespace("<book><info>" + fixedWrappedElement + "</info></book>");
            } else {
                fixedWrappedElement = DocBookUtilities.addDocBook50Namespace("<book><info><title />" + fixedWrappedElement + "</info></book>");
            }
            parentElement = "book";
        } else {
            final BlobConstantWrapper rocbookDtd = blobConstantProvider.getBlobConstant(serverEntities.getRocBook45DTDBlobConstantId());
            docbookFileName = rocbookDtd.getName();
            validationMethod = XMLValidator.ValidationMethod.DTD;
            docbookSchema = rocbookDtd.getValue();
        }

        // Create the dummy XML entities file
        final StringBuilder xmlEntities = new StringBuilder(DocBookUtilities.DOCBOOK_ENTITIES_STRING);
        xmlEntities.append("\n").append(CSConstants.DUMMY_CS_NAME_ENT_FILE);
        if (!isNullOrEmpty(contentSpec.getEntities())) {
            xmlEntities.append(contentSpec.getEntities());
        }

        // Validate the XML content against the dtd
        final XMLValidator validator = new XMLValidator(false);
        if (!validator.validate(validationMethod, fixedWrappedElement, docbookFileName, docbookSchema, xmlEntities.toString(),
                parentElement)) {
            final String line = keyValueNode.getText();
            log.error(String.format(ProcessorConstants.ERROR_INVALID_METADATA_MSG, keyValueNode.getKey(), validator.getErrorText(), line));

            return false;
        }

        return true;
    }
1342192
public static void validateXml(Node doc, File schemaFile)
 throws AlipayApiException {
        validateXml(doc, getInputStream(schemaFile));
    }
350238
@Override
    public InputStream validateResource(InputStream configDocInputStream, String docLocation) throws ConfigValidationException {

        errorMsgIssued = false;
        InputStream returnInputStream = null;

        try {
            // Reads the input stream into an output stream where we can copy it
            byte[] bfr = new byte[4096];
            int len = 0;
            ByteArrayOutputStream bfrOutputStream = new ByteArrayOutputStream();
            while ((len = configDocInputStream.read(bfr, 0, bfr.length)) > -1)
                bfrOutputStream.write(bfr, 0, len);
            configDocInputStream.close();
            bfrOutputStream.close();

            // Makes two copies of the input stream (one for us and one for the
            // the configuration document parser)
            InputStream validatorInputStream =
                            new ByteArrayInputStream(bfrOutputStream.toByteArray());
            returnInputStream = new ByteArrayInputStream(bfrOutputStream.toByteArray());

            // Parses the document to be verified
            Document document = dbFactory.newDocumentBuilder().parse(validatorInputStream);

            // Verifies the signature
            verifyDocument(document, docLocation);
        }

        // An error occurred while attempting to verify the document signature
        catch (Throwable t) {
            if (!errorMsgIssued) {
                if (t instanceof SAXException)
                    printErrorMessage("error.configValidator.parseFailed",
                                      docLocation, t.getMessage());
                else if (t instanceof MarshalException)
                    printErrorMessage("error.configValidator.unmarshalFailed",
                                      docLocation, t.getMessage());
                else
                    printErrorMessage("error.configValidator.error",
                                      docLocation, t.getMessage());
            }

            FFDCFilter.processException(t, CLASS_NAME, "138", this, new Object[] { docLocation });

            returnInputStream = null;

            // Throw exception to terminate the server
            throw new ConfigValidationException("Configuration parsing encountered an invalid document", docLocation);
        }

        return returnInputStream;
    }
1219141
public void readConfiguration(InputStream inputStream) throws TracerFactory.Exception {
    if (this.traceConfigSchema == null)
      System.err.println("CAUTION: Unable to validate the given configuration against a schema.");

    DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    builderFactory.setXIncludeAware(false);

    try {
      DocumentBuilder parser = builderFactory.newDocumentBuilder();
      Document tracerConfigDoc = parser.parse(inputStream);

      if (this.traceConfigSchema != null) {
        DOMSource domSource = new DOMSource(tracerConfigDoc);
        Validator traceConfigValidator = this.traceConfigSchema.newValidator();
        TracerFactory.ErrorHandler errorHandler = new TracerFactory.ErrorHandler();
        traceConfigValidator.setErrorHandler(errorHandler);
        traceConfigValidator.validate(domSource);
      }
      
      this.poolWriteLock.lock();
      try {
        NodeList tracerNodes = (NodeList) this.xpath.evaluate("/dns:TraceConfig/dns:Pool/dns:TraceLogger", tracerConfigDoc.getDocumentElement(), XPathConstants.NODESET);
        System.out.println();
        System.out.println("Configured Pool Tracers = " + tracerNodes.getLength());
        for (int i = 0; i < tracerNodes.getLength(); i++) {
          System.out.println();
          System.out.println("(+) " + (i + 1) + ". TraceLogger");
          Element tracerElement = (Element) tracerNodes.item(i);
          if (!tracerElement.hasAttribute("name"))
            throw new TracerFactory.Exception("Missing 'name' attribut.");
          String name = tracerElement.getAttribute("name");
          String className = tracerElement.getAttribute("class");
          System.out.println("name = " + name);
          System.out.println("className = " + className);
          Class<?> tracerClass = Class.forName(className);
          if (!AbstractTracer.class.isAssignableFrom(tracerClass))
            throw new TracerFactory.Exception("Illegal tracer class!");
          AbstractTracer tracer = createTracer((Class<? extends AbstractTracer>) tracerClass, name);
          tracer.readConfiguration(this.xpath, tracerElement);

  //        synchronized (this.mapGuardObj) {
  //          this.tracerPool.put(name, tracer);
  //        }
          this.tracerPool.put(name, tracer);
        }

        NodeList threadNodes = (NodeList) this.xpath.evaluate("/dns:TraceConfig/dns:Map/dns:Threads/dns:Thread", tracerConfigDoc.getDocumentElement(), XPathConstants.NODESET);
        System.out.println();
        System.out.println("Configured Tracermappings = " + threadNodes.getLength());
        for (int i = 0; i < threadNodes.getLength(); i++) {
          System.out.println();
          System.out.println("(+) " + (i + 1) + ". Mapping");
          Element threadElement = (Element) threadNodes.item(i);
          String threadName = threadElement.getAttribute("name");
          String referencedTracerName = (String) this.xpath.evaluate("./dns:TraceLogger/@ref", threadElement, XPathConstants.STRING);
          System.out.println(threadName + " => " + referencedTracerName);
          this.threadName2Element.put(threadName, threadElement);
        }

        Node defaultTracerNode = (Node) this.xpath.evaluate("/dns:TraceConfig/dns:DefaultTracer", tracerConfigDoc.getDocumentElement(), XPathConstants.NODE);
        if (defaultTracerNode != null) {
          String className = ((Element) defaultTracerNode).getAttribute("class");
          Class<?> tracerClass = Class.forName(className);
          if (!NullTracer.class.isAssignableFrom(tracerClass))
            throw new TracerFactory.Exception("Requiring a NullTracer as default tracer!");
          this.defaultTracer = createTracer((Class<? extends NullTracer>) tracerClass);
        }
        else {
          this.defaultTracer = TracerFactory.NULLTRACER;
        }
      }
      finally {
        this.poolWriteLock.unlock();
      }
      
      this.queueWriteLock.lock();
      try {
        Node queueNode = (Node) this.xpath.evaluate("/dns:TraceConfig/dns:Queue", tracerConfigDoc.getDocumentElement(), XPathConstants.NODE);
        if (queueNode != null) {
          this.queueConfig = new Queue(queueNode);
        }
        else {
          this.queueConfig = new Queue();
        }
      }
      finally {
        this.queueWriteLock.unlock();
      }
    }
    catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException | ClassNotFoundException | AbstractTracer.Exception ex) {
      throw new TracerFactory.Exception(ex);
    }
  }
1138863
public static void generate(ConfigurationImpl configuration,
                                ClassUseMapper mapper, ClassDoc classdoc) {
        ClassUseWriter clsgen;
        DocPath path = DocPath.forPackage(classdoc)
                .resolve(DocPaths.CLASS_USE)
                .resolve(DocPath.forName(classdoc));
        try {
            clsgen = new ClassUseWriter(configuration,
                                        mapper, path,
                                        classdoc);
            clsgen.generateClassUseFile();
            clsgen.close();
        } catch (IOException exc) {
            configuration.standardmessage.
                error("doclet.exception_encountered",
                      exc.toString(), path.getPath());
            throw new DocletAbortException(exc);
        }
    }
802309
private void validateXmlTree(Node received, Node source, 
            XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) {
        switch(received.getNodeType()) {
            case Node.DOCUMENT_TYPE_NODE:
                doDocumentTypeDefinition(received, source, validationContext, namespaceContext, context);
                break;
            case Node.DOCUMENT_NODE:
                validateXmlTree(received.getFirstChild(), source.getFirstChild(),
                        validationContext, namespaceContext, context);
                break;
            case Node.ELEMENT_NODE:
                doElement(received, source, validationContext, namespaceContext, context);
                break;
            case Node.ATTRIBUTE_NODE:
                throw new IllegalStateException();
            case Node.COMMENT_NODE:
                validateXmlTree(received.getNextSibling(), source,
                        validationContext, namespaceContext, context);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                doPI(received);
                break;
        }
    }
192025
@Override
    public void validateDefault(InputProblemReporter rep, boolean normalize)
        throws XMLStreamException
    {
        String normStr = validateDefaultName(rep, normalize);
        if (normalize) {
            mDefValue.setValue(normStr);
        }

        // Ok, but was it declared?

        /* 03-Dec-2004, TSa: This is rather ugly -- need to know we
         *   actually really get a DTD reader, and DTD reader needs
         *   to expose a special method... but it gets things done.
         */
        EntityDecl ent = ((MinimalDTDReader) rep).findEntity(normStr);
        checkEntity(rep, normStr, ent);
    }
503500
@Override
	protected RequestMapping parseRequestMapping(MethodDoc methodDoc) {
		ClassDoc controllerClass = methodDoc.containingClass();
		RequestMapping baseMapping = null;
		boolean controllerCustomizedMapping = false;
		boolean actionCustomizedMapping = false;
		Tag[] tags = controllerClass.tags(WRAPITaglet.NAME);
		if (tags.length > 0) {
			baseMapping = this.parseRequestMapping(tags[0]);
		}

		if (baseMapping == null) {
			AnnotationDesc[] baseAnnotations = controllerClass.annotations();
			baseMapping = this.parseRequestMapping(baseAnnotations);
			controllerCustomizedMapping = false;
		} else {
			controllerCustomizedMapping = true;
		}

		RequestMapping mapping = null;
		Tag[] methodTags = methodDoc.tags(WRAPITaglet.NAME);
		if (methodTags.length > 0) {
			mapping = this.parseRequestMapping(methodTags[0]);
		}
		if (mapping == null) {
			AnnotationDesc[] annotations = methodDoc.annotations();
			mapping = this.parseRequestMapping(annotations);
			actionCustomizedMapping = false;
		} else {
			actionCustomizedMapping = true;
		}
		RequestMapping result;
		if (baseMapping == null) {
			result = mapping;
		} else if (mapping == null) {
			result = baseMapping;
		} else {
			if(!actionCustomizedMapping || controllerCustomizedMapping) {
				mapping.setUrl(net.winroad.wrdoclet.utils.Util.urlConcat(
						baseMapping.getUrl(), mapping.getUrl()));
			}
			if (baseMapping.getMethodType() != null) {
				if (mapping.getMethodType() != null) {
					mapping.setMethodType(baseMapping.getMethodType() + ","
							+ mapping.getMethodType());
				} else {
					mapping.setMethodType(baseMapping.getMethodType());
				}
			}
			result = mapping;
		}
		if (result != null) {
			result.setTooltip(methodDoc.containingClass().simpleTypeName());
			result.setContainerName(methodDoc.containingClass()
					.simpleTypeName());
		}
		return result;
	}
91663
public static DocumentBuilder newDocumentBuilder(boolean nsAware, boolean validating) throws ParserConfigurationException{
        return newDocumentBuilder(nsAware, validating, false, false);
    }
435824
function validateConfig(configOrFileName) {
    var expectedKeys = [],
        mountPoints = {},
        mountPoint,
        config,
        errMsg,
        key;

    if (typeof configOrFileName === 'string') {
        configFileName = configOrFileName;
        config = require(configFileName);
    } else {
        config = configOrFileName;
    }

    assertObject('config', config);

    // addOn
    expectedKeys.push('addOn');
    assertObject('config.addOn', config.addOn);
    assertBoolean('config.addOn.enable', config.addOn.enable);
    assertArray('config.addOn.basePaths', config.addOn.basePaths);

    // authentication
    expectedKeys.push('authentication');
    assertObject('config.authentication', config.authentication);
    assertBoolean('config.authentication.enable', config.authentication.enable);
    assertBoolean('config.authentication.allowGuests', config.authentication.allowGuests);
    assertBooleanOrString('config.authentication.allowUserRegistration', config.authentication.allowUserRegistration);
    assertBoolean('config.authentication.registeredUsersCanCreate', config.authentication.registeredUsersCanCreate);
    assertBoolean('config.authentication.inferredUsersCanCreate', config.authentication.inferredUsersCanCreate);
    assertBoolean('config.authentication.guestCanCreate', config.authentication.guestCanCreate);
    assertString('config.authentication.guestAccount', config.authentication.guestAccount);
    assertString('config.authentication.logOutUrl', config.authentication.logOutUrl);
    assertNumber('config.authentication.salts', config.authentication.salts);
    assertObject('config.authentication.jwt', config.authentication.jwt);
    assertNumber('config.authentication.jwt.expiresIn', config.authentication.jwt.expiresIn);
    assertString('config.authentication.jwt.privateKey', config.authentication.jwt.privateKey);
    assertString('config.authentication.jwt.publicKey', config.authentication.jwt.publicKey);
    assertArray('config.authentication.publicOrganizations', config.authentication.publicOrganizations);
    config.authentication.publicOrganizations.forEach(function (publicOrg, idx) {
        assertString('config.authentication.publicOrganizations[' + idx, ']', publicOrg);
    });

    if (config.authentication.adminAccount) {
        assertString('config.authentication.adminAccount', config.authentication.adminAccount);
    }

    // bin scripts
    expectedKeys.push('bin');
    assertObject('config.bin', config.bin);
    assertObject('config.bin.log', config.bin.log);

    // blob
    expectedKeys.push('blob');
    assertObject('config.blob', config.blob);
    assertNumber('config.blob.compressionLevel', config.blob.compressionLevel);

    if (config.blob.compressionLevel < 0 || config.blob.compressionLevel > 9) {
        throw new Error('config.blob.compressionLevel must be an integer between 0 and 9. Got: ' +
            config.blob.compressionLevel);
    }

    assertString('config.blob.type', config.blob.type);
    assertString('config.blob.fsDir', config.blob.fsDir);
    assertObject('config.blob.s3', config.blob.s3);

    // client
    expectedKeys.push('client');
    assertObject('config.client', config.client);
    assertString('config.client.appDir', config.client.appDir);
    assertString('config.client.appVersion', config.client.appVersion);
    assertString('config.client.faviconPath', config.client.faviconPath);
    assertString('config.client.pageTitle', config.client.pageTitle, true);
    assertObject('config.client.log', config.client.log);
    assertString('config.client.log.level', config.client.log.level);

    // core
    expectedKeys.push('core');
    assertBoolean('config.core.enableCustomConstraints', config.core.enableCustomConstraints);
    assertNumber('config.core.overlayShardSize', config.core.overlayShardSize);
    if (config.core.overlayShardSize < 1000) {
        throw new Error('Overlay shard size must be at least 1000.');
    }

    // debug
    expectedKeys.push('debug');
    assertBoolean('config.debug', config.debug);

    expectedKeys.push('documentEditing');
    assertObject('config.documentEditing', config.documentEditing);
    assertBoolean('config.documentEditing.enable', config.documentEditing.enable, true);
    assertNumber('config.documentEditing.disconnectTimeout', config.documentEditing.disconnectTimeout);

    // executor
    expectedKeys.push('executor');
    assertObject('config.executor', config.executor);
    assertBoolean('config.executor.enable', config.executor.enable);
    assertString('config.executor.nonce', config.executor.nonce, true);
    warnDeprecated('config.executor.outputDir', config.executor.outputDir);
    assertString('config.executor.labelJobs', config.executor.labelJobs);
    assertNumber('config.executor.workerRefreshInterval', config.executor.workerRefreshInterval);
    assertNumber('config.executor.clearOutputTimeout', config.executor.clearOutputTimeout);
    assertBoolean('config.executor.clearOldDataAtStartUp', config.executor.clearOldDataAtStartUp);

    // mongo configuration
    expectedKeys.push('mongo');
    assertObject('config.mongo', config.mongo);
    assertString('config.mongo.uri', config.mongo.uri);
    assertObject('config.mongo.options', config.mongo.options);

    // plugin
    expectedKeys.push('plugin');
    assertObject('config.plugin', config.plugin);
    assertBoolean('config.plugin.allowServerExecution', config.plugin.allowServerExecution);
    assertArray('config.plugin.basePaths', config.plugin.basePaths);
    assertBoolean('config.plugin.displayAll', config.plugin.displayAll);

    // requirejsPaths
    expectedKeys.push('requirejsPaths');
    assertObject('config.requirejsPaths', config.requirejsPaths);

    // rest
    expectedKeys.push('rest');
    assertObject('config.rest', config.rest);
    assertObject('config.rest.components', config.rest.components);

    for (key in config.rest.components) {
        if (typeof config.rest.components[key] === 'string') {
            mountPoint = key;
            // TODO: Add this warn when the cli tool has been updated.
            // console.warn('config.rest.components[' + key + '] is a string a not an object. ' +
            // 'It is recommended to change to the format described in #xxxx');
        } else {
            assertObject('config.rest.components[' + key + ']', config.rest.components[key]);
            assertString('config.rest.components[' + key + '].mount', config.rest.components[key].mount);
            assertString('config.rest.components[' + key + '].src', config.rest.components[key].src);
            assertObject('config.rest.components[' + key + '].options', config.rest.components[key].options, true);
            mountPoint = config.rest.components[key].mount;
        }

        if (mountPoints[mountPoint] === true) {
            throw new Error('Same mount point [' + mountPoint + '] specified more than once ' +
                'in config.rest.components.');
        } else {
            mountPoints[mountPoint] = true;
        }
    }

    //seedProjects
    expectedKeys.push('seedProjects');
    assertBoolean('config.seedProjects.enable', config.seedProjects.enable);
    assertString('config.seedProjects.defaultProject', config.seedProjects.defaultProject);
    assertArray('config.seedProjects.basePaths', config.seedProjects.basePaths);
    assertArray('config.seedProjects.createAtStartup', config.seedProjects.createAtStartup);
    config.seedProjects.createAtStartup.forEach(function (seedInfo, index) {
        assertObject('config.seedProjects.createAtStartup[' + index + ']', config.seedProjects.createAtStartup[index]);
        assertString('config.seedProjects.createAtStartup[' + index + '].seedId',
            config.seedProjects.createAtStartup[index].seedId);
        assertString('config.seedProjects.createAtStartup[' + index + '].projectName', seedInfo.projectName);
        assertObject('config.seedProjects.createAtStartup[' + index + '].rights', seedInfo.rights, true);
        if (seedInfo.creatorId) {
            assertString('config.seedProjects.createAtStartup[' + index + '].creatorId', seedInfo.creatorId);
        } else if (typeof config.authentication.adminAccount !== 'string') {
            throw new Error('Either config.seedProjects.createAtStartup[' + index +
                '].creatorId or config.authentication.adminAccount should exists!');
        }

        assertString('config.seedProjects.createAtStartup[' + index + '].ownerId', seedInfo.ownerId, true);
    });

    // server configuration
    expectedKeys.push('server');
    assertObject('config.server', config.server);
    assertNumber('config.server.port', config.server.port);
    assertNumber('config.server.timeout', config.server.timeout);
    assertObject('config.server.handle', config.server.handle);
    assertObject('config.server.workerManager', config.server.workerManager);
    assertString('config.server.workerManager.path', config.server.workerManager.path);
    assertObject('config.server.workerManager.options', config.server.workerManager.options);
    assertNumber('config.server.maxWorkers', config.server.maxWorkers);
    warnDeprecated('config.server.sessionStore', config.server.sessionStore,
        'JWTokens are used for authentication, see config.authentication.jwt');

    // server log
    assertObject('config.server.log', config.server.log);
    assertArray('config.server.log.transports', config.server.log.transports);
    // server extlib
    assertArray('config.server.extlibExcludes', config.server.extlibExcludes);
    // server bodyParser config
    assertObject('config.server.bodyParser', config.server.bodyParser);
    assertObject('config.server.bodyParser.json', config.server.bodyParser.json);

    // socketIO
    expectedKeys.push('socketIO');
    assertObject('config.socketIO', config.socketIO);
    assertObject('config.socketIO.clientOptions', config.socketIO.clientOptions);
    assertObject('config.socketIO.serverOptions', config.socketIO.serverOptions);
    assertObject('config.socketIO.adapter', config.socketIO.adapter);
    assertEnum('config.socketIO.adapter.type', config.socketIO.adapter.type.toLowerCase(), 'memory', 'redis');

    // storage
    expectedKeys.push('storage');
    assertObject('config.storage', config.storage);
    assertBoolean('config.storage.broadcastProjectEvents', config.storage.broadcastProjectEvents);
    warnDeprecated('config.storage.emitCommittedCoreObjects', config.storage.emitCommittedCoreObjects,
        'see new config at config.storage.maxEmittedCoreObjects');
    assertNumber('config.storage.maxEmittedCoreObjects', config.storage.maxEmittedCoreObjects);
    warnDeprecated('config.storage.patchRootCommunicationEnabled', config.storage.patchRootCommunicationEnabled,
        'Since 1.7.0 all node changes are transmitted as patch objects (unless newly created).');
    assertNumber('config.storage.cache', config.storage.cache);
    assertNumber('config.storage.loadBucketSize', config.storage.loadBucketSize);
    assertNumber('config.storage.loadBucketTimer', config.storage.loadBucketTimer);
    assertEnum('config.storage.keyType', config.storage.keyType, 'rand160Bits', 'ZSSHA', 'plainSHA1');
    assertObject('config.storage.database', config.storage.database);
    assertEnum('config.storage.database.type', config.storage.database.type.toLowerCase(), 'mongo', 'redis', 'memory');
    assertObject('config.storage.database.options', config.storage.database.options);
    assertBoolean('config.storage.disableHashChecks', config.storage.disableHashChecks);
    assertBoolean('config.storage.requireHashesToMatch', config.storage.requireHashesToMatch);
    if (config.storage.disableHashChecks && config.storage.requireHashesToMatch) {
        throw new Error('Cannot set config.storage.disableHashChecks and requireHashesToMatch ' +
            'to true at the same time!');
    }

    //visualization
    expectedKeys.push('visualization');
    assertObject('config.visualization', config.visualization);
    assertArray('config.visualization.decoratorPaths', config.visualization.decoratorPaths);
    assertArray('config.visualization.svgDirs', config.visualization.svgDirs);
    assertArray('config.visualization.panelPaths', config.visualization.panelPaths);
    assertArray('config.visualization.visualizerDescriptors', config.visualization.visualizerDescriptors);
    assertObject('config.visualization.layout', config.visualization.layout);
    assertArray('config.visualization.layout.basePaths', config.visualization.layout.basePaths);

    //webhooks
    expectedKeys.push('webhooks');
    assertBoolean('config.webhooks.enable', config.webhooks.enable);
    assertEnum('config.webhooks.manager', config.webhooks.manager.toLowerCase(), 'memory', 'redis');
    if (config.webhooks.manager.toLowerCase() === 'redis' && config.socketIO.adapter.type.toLowerCase() !== 'redis') {
        throw new Error('config.webhooks.manager can only be ' +
            '\'redis\' if config.socketIO.adapter.type is \'redis\' as well');
    }

    if (Object.keys(config).length !== expectedKeys.length) {
        errMsg = 'Configuration had unexpected key(s):';
        for (key in config) {
            if (expectedKeys.indexOf(key) < 0) {
                errMsg += ' "' + key + '"';
            }
        }
        throw new Error(errMsg);
    }

    return config;
}
243945
def validate_config_file(cls, config_filepath):
        
        is_file = os.path.isfile(config_filepath)
        if not is_file and os.path.isabs(config_filepath):
            raise IOError('File path %s is not a valid yml, ini or cfg file or does not exist' % config_filepath)

        elif is_file:
            if os.path.getsize(config_filepath) == 0:
                raise IOError('File %s is empty' % config_filepath)

        with open(config_filepath, 'r') as f:
            if yaml.load(f) is None:
                raise IOError('No YAML config was found in file %s' % config_filepath)
16097
public final Configuration getConfig(final File configFile, final InputStream configData)
            throws IOException {
        final Configuration configuration = this.context.getBean(Configuration.class);
        configuration.setConfigurationFile(configFile);
        MapfishPrintConstructor.setConfigurationUnderConstruction(configuration);

        final Configuration config =
                this.yaml.load(new InputStreamReader(configData, "UTF-8"));
        if (this.doValidation) {
            final List<Throwable> validate = config.validate();
            if (!validate.isEmpty()) {
                StringBuilder errors = new StringBuilder();
                for (Throwable throwable: validate) {
                    errors.append("\n\t* ").append(throwable.getMessage());
                    LOGGER.error("Configuration Error found", throwable);
                }
                throw new Error(errors.toString(), validate.get(0));
            }
        }
        return config;
    }
1350635
public static void checkChangelogActivity(Context ctx, @XmlRes int configId){

        // Parse configuration
        ChangeLog changeLog = Parser.parse(ctx, configId);
        if(changeLog != null){

            // Validate that there is a new version code
            if(validateVersion(ctx, changeLog)) {
                openChangelogActivity(ctx, configId);
            }

        }else{
            throw new NullPointerException("Unable to find a 'Winds' configuration @ " + configId);
        }

    }
233925
def initdoc(request, namespace, docid, mode, template, context=None, configuration=None):
    """"""
    perspective = request.GET.get('perspective','document')
    if context is None: context = {}
    if 'configuration' in request.session:
        configuration = request.session['configuration']
    elif configuration is None:
        return fatalerror(request, "No configuration specified")
    if configuration not in settings.CONFIGURATIONS:
        return fatalerror(request, "Specified configuration does not exist")
    flatargs = {
        'setdefinitions': True,
        'declarations': True, #implies provenance as well
        'metadata': True,
        'toc': True,
        'slices': request.GET.get('slices',settings.CONFIGURATIONS[configuration].get('slices','p:25,s:100')), #overriden either by configuration or by user
        'customslicesize': 0, #disabled for initial probe
        'textclasses': True,
    }
    error = False
    try:
        doc = flat.comm.query(request, "USE " + namespace + "/" + docid + " PROBE", **flatargs) #retrieves only the meta information, not document content
        context.update(getcontext(request,namespace,docid, doc, mode, configuration))
    except Exception as e:
        context.update(docserveerror(e))
        error = True

    if not error:
        dorequiredeclaration = 'requiredeclaration' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['requiredeclaration']
        if dorequiredeclaration:
            if not 'declarations' in doc:
                return fatalerror(request, "Refusing to load document, missing expected declarations, none declared")
            declarations = doc['declarations']
            for annotationtype, annotationset in settings.CONFIGURATIONS[configuration]['requiredeclaration']:
                found = False
                for d in declarations:
                    if annotationtype == d['annotationtype'] and (not annotationset or annotationset == d['set']):
                        found = True
                        break
                if not found:
                    if annotationset:
                        return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype + "/" + annotationset)
                    else:
                        return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype)

        dometadataindex = 'metadataindex' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['metadataindex']
        if dometadataindex:
            metadata = json.loads(context['metadata'])
            for metakey in settings.CONFIGURATIONS[configuration]['metadataindex']:
                if metakey in metadata:
                    MetadataIndex.objects.update_or_create(namespace=namespace,docid=docid, key=metakey,defaults={'value':metadata[metakey]})
    response = render(request, template, context)
    if 'fatalerror' in context:
        response.status_code = 500
    return response
758508
public void validateUpdateItem(Long configId, String value) {

        //
        // config
        //
        valideConfigExist(configId);

        //
        // value
        //
        try {

            if (StringUtils.isEmpty(value)) {
                throw new Exception();
            }

        } catch (Exception e) {

            throw new FieldException("value", "conf.item.value.null", e);
        }

    }
1305841
public static boolean fixLogging(ConfigServerImpl cs, ConfigImpl config, Document doc) {

	// if version is bigger than 4.2 there is nothing to do
	Element luceeConfiguration = doc.getDocumentElement();
	String strVersion = luceeConfiguration.getAttribute("version");
	double version = Caster.toDoubleValue(strVersion, 1.0d);
	config.setVersion(version);

	if (version >= 4.3D) return false;

	// datasource
	Element src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "datasource");
	fixLogging(cs, doc, src, "datasource", false, "{lucee-config}/logs/datasource.log");

	setVersion(doc, ConfigWebUtil.getEngine(config).getInfo().getVersion());

	if (version >= 4.2D) return true;

	// mapping
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "mappings");
	fixLogging(cs, doc, src, "mapping", false, "{lucee-config}/logs/mapping.log");

	// rest
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "rest");
	fixLogging(cs, doc, src, "rest", false, "{lucee-config}/logs/rest.log");

	// gateway
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "gateways");
	fixLogging(cs, doc, src, "gateway", false, "{lucee-config}/logs/gateway.log");

	// remote clients
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "remote-clients");
	fixLogging(cs, doc, src, "remoteclient", false, "{lucee-config}/logs/remoteclient.log");

	// orm
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "orm");
	fixLogging(cs, doc, src, "orm", false, "{lucee-config}/logs/orm.log");

	// mail
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "mail");
	fixLogging(cs, doc, src, "mail", false, "{lucee-config}/logs/mail.log");

	// search
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "search");
	fixLogging(cs, doc, src, "search", false, "{lucee-config}/logs/search.log");

	// scheduler
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "scheduler");
	fixLogging(cs, doc, src, "scheduler", false, "{lucee-config}/logs/scheduler.log");

	// scope
	src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "scope");
	fixLogging(cs, doc, src, "scope", false, "{lucee-config}/logs/scope.log");

	// application
	Element app = src = XMLConfigWebFactory.getChildByName(doc.getDocumentElement(), "application");
	fixLogging(cs, doc, src, "application", "application-log", "application-log-level", false, "{lucee-config}/logs/application.log");

	// exception
	fixLogging(cs, doc, app, "exception", "exception-log", "exception-log-level", false, "{lucee-config}/logs/exception.log");

	// trace
	fixLogging(cs, doc, app, "trace", "trace-log", "trace-log-level", false, "{lucee-config}/logs/trace.log");

	// thread
	fixLogging(cs, doc, app, "thread", "thread-log", "thread-log-level", false, "{lucee-config}/logs/thread.log");

	// deploy
	fixLogging(cs, doc, app, "deploy", "deploy-log", "deploy-log-level", false, "{lucee-config}/logs/deploy.log");

	// requesttimeout
	fixLogging(cs, doc, app, "requesttimeout", "requesttimeout-log", "requesttimeout-log-level", false, "{lucee-config}/logs/requesttimeout.log");

	setVersion(doc, ConfigWebUtil.getEngine(config).getInfo().getVersion());

	return true;
    }