Starts link processing for the given content in replacement mode.<p>

Links are replaced by macros.<p>

@param content the content to process
@return the processed content with replaced links

@throws ParserException if something goes wrong
776076
public String replaceLinks(String content) throws ParserException {

        m_mode = REPLACE_LINKS;
        return process(content, m_encoding);
    }
1164310
@Override
    public int doEndTag() throws JspException {

        ServletRequest req = pageContext.getRequest();
        A_CmsConfiguredHtmlParser parser;
        if (m_allowInlineEdit && CmsJspTagEditable.isEditableRequest(req)) {
            // during inline editing the content should not be parsed
            try {
                getBodyContent().writeOut(pageContext.getOut());
                release();
            } catch (Exception ex) {
                release();
                if (LOG.isErrorEnabled()) {
                    LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, TAG_NAME), ex);
                }
                // this is severe
                throw new JspException(ex);
            }
        } else {
            // This will always be true if the page is called through OpenCms
            if (CmsFlexController.isCmsRequest(req)) {
                String content = "";
                try {
                    if (CmsStringUtil.isEmpty(m_configuredParserClassname)) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error(
                                Messages.get().getBundle().key(
                                    Messages.GUI_ERR_TAG_ATTRIBUTE_MISSING_2,
                                    new Object[] {TAG_NAME, ATT_VISITOR_CLASS}));
                        }

                    }
                    // wrong attribute visitorClass -> content will remain empty, but no exception is
                    // thrown
                    try {
                        // load
                        Class<?> cl = Class.forName(m_configuredParserClassname);
                        // Instantiate
                        Object instance = cl.newInstance();
                        // cast
                        parser = (A_CmsConfiguredHtmlParser)instance;
                        parser.setParam(m_param);
                        // cms object:
                        CmsFlexController controller = CmsFlexController.getController(req);
                        CmsObject cms = controller.getCmsObject();
                        parser.setCmsObject(cms);
                        content = parseTagAction(getBodyContent().getString(), pageContext, parser);

                    } catch (Exception e) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error(
                                Messages.get().getBundle().key(
                                    Messages.GUI_ERR_TAG_ATTRIBUTE_INVALID_3,
                                    new Object[] {
                                        TAG_NAME,
                                        ATT_VISITOR_CLASS,
                                        A_CmsConfiguredHtmlParser.class.getName()}),
                                e);
                        }
                        e.printStackTrace(System.err);
                    }

                } finally {
                    try {
                        getBodyContent().clear();
                        getBodyContent().print(content);
                        getBodyContent().writeOut(pageContext.getOut());
                        release();

                    } catch (Exception ex) {
                        release();
                        if (LOG.isErrorEnabled()) {
                            LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, TAG_NAME), ex);
                        }
                        // this is severe
                        throw new JspException(ex);
                    }

                }

            }
        }
        return EVAL_PAGE;
    }
1013611
public final void setContent(String content)
    {
        //clear non relevant flags
        this.contentBinary=null;
        this.contentParts=null;
        this.contentType=ContentType.STRING;

        this.contentString=content;
    }
1027100
public List<String> findAllInContent(String content) {
        
        List<String> results = new LinkedList<String>();
        
        // First check for all simple exact occurrences
        for (BoyerMooreMatcher matcher : strings) {
            if (matcher.findInContent(content) >= 0)
                results.add(matcher.getPattern());
        }
        
        // Then check for all regex occurrences
        Matcher matcher;
        for (Pattern pattern : patterns) {
            matcher = pattern.matcher(content);
            if (matcher.find()) {
                results.add(content);
            }
        }
        
        return results;
    }
508564
public static String urlDecode(String content, Charset charset, TestContext context) {
        return new UrlDecodeFunction().execute(Arrays.asList(content, charset.displayName()), context);
    }
826366
def parse_content(self, content):
        
        self.program = None
        self.status = None
        self.link = None
        self.best = None
        self.paths = []
        current_path = None
        # Set up instance variable

        for line in content:
            words = line.split(None)
            if ' - status is' in line:
                # alternatives only displays one program, so finding
                # this line again is an error.
                if self.program:
                    raise ParseException(
                        "Program line for {newprog} found in output for {oldprog}".format(
                            newprog=words[0], oldprog=self.program
                        )
                    )
                # Set up new program data
                self.program = words[0]
                self.status = words[4][:-1]  # remove trailing .
                self.alternatives = []
                current_path = {}
            elif not self.program:
                # Lines before 'status is' line are ignored
                continue
            elif line.startswith(' link currently points to ') and len(words) == 5:
                # line: ' link currently points to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-1.b15.el7_2.x86_64/jre/bin/java'
                self.link = words[4]
            elif ' - priority ' in line and len(words) == 4 and words[3].isdigit():
                # line: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java - priority 16091
                # New path - save current path if set
                self.paths.append({
                    'path': words[0],
                    'priority': int(words[3]),
                    'slave': {},
                })
                current_path = self.paths[-1]
            elif line.startswith(' slave ') and len(words) == 3 and current_path:
                # line: ' slave ControlPanel: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/ControlPanel'
                current_path['slave'][words[1][:-1]] = words[2]  # remove final : from program
            elif line.startswith("Current `best' version is ") and len(words) == 5:
                # line: 'Current `best' version is /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java.'
                self.best = words[4][:-1]
579525
@Override
	public JacksonWrapperParser createParser(String content) {
		try {
			return new JacksonWrapperParser(innerFactory.createParser(content), getSupportedFormat());
		} catch (IOException e) {
			e.printStackTrace();
			throw new KriptonRuntimeException(e);
		}
	}
315923
public String transform(CharSequence content, File inputFile) {
		final ParsingContext rootContextForReplacements = new ParsingContext();
		initializeContext(rootContextForReplacements);
		CharSequence rawContent = preProcessing(content);
		Stage stage = Stage.first();
		do {
			final ContentParserInterceptor interceptor = new ContentParserInterceptor();
			// Reset the lineno because it is not reset between the different stages.
			rootContextForReplacements.setLineNo(1);
			final boolean hasChanged = parse(rawContent, inputFile, 0, stage, rootContextForReplacements, interceptor);
			if (hasChanged) {
				rawContent = interceptor.getResult();
			}
			stage = stage.next();
		} while (stage != null);
		return postProcessing(rawContent);
	}
995303
private String transformContent(String content) {

        try {
            List<CmsJsonPart> parts = CmsJsonPart.parseJsonParts(content);
            JSONArray keys = new JSONArray();
            JSONObject output = new JSONObject();
            for (CmsJsonPart part : parts) {
                if (output.has(part.getKey())) {
                    LOG.warn("Duplicate key for JSON parts: " + part.getKey());
                }
                keys.put(part.getKey());
                output.put(part.getKey(), part.getValue());
            }
            output.put(KEY_PARTS, keys);
            return output.toString();
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
            return content;

        }
    }
540640
public static List<Block> parse(final String content, final String baseUri) throws ParseException {
      Document doc = Jsoup.parseBodyFragment(content, baseUri);
      List<Node> blockMarkers = Lists.newArrayList();
      doc.body().traverse(new NodeVisitor() {
         @Override
         public void head(final Node node, final int i) {
            if(node instanceof Comment) {
               String comment = Strings.nullToEmpty(((Comment)node).getData()).trim();
               if(comment.startsWith("wp:") || comment.startsWith("/wp:")) {
                  blockMarkers.add(node);
               }
            }
         }

         @Override
         public void tail(final Node node, final int i) {

         }
      });

      //Parse/tidy of invalid markup may leave markers as children
      //of nested elements. Move them to the body...

      for(int i = 0; i < blockMarkers.size(); i++) {
         Node node = blockMarkers.get(i);
         if(node.parent() != doc.body()) {
            Node cloneNode = node.clone();
            node.remove();
            if(i == 0) {
               doc.body().prependChild(cloneNode);
            } else {
               blockMarkers.get(i-1).after(cloneNode);
            }
            blockMarkers.set(i, cloneNode);
         }
      }

      Set<Node> markerSet = Sets.newIdentityHashSet();
      markerSet.addAll(blockMarkers);

      List<Block> blocks = Lists.newArrayList();
      Block currBlock = null;
      List<Node> currNodes = Lists.newArrayList();

      for(Node node : doc.body().childNodes()) {
         if(markerSet.contains(node)) {
            String comment = ((Comment)node).getData().trim();
            if(comment.startsWith("wp:")) {
               if(!currNodes.isEmpty()) {
                  //Default block...
                  blocks.add(new Block("html", currNodes));
                  currNodes.clear();
               }
               currBlock = block(comment, 3);
            } else if(comment.startsWith("/wp:")) {
               Block checkBlock = block(comment, 4);
               if(currBlock == null) {
                  throw new ParseException(String.format("Missing start block for 'wp:%s'", checkBlock.type), 0);
               } else if(!currBlock.type.equals(checkBlock.type)) {
                  throw new ParseException(String.format("Start/end block mismatch. Expecting '/wp:%s' but found '/wp:%s",
                          currBlock.type, checkBlock.type), 0);
               } else {
                  blocks.add(currBlock.withContent(currNodes));
                  currBlock = null;
                  currNodes.clear();
               }
            } else {
               currNodes.add(node);
            }
         } else {
            currNodes.add(node);
         }
      }

      if(currBlock != null) {
         throw new ParseException(String.format("Expecting end block for 'wp:%s'", currBlock.type), 0);
      }

      if(!currNodes.isEmpty()) {
         blocks.add(new Block("html", currNodes));
      }

      return removeEmptyBlocks(blocks);
   }
196530
public static String encodeXMLContent(final String content) {
		StringBuffer encoded = new StringBuffer(content);
		
		replaceAll(encoded,"&","&amp;");
		replaceAll(encoded,"\"","&quot;");
		replaceAll(encoded,"'","&apos;");
		replaceAll(encoded,"<","&lt;");
		replaceAll(encoded,">","&gt;");
		
		return encoded.toString();
	}
112353
public static String replaceAll(CharSequence content, Pattern pattern, String replacementTemplate) {
		if (StrUtil.isEmpty(content)) {
			return StrUtil.str(content);
		}

		final Matcher matcher = pattern.matcher(content);
		boolean result = matcher.find();
		if (result) {
			final Set<String> varNums = findAll(PatternPool.GROUP_VAR, replacementTemplate, 1, new HashSet<String>());
			final StringBuffer sb = new StringBuffer();
			do {
				String replacement = replacementTemplate;
				for (String var : varNums) {
					int group = Integer.parseInt(var);
					replacement = replacement.replace("$" + var, matcher.group(group));
				}
				matcher.appendReplacement(sb, escape(replacement));
				result = matcher.find();
			} while (result);
			matcher.appendTail(sb);
			return sb.toString();
		}
		return StrUtil.str(content);
	}
346229
private ResourceReference parseInterWikiLinks(StringBuilder content)
    {
        ResourceReference result = null;
        String interWikiAlias = parseElementAfterString(content, SEPARATOR_INTERWIKI);
        if (interWikiAlias != null) {
            InterWikiResourceReference link = new InterWikiResourceReference(removeEscapes(content.toString()));
            link.setInterWikiAlias(removeEscapes(interWikiAlias));
            result = link;
        }
        return result;
    }
325137
private byte[] replaceInContent(CmsFile file, byte[] contents) throws Exception {

        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_settings.getLocale())) {
            Locale contentLocale = CmsLocaleManager.getMainLocale(getCms(), file);
            if (!contentLocale.toString().equalsIgnoreCase(m_settings.getLocale())) {
                // content does not match the requested locale, skip it
                getReport().println(
                    Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
                    I_CmsReport.FORMAT_NOTE);
                return null;
            }
        }

        String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file);
        String content = new String(contents, encoding);

        if (CmsSourceSearchForm.REGEX_ALL.equals(m_settings.getSearchpattern()) & !m_replace) {
            m_matchedResources.add(file);
            getReport().print(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
            return null;
        }

        Matcher matcher = Pattern.compile(m_settings.getSearchpattern()).matcher(content);

        if (matcher.find()) {
            // search pattern did match here, so take this file in the list with matches resources
            m_matchedResources.add(file);
            getReport().print(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
            if (m_replace) {
                if (m_settings.getType().equals(SearchType.renameContainer)) {

                    return renameNestedContainers(
                        file,
                        m_settings.getElementResource(),
                        m_settings.getReplacepattern().split(";")[0],
                        m_settings.getReplacepattern().split(";")[1]);
                }
                return matcher.replaceAll(m_settings.getReplacepattern()).getBytes(encoding);
            }
        } else {
            // search pattern did not match
            getReport().print(
                Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
                I_CmsReport.FORMAT_NOTE);
        }
        return null;
    }
530390
protected void parse( String content ) {
        Tokenizer tokenizer = new CndTokenizer(false, true);
        TokenStream tokens = new TokenStream(content, tokenizer, false);
        tokens.start();
        while (tokens.hasNext()) {
            // Keep reading while we can recognize one of the two types of statements ...
            if (tokens.matches("<", ANY_VALUE, "=", ANY_VALUE, ">")) {
                parseNamespaceMapping(tokens);
            } else if (tokens.matches("[", ANY_VALUE, "]")) {
                parseNodeTypeDefinition(tokens);
            } else {
                Position position = tokens.previousPosition();
                throw new ParsingException(position, CndI18n.expectedNamespaceOrNodeDefinition.text(tokens.consume(),
                                                                                                    position.getLine(),
                                                                                                    position.getColumn()));
            }
        }
    }
1228221
@SuppressWarnings("unchecked")
  @NonNull public CMARichBlock addContent(@NonNull CMARichNode... content) {
    if (content == null) {
      throw new NullPointerException("content is null");
    }

    this.content.addAll(Arrays.asList(content));

    return this;
  }
278496
public static RedirectionAction buildFormPostContentAction(final WebContext context, final String content) {
        if (ContextHelper.isPost(context) && useModernHttpCodes) {
            return new TemporaryRedirectAction(content);
        } else {
            return new OkAction(content);
        }
    }