To find the closet node that we need to insert the endpoints before, so the Camel schema is valid.
338594
private Node insertEndpointBefore(Node camel) {
        // if there is endpoints then the cut-off is after the last
        Node endpoint = null;
        for (int i = 0; i < camel.getChildNodes().getLength(); i++) {
            Node found = camel.getChildNodes().item(i);
            String name = found.getNodeName();
            if ("endpoint".equals(name)) {
                endpoint = found;
            }
        }
        if (endpoint != null) {
            return endpoint;
        }

        Node last = null;
        // if no endpoints then try to find cut-off according the XSD rules
        for (int i = 0; i < camel.getChildNodes().getLength(); i++) {
            Node found = camel.getChildNodes().item(i);
            String name = found.getNodeName();
            if ("dataFormats".equals(name) || "redeliveryPolicyProfile".equals(name)
                    || "onException".equals(name) || "onCompletion".equals(name)
                    || "intercept".equals(name) || "interceptFrom".equals(name)
                    || "interceptSendToEndpoint".equals(name) || "restConfiguration".equals(name)
                    || "rest".equals(name) || "route".equals(name)) {
                return found;
            }
            if (found.getNodeType() == Node.ELEMENT_NODE) {
                last = found;
            }
        }

        return last;
    }
1365328
function(node, name, data) {
  typeCheckString(key, 'key');
  typeCheckObject(data, 'data');
  typeCheckObject(node, 'node');
  runValidator(node, 'node');

  if (typeof node !== 'object') {
    throw new error.InvalidParameterError(
      'Parameter ast must be a well-defined JSON object.'
    );
  }
  if (validator(node)) {
    throw new error.MalformedAstError(
      'Parameter ast needs to be a JSON structure according to the schema.'
    );
  }
  if (typeof data !== 'object') {
    throw new error.InvalidParameterError(
      'Parameter data must be a well-defined JSON object.'
    );
  }
  if (typeof name !== 'string') {
    throw new error.InvalidParameterError('Parameter name must be a string.');
  }
  const newNode = Object.assign({}, node);
  if (newNode.properties) {
    newNode.properties[name] = data;
  }
  return newNode;
}
425757
public static void assertValidMetadata(ByteArray key,
                                           RoutingStrategy routingStrategy,
                                           Node currentNode) {
        List<Node> nodes = routingStrategy.routeRequest(key.get());
        for(Node node: nodes) {
            if(node.getId() == currentNode.getId()) {
                return;
            }
        }

        throw new InvalidMetadataException("Client accessing key belonging to partitions "
                                           + routingStrategy.getPartitionList(key.get())
                                           + " not present at " + currentNode);
    }
300918
private void initSchema(final SchemaManager schemaManager, final CoreSession adminSession, final StructrPartition partition) throws Exception {

		final URL url            = SchemaEntityFactory.class.getProtectionDomain().getCodeSource().getLocation();
		final JarFile jarFile    = new JarFile(new File(url.toURI()));
		final List<String> names = new LinkedList<>();

		for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

			final ZipEntry zipEntry = e.nextElement();
			final String name = zipEntry.getName();

			if (name.startsWith("schema/") && name.endsWith(".ldif")) {

				names.add(name);
			}
		}

		Collections.sort(names, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {

				// first sort key: number of slashes (level)
				Integer s1 = StringUtils.countMatches(o1, "/");
				Integer s2 = StringUtils.countMatches(o2, "/");

				if (s1.equals(s2)) {

					// secondary sort key: string length
					Integer l1 = o1.length();
					Integer l2 = o2.length();

					if (l1.equals(l2)) {

						// tertiary sort key: the string values
						return o1.compareTo(o2);
					}

					return l1.compareTo(l2);
				}

				return s1.compareTo(s2);
			}

		});

		for (final String name : names) {

			try (final LdifReader reader = new LdifReader(jarFile.getInputStream(jarFile.getEntry(name)))) {

				for (final LdifEntry entry : reader) {

					final Entry schemaEntry  = new DefaultEntry(schemaManager, entry.getEntry());
					final Dn dn              = schemaEntry.getDn();

					if (!partition.hasEntry(new HasEntryOperationContext(adminSession, dn))) {

						logger.info("Importing {}...", name);
						partition.add(new AddOperationContext(adminSession, schemaEntry));
					}
				}
			}
		}
	}
901182
def get_schema_descendant(
            self, route: SchemaRoute) -> Optional[SchemaNode]:
        
        node = self
        for p in route:
            node = node.get_child(*p)
            if node is None:
                return None
        return node
376541
function prepareHeaders(endpointSchema) {
  const isSendInHeader = p => p.in === 'header';
  const parameters = endpointSchema.parameters || [];
  const headerParameters = parameters.filter(isSendInHeader);
  return convertParameters(headerParameters);
}
1111184
public void marshalToDoc(XmlModel model) throws JAXBException {
        Marshaller marshaller = jaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, java.lang.Boolean.TRUE);
        try {
            marshaller.setProperty("com.sun.xml.bind.indentString", "  ");
        } catch (Exception e) {
            LOG.debug("Property not supported: {}", e);
        }

        Object value = model.marshalRootElement();
        Document doc = model.getDoc();
        Element docElem = doc.getRootElement();

        // JAXB only seems to do nice whitespace/namespace stuff when writing to stream
        // rather than DOM directly
        // marshaller.marshal(value, docElem);

        StringWriter buffer = new StringWriter();
        marshaller.marshal(value, buffer);

        // now lets parse the XML and insert the root element into the doc
        String xml = buffer.toString();
        if (!model.getNs().equals(springNS)) {
            // !!!
            xml = xml.replaceAll(springNS, model.getNs());
        }
        Document camelDoc = parse(new XMLStringSource(xml));
        Node camelElem = camelDoc.getRootElement();

        // TODO
        //val camelElem = doc.importNode(element, true)

        if (model.isRoutesContext() && camelDoc.getRootElement().getName().equals("camelContext")) {
            camelDoc.getRootElement().setName("routeContext");
        }
        if (model.isJustRoutes()) {
            replaceChild(doc, camelElem, docElem);
        } else {
            if (model.getNode() != null) {
                replaceCamelElement(docElem, camelElem, model.getNode());
            } else {
                docElem.addNode(camelElem);
            }
        }
    }
773287
def schemaValidateDoc(self, ctxt):
        
        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        ret = libxml2mod.xmlSchemaValidateDoc(ctxt__o, self._o)
        return ret
1036683
function validateNode(node, path, ancestors) {
  let errors = [];

  if (!node.type) {
    return [{ path, error: 'Node is missing the type property' }];
  }

  if (ancestors.length && node.type === 'Page') {
    errors = [...errors, { path, error: 'Encountered a nested page. Page is only allowed at the top level' }];
  }

  errors = [
    ...errors,
    ...assertProperties(node, path, requiredProperties[node.type]),
    ...assertDeprecations(node, path, deprecatedProperties[node.type]),
  ];

  // Parse logical expressions
  ['hidden', 'disabled', 'test'].forEach((field) => {
    if (!node[field]) {
      return;
    }

    try {
      parseExpression(node[field]);
    } catch (e) {
      errors = [...errors, { path: [...path, field], error: e.message }];
    }
  });

  // Recurse through children
  if (node.children) {
    node.children.forEach((child, index) => {
      errors = [
        ...errors,
        ...validateNode(child, [...path, 'children', index], [...ancestors, node]),
      ];
    });
  }

  // Check and recurse through branches
  if (node.branches) {
    node.branches.forEach((branch, branchIndex) => {
      errors = [
        ...errors,
        ...assertProperties(
          branch,
          [...path, 'branches', branchIndex],
          ['test', 'children'],
        ),
      ];

      // Validate the text expression
      if (branch.test) {
        try {
          parseExpression(branch.test);
        } catch (e) {
          errors = [...errors, { path: [...path, 'branches', branchIndex, 'test'], error: e.message }];
        }
      }

      // Recurse through the branch children
      if (branch.children) {
        branch.children.forEach((child, index) => {
          errors = [
            ...errors,
            ...validateNode(child, [...path, 'branches', branchIndex, 'children', index], [...ancestors, node]),
          ];
        });
      }
    });
  }

  // Recurse over the options
  if (node.options) {
    node.options.forEach((option, index) => {
      errors = [
        ...errors,
        ...validateNode(option, [...path, 'options', index], [...ancestors, node]),
      ];
    });
  }

  // Check image
  if (node.image) {
    if (typeof node.image !== 'object') {
      errors = [
        ...errors,
        { path, error: `an object was expected for the image property. Got ${typeof node.image}` },
      ];
    }

    errors = [
      ...errors,
      ...assertProperties(
        { ...node.image, type: 'Image' },
        [...path, 'image'],
        ['url', 'alt'],
      ),
    ];
  }

  return errors;
}
1341937
def __merge_schema_locations(self, ni, incoming_schemaloc):
        
        if ni.schema_location == incoming_schemaloc:  # TODO (bworrell): empty strings?
            return
        elif not ni.schema_location:
            ni.schema_location = incoming_schemaloc or None
        elif not incoming_schemaloc:
            return
        else:
            raise ConflictingSchemaLocationError(ni.uri, ni.schema_location, incoming_schemaloc)
954917
public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        setHeaders(rsp);
        rsp.setContentType("application/xml");
        StreamResult r = new StreamResult(rsp.getOutputStream());
        new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
        r.getOutputStream().close();
    }
1234634
def _make_xml(self, endpoints):
        # type: (List[EndpointDescription]) -> ElementTree.Element
        
        root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS)
        for endpoint in endpoints:
            self._make_endpoint(root, endpoint)

        # Prepare pretty-printing
        self._indent(root)
        return root
693145
function parseBODYSTRUCTURE(node, path = []) {
  let curNode = {};
  let i = 0;
  let part = 0;

  if (path.length) {
    curNode.part = path.join('.');
  }

  // multipart
  if (Array.isArray(node[0])) {
    curNode.childNodes = [];
    while (Array.isArray(node[i])) {
      curNode.childNodes.push(parseBODYSTRUCTURE(node[i], path.concat(++part)));
      i++;
    }

    // multipart type
    curNode.type = 'multipart/' + ((node[i++] || {}).value || '').toString().toLowerCase();

    // extension data (not available for BODY requests)

    // body parameter parenthesized list
    if (i < node.length - 1) {
      if (node[i]) {
        curNode.parameters = attributesToObject(node[i]);
      }
      i++;
    }
  } else {
    // content type
    curNode.type = [((node[i++] || {}).value || '').toString().toLowerCase(), ((node[i++] || {}).value || '').toString().toLowerCase()].join('/');

    // body parameter parenthesized list
    if (node[i]) {
      curNode.parameters = attributesToObject(node[i]);
    }
    i++;

    // id
    if (node[i]) {
      curNode.id = ((node[i] || {}).value || '').toString();
    }
    i++;

    // description
    if (node[i]) {
      curNode.description = ((node[i] || {}).value || '').toString();
    }
    i++;

    // encoding
    if (node[i]) {
      curNode.encoding = ((node[i] || {}).value || '').toString().toLowerCase();
    }
    i++;

    // size
    if (node[i]) {
      curNode.size = Number((node[i] || {}).value || 0) || 0;
    }
    i++;

    if (curNode.type === 'message/rfc822') {
      // message/rfc adds additional envelope, bodystructure and line count values

      // envelope
      if (node[i]) {
        curNode.envelope = parseENVELOPE([].concat(node[i] || []));
      }
      i++;

      if (node[i]) {
        curNode.childNodes = [
        // rfc822 bodyparts share the same path, difference is between MIME and HEADER
        // path.MIME returns message/rfc822 header
        // path.HEADER returns inlined message header
        parseBODYSTRUCTURE(node[i], path)];
      }
      i++;

      // line count
      if (node[i]) {
        curNode.lineCount = Number((node[i] || {}).value || 0) || 0;
      }
      i++;
    } else if (/^text\//.test(curNode.type)) {
      // text/* adds additional line count values

      // line count
      if (node[i]) {
        curNode.lineCount = Number((node[i] || {}).value || 0) || 0;
      }
      i++;
    }

    // extension data (not available for BODY requests)

    // md5
    if (i < node.length - 1) {
      if (node[i]) {
        curNode.md5 = ((node[i] || {}).value || '').toString().toLowerCase();
      }
      i++;
    }
  }

  // the following are shared extension values (for both multipart and non-multipart parts)
  // not available for BODY requests

  // body disposition
  if (i < node.length - 1) {
    if (Array.isArray(node[i]) && node[i].length) {
      curNode.disposition = ((node[i][0] || {}).value || '').toString().toLowerCase();
      if (Array.isArray(node[i][1])) {
        curNode.dispositionParameters = attributesToObject(node[i][1]);
      }
    }
    i++;
  }

  // body language
  if (i < node.length - 1) {
    if (node[i]) {
      curNode.language = [].concat(node[i]).map(val => (0, _ramda.propOr)('', 'value', val).toLowerCase());
    }
    i++;
  }

  // body location
  // NB! defined as a "string list" in RFC3501 but replaced in errata document with "string"
  // Errata: http://www.rfc-editor.org/errata_search.php?rfc=3501
  if (i < node.length - 1) {
    if (node[i]) {
      curNode.location = ((node[i] || {}).value || '').toString();
    }
    i++;
  }

  return curNode;
}
156020
def addIncludeSchema(self, schemaLocation, schema):
        
        if not isinstance(schema, XMLSchema):
            raise TypeError, 'expecting a Schema instance'
        if not schema.targetNamespace or\
             schema.targetNamespace == self.targetNamespace:
            self._included_schemas[schemaLocation] = schema
        else:
            raise SchemaError, 'include schema bad targetNamespace'
777094
function validateEndpointData(
  data,
  { prettyErrorMessage = 'invalid response data', includeKeys = false } = {}
) {
  return validate(
    {
      ErrorClass: InvalidResponse,
      prettyErrorMessage,
      includeKeys,
      traceErrorMessage: 'Response did not match schema',
      traceSuccessMessage: 'Response after validation',
      allowAndStripUnknownKeys: false,
    },
    data,
    endpointSchema
  )
}
402002
private void preInsert(RdKNNEntry q, RdKNNEntry nodeEntry, KNNHeap knns_q) {
    double knnDist_q = knns_q.getKNNDistance();
    RdKNNNode node = getNode(nodeEntry);
    double knnDist_node = 0.;

    // leaf node
    if(node.isLeaf()) {
      for(int i = 0; i < node.getNumEntries(); i++) {
        RdKNNLeafEntry p = (RdKNNLeafEntry) node.getEntry(i);
        double dist_pq = distanceQuery.distance(p.getDBID(), ((LeafEntry) q).getDBID());

        // p is nearer to q than the farthest kNN-candidate of q
        // ==> p becomes a knn-candidate
        if(dist_pq <= knnDist_q) {
          knns_q.insert(dist_pq, p.getDBID());
          if(knns_q.size() >= settings.k_max) {
            knnDist_q = knns_q.getKNNDistance();
            q.setKnnDistance(knnDist_q);
          }

        }
        // p is nearer to q than to its farthest knn-candidate
        // q becomes knn of p
        if(dist_pq <= p.getKnnDistance()) {
          KNNList knns_without_q = knnQuery.getKNNForObject(relation.get(p.getDBID()), settings.k_max);
          p.setKnnDistance(knns_without_q.size() + 1 < settings.k_max ? Double.NaN : //
              Math.min(knns_without_q.doubleValue(knns_without_q.size() - 1), dist_pq));
        }
        knnDist_node = Math.max(knnDist_node, p.getKnnDistance());
      }
    }
    // directory node
    else {
      O obj = relation.get(((LeafEntry) q).getDBID());
      List<DoubleObjPair<RdKNNEntry>> entries = getSortedEntries(node, obj, settings.distanceFunction);
      for(DoubleObjPair<RdKNNEntry> distEntry : entries) {
        RdKNNEntry entry = distEntry.second;
        double entry_knnDist = entry.getKnnDistance();

        if(distEntry.first < entry_knnDist || distEntry.first < knnDist_q) {
          preInsert(q, entry, knns_q);
          knnDist_q = knns_q.getKNNDistance();
        }
        knnDist_node = Math.max(knnDist_node, entry.getKnnDistance());
      }
    }
    nodeEntry.setKnnDistance(knnDist_node);
  }
1248414
def schemaValidateOneElement(self, ctxt):
        
        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        ret = libxml2mod.xmlSchemaValidateOneElement(ctxt__o, self._o)
        return ret