/*
String[] validTypes = new String[]
{ "application/xhtml+xml",
"application/x-dtbncx+xml", "text/css" };
122
void buildCSSTypesDictionary()
  {
    String description;
    String value;
    TextSearchDictionaryEntry de;


    //search eval() expression
    description = "text/css";
    value = "text/css";
    de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009);
    v.add(de);


  }
449845
protected void ensureNoInvalidFlags(final String actual, 
                                        final char[] invalid) {
        if (actual == null) return;
        StringBuilder unexpected = null;
        for (int i = 0; i < actual.length(); i++) {
            char c = actual.charAt(i);
            if (oneOf(c, invalid)) {
                if (unexpected == null) unexpected = new StringBuilder();
                unexpected.append(c);
            }
        }
        if (unexpected != null) {
            throw FormatException.formatFlagsMismatch(
                    unexpected.toString(), getFormatName());
        }
    }
130472
private function validateDtd()
    {
        $libxmlUseInternalErrors = libxml_use_internal_errors(true);
        $dom = $this->writeXml();

        $secureDtdEntityResolver = new SecureDtdEntityResolver();
        $dtd = $secureDtdEntityResolver->resolveEntity($dom->doctype);


        $systemId = 'data://text/plain;base64,'.base64_encode($dtd);

        $creator = new DOMImplementation;
        $doctype = $creator->createDocumentType(
            static::DOCUMENT_TYPE_QUALIFIED_NAME,
            static::DOCUMENT_TYPE_PUBLIC_ID,
            $systemId
        );
        $new = $creator->createDocument('', '', $doctype);

        $oldNode = $dom->getElementsByTagName(static::DOCUMENT_TYPE_QUALIFIED_NAME)->item(0);
        $newNode = $new->importNode($oldNode, true);
        $new->appendChild($newNode);

        if (!$new->validate()) {
            /** @var LibXMLError[] $errors */
            $errors = libxml_get_errors();
            $errMsgStack = [];
            foreach ($errors as $error) {
                $errMsgStack[] = $error->message;
            }
            $errMsg = implode(" \n", $errMsgStack);

            libxml_use_internal_errors($libxmlUseInternalErrors);
            throw new InvalidDtdSchemaException($errMsg);
        }
        libxml_use_internal_errors($libxmlUseInternalErrors);
    }
773325
@Override
    public XMLValidationSchema createSchema(InputStream in, String encoding,
    		String publicId, String systemId)
        throws XMLStreamException
    {
        ReaderConfig rcfg = createPrivateReaderConfig();
        return doCreateSchema(rcfg, StreamBootstrapper.getInstance
        		(publicId, SystemId.construct(systemId), in), publicId, systemId, null);
    }
898482
public static String validateXMLAgainstSchema(final String xml) {
		// Validate XML against schema
		if (xml != null && !xml.equals("")) {
			// Wrap XML with a root element (if required)
			String testXML = wrapXMLInRootElement(xml);
			try {
				// Create SAX Parser Factory
				SAXParserFactory spf = SAXParserFactory.newInstance();
				spf.setNamespaceAware(true);
				spf.setValidating(true);

				// Create SAX Parser
				SAXParser parser = spf.newSAXParser();
				parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
						XMLConstants.W3C_XML_SCHEMA_NS_URI);

				// Set schema location
				Object schema = DebugValidateXML.class.getResource(getSchemaPath()).toString();
				parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);

				// Setup the handler to throw an exception when an error occurs
				DefaultHandler handler = new DefaultHandler() {
					@Override
					public void warning(final SAXParseException e) throws SAXException {
						LOG.warn("XML Schema warning: " + e.getMessage(), e);
						super.warning(e);
					}

					@Override
					public void fatalError(final SAXParseException e) throws SAXException {
						throw e;
					}

					@Override
					public void error(final SAXParseException e) throws SAXException {
						throw e;
					}
				};

				// Validate the XML
				InputSource xmlSource = new InputSource(new StringReader(testXML));
				parser.parse(xmlSource, handler);

			} catch (SAXParseException e) {
				return "At line " + e.getLineNumber() + ", column: " + e.getColumnNumber()
						+ " ==> " + e.getMessage();
			} catch (Exception e) {
				return e.getMessage();
			}
		}

		return null;
	}
227362
private String createValueString(String[] values) {

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < values.length; i++) {

            // escape commas and equals in value
            values[i] = CmsStringUtil.substitute(values[i], ",", "\\,");
            values[i] = CmsStringUtil.substitute(values[i], "=", "\\=");

            buf.append("\t" + values[i] + ((i < (values.length - 1)) ? ",\\\n" : ""));
        }
        return buf.toString();
    }
1142040
public PactDslJsonArray stringType(String example) {
        body.put(example);
        matchers.addRule(rootPath + appendArrayIndex(0), TypeMatcher.INSTANCE);
        return this;
    }
1149774
private static void validateTypeStr(String typeStr) {
    if (typeStr.contains("[") || typeStr.contains("]")) {
      throw new IllegalArgumentException(
          String.format(
              "Cannot convert array types (%s), please build them using getType()", typeStr));
    }
    if (typeStr.contains("<") || typeStr.contains(">")) {
      throw new IllegalArgumentException(
          String.format(
              "Cannot convert generic types (%s), please build them using getType()", typeStr));
    }
  }
1005630
static String getCharsetFromContentType(String contentType) {
        if (contentType == null) return null;
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            String charset = m.group(1).trim();
            charset = charset.replace("charset=", "");
            return validateCharset(charset);
        }
        return null;
    }
120144
private ValidationResult isValidClassForType(Class<?> clazz, SoyType type) {
    // Exit early if the class is primitive and the type is nullable -- that's not allowed.
    // Then remove null from the type.  This allows us to accept precise params for nullable
    // types, e.g, for int|null we can allow IntegerData (which will be passed as 'null').
    if (SoyTypes.isNullable(type) && Primitives.allPrimitiveTypes().contains(clazz)) {
      return ValidationResult.forNullToPrimitive(type);
    }
    // Also exit early if the type is a VE, since those aren't allowed as params.
    if (SoyTypes.isKindOrUnionOfKind(type, SoyType.Kind.VE)
        || SoyTypes.isKindOrUnionOfKind(type, SoyType.Kind.VE_DATA)) {
      return ValidationResult.ve(type);
    }

    ImmutableSet<Class<?>> expectedClasses = null;
    GenericDescriptor expectedDescriptor = null;
    type = SoyTypes.tryRemoveNull(type);
    switch (type.getKind()) {
      case ANY:
      case UNKNOWN:
        expectedClasses = UNKNOWN_TYPES;
        break;
      case ATTRIBUTES:
      case CSS:
      case HTML:
      case URI:
      case TRUSTED_RESOURCE_URI:
      case JS:
        expectedClasses = SANITIZED_TYPES;
        break;
      case BOOL:
        expectedClasses = BOOL_TYPES;
        break;
      case FLOAT:
        expectedClasses = FLOAT_TYPES;
        break;
      case INT:
        expectedClasses = INT_TYPES;
        break;
      case LEGACY_OBJECT_MAP:
        expectedClasses = LEGACY_OBJECT_MAP_TYPES;
        break;
      case LIST:
        expectedClasses = LIST_TYPES;
        break;
      case MAP:
        expectedClasses = MAP_TYPES;
        break;
      case RECORD:
        expectedClasses = RECORD_TYPES;
        break;
      case STRING:
        expectedClasses = STRING_TYPES;
        break;
      case NULL:
        expectedClasses = NULL_TYPES;
        break;
      case PROTO:
        expectedClasses = PROTO_TYPES;
        expectedDescriptor = ((SoyProtoType) type).getDescriptor();
        break;
      case PROTO_ENUM:
        expectedClasses = PROTO_ENUM_TYPES;
        expectedDescriptor = ((SoyProtoEnumType) type).getDescriptor();
        break;
      case UNION:
        // number is a special case, it should work for double and NumberData
        if (type.equals(SoyTypes.NUMBER_TYPE)) {
          expectedClasses = NUMBER_TYPES;
          break;
        }
        // If this is a union, make sure the type is valid for every member.
        // If the type isn't valid for any member, then there's no guarantee this will work
        // for an arbitrary template at runtime.
        ValidationResult result = ValidationResult.valid();
        for (SoyType member : ((UnionType) type).getMembers()) {
          result.merge(isValidClassForType(clazz, member));
        }
        return result;
      case VE:
      case VE_DATA:
        throw new IllegalStateException("This should have been caught above");
      case ERROR:
        throw new IllegalStateException("Cannot have error type from function signature");
    }

    checkState(expectedClasses != null, "expectedClass not set!");
    if (expectedClasses.contains(clazz)) {
      return ValidationResult.valid();
    }
    ImmutableSet<String> expectedDescriptorNames = ImmutableSet.of();
    if (expectedDescriptor instanceof Descriptor) {
      expectedDescriptorNames =
          ImmutableSet.of(JavaQualifiedNames.getClassName((Descriptor) expectedDescriptor));
      if (matchesProtoDescriptor(Message.class, clazz, expectedDescriptor)) {
        return ValidationResult.valid();
      }
    }
    if (expectedDescriptor instanceof EnumDescriptor) {
      expectedDescriptorNames =
          ImmutableSet.of(JavaQualifiedNames.getClassName((EnumDescriptor) expectedDescriptor));
      if (clazz.isEnum()
          && matchesProtoDescriptor(ProtocolMessageEnum.class, clazz, expectedDescriptor)) {
        return ValidationResult.valid();
      }
    }
    // If none of the above conditions match, we failed.
    return ValidationResult.invalid(
        Stream.concat(
                expectedClasses.stream().map(Class::getName), expectedDescriptorNames.stream())
            .collect(toImmutableSet()));
  }
508313
@SuppressWarnings("squid:S1168")
    public String[] selectedValues() {
        if (isNotPresentSelect()) {
            return null;    // returning an empty array could be confused with no values selected
        }
        WebElement webElement = element.getWebElement();
        Select dropdown = new Select(webElement);
        List<WebElement> options = dropdown.getAllSelectedOptions();
        String[] stringOptions = new String[options.size()];
        for (int i = 0; i < options.size(); i++) {
            stringOptions[i] = options.get(i).getAttribute(VALUE);
        }
        return stringOptions;
    }
1371888
@Override
    public void validateElementStart(String localName, String uri, String prefix)
        throws XMLStreamException
    {
        // Ok, can we find the element definition?
        mTmpKey.reset(prefix, localName);
        DTDElement elem = mElemSpecs.get(mTmpKey);
        // whether it's found or not, let's add a stack frame:
        int elemCount = mElemCount++;
        if (elemCount >= mElems.length) {
            mElems = (DTDElement[]) DataUtil.growArrayBy50Pct(mElems);
        }

        mElems[elemCount] = mCurrElem = elem;
        mAttrCount = 0;
        mIdAttrIndex = -2; // -2 as a "don't know yet" marker

        /* but if not found, can not obtain any type information. Not
         * a validation problem though, since we are doing none...
         * Oh, also, unlike with real validation, not having actual element
         * information is ok; can still have attributes!
         */
        if (elem == null) { // || !elem.isDefined())
            mCurrAttrDefs = NO_ATTRS;
            mHasAttrDefaults = false;
            mCurrDefaultAttrs = null;
            mHasNormalizableAttrs = false;
            return;
        }

        // If element found, does it have any attributes?
        mCurrAttrDefs = elem.getAttributes();
        if (mCurrAttrDefs == null) {
            mCurrAttrDefs = NO_ATTRS;
            mHasAttrDefaults = false;
            mCurrDefaultAttrs = null;
            mHasNormalizableAttrs = false;
            return;
        }

        // Any normalization needed?
        mHasNormalizableAttrs = mNormAttrs || elem.attrsNeedValidation();

        // Any default values?
        mHasAttrDefaults = elem.hasAttrDefaultValues();
        if (mHasAttrDefaults) {
            /* Special count also contains ones with #REQUIRED value, but
             * that's a minor sub-optimality...
             */
            int specCount = elem.getSpecialCount();
            BitSet bs = mTmpDefaultAttrs;
            if (bs == null) {
                mTmpDefaultAttrs = bs = new BitSet(specCount);
            } else {
                bs.clear();
            }
            mCurrDefaultAttrs = bs;
        } else {
            mCurrDefaultAttrs = null;
        }
    }
582334
@Override
  public ValidationResult validateCode(String system, String code, String display) {
    Coding c = new Coding(system, code, display);
    return validateCode(c, null);
  }
1103162
private static void validateTags(String[] tagList, ArrayList<String> validList, ArrayList<String> invalidList) {
        for (String tag : tagList) {
            tag = tag.trim();
            if (tag.contains("\\") || tag.contains(" ") || tag.contains("\n") || tag.contains("-") || tag.equals("")) {
                invalidList.add(tag);
            } else {
                validList.add(tag);
            }
        }
    }
217913
@VisibleForTesting
  String sanitizeCssProperties(String style) {
    final StringBuilder sanitizedCss = new StringBuilder();
    CssGrammar.parsePropertyGroup(style, new CssGrammar.PropertyHandler() {
      CssSchema.Property cssProperty = CssSchema.DISALLOWED;
      List<CssSchema.Property> cssProperties = null;
      int propertyStart = 0;
      boolean hasTokens;
      boolean inQuotedIdents;
      String lastToken = null;

      private void emitToken(String token) {
        closeQuotedIdents();
        if (hasTokens) { sanitizedCss.append(' '); }
        sanitizedCss.append(token);
        hasTokens = true;
      }

      private void closeQuotedIdents() {
        if (inQuotedIdents) {
          sanitizedCss.append('\'');
          inQuotedIdents = false;
        }
      }

      private void sanitizeAndAppendUrl(String urlContent) {
        if (urlContent.length() < 1024) {
          String rewrittenUrl = urlRewriter.apply(urlContent);
          if (rewrittenUrl != null && !rewrittenUrl.isEmpty()) {
            if (hasTokens) { sanitizedCss.append(' '); }
            sanitizedCss.append("url('").append(rewrittenUrl).append("')");
            hasTokens = true;
          }
        }
      }

      public void url(String token) {
        closeQuotedIdents();
        if (cssProperty != null) {
          if ((cssProperty.bits & CssSchema.BIT_URL) != 0) {
            String urlContent = CssGrammar.cssContent(
                Strings.stripHtmlSpaces(  // TODO: css spaces
                    token.substring(4, token.length() - 1)));
            sanitizeAndAppendUrl(urlContent);
          }
        }
        lastToken = token;
      }

      public void startProperty(String propertyName) {
        if (cssProperties != null) { cssProperties.clear(); }
        cssProperty = cssSchema.forKey(propertyName);
        hasTokens = false;
        propertyStart = sanitizedCss.length();
        if (sanitizedCss.length() != 0) {
          sanitizedCss.append(';');
        }
        sanitizedCss.append(propertyName).append(':');
      }

      public void startFunction(String uncanonToken) {
        closeQuotedIdents();
        if (cssProperties == null) { cssProperties = Lists.newArrayList(); }
        cssProperties.add(cssProperty);
        String token = Strings.toLowerCase(uncanonToken);
        String key = cssProperty.fnKeys.get(token);
        cssProperty = key != null
            ? cssSchema.forKey(key)
            : CssSchema.DISALLOWED;
        if (cssProperty != CssSchema.DISALLOWED) {
          emitToken(token);
        }
        lastToken = token;
      }

      public void quotedString(String token) {
        closeQuotedIdents();
        // The contents of a quoted string could be treated as
        // 1. a run of space-separated words, as in a font family name,
        // 2. as a URL,
        // 3. as plain text content as in a list-item bullet,
        // 4. or it could be ambiguous as when multiple bits are set.
        int meaning =
            cssProperty.bits
            & (CssSchema.BIT_UNRESERVED_WORD | CssSchema.BIT_URL);
        if ((meaning & (meaning - 1)) == 0) {  // meaning is unambiguous
          if (meaning == CssSchema.BIT_UNRESERVED_WORD
              && token.length() > 2
              && isAlphanumericOrSpaceOrHyphen(token, 1, token.length() - 1)) {
            emitToken(Strings.toLowerCase(token));
          } else if (meaning == CssSchema.BIT_URL) {
            // convert to a URL token and hand-off to the appropriate method
            sanitizeAndAppendUrl(CssGrammar.cssContent(token));
          }
        }
        lastToken = token;
      }

      public void quantity(String token) {
        int test = token.startsWith("-")
            ? CssSchema.BIT_NEGATIVE : CssSchema.BIT_QUANTITY;
        if ((cssProperty.bits & test) != 0
            // font-weight uses 100, 200, 300, etc.
            || cssProperty.literals.contains(token)) {
          emitToken(token);
        }
        lastToken = token;
      }

      public void punctuation(String token) {
        closeQuotedIdents();
        if (cssProperty.literals.contains(token)) {
          emitToken(token);
        }
        lastToken = token;
      }

      private static final int IDENT_TO_STRING =
          CssSchema.BIT_UNRESERVED_WORD | CssSchema.BIT_STRING;
      public void identifier(String uncanonToken) {
        String token = Strings.toLowerCase(uncanonToken);
        if ("!".equals(lastToken) && "important".equals(token)) {
          emitToken("!important");
        } else if (cssProperty.literals.contains(token)) {
          emitToken(token);
        } else if ((cssProperty.bits & IDENT_TO_STRING) == IDENT_TO_STRING) {
          if (!inQuotedIdents) {
            inQuotedIdents = true;
            if (hasTokens) { sanitizedCss.append(' '); }
            sanitizedCss.append('\'');
            hasTokens = true;
          } else {
            sanitizedCss.append(' ');
          }
          sanitizedCss.append(Strings.toLowerCase(token));
        }
        lastToken = token;
      }

      public void hash(String token) {
        closeQuotedIdents();
        if ((cssProperty.bits & CssSchema.BIT_HASH_VALUE) != 0) {
          emitToken(Strings.toLowerCase(token));
        }
        lastToken = token;
      }

      public void endProperty() {
        if (!hasTokens) {
          sanitizedCss.setLength(propertyStart);
        } else {
          closeQuotedIdents();
        }
        lastToken = null;
      }

      public void endFunction(String token) {
        if (cssProperty != CssSchema.DISALLOWED) { emitToken(")"); }
        cssProperty = cssProperties.remove(cssProperties.size() - 1);
        lastToken = ")";
      }
    });
    return sanitizedCss.length() == 0 ? null : sanitizedCss.toString();
  }
608833
public static StringTypeDeclaration createDefaultStringDeclaration(String paramName) {
		return new StringTypeDeclaration() {

			String name = paramName;

			@Override
			public List<AnnotationRef> annotations() {
				return null;
			}

			@Override
			public XMLFacetInfo xml() {
				return null;
			}

			@Override
			public List<ValidationResult> validate(String payload) {
				return null;
			}

			@Override
			public String type() {
				return "string";
			}

			@Override
			public String toXmlSchema() {
				return null;
			}

			@Override
			public Boolean required() {
				return true;
			}

			@Override
			public List<TypeDeclaration> parentTypes() {
				return null;
			}

			@Override
			public String name() {
				return name;
			}

			@Override
			public List<TypeDeclaration> facets() {
				return Collections.emptyList();
			}

			@Override
			public List<ExampleSpec> examples() {
				return Collections.emptyList();
			}

			@Override
			public ExampleSpec example() {
				return null;
			}

			@Override
			public AnnotableStringType displayName() {
				return new AnnotableStringType() {

					@Override
					public List<AnnotationRef> annotations() {
						return null;
					}

					@Override
					public String value() {
						return name;
					}

				};
			}

			@Override
			public MarkdownString description() {
				return null;
			}

			@Override
			public String defaultValue() {
				return null;
			}

			@Override
			public List<AnnotationTarget> allowedTargets() {
				return Collections.emptyList();
			}

			@Override
			public String pattern() {
				return null;
			}

			@Override
			public Integer minLength() {
				return null;
			}

			@Override
			public Integer maxLength() {
				return null;
			}

			@Override
			public List<String> enumValues() {
				return null;
			}

			@Override
			public String toJsonSchema() {
				return null;
			}
		};

	}
99987
@Override
    public XMLValidator createValidator(ValidationContext ctxt)
        throws XMLStreamException
    {
        if (mFullyValidating) {
            return new DTDValidator(this, ctxt, mHasNsDefaults,
                                    getElementMap(), getGeneralEntityMap());
        }
        return new DTDTypingNonValidator(this, ctxt, mHasNsDefaults,
                                         getElementMap(), getGeneralEntityMap());

    }