Java 类org.springframework.web.util.HtmlUtils 实例源码

项目:emergentmud    文件:ShoutCommand.java   
@Override
public GameOutput execute(GameOutput output, Entity entity, String command, String[] tokens, String raw) {
    if (StringUtils.isEmpty(raw)) {
        output.append("What would you like to shout?");

        return output;
    }

    output.append(String.format("[dyellow]You shout '%s[dyellow]'", HtmlUtils.htmlEscape(raw)));

    GameOutput toZone = new GameOutput(String.format("[dyellow]%s shouts '%s[dyellow]'", entity.getName(), HtmlUtils.htmlEscape(raw)));
    List<Entity> contents = entityRepository.findByXBetweenAndYBetweenAndZBetween(
            entity.getX() - SHOUT_DISTANCE, entity.getX() + SHOUT_DISTANCE,
            entity.getY() - SHOUT_DISTANCE, entity.getY() + SHOUT_DISTANCE,
            entity.getZ() - SHOUT_DISTANCE, entity.getZ() + SHOUT_DISTANCE
    );

    contents = contents.stream()
            .filter(r -> roomService.isWithinDistance(entity, r.getX(), r.getY(), r.getZ(), SHOUT_DISTANCE))
            .collect(Collectors.toList());

    entityService.sendMessageToListeners(contents, entity, toZone);

    return output;
}
项目:lams    文件:EscapedErrors.java   
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
    if (source == null) {
        return null;
    }
    if (source instanceof FieldError) {
        FieldError fieldError = (FieldError) source;
        Object value = fieldError.getRejectedValue();
        if (value instanceof String) {
            value = HtmlUtils.htmlEscape((String) value);
        }
        return (T) new FieldError(
                fieldError.getObjectName(), fieldError.getField(), value,
                fieldError.isBindingFailure(), fieldError.getCodes(),
                fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
    }
    else {
        return (T) new ObjectError(
                source.getObjectName(), source.getCodes(), source.getArguments(),
                HtmlUtils.htmlEscape(source.getDefaultMessage()));
    }
}
项目:unitimes    文件:WebInstructionalOfferingTableBuilder.java   
protected TableCell buildNote(PreferenceGroup prefGroup, boolean isEditable, UserContext user){
    TableCell cell = null;
    if (prefGroup instanceof Class_) {
        Class_ c = (Class_) prefGroup;
        if (c.getNotes() != null && !c.getNotes().trim().isEmpty()) {
            if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                String note = (c.getNotes().length() <= 20 ? c.getNotes() : c.getNotes().substring(0, 20) + "...");
                cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                cell = initNormalCell(c.getNotes().replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else {
                cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(c.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
                cell.setAlign("center");
            }
        } else { 
            cell = this.initNormalCell("&nbsp;" ,isEditable);
        }
    } else { 
        cell = this.initNormalCell("&nbsp;" ,isEditable);
    }
    return(cell);
}
项目:unitimes    文件:WebInstructionalOfferingTableBuilder.java   
private TableCell buildNote(InstructionalOffering offering, boolean isEditable, UserContext user){
    TableCell cell = null;
if (offering.getNotes() != null && !offering.getNotes().trim().isEmpty()) {
    if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
        String note = (offering.getNotes().length() <= 20 ? offering.getNotes() : offering.getNotes().substring(0, 20) + "...");
        cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
            cell.setAlign("left");
    } else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
        cell = initNormalCell(offering.getNotes().replaceAll("\n","<br>"), isEditable);
            cell.setAlign("left");
    } else {
        cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(offering.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
        cell.setAlign("center");
    }
} else { 
        cell = this.initNormalCell("&nbsp;" ,isEditable);
    }
      return(cell);
  }
项目:spring4-understanding    文件:EscapedErrors.java   
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
    if (source == null) {
        return null;
    }
    if (source instanceof FieldError) {
        FieldError fieldError = (FieldError) source;
        Object value = fieldError.getRejectedValue();
        if (value instanceof String) {
            value = HtmlUtils.htmlEscape((String) value);
        }
        return (T) new FieldError(
                fieldError.getObjectName(), fieldError.getField(), value,
                fieldError.isBindingFailure(), fieldError.getCodes(),
                fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
    }
    else {
        return (T) new ObjectError(
                source.getObjectName(), source.getCodes(), source.getArguments(),
                HtmlUtils.htmlEscape(source.getDefaultMessage()));
    }
}
项目:simbest-cores    文件:CustomMultipartResolver.java   
public static void main(String[] args) {  
    String specialStr = " #测试转义:#<table id=\"testid\"><tr>test1;test2</tr></table>";
 // ①转换为HTML转义字符表示
    String str1 = HtmlUtils.htmlEscape(specialStr);
    System.out.println(str1);

 // ②转换为数据转义表示
    String str2 = HtmlUtils.htmlEscapeDecimal(specialStr);
    System.out.println(str2);

  //③转换为十六进制数据转义表示
    String str3 = HtmlUtils.htmlEscapeHex(specialStr);
    System.out.println(str3);

   // ④下面对转义后字符串进行反向操作
    System.out.println(HtmlUtils.htmlUnescape(str1));
    System.out.println(HtmlUtils.htmlUnescape(str2));
    System.out.println(HtmlUtils.htmlUnescape(str3));
}
项目:nbone    文件:UnsafeStringEscape.java   
/**
 * 大颗粒标签过滤(含<>)
 * @param value
 * @return 返回转义后的字符
 */
public String largeGrainedTagFilter(String value) {
     //标准脚本和HTML<script>alert(999)</script>
     //简化脚本和HTML<script type="" src=""/>
     //</script>
    Pattern scriptPattern = Pattern.compile("(<(.*?)>(.*)</(.*?)>|<(.*?)/>|</(.*?)>)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    //value = scriptPattern.matcher(value).replaceAll("");
    boolean boo = scriptPattern.matcher(value).find();
       if(boo){
        value = HtmlUtils.htmlEscape(value);
       }
       System.out.println("1:"+value);

       //不规范的脚本<script>
       scriptPattern = Pattern.compile("<(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
       boo = scriptPattern.matcher(value).find();
       if(boo){
        value = HtmlUtils.htmlEscape(value);
       }
       System.out.println(value);

       return value;

}
项目:openmrs-module-legacyui    文件:OpenmrsMessageTag.java   
/**
 * @see MessageTag#doStartTagInternal()
 * @should evaluate specified message resolvable
 * @should resolve message by code
 * @should resolve message in locale that different from default
 * @should return code if no message resolved
 * @should use body content as fallback if no message resolved
 * @should use text attribute as fallback if no message resolved
 * @should use body content in prior to text attribute as fallback if no message resolved
 * @should ignore fallbacks if tag locale differs from context locale
 */
@Override
protected int doEndTagInternal() throws JspException, IOException {
    try {
        // Resolve the unescaped message.
        String msg = resolveMessage();

        // HTML and/or JavaScript escape, if demanded.
        msg = isHtmlEscape() ? HtmlUtils.htmlEscape(msg) : msg;
        msg = this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(msg) : msg;

        // Expose as variable, if demanded, else write to the page.
        String resolvedVar = this.var;
        if (resolvedVar != null) {
            pageContext.setAttribute(resolvedVar, msg, TagUtils.getScope(this.scope));
        } else {
            writeMessage(msg);
        }

        return EVAL_PAGE;
    }
    catch (NoSuchMessageException ex) {
        throw new JspTagException(getNoSuchMessageExceptionDescription(ex));
    }
}
项目:kaif    文件:Article.java   
public static Article createSpeak(Zone zone,
    String zoneAliasName,
    FlakeId articleId,
    Account author,
    String title,
    String content,
    Instant now) {
  Preconditions.checkArgument(isValidTitle(title));
  Preconditions.checkArgument(isValidContent(content));
  String safeTitle = HtmlUtils.htmlEscape(title);
  return new Article(zone,
      zoneAliasName,
      articleId,
      safeTitle,
      null,
      content,
      ArticleContentType.MARK_DOWN,
      now,
      author.getAccountId(),
      author.getUsername(),
      false,
      0,
      0,
      0);
}
项目:kaif    文件:Article.java   
public static Article createExternalLink(Zone zone,
    String zoneAliasName,
    FlakeId articleId,
    Account author,
    String title,
    String link,
    Instant now) {
  Preconditions.checkArgument(isValidTitle(title));
  Preconditions.checkArgument(isValidLink(link));
  String safeTitle = HtmlUtils.htmlEscape(title);
  String safeLink = HtmlUtils.htmlEscape(link);
  return new Article(zone,
      zoneAliasName,
      articleId,
      safeTitle,
      safeLink,
      null,
      ArticleContentType.NONE,
      now,
      author.getAccountId(),
      author.getUsername(),
      false,
      0,
      0,
      0);
}
项目:unitime    文件:WebInstructionalOfferingTableBuilder.java   
protected TableCell buildNote(PreferenceGroup prefGroup, boolean isEditable, UserContext user){
    TableCell cell = null;
    if (prefGroup instanceof Class_) {
        Class_ c = (Class_) prefGroup;
        if (c.getNotes() != null && !c.getNotes().trim().isEmpty()) {
            if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                String note = (c.getNotes().length() <= 20 ? c.getNotes() : c.getNotes().substring(0, 20) + "...");
                cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                cell = initNormalCell(c.getNotes().replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else {
                cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(c.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
                cell.setAlign("center");
            }
        } else { 
            cell = this.initNormalCell("&nbsp;" ,isEditable);
        }
    } else { 
        cell = this.initNormalCell("&nbsp;" ,isEditable);
    }
    return(cell);
}
项目:unitime    文件:WebInstructionalOfferingTableBuilder.java   
private TableCell buildNote(InstructionalOffering offering, boolean isEditable, UserContext user){
    TableCell cell = null;
if (offering.getNotes() != null && !offering.getNotes().trim().isEmpty()) {
    if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
        String note = (offering.getNotes().length() <= 20 ? offering.getNotes() : offering.getNotes().substring(0, 20) + "...");
        cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
            cell.setAlign("left");
    } else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
        cell = initNormalCell(offering.getNotes().replaceAll("\n","<br>"), isEditable);
            cell.setAlign("left");
    } else {
        cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(offering.getNotes()) + "' align='absmiddle' src='images/note.png'>", isEditable);
        cell.setAlign("center");
    }
} else { 
        cell = this.initNormalCell("&nbsp;" ,isEditable);
    }
      return(cell);
  }
项目:GeneralUtils    文件:StringEscapeEditor.java   
/**
 * override setAsText method , then register
 */
@Override
public void setAsText(String text) throws IllegalArgumentException {

     if (!StringUtils.hasText(text)) {  
            return;  
        }else {
        String value = text;
        if (escapeHTML) {
            value = HtmlUtils.htmlEscape(value);
        }
        if (escapeJavaScript) {
            value = JavaScriptUtils.javaScriptEscape(value);
        }
        super.setValue(value);
    }
}
项目:lognavigator    文件:LogNavigatorHandlerExceptionResolver.java   
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
    LOGGER.error("Error when calling web action", exception);

    // Compute error message to display
    String errorTitle = exception.getClass().getSimpleName().replaceFirst("(Error|Exception)", " Error");
    String errorMessage = HtmlUtils.htmlEscape(exception.getMessage()).replace("\n", "<br/>");

    ModelAndView modelAndView = new ModelAndView(Constants.VIEW_ERROR);
    modelAndView.addObject(Constants.ERROR_TITLE_KEY, errorTitle);
    modelAndView.addObject(Constants.ERROR_MESSAGE_KEY, errorMessage);
    if (exception instanceof AccessDeniedException || exception instanceof ConfigException) {
        modelAndView.addObject(Constants.BLOCKING_ERROR_KEY, Boolean.TRUE);
    }
    return modelAndView;
}
项目:easyrec-PoC    文件:ItemDAOMysqlImpl.java   
@Override
public Item add(Integer tenantId, String itemId, String itemType, String itemDescription, String url,
                String imageurl) {
    try {
        Object[] args = {tenantId, itemId, itemType, HtmlUtils.htmlEscape(itemDescription), Web.makeUrlSecure(url),
                Web.makeUrlSecure(imageurl)};

        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(PS_ADD_ITEM.newPreparedStatementCreator(args), keyHolder);

        return new Item(keyHolder.getKey().toString(), tenantId, itemId, itemType,
                HtmlUtils.htmlEscape(itemDescription), Web.makeUrlSecure(url), Web.makeUrlSecure(imageurl),
                null, true, new Date().toString());

    } catch (Exception e) {
        logger.error("An error occured adding an item!", e);
        return null;
    }

}
项目:class-guard    文件:EscapedErrors.java   
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
    if (source == null) {
        return null;
    }
    if (source instanceof FieldError) {
        FieldError fieldError = (FieldError) source;
        Object value = fieldError.getRejectedValue();
        if (value instanceof String) {
            value = HtmlUtils.htmlEscape((String) value);
        }
        return (T) new FieldError(
                fieldError.getObjectName(), fieldError.getField(), value,
                fieldError.isBindingFailure(), fieldError.getCodes(),
                fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
    }
    else {
        return (T) new ObjectError(
                source.getObjectName(), source.getCodes(), source.getArguments(),
                HtmlUtils.htmlEscape(source.getDefaultMessage()));
    }
}
项目:WMarket    文件:PricePlan.java   
/**
 * Creates a Price Plan from a raw price plan extracted from RDF
 * @param rawPricePlan The raw price plan
 * @param offering The offering that contains the price plan
 * @throw ParseException When the raw price plan does is not valid
 */
public PricePlan(Map<String, List<Object>> rawPricePlan, Offering offering) throws ParseException {

    List<Object> titles = rawPricePlan.get("title");
    String title = (titles == null || titles.isEmpty()) ? "" : (String) titles.get(0);
    if (title.isEmpty()) {
        throw new ParseException("Offering " + offering.getDisplayName() + 
                " contains a price plan without title");
    }

    this.title = HtmlUtils.htmlEscape(title);
    List<Object> ppDescriptions = rawPricePlan.get("description");
    this.comment = (ppDescriptions != null && ppDescriptions.size() == 1) ? 
            HtmlUtils.htmlEscape((String) ppDescriptions.get(0)) : "";
    this.offering = offering;
    this.priceComponents = new HashSet<>();
}
项目:sinavi-jfw    文件:TagUtils.java   
/**
 * リンクとして出力するURLを生成します。
 * @param url パス
 * @param params パスに付与するパラメータ
 * @param pageContext ページコンテキスト
 * @param isHtmlEscape HTMLの特殊文字をエスケープするかどうか
 * @param isJavaScriptEscape JavaScriptの特殊文字をエスケープするかどうか
 * @return パス
 * @throws JspException 予期しない例外
 */
public static String createUrl(String url, Map<String, String[]> params, PageContext pageContext, boolean isHtmlEscape, boolean isJavaScriptEscape) throws JspException {
    HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse)pageContext.getResponse();

    StringBuilder buffer = new StringBuilder();
    UrlType urlType = getUrlType(url);
    if (urlType == UrlType.CONTEXT_RELATIVE) {
        buffer.append(request.getContextPath());
        if (!url.startsWith("/")) {
            buffer.append("/");
        }
    }
    buffer.append(replaceUriTemplateParams(url, params, pageContext));
    buffer.append(createQueryString(params, (url.indexOf("?") == -1), pageContext));

    String urlStr = buffer.toString();
    if (urlType != UrlType.ABSOLUTE) {
        urlStr = response.encodeURL(urlStr);
    }

    urlStr = isHtmlEscape ? HtmlUtils.htmlEscape(urlStr) : urlStr;
    urlStr = isJavaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr;

    return urlStr;
}
项目:easyrec    文件:ItemDAOMysqlImpl.java   
@Override
public Item add(Integer tenantId, String itemId, String itemType, String itemDescription, String url,
                String imageurl) {
    try {
        Object[] args = {tenantId, itemId, itemType, HtmlUtils.htmlEscape(itemDescription), Web.makeUrlSecure(url),
                Web.makeUrlSecure(imageurl)};

        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(PS_ADD_ITEM.newPreparedStatementCreator(args), keyHolder);

        return new Item(keyHolder.getKey().toString(), tenantId, itemId, itemType,
                HtmlUtils.htmlEscape(itemDescription), Web.makeUrlSecure(url), Web.makeUrlSecure(imageurl),
                null, true, new Date().toString());

    } catch (Exception e) {
        logger.error("An error occured adding an item!", e);
        return null;
    }

}
项目:corsoiseng    文件:Service.java   
public String normalizePseudo(final String pseudo) throws ExecutionException {
    if (null == pseudo || pseudo.trim().isEmpty()) {
        return new StringBuilder("Ann Onymous #").append(getAnonymousCounter().incrementAndGet()).toString();
    } else {
        String lpseudo = pseudo.trim();
        final Matcher m = Service.PATTERN.matcher(lpseudo);
        if (m.matches()) {
            if(lpseudo.length() > 40) {
                lpseudo = HtmlUtils.htmlEscape(new StringBuilder(lpseudo.substring(0, 40)).append("...").toString());
            }
            return lpseudo;
        } else {
            return new StringBuilder("Fucked up #").append(getFuckedupCounter().incrementAndGet()).toString();
        }
    }
}
项目:forweaver2.0    文件:WebUtil.java   
/** 글의 http 주소가 있으면 링크로 바꿔줌.
 * @param plain
 * @return
 */
public static String addLink(String text){
    if (text == null) {
        return text;
    }

    String escapedText = HtmlUtils.htmlEscape(text)
            .replaceAll("(\\A|\\s)((http|https|ftp|mailto):\\S+)(\\s|\\z)","$1<a href=\"$2\">$2</a>$4");

    return escapedText;
}
项目:emergentmud    文件:TellCommand.java   
@Override
public GameOutput execute(GameOutput output, Entity entity, String command, String[] tokens, String raw) {
    if (StringUtils.isEmpty(raw) || tokens.length < 2) {
        output.append("Usage: TELL &lt;target&gt; &lt;message&gt;");

        return output;
    }

    String targetName = tokens[0];
    String message = raw.substring(tokens[0].length() + 1);
    Entity target = entityRepository.findByNameStartingWithIgnoreCase(targetName);

    if (target == null) {
        output.append("You don't know of anyone by that name.");

        return output;
    }

    if (target.equals(entity)) {
        output.append("You murmur quietly to yourself.");

        return output;
    }

    output.append(String.format("[red]You tell %s '%s[red]'", target.getName(), HtmlUtils.htmlEscape(message)));

    GameOutput toTarget = new GameOutput(String.format("[red]%s tells you '%s[red]'", entity.getName(), HtmlUtils.htmlEscape(message)));

    entityService.sendMessageToEntity(target, toTarget);

    return output;
}
项目:lams    文件:GBActivityGridRowDTO.java   
public GBActivityGridRowDTO(Activity activity, String groupName, Long groupId) {

    if (groupName != null && groupId != null) {
        // Need to make the id unique, so appending the group id for this row
        this.id = activity.getActivityId().toString() + "_" + groupId.toString();

        this.groupId = groupId;
        // If grouped acitivty, append group name
        this.rowName = HtmlUtils.htmlEscape(activity.getTitle()) + " (" + groupName + ")";
    } else {
        this.id = activity.getActivityId().toString();

        this.rowName = HtmlUtils.htmlEscape(activity.getTitle());
    }

    String competenceMappingsStr = "";
    if ( activity.isToolActivity() ) {
        ToolActivity toolActivity = (ToolActivity) activity;
            //Constructs the competences for this activity.
            Set<CompetenceMapping> competenceMappings = toolActivity.getCompetenceMappings();

            if (competenceMappings != null) {
                for (CompetenceMapping mapping : competenceMappings) {
                competenceMappingsStr += mapping.getCompetence().getTitle() + ", ";
                }

                // trim the last comma off
                if (competenceMappingsStr.length() > 0) {
                competenceMappingsStr = competenceMappingsStr.substring(0, competenceMappingsStr.lastIndexOf(","));
                }
            }

    } 
    this.competences = competenceMappingsStr;

    }
项目:lams    文件:MultiLinesOutputTag.java   
@Override
   public void doTag() throws JspException, IOException {
if (escapeHtml) {
    value = HtmlUtils.htmlEscape(value);
}
value = value.replaceAll("\n", "<br>");
getJspContext().getOut().write(value.toString());
   }
项目:unitimes    文件:WebClassListTableBuilder.java   
@Override
protected TableCell buildNote(PreferenceGroup prefGroup, boolean isEditable, UserContext user){
    TableCell cell = null;
    if (prefGroup instanceof Class_) {
        Class_ c = (Class_) prefGroup;
        String offeringNote = c.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getNotes();
        String classNote = c.getNotes();
        String note = (offeringNote == null || offeringNote.isEmpty() ? classNote : offeringNote + (classNote == null || classNote.isEmpty() ? "" : "\n" + classNote));
        if (note != null && !note.isEmpty()) {
            if (CommonValues.NoteAsShortText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                if (classNote != null && !classNote.isEmpty()) note = classNote;
                if (note.length() > 20) note = note.substring(0, 20) + "...";
                cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else if (CommonValues.NoteAsFullText.eq(user.getProperty(UserProperty.ManagerNoteDisplay))) {
                cell = initNormalCell(note.replaceAll("\n","<br>"), isEditable);
                cell.setAlign("left");
            } else {
                cell = initNormalCell("<IMG border='0' alt='" + MSG.altHasNoteToMgr() + "' title='" + HtmlUtils.htmlEscape(note) + "' align='absmiddle' src='images/note.png'>", isEditable);
                cell.setAlign("center");
            }
        } else { 
            cell = this.initNormalCell("&nbsp;" ,isEditable);
        }
    } else { 
        cell = this.initNormalCell("&nbsp;" ,isEditable);
    }
    return(cell);
}
项目:unitimes    文件:Preference.java   
public String preferenceHtml(String nameFormat, boolean highlightClassPrefs) {
    StringBuffer sb = new StringBuffer("<span ");
    String style = "font-weight:bold;";
    if (this.getPrefLevel().getPrefId().intValue() != 4) {
        style += "color:" + this.getPrefLevel().prefcolor() + ";";
    }
    if (this.getOwner() != null && this.getOwner() instanceof Class_ && highlightClassPrefs) {
        style += "background: #ffa;";
    }
    sb.append("style='" + style + "' ");
    String owner = "";
    if (getOwner() != null && getOwner() instanceof Class_) {
        owner = " (" + MSG.prefOwnerClass() + ")";
    } else if (getOwner() != null && getOwner() instanceof SchedulingSubpart) {
        owner = " (" + MSG.prefOwnerSchedulingSubpart() + ")";
    } else if (getOwner() != null && getOwner() instanceof DepartmentalInstructor) {
        owner = " (" + MSG.prefOwnerInstructor() + ")";
    } else if (getOwner() != null && getOwner() instanceof Exam) {
        owner = " (" + MSG.prefOwnerExamination() + ")";
    } else if (getOwner() != null && getOwner() instanceof Department) {
        owner = " (" + MSG.prefOwnerDepartment() + ")";
    } else if (getOwner() != null && getOwner() instanceof Session) {
        owner = " (" + MSG.prefOwnerSession() + ")";
    }
    String hint = HtmlUtils.htmlEscape(preferenceTitle(nameFormat) + owner);
    String description = preferenceDescription();
    if (description != null && !description.isEmpty())
        hint += "<br>" + HtmlUtils.htmlEscape(description.replace("\'", "\\\'")).replace("\n", "<br>");
    sb.append("onmouseover=\"showGwtHint(this, '" + hint + "');\" onmouseout=\"hideGwtHint();\">");

    sb.append(this.preferenceAbbv(nameFormat));
    sb.append("</span>");
    return (sb.toString());
}
项目:unitimes    文件:DataExchangeHelper.java   
public void log(String level, String message, Throwable t) {
    if (iTextLog==null) return;
    if (message!=null) {
        String escapedMessage = HtmlUtils.htmlEscape(message);
        if (sLogLevelDebug.equals(level)) iTextLog.println("<font color='gray'>&nbsp;&nbsp;--"+escapedMessage+"</font>");
        else if (sLogLevelInfo.equals(level)) iTextLog.println(escapedMessage+"");
        else if (sLogLevelWarn.equals(level)) iTextLog.println("<font color='orange'>"+escapedMessage+"</font>");
        else if (sLogLevelError.equals(level)) iTextLog.println("<font color='red'>"+escapedMessage+"</font>");
        else if (sLogLevelFatal.equals(level)) iTextLog.println("<font color='red'><b>"+escapedMessage+"</b></font>");
        else iTextLog.println(escapedMessage);
    }
}
项目:xmanager    文件:StringEscapeEditor.java   
@Override
public void setAsText(String text) throws IllegalArgumentException {
    if (text == null) {
        setValue(null);
    } else {
        setValue(HtmlUtils.htmlEscape(text));
    }
}
项目:Android_Code_Arbiter    文件:XssServlet6.java   
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String param = req.getHeader("hello");

    String out = HtmlUtils.htmlEscape(param);
    resp.getWriter().print(out);
}
项目:spring4-understanding    文件:BindStatus.java   
/**
 * Return a suitable display value for the field, i.e. the stringified
 * value if not null, and an empty string in case of a null value.
 * <p>This value will be an HTML-escaped String if the original value
 * was non-null: the {@code toString} result of the original value
 * will get HTML-escaped.
 */
public String getDisplayValue() {
    if (this.value instanceof String) {
        return (String) this.value;
    }
    if (this.value != null) {
        return (this.htmlEscape ? HtmlUtils.htmlEscape(this.value.toString()) : this.value.toString());
    }
    return "";
}
项目:spring4-understanding    文件:HtmlEscapingAwareTag.java   
/**
 * HTML-encodes the given String, only if the "htmlEscape" setting is enabled.
 * <p>The response encoding will be taken into account if the
 * "responseEncodedHtmlEscape" setting is enabled as well.
 * @param content the String to escape
 * @return the escaped String
 * @since 4.1.2
 * @see #isHtmlEscape()
 * @see #isResponseEncodedHtmlEscape()
 */
protected String htmlEscape(String content) {
    String out = content;
    if (isHtmlEscape()) {
        if (isResponseEncodedHtmlEscape()) {
            out = HtmlUtils.htmlEscape(content, this.pageContext.getResponse().getCharacterEncoding());
        }
        else {
            out = HtmlUtils.htmlEscape(content);
        }
    }
    return out;
}
项目:mblog    文件:CommentController.java   
@RequestMapping("/submit")
public @ResponseBody Data post(Long toId, String text, HttpServletRequest request) {
    Data data = Data.failure("操作失败");

    long pid = ServletRequestUtils.getLongParameter(request, "pid", 0);

    if (!SecurityUtils.getSubject().isAuthenticated()) {
        data = Data.failure("请先登录在进行操作");

        return data;
    }
    if (toId > 0 && StringUtils.isNotEmpty(text)) {
        UserProfile up = getSubject().getProfile();

        Comment c = new Comment();
        c.setToId(toId);
        c.setContent(HtmlUtils.htmlEscape(text));
        c.setAuthorId(up.getId());

        c.setPid(pid);

        commentService.post(c);

           if(toId != up.getId()) {
            sendNotify(up.getId(), toId, pid);
           }

        data = Data.success("发表成功!", Data.NOOP);
    }
    return data;
}
项目:roncoo-jui-springboot    文件:XSSFilter.java   
@Override
public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values != null) {
        int length = values.length;
        String[] escapseValues = new String[length];
        for (int i = 0; i < length; i++) {
            escapseValues[i] = HtmlUtils.htmlEscape(values[i]);
        }
        return escapseValues;
    }
    return super.getParameterValues(name);
}
项目:roncoo-jui-springboot    文件:WebXssFilter.java   
@Override
public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values != null) {
        int length = values.length;
        String[] escapseValues = new String[length];
        for (int i = 0; i < length; i++) {
            // 防xss攻击和过滤前后空格
            escapseValues[i] = HtmlUtils.htmlEscape(values[i]).trim();
        }
        return escapseValues;
    }
    return super.getParameterValues(name);
}
项目:codefolio    文件:WebUtil.java   
/** 글의 http 주소가 있으면 링크로 바꿔줌.
 * @param plain
 * @return
 */
public static String addLink(String text){
   if (text == null) {
      return text;
   }

   String escapedText = HtmlUtils.htmlEscape(text)
         .replaceAll("(\\A|\\s)((http|https|ftp|mailto):\\S+)(\\s|\\z)","$1<a href=\"$2\">$2</a>$4");

   return escapedText;
}
项目:simbest-cores    文件:JacksonObjectMapperConfig.java   
public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
    if (value != null) {
        String encodedValue = HtmlUtils.htmlEscape(value.toString());
        jsonGenerator.writeString(encodedValue);
    }
}
项目:restricted-register-plugin    文件:Utils.java   
public static String escapeInputString(String value) {
    String ret = HtmlUtils.htmlEscape(value);
    for (String[] mapping : STR_SUBSTITUTOR_SPECIAL_CHARACTERS) {
        ret = ret.replace(mapping[0], mapping[1]);
    }
    return ret;
}
项目:singular-server    文件:PServerFreeMarkerUtil.java   
private Object encode(Object o) {
    final Map m = new HashMap();
    if (o instanceof Map) {
        ((Map) o).forEach((k, v) -> m.put(k, encode(v)));
    } else if (o instanceof String) {
        return HtmlUtils.htmlEscape((String) o);
    } else if (o instanceof Collection) {
        List<Object> list = new ArrayList<>();
        ((Collection) o).forEach(x -> list.add(encode(x)));
        return list;
    } else {
        return o;
    }
    return m;
}
项目:citrine-scheduler    文件:DisplayLogsController.java   
/**
 * Displays the contents of a particular log file.
 * 
 * @param request
 * @param response
 * @return A ModelAndView to render.
 * @throws Exception
 */
public ModelAndView display(HttpServletRequest request, HttpServletResponse response) throws Exception {
  String logFileName = request.getParameter(PARAM_LOG_FILE);
  String contents = logFileManager.tail(logFileName, tailBytes);
  Map<String, Object> model = new HashMap<String, Object>();
  model.put("contents", HtmlUtils.htmlEscape(contents));
  // task id will only be set if we activate this controller from the task runs view
  Long taskId = RequestUtils.getLongValue(request, Constants.PARAM_TASK_ID, false);
  model.put("taskId", taskId);
  model.put(Constants.PARAM_SELECTED_GROUP_NAME, request.getParameter(Constants.PARAM_SELECTED_GROUP_NAME));
  return new ModelAndView("log_display", model);
}