Check some limits of our simplified XML output.
553258
public void checkSimpleXMLString(String xml) throws IOException {
    Pattern pattern = Pattern.compile("(<error.*?/>)", Pattern.DOTALL|Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(xml);
    int pos = 0;
    while (matcher.find(pos)) {
      String errorElement = matcher.group();
      pos = matcher.end();
      if (errorElement.contains("\n") || errorElement.contains("\r")) {
        throw new IOException("<error ...> may not contain line breaks");
      }
      char beforeError = xml.charAt(matcher.start()-1);
      if (beforeError != '\n' && beforeError != '\r') {
        throw new IOException("Each <error ...> must start on a new line");
      }
    }
  }
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;
        }
    }
1282305
private void onLimit(StringBuilder builder) {
        if (Integer.MAX_VALUE != maxResult) {
            builder.append(CQLTranslator.LIMIT);
            builder.append(isSingleResult ? 1 : this.maxResult);
        }
    }
782920
private static void checkPreconditions(final Collection<Integer> requriedLengths) {
        if( requriedLengths == null ) {
            throw new NullPointerException("requriedLengths should not be null");
        } else if( requriedLengths.isEmpty()) {
            throw new IllegalArgumentException("requriedLengths should not be empty");
        }
    }
1111033
private <T> void addLimit(ElementDescriptor<T> descriptor, T limit)
	{
		if (mLimit == null)
		{
			mLimit = new HashMap<ElementDescriptor<?>, Object>(6);
		}
		mLimit.put(descriptor, limit);
	}
1109879
private void checkBuffer() {
        // Doc count limit
        if (docBuffer.size() >= bufferDocLimit) {
            log.debug("=== Buffer check: Doc limit reached '{}'", docBuffer.size());
            submitBuffer(false);
            return;
        }
        // Size limit
        if (bufferSize > bufferSizeLimit) {
            log.debug("=== Buffer check: Size exceeded '{}'", bufferSize);
            submitBuffer(false);
            return;
        }
        // Time limit
        long age = ((new Date().getTime()) - bufferOldest) / 1000;
        if (age > bufferTimeLimit) {
            log.debug("=== Buffer check: Age exceeded '{}s'", age);
            submitBuffer(false);
            return;
        }
    }
883806
private void checkAndLimitFeatureUsedPerSplit(Frame fr) {
      int validCols = fr.numCols()-1; // for classIdx column
      if (validCols < _rfParams.num_split_features) {
        Log.info(Log.Tag.Sys.RANDF, "Limiting features from " + _rfParams.num_split_features +
                " to " + validCols + " because there are no more valid columns in the dataset");
        _rfParams.num_split_features= validCols;
      }
    }
717847
LimitPlanNode limitPlanNodeFromXml(VoltXMLElement limitXml, VoltXMLElement offsetXml) {

        if (limitXml == null && offsetXml == null) {
            return null;
        }

        String node;
        long limitParameterId = -1;
        long offsetParameterId = -1;
        long limit = -1;
        long offset = 0;
        if (limitXml != null) {
            // Parse limit
            if ((node = limitXml.attributes.get("limit_paramid")) != null) {
                limitParameterId = Long.parseLong(node);
            }
            else {
                assert(limitXml.children.size() == 1);
                VoltXMLElement valueNode = limitXml.children.get(0);
                String isParam = valueNode.attributes.get("isparam");
                if ((isParam != null) && (isParam.equalsIgnoreCase("true"))) {
                    limitParameterId = Long.parseLong(valueNode.attributes.get("id"));
                }
                else {
                    node = limitXml.attributes.get("limit");
                    assert(node != null);
                    limit = Long.parseLong(node);
                }
            }
        }
        if (offsetXml != null) {
            // Parse offset
            if ((node = offsetXml.attributes.get("offset_paramid")) != null) {
                offsetParameterId = Long.parseLong(node);
            }
            else {
                if (offsetXml.children.size() == 1) {
                    VoltXMLElement valueNode = offsetXml.children.get(0);
                    String isParam = valueNode.attributes.get("isparam");
                    if ((isParam != null) && (isParam.equalsIgnoreCase("true"))) {
                        offsetParameterId = Long.parseLong(valueNode.attributes.get("id"));
                    }
                    else {
                        node = offsetXml.attributes.get("offset");
                        assert(node != null);
                        offset = Long.parseLong(node);
                    }
                }
            }
        }

        // limit and offset can't have both value and parameter
        if (limit != -1) assert limitParameterId == -1 : "Parsed value and param. limit.";
        if (offset != 0) assert offsetParameterId == -1 : "Parsed value and param. offset.";

        LimitPlanNode limitPlanNode = new LimitPlanNode();
        limitPlanNode.setLimit((int) limit);
        limitPlanNode.setOffset((int) offset);
        limitPlanNode.setLimitParameterIndex(parameterCountIndexById(limitParameterId));
        limitPlanNode.setOffsetParameterIndex(parameterCountIndexById(offsetParameterId));
        return limitPlanNode;
    }
827297
def key_is_valid_xml(key):
    """"""
    LOG.info('Inside key_is_valid_xml(). Testing "%s"' % (unicode_me(key)))
    test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % (key, key)
    try:
        parseString(test_xml)
        return True
    except Exception: # minidom does not implement exceptions well
        return False
1366258
public boolean isXmlDeclaration() {
        String data = getData();
        return (data.length() > 1 && (data.startsWith("!") || data.startsWith("?")));
    }
159486
private void onLimit(StringBuilder builder)
    {
        builder.append(CQLTranslator.LIMIT);
        builder.append(this.maxResult);
    }
61983
def _is_xml_mode(self):
        '''
        
        '''
        return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
1022748
protected void checkLength(final Element parent, final String childName, final int minLen, final int maxLen) throws FeedException {
        final Element child = parent.getChild(childName, getFeedNamespace());
        if (child != null) {
            if (minLen > 0 && child.getText().length() < minLen) {
                throw new FeedException("Invalid " + getType() + " feed, " + parent.getName() + " " + childName + "short of " + minLen + " length");
            }
            if (maxLen > -1 && child.getText().length() > maxLen) {
                throw new FeedException("Invalid " + getType() + " feed, " + parent.getName() + " " + childName + "exceeds " + maxLen + " length");
            }
        }
    }
763675
function validateObjectLimits( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList )
    {
        $options =& $persistentData['object_options'];

        $options['include_classes'] = $http->hasPostVariable( 'IncludeClasses' ) ? $http->postVariable( 'IncludeClasses' ) : false;
        $options['include_templates'] = $http->hasPostVariable( 'IncludeTemplates' ) ? $http->postVariable( 'IncludeTemplates' ) : false;
        $options['site_access_array'] = $http->postVariable( 'SiteAccesses' );
        $options['versions'] = $http->postVariable( 'VersionExport' );
        $options['language_array'] = $http->postVariable( 'Languages' );
        $options['node_assignment'] = $http->postVariable( 'NodeAssignment' );
        $options['related_objects'] = $http->postVariable( 'RelatedObjects' );
        $options['minimal_template_set'] = $http->hasPostVariable( 'MinimalTemplateSet' ) ? $http->postVariable( 'MinimalTemplateSet' ) : false;

        $result = true;
        if ( count( $persistentData['object_options']['language_array'] ) == 0 )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Selected nodes' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'You must choose one or more languages.' ) );
            $result = false;
        }

        if ( $persistentData['object_options']['include_templates'] &&
             count( $persistentData['object_options']['site_access_array'] ) == 0 )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Selected nodes' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'You must choose one or more site access.' ) );
            $result = false;
        }

        return $result;
    }
717976
def doShow(self, xml=0):
		""""""

		if xml == 0:
			print 'Errorcode:', self.errorcode
			print 
			
			print 'Product information:'
			for key in self.product.keys():
				print '	 ', key.encode('UTF-8'),
				print '->', self.product[key].encode('UTF-8')
			print
			
			print 'Database information:'
			for key in self.database.keys():
				print '	 ', key.encode('UTF-8'),
				print'->', self.database[key].encode('UTF-8')
			print
			
			print 'Metadata:'
			for field in self.metadata.keys():
				print
				print '	  ', field.encode('UTF-8')
				for property in self.metadata[field]:
					print '		  ', property.encode('UTF-8'),
					print '->', self.metadata[field][property].encode('UTF-8') 
			print

			print 'Records:'
			for record in self.resultset:
				print
				for column in record:
					print '	  ', column.encode('UTF-8'),
					if type(record[column]) == UnicodeType:
						print '->', record[column].encode('UTF-8')
					else:
						print '->', record[column]

		else:
			tags = [
				'FMPXMLRESULT',
				'ERRORCODE',
				'PRODUCT',
				'DATABASE',
				'METADATA',
				'FIELD',
				'RESULTSET',
				'ROW',
				'COL',
				'DATA'
			]

			xml = self.data

			for tag in tags:
				xml = string.replace(xml, '></' + tag, '>\n</' + tag)
				xml = string.replace(xml, '><' + tag, '>\n<' + tag)

			print xml
444180
def output_xml(data, code, headers=None):
    """"""
    resp = make_response(dumps({'response' :data}), code)
    resp.headers.extend(headers or {})
    return resp
1271943
public static void checkPersistenceXMLValidity ()
  {
    // Check if all persistence.xml files contain valid classes!
    try
    {
      int nCount = 0;
      final Enumeration <URL> aEnum = ClassLoaderHelper.getResources (ClassLoaderHelper.getDefaultClassLoader (),
                                                                      PATH_PERSISTENCE_XML);
      while (aEnum.hasMoreElements ())
      {
        nCount++;
        final URL aURL = aEnum.nextElement ();
        final IMicroDocument aDoc = MicroReader.readMicroXML (new URLResource (aURL));
        if (aDoc == null || aDoc.getDocumentElement () == null)
          throw new IllegalStateException ("No XML file: " + aURL);
        for (final IMicroElement ePU : aDoc.getDocumentElement ().getAllChildElements (PERSISTENCE_NAMESPACE_URI,
                                                                                       "persistence-unit"))
          for (final IMicroElement eClass : ePU.getAllChildElements (PERSISTENCE_NAMESPACE_URI, "class"))
          {
            final String sClass = eClass.getTextContent ();
            if (StringHelper.hasNoTextAfterTrim (sClass))
              throw new IllegalStateException ("Persistence file " + aURL + ": class name is missing!");
            GenericReflection.getClassFromName (sClass.trim ());
          }
      }
      LOGGER.info ("All " + PATH_PERSISTENCE_XML + " files are valid (count=" + nCount + ")");
    }
    catch (final IOException ex)
    {
      // From getResources
      throw new IllegalStateException ("Failed to read " + PATH_PERSISTENCE_XML + " file", ex);
    }
    catch (final ClassNotFoundException ex)
    {
      // If forName fails
      throw new IllegalStateException ("Failed to resolve class", ex);
    }
  }