Return a {@link SanitizedContent} valued continuation. Rendering logic is delegated to the
{@link WriteContinuation}, but it is assumed that the builder is the render target.
15287
static Continuation<SanitizedContent> strictContinuation(
      WriteContinuation delegate,
      final StringBuilder buffer,
      final ContentKind kind) {
    if (delegate.result().isDone()) {
      return new ResultContinuation<>(
          UnsafeSanitizedContentOrdainer.ordainAsSafe(buffer.toString(), kind));
    }
    return new AbstractContinuation<SanitizedContent>(delegate) {
      @Override
      Continuation<SanitizedContent> nextContinuation(WriteContinuation next) {
        return strictContinuation(next, buffer, kind);
      }
    };
  }
1202148
public static SanitizedContent constantAttributes(@CompileTimeConstant final String constant) {
    return fromConstant(constant, ContentKind.ATTRIBUTES, Dir.LTR);
  }
670102
public boolean isValidStartContextForContentKind(SanitizedContentKind contentKind) {
    if (templateNestDepth != 0) {
      return false;
    }
    switch (contentKind) {
      case ATTRIBUTES:
        // Allow HTML attribute names, regardless of the kind of attribute (e.g. plain text)
        // or immediately after an open tag.
        return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
      default:
        // NOTE: For URI's, we need to be picky that the context has no attribute type, since we
        // don't want to forget to escape ampersands.
        return this.equals(getStartContextForContentKind(contentKind));
    }
  }
983124
protected void endContent() throws RepositoryException {
        // Process the content of the element ...
        String content = StringUtil.normalize(contentBuilder.toString());
        // Null-out builder to setup for subsequent content.
        // Must be done before call to startElement below to prevent infinite loop.
        contentBuilder = null;
        // Skip if nothing in content but whitespace
        if (content.length() > 0) {
            // Create separate node for each content entry since entries can be interspersed amongst child elements
            startNode(XmlLexicon.ELEMENT_CONTENT, XmlLexicon.ELEMENT_CONTENT);
            currentNode.setProperty(XmlLexicon.ELEMENT_CONTENT, content);
            endNode();
        }
    }
494628
@Override
  protected Expression maybeWrapContent(
      CodeChunk.Generator generator, CallParamContentNode node, Expression content) {
    SanitizedContentKind kind = node.getContentKind();
    if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) {
    return content;
  }
    return super.maybeWrapContent(generator, node, content);
  }
258167
protected void renderContent(AbstractRenderAppender writer, TreeElement node)
    {
        String ctnt = node.getContent();
        if (ctnt != null) {
            renderContentPrefix(writer, node);
            if (_trs.escapeContent) {
                HtmlUtils.filter(ctnt, writer);
            }
            else {
                writer.append(ctnt);
            }
            renderContentSuffix(writer, node);
        }
    }
520506
public static SanitizedContent fromSafeHtmlProto(SafeHtmlProto html) {
    return SanitizedContent.create(SafeHtmls.fromProto(html).getSafeHtmlString(), ContentKind.HTML);
  }
196778
protected String rewriteContentString(String originalContent) {

        Pattern uuidPattern = Pattern.compile(CmsUUID.UUID_REGEX);
        I_CmsRegexSubstitution substitution = new I_CmsRegexSubstitution() {

            public String substituteMatch(String text, Matcher matcher) {

                String uuidString = text.substring(matcher.start(), matcher.end());
                CmsUUID uuid = new CmsUUID(uuidString);
                String result = uuidString;
                if (m_translationsById.containsKey(uuid)) {
                    result = m_translationsById.get(uuid).getStructureId().toString();
                }
                return result;
            }
        };
        return CmsStringUtil.substitute(uuidPattern, originalContent, substitution);
    }
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();
  }
301820
function handleContent(element, spaces, marker) {
  let renderedContent = '';
  let objectLike = null;

  if (element.content === undefined) {
    return [renderedContent, objectLike];
  }

  for (const item of element.content) {
    // Note: the `initialIndent` option above works because we specifically
    //       do *not* pass it down the rabbit hole here.
    if (item.element === 'member') {
      // This is an object type or something similar.
      objectLike = true;
      /* eslint-disable no-use-before-define */
      renderedContent += handle(item.key.content, item.value, {
        parent: element,
        spaces,
        marker,
        attributesElement: item,
      });
      /* eslint-enable no-use-before-define */
    } else if (item.element === 'ref') {
      renderedContent += `${marker} Include ${item.content.href}\n`;
    } else if (item.element === 'select') {
      // This is a `OneOf` mutually exclusive type. Currently not
      // supported as it needs some support upstream in Minim.
      console.warn('MSON select/option elements are not yet supported!');
    } else {
      // This is an array type or something similar.
      objectLike = false;
      /* eslint-disable no-use-before-define */
      renderedContent += handle(item.title, item, {
        parent: element,
        spaces,
        marker,
      });
      /* eslint-enable no-use-before-define */
    }
  }

  return [renderedContent, objectLike];
}
356890
public static SanitizedContent jsIdentifier(String identifier) {
    checkArgument(
        VALID_JS_IDENTIFIER_PATTERN.matcher(identifier).matches(),
        "JS identifier '%s' should match the pattern '%s'",
        identifier,
        VALID_JS_IDENTIFIER_PATTERN.pattern());
    checkArgument(
        !INVALID_JS_IDENTIFIERS.contains(identifier),
        "JS identifier '%s' should not be a reserved word or match a literal",
        identifier);
    return UnsafeSanitizedContentOrdainer.ordainAsSafe(identifier, ContentKind.JS);
  }
1247419
@NonNull
    public ContentValues toContentValues() {
        ContentValues values = new ContentValues();
        values.put(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME, (mComponentName != null)
                ? mComponentName.flattenToShortString() : null);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, (mImageUri != null)
                ? mImageUri.toString() : null);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_TITLE, mTitle);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_BYLINE, mByline);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_ATTRIBUTION, mAttribution);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_TOKEN, mToken);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT, (mViewIntent != null)
                ? mViewIntent.toUri(Intent.URI_INTENT_SCHEME) : null);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_META_FONT, mMetaFont);
        values.put(MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED, mDateAdded != null ?
                mDateAdded.getTime() : 0);
        return values;
    }
1156252
def continuation(self, body=None, final=True):
        ''''''
        return self.encode(body, opcode=0, final=final)
222193
@Override
  protected void visitLetContentNode(LetContentNode node) {
    String generatedVarName = node.getUniqueVarName();
    Expression generatedVar = id(generatedVarName);

    // Generate code to define the local var.
    jsCodeBuilder.pushOutputVar(generatedVarName);

    visitChildren(node);

    jsCodeBuilder.popOutputVar();

    if (node.getContentKind() != null) {
      // If the let node had a content kind specified, it was autoescaped in the corresponding
      // context. Hence the result of evaluating the let block is wrapped in a SanitizedContent
      // instance of the appropriate kind.

      // The expression for the constructor of SanitizedContent of the appropriate kind (e.g.,
      // "soydata.VERY_UNSAFE.ordainSanitizedHtml"), or null if the node has no 'kind' attribute.
      // Introduce a new variable for this value since it has a different type from the output
      // variable (SanitizedContent vs String) and this will enable optimizations in the jscompiler
      String wrappedVarName = node.getVarName() + "__wrapped" + node.getId();
      jsCodeBuilder.append(
          VariableDeclaration.builder(wrappedVarName)
              .setRhs(
                  sanitizedContentOrdainerFunctionForInternalBlocks(node.getContentKind())
                      .call(generatedVar))
              .build());
      generatedVar = id(wrappedVarName);
    }

    // Add a mapping for generating future references to this local var.
    templateTranslationContext.soyToJsVariableMappings().put(node.getVarName(), generatedVar);
  }
166095
public final boolean isValidEndContextForContentKind(SanitizedContentKind contentKind) {
    if (templateNestDepth != 0) {
      return false;
    }
    switch (contentKind) {
      case CSS:
        return state == HtmlContext.CSS && elType == ElementType.NONE;
      case HTML:
        return state == HtmlContext.HTML_PCDATA && elType == ElementType.NONE;
      case ATTRIBUTES:
        // Allow any html attribute context or html tag this. HTML_TAG is needed for constructs
        // like "checked" that don't require an attribute value. Explicitly disallow
        // HTML_NORMAL_ATTR_VALUE (e.g. foo={$x} without quotes) to help catch cases where
        // attributes aren't safely composable (e.g. foo={$x}checked would end up with one long
        // attribute value, whereas foo="{$x}"checked would be parsed as intended).
        return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
      case JS:
        // Just ensure the state is JS -- don't worry about whether a regex is coming or not.
        return state == HtmlContext.JS && elType == ElementType.NONE;
      case URI:
        // Ensure that the URI content is non-empty and the URI type remains normal (which is
        // the assumed type of the URI content kind).
        return state == HtmlContext.URI && uriType == UriType.NORMAL && uriPart != UriPart.START;
      case TEXT:
        return state == HtmlContext.TEXT;
      case TRUSTED_RESOURCE_URI:
        // Ensure that the URI content is non-empty and the URI type remains normal (which is
        // the assumed type of the URI content kind).
        return state == HtmlContext.URI
            && uriType == UriType.TRUSTED_RESOURCE
            && uriPart != UriPart.START;
    }
    throw new IllegalArgumentException(
        "Specified content kind " + contentKind + " has no associated end context.");
  }
1071903
public static SanitizedContent filterSmsUri(String value) {
    if (EscapingConventions.FilterSmsUri.INSTANCE.getValueFilter().matcher(value).find()) {
      // NOTE: No need to escape. Escaping for other contexts (e.g. HTML) happen after this.
      return UnsafeSanitizedContentOrdainer.ordainAsSafe(value, ContentKind.URI);
    }
    logger.log(Level.WARNING, "|filterSmsUri received bad value ''{0}''", value);
    return UnsafeSanitizedContentOrdainer.ordainAsSafe(
        EscapingConventions.FilterSmsUri.INSTANCE.getInnocuousOutput(),
        SanitizedContent.ContentKind.URI);
  }
827715
@Override
    public void setContent(final InputStream content, final String contentType,
            final Collection<URI> checksums, final String originalFileName,
            final StoragePolicyDecisionPoint storagePolicyDecisionPoint)
            throws InvalidChecksumException {

        try {


            final Node dsNode = getNode();

            LOGGER.debug("Created content node at path: {}", dsNode.getPath());

            String hint = null;

            if (storagePolicyDecisionPoint != null) {
                hint = storagePolicyDecisionPoint.evaluatePolicies(this);
            }
            final ValueFactory modevf =
                    (ValueFactory) node.getSession().getValueFactory();
            final Binary binary = modevf.createBinary(content, hint);

        /*
         * This next line of code deserves explanation. If we chose for the
         * simpler line: Property dataProperty =
         * contentNode.setProperty(JCR_DATA, requestBodyStream); then the JCR
         * would not block on the stream's completion, and we would return to
         * the requester before the mutation to the repo had actually completed.
         * So instead we use createBinary(requestBodyStream), because its
         * contract specifies: "The passed InputStream is closed before this
         * method returns either normally or because of an exception." which
         * lets us block and not return until the job is done! The simpler code
         * may still be useful to us for an asynchronous method that we develop
         * later.
         */
            final Property dataProperty = dsNode.setProperty(JCR_DATA, binary);

            // Ensure provided checksums are valid
            final Collection<URI> nonNullChecksums = (null == checksums) ? new HashSet<>() : checksums;
            verifyChecksums(nonNullChecksums, dataProperty);

            final Node descNode = getDescriptionNodeOrNull();

            decorateContentNode(dsNode, descNode, nonNullChecksums);
            FedoraTypesUtils.touch(dsNode);

            if (descNode != null) {
                descNode.setProperty(HAS_MIME_TYPE, contentType);

                if (originalFileName != null) {
                    descNode.setProperty(FILENAME, originalFileName);
                }

                FedoraTypesUtils.touch(descNode);
            }

            LOGGER.debug("Created data property at path: {}", dataProperty.getPath());

        } catch (final RepositoryException e) {
            throw new RepositoryRuntimeException(e);
        }
    }