Java Code Examples for javax.servlet.jsp.tagext.BodyContent#getString()

The following examples show how to use javax.servlet.jsp.tagext.BodyContent#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URLParTag.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	BodyContent body = this.getBodyContent();
	String value = body.getString();
	URLTag parentTag = null;
	try {
		Tag tag = this;
		do {
			tag = tag.getParent();
		} while (!(tag instanceof URLTag));
		parentTag = (URLTag) tag;
	} catch (RuntimeException e) {
		throw new JspException("Error nesting parameter in url tag.", e);
	}
	parentTag.addParameter(this.getName(), value);
	return EVAL_PAGE;
}
 
Example 2
Source File: AttributeTag.java    From ontopia with Apache License 2.0 6 votes vote down vote up
/**
 * Actions after some body has been evaluated.
 */
@Override
public int doAfterBody() throws JspTagException {
  ElementTag elementTag = (ElementTag)
    findAncestorWithClass(this, ElementTag.class);

  if (elementTag != null) {
    // get body content
    BodyContent body = getBodyContent();
    if (body != null) {
      String content = body.getString();
      // add this attribute to parent element tag 
      elementTag.addAttribute(attrName, content);
      body.clearBody();
    } else {
      log.warn("AttributeTag: body content is null!");
    }
  } else {
    log.warn("AttributeTag: no parent element tag found!");
  }
  
  // only evaluate body once
  return SKIP_BODY;
}
 
Example 3
Source File: StringTag.java    From ontopia with Apache License 2.0 6 votes vote down vote up
/**
 * Actions after some body has been evaluated.
 */
@Override
public int doAfterBody() throws JspTagException {

  // retrieve parent tag which accepts the result of this operation
  ValueAcceptingTagIF acceptingTag = (ValueAcceptingTagIF)
    findAncestorWithClass(this, ValueAcceptingTagIF.class);

  // get body content which should contain the string we want to set.
  BodyContent body = getBodyContent();
  String content = body.getString();

  // construct new collection which consists of one String entry
  // kick it over to the nearest accepting tag
  acceptingTag.accept( Collections.singleton(content) );

  // reset body contents
  body.clearBody();
  
  return SKIP_BODY;
}
 
Example 4
Source File: XmlCompressorTag.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();
	
	XmlCompressor compressor = new XmlCompressor();
	compressor.setEnabled(enabled);
	compressor.setRemoveComments(removeComments);
	compressor.setRemoveIntertagSpaces(removeIntertagSpaces);
	
	try {
		bodyContent.clear();
		bodyContent.append(compressor.compress(content));
		bodyContent.writeOut(pageContext.getOut());
	} catch (Exception e) {
		throw new JspException("Failed to compress xml",e);
	}
	
	return super.doEndTag();
}
 
Example 5
Source File: HighlightTag.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int doEndTag() throws JspException {

    // Make sure there is something in the body for this tag
    // to process
    BodyContent bc = getBodyContent();
    if (bc == null) {
        return SKIP_BODY;
    }

    // Make sure tags are set and valid.
    initTags();

    String body = bc.getString();
    String search = "(" + text + ")"; //add grouping so we can get correct case out

    try {
        Pattern pattern = Pattern.compile(search,
                                          Pattern.CASE_INSENSITIVE |
                                          Pattern.UNICODE_CASE);

        Matcher matcher = pattern.matcher(body);

        body = matcher.replaceAll(startTag + "$1" + endTag);
    }
    catch (PatternSyntaxException e) {
        log.warn("highlighting disabled. Invalid pattern [" + search +
                "]." + e.getMessage());
    }

    try {
        pageContext.getOut().println(body);
    }
    catch (IOException ioe) {
        throw new JspException("IO error writing to JSP file:", ioe);
    }

    return EVAL_PAGE;
}
 
Example 6
Source File: ParameterTag.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String extractValue() {
	if (null != this.getValue()) {
		return this.getValue();
	} else {
		BodyContent body = this.getBodyContent();
		if (null != body) {
			return body.getString();
		} else {
			return null;
		}
	}
}
 
Example 7
Source File: PutTag.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
public int doAfterBody() throws JspException {
  BodyContent bodyContent = getBodyContent();
  String content = bodyContent.getString();

  // save body content into params after evaluation
  if (log.isDebugEnabled())
    log.debug("doAfterBody: register variable '"+name+"'.");

  putParameter(content, true);

  bodyContent.clearBody();
  return SKIP_BODY;
}
 
Example 8
Source File: CssCompressorTag.java    From htmlcompressor with Apache License 2.0 5 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();

	try {
		if(enabled) {
			//call YUICompressor
			YuiCssCompressor compressor = new YuiCssCompressor();
			compressor.setLineBreak(yuiCssLineBreak);
			String result = compressor.compress(content);

			bodyContent.clear();
			bodyContent.append(result);
			bodyContent.writeOut(pageContext.getOut());
		} else {
			bodyContent.clear();
			bodyContent.append(content);
			bodyContent.writeOut(pageContext.getOut());
		}
	} catch (Exception e) {
		throw new JspException("Failed to compress css",e);
	}
	
	return super.doEndTag();
}
 
Example 9
Source File: HighlightTag.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int doEndTag() throws JspException {

    // Make sure there is something in the body for this tag
    // to process
    BodyContent bc = getBodyContent();
    if (bc == null) {
        return SKIP_BODY;
    }

    // Make sure tags are set and valid.
    initTags();

    String body = bc.getString();
    String search = "(" + text + ")"; //add grouping so we can get correct case out

    try {
        Pattern pattern = Pattern.compile(search,
                                          Pattern.CASE_INSENSITIVE |
                                          Pattern.UNICODE_CASE);

        Matcher matcher = pattern.matcher(body);

        body = matcher.replaceAll(startTag + "$1" + endTag);
    }
    catch (PatternSyntaxException e) {
        log.warn("highlighting disabled. Invalid pattern [" + search +
                "]." + e.getMessage());
    }

    try {
        pageContext.getOut().println(body);
    }
    catch (IOException ioe) {
        throw new JspException("IO error writing to JSP file:", ioe);
    }

    return EVAL_PAGE;
}
 
Example 10
Source File: JspUtils.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a {@link Tag}.
 *
 * @param context The directive context.
 * @param node The main node of the directive.
 * @param pageContext The page context.
 * @param tag The tag to execute.
 * @throws JspException If something goes wrong.
 */
public static void executeTag(InternalContextAdapter context, Node node,
        PageContext pageContext, Tag tag) throws JspException
{
    int result = tag.doStartTag();
    if (tag instanceof BodyTag)
    {
        BodyTag bodyTag = (BodyTag) tag;
        BodyContent bodyContent = new VelocityBodyContent(
                pageContext.getOut(), (ASTBlock) node.jjtGetChild(1),
                context);
        switch (result)
        {
        case BodyTag.EVAL_BODY_BUFFERED:
            bodyTag.setBodyContent(bodyContent);
            bodyTag.doInitBody();
        case BodyTag.EVAL_BODY_INCLUDE:
            bodyContent.getString();
        default:
            break;
        }
        while (bodyTag.doAfterBody() == BodyTag.EVAL_BODY_AGAIN) {
            bodyContent.getString();
        }
    }
    tag.doEndTag();
}
 
Example 11
Source File: HtmlCompressorTag.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();
	
	HtmlCompressor htmlCompressor = new HtmlCompressor();
	htmlCompressor.setEnabled(enabled);
	htmlCompressor.setRemoveComments(removeComments);
	htmlCompressor.setRemoveMultiSpaces(removeMultiSpaces);
	htmlCompressor.setRemoveIntertagSpaces(removeIntertagSpaces);
	htmlCompressor.setRemoveQuotes(removeQuotes);
	htmlCompressor.setPreserveLineBreaks(preserveLineBreaks);
	htmlCompressor.setCompressJavaScript(compressJavaScript);
	htmlCompressor.setCompressCss(compressCss);
	htmlCompressor.setYuiJsNoMunge(yuiJsNoMunge);
	htmlCompressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
	htmlCompressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
	htmlCompressor.setYuiJsLineBreak(yuiJsLineBreak);
	htmlCompressor.setYuiCssLineBreak(yuiCssLineBreak);

	htmlCompressor.setSimpleDoctype(simpleDoctype);
	htmlCompressor.setRemoveScriptAttributes(removeScriptAttributes);
	htmlCompressor.setRemoveStyleAttributes(removeStyleAttributes);
	htmlCompressor.setRemoveLinkAttributes(removeLinkAttributes);
	htmlCompressor.setRemoveFormAttributes(removeFormAttributes);
	htmlCompressor.setRemoveInputAttributes(removeInputAttributes);
	htmlCompressor.setSimpleBooleanAttributes(simpleBooleanAttributes);
	htmlCompressor.setRemoveJavaScriptProtocol(removeJavaScriptProtocol);
	htmlCompressor.setRemoveHttpProtocol(removeHttpProtocol);
	htmlCompressor.setRemoveHttpsProtocol(removeHttpsProtocol);
	
	if(compressJavaScript && jsCompressor.equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
		ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
		if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
			closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
		} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
			closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
		} else {
			closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
		}
		htmlCompressor.setJavaScriptCompressor(closureCompressor);
	}
	
	try {
		bodyContent.clear();
		bodyContent.append(htmlCompressor.compress(content));
		bodyContent.writeOut(pageContext.getOut());
	} catch (Exception e) {
		throw new JspException("Failed to compress html",e);
	}
	
	return super.doEndTag();
}
 
Example 12
Source File: JavaScriptCompressorTag.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();

	try {
		if(enabled) {
			
			String result = content;
			
			if(jsCompressor.equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
				//call Closure compressor
				ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
				if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
					closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
				} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
					closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
				} else {
					closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
				}
				
				result = closureCompressor.compress(content);
				
			} else {
				//call YUICompressor
				YuiJavaScriptCompressor yuiCompressor = new YuiJavaScriptCompressor();
				yuiCompressor.setDisableOptimizations(yuiJsDisableOptimizations);
				yuiCompressor.setLineBreak(yuiJsLineBreak);
				yuiCompressor.setNoMunge(yuiJsNoMunge);
				yuiCompressor.setPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
				
				result = yuiCompressor.compress(content);
			}
			
			bodyContent.clear();
			bodyContent.append(result);
			bodyContent.writeOut(pageContext.getOut());
		} else {
			bodyContent.clear();
			bodyContent.append(content);
			bodyContent.writeOut(pageContext.getOut());
		}

	} catch (Exception e) {
		throw new JspException("Failed to compress javascript",e);
	}
	
	return super.doEndTag();
}
 
Example 13
Source File: BaseLayoutTag.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public OverrideBody(String name, BodyContent content) {
	super();
	this.name = name;
	this.content = content.getString();
}
 
Example 14
Source File: OptionTag.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected void renderFromBodyContent(BodyContent bodyContent, TagWriter tagWriter) throws JspException {
	Object value = this.pageContext.getAttribute(VALUE_VARIABLE_NAME);
	String label = bodyContent.getString();
	renderOption(value, label, tagWriter);
}
 
Example 15
Source File: OptionTag.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void renderFromBodyContent(BodyContent bodyContent, TagWriter tagWriter) throws JspException {
	Object value = this.pageContext.getAttribute(VALUE_VARIABLE_NAME);
	String label = bodyContent.getString();
	renderOption(value, label, tagWriter);
}
 
Example 16
Source File: FieldTag.java    From ontopia with Apache License 2.0 4 votes vote down vote up
/**
 * Renders the input field element with it's content.
 */
@Override
public int doEndTag() throws JspException {
  // get current value
  BodyContent bodyContent = getBodyContent();
  String value = (bodyContent == null ? "" : bodyContent.getString());
  if (value == null) value = "";

  if (InteractionELSupport.getBooleanValue(this.trim, true, pageContext))
    value = value.trim();

  boolean readonly = TagUtils.isComponentReadOnly(pageContext, this.readonly);

  VelocityContext vc = TagUtils.getVelocityContext(pageContext);

  // register action data and produce input field name
  String name = null;
  if (action_name != null && !readonly) {
    // retrieve the action group
    String group_name = TagUtils.getActionGroup(pageContext);
    if (group_name == null)
      throw new JspException("field tag has no action group available.");
    
    name = TagUtils.registerData(pageContext, action_name, group_name,
        params, Collections.singleton(value));
    vc.put("name", name);

    if (pattern != null) {
      Collection regexColl = InteractionELSupport.extendedGetValue(pattern,
          pageContext);
      if (!regexColl.isEmpty()) {
        String regex = (String) regexColl.iterator().next();
        UserIF user = FrameworkUtils.getUser(pageContext);
        String requestId = TagUtils.getRequestId(pageContext);
        if (requestId != null && name != null) {
          ActionDataSet ads = (ActionDataSet)
            user.getWorkingBundle(requestId);
          ActionData data = ads.getActionData(name);
          data.setMatchExpression(regex);
        }
      }
    }
  }

  // fill in attribute values
  vc.put("readonly", readonly);
  vc.put("value", value);

  if (id != null) vc.put("id", id);
  if (klass != null) vc.put("class", klass);

  // get the field configuration from the application configuration
  ActionRegistryIF registry = TagUtils.getActionRegistry(pageContext);
  FieldInformationIF fieldconfig = registry.getField(fieldtype_name);

  String type = fieldconfig.getType();
  vc.put("type", type);

  // --- simple input field (type=text)
  if (type.equals("text") || type.equals("password")) {
    vc.put("maxlength", fieldconfig.getMaxLength());
    vc.put("size", fieldconfig.getColumns());
  }
  // --- multiple line input field (type=textarea)
  else if (type.equals("textarea")) {
    vc.put("cols", fieldconfig.getColumns());
    vc.put("rows", fieldconfig.getRows());
  }
  // -- hidden field (type=hidden)
  else if (type.equals("hidden"))
    ; // noop
  else {
    // could be done using separate TagExtraInfo class
    throw new JspException("field " + action_name
        + " uses unsupported type '" + type + "'.");
  }

  // all variables are now set, proceed with outputting
  JspWriter out = (bodyContent == null ? pageContext.getOut() : getBodyContent().getEnclosingWriter());
  TagUtils.processWithVelocity(pageContext, TEMPLATE_FILE, out, vc);

  // Continue processing this page
  return EVAL_PAGE;
}
 
Example 17
Source File: LinkTag.java    From ontopia with Apache License 2.0 4 votes vote down vote up
/**
 * Generate the required input tag.
 * @exception JspException if a JSP exception has occurred
 */
@Override
public int doEndTag() throws JspException {
  // Get the velocity context.
  VelocityContext vc = TagUtils.getVelocityContext(pageContext);

  FormTag form = TagUtils.getCurrentFormTag(pageContext.getRequest());

  boolean readonly = TagUtils.isComponentReadOnly(pageContext, this.readonly);
  
  if (!readonly) {
    // Get the requestid of the ancestor form of this tag.
    String rid = TagUtils.getRequestId(pageContext);
    if (rid == null)
      throw new OntopiaRuntimeException("Request id not found.");
    vc.put("rid", rid);
    if (form != null)
      form.setOutputSubmitFunc(true);
  }
  
  
  if (action_name != null && !readonly) {
    // retrieve the action group
    String group_name = TagUtils.getActionGroup(pageContext);
    if (group_name == null)
      throw new JspException("link tag has no action group available.");
  
    // register action data    
    Set previous = Collections.singleton(""); 
    String name = TagUtils.registerData(pageContext, action_name, group_name,
                                        params, previous);
    vc.put("name", name);
  } else {
    vc.put("name", "");
  }

  // read-only state
  vc.put("readonly", readonly);
      
  if (href != null)
    vc.put("href", href);
  else
    vc.put("href", "");

  if (target != null)
    vc.put("target", target);
  else
    vc.put("target", "");

  // submit and reload information
  if (type == null || type.startsWith("submit")) {
    vc.put("submit", Boolean.TRUE);
    if (type != null && type.equals("submitNoReload"))
      vc.put("reload", Boolean.FALSE);
    else
      vc.put("reload", Boolean.TRUE);        
  } else {
    vc.put("submit", Boolean.FALSE);
  }
  
  if (id != null) vc.put("id", id);
  if (klass != null) vc.put("class", klass);
  
  // get link value from element content.
  BodyContent bodyContent = getBodyContent();
  String content = (bodyContent == null ? "" : bodyContent.getString());
  if (content == null) content = "";
  vc.put("content", content);
  
  // all variables are now set, proceed wi2th outputting
  JspWriter out = (bodyContent == null ? pageContext.getOut() : getBodyContent().getEnclosingWriter());
  TagUtils.processWithVelocity(pageContext, TEMPLATE_FILE, out, vc);
  
  // Continue processing this page
  return EVAL_PAGE;
}
 
Example 18
Source File: UnpagedListDisplayTag.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public int doEndTag() throws JspException {
    JspWriter out = null;
    try {
        if (getPageList().isEmpty()) {
            return EVAL_PAGE;
        }

        if (isExport()) {
            ExportWriter eh = createExportWriter();
            String[] columns = StringUtils.split(this.getExportColumns(),
                    ',');
            eh.setColumns(Arrays.asList(columns));
            ServletExportHandler seh = new ServletExportHandler(eh);
            pageContext.getOut().clear();
            pageContext.getOut().clearBuffer();
            pageContext.getResponse().reset();
            seh.writeExporterToOutput(
                    (HttpServletResponse) pageContext.getResponse(),
                    getPageList());
            return SKIP_PAGE;
        }

        // Get the JSPWriter that the body used, then pop the
        // bodyContent, so that we can get the real JspWriter with getOut.
        BodyContent body = getBodyContent();
        pageContext.popBody();
        out = pageContext.getOut();

        if (body != null) {
            String bodyString = body.getString();
            out.println(bodyString);
        }
        // Rely on content to have emitted a tbody tag somewhere
        out.println("</tbody>");
        out.println("</table>\n");
        out.println("</div>\n");
        out.println("</div>\n");
        setNumberOfColumns(0);
        setColumnCount(0);
        setCurrRow(0);

    }
    catch (IOException e) {
        throw new JspException("IO error" + e.getMessage());
    }
    finally {
        pageContext.setAttribute("current", null);
    }

    return EVAL_PAGE;
}
 
Example 19
Source File: UnpagedListDisplayTag.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public int doEndTag() throws JspException {
    JspWriter out = null;
    try {
        if (getPageList().isEmpty()) {
            return EVAL_PAGE;
        }

        if (isExport()) {
            ExportWriter eh = createExportWriter();
            String[] columns = StringUtils.split(this.getExportColumns(),
                    ',');
            eh.setColumns(Arrays.asList(columns));
            ServletExportHandler seh = new ServletExportHandler(eh);
            pageContext.getOut().clear();
            pageContext.getOut().clearBuffer();
            pageContext.getResponse().reset();
            seh.writeExporterToOutput(
                    (HttpServletResponse) pageContext.getResponse(),
                    getPageList());
            return SKIP_PAGE;
        }

        // Get the JSPWriter that the body used, then pop the
        // bodyContent, so that we can get the real JspWriter with getOut.
        BodyContent body = getBodyContent();
        pageContext.popBody();
        out = pageContext.getOut();

        if (body != null) {
            String bodyString = body.getString();
            out.println(bodyString);
        }
        // Rely on content to have emitted a tbody tag somewhere
        out.println("</tbody>");
        out.println("</table>\n");
        out.println("</div>\n");
        out.println("</div>\n");
        setNumberOfColumns(0);
        setColumnCount(0);
        setCurrRow(0);

    }
    catch (IOException e) {
        throw new JspException("IO error" + e.getMessage());
    }
    finally {
        pageContext.setAttribute("current", null);
    }

    return EVAL_PAGE;
}
 
Example 20
Source File: OptionTag.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected void renderFromBodyContent(BodyContent bodyContent, TagWriter tagWriter) throws JspException {
	Object value = this.pageContext.getAttribute(VALUE_VARIABLE_NAME);
	String label = bodyContent.getString();
	renderOption(value, label, tagWriter);
}