Java Code Examples for org.springframework.web.util.HtmlUtils#htmlEscape()

The following examples show how to use org.springframework.web.util.HtmlUtils#htmlEscape() . 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: Article.java    From kaif with Apache License 2.0 8 votes vote down vote up
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);
}
 
Example 2
Source File: JwtLoginFilter.java    From SpringSecurity-JWT-Vue-Deom with MIT License 6 votes vote down vote up
/**
 * 提取用户账号密码进行验证
 * */
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
    // 判断是否要抛出 登陆请求过快的异常
    loginCountService.judgeLoginCount(httpServletRequest);
    // 获取 User 对象
    // readValue 第一个参数 输入流,第二个参数 要转换的对象
    User user = new ObjectMapper().readValue(httpServletRequest.getInputStream(), User.class);
    // 验证码验证
    verifyCodeService.verify(httpServletRequest.getSession().getId(), user.getVerifyCode());
    // 对 html 标签进行转义,防止 XSS 攻击
    String username = user.getUsername();
    username = HtmlUtils.htmlEscape(username);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            username,
            user.getPassword(),
            user.getAuthorities()
    );
    // 添加验证的附加信息
    // 包括验证码信息和是否记住我
    token.setDetails(new LoginDetails(user.getRememberMe(), user.getVerifyCode()));
    // 进行登陆验证
    return getAuthenticationManager().authenticate(token);
}
 
Example 3
Source File: GradebookService.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Returns the activity status string which is a reference to an image
    *
    * @param learnerProgress
    * @param activity
    * @return
    */
   private String getActivityStatusStr(Object learnerProgress, Activity activity) {

final String IMAGES_DIR = Configuration.get(ConfigurationKeys.SERVER_URL) + "images";
if (learnerProgress != null) {
    // this construct looks bad but see LDEV-4609 commit for explanation
    byte statusByte = learnerProgress instanceof LearnerProgressArchive
	    ? ((LearnerProgressArchive) learnerProgress).getProgressState(activity)
	    : ((LearnerProgress) learnerProgress).getProgressState(activity);
    Activity currentActivity = learnerProgress instanceof LearnerProgressArchive
	    ? ((LearnerProgressArchive) learnerProgress).getCurrentActivity()
	    : ((LearnerProgress) learnerProgress).getCurrentActivity();
    if (statusByte == LearnerProgress.ACTIVITY_ATTEMPTED && currentActivity != null) {
	return "<i class='fa fa-cog' title='" + HtmlUtils.htmlEscape(currentActivity.getTitle()) + "'></i>";
    } else if (statusByte == LearnerProgress.ACTIVITY_COMPLETED) {
	return "<i class='fa fa-check text-success'></i>";
    }
}
return "-";
   }
 
Example 4
Source File: PeerreviewServiceImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   public ArrayNode getUsersRatingsCommentsByCriteriaIdJSON(Long toolContentId, Long toolSessionId,
    RatingCriteria criteria, Long currentUserId, Integer page, Integer size, int sorting, String searchString,
    boolean getAllUsers, boolean getByUser, boolean needRatesPerUser) {

List<Object[]> rawData = peerreviewUserDao.getRatingsComments(toolContentId, toolSessionId, criteria,
	currentUserId, page, size, sorting, searchString, getByUser, ratingService, userManagementService);

for (Object[] raw : rawData) {
    raw[raw.length - 2] = HtmlUtils.htmlEscape((String) raw[raw.length - 2]);
}
// if !getByUser -> is get current user's ratings from other users ->
// convertToStyledJSON.getAllUsers needs to be true otherwise current user (the only one in the set!) is dropped
return ratingService.convertToStyledJSON(criteria, toolSessionId, currentUserId, !getByUser || getAllUsers,
	rawData, needRatesPerUser);
   }
 
Example 5
Source File: BindStatus.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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 "";
}
 
Example 6
Source File: BindStatus.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 "";
}
 
Example 7
Source File: HtmlEscapingAwareTag.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source File: BindStatus.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 "";
}
 
Example 9
Source File: HtmlElement.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected StringBuilder buildAttributeTag(StringBuilder attributesBuf, String attr, Object val){
	String valStr = val==null?"":val.toString();
	if(StringUtils.isBlank(valStr))
		return attributesBuf;
	valStr = HtmlUtils.htmlEscape(valStr);
	attributesBuf.append(attr).append("=\"").append(valStr).append("\"");
	return attributesBuf;
}
 
Example 10
Source File: GreetingController.java    From code with Apache License 2.0 4 votes vote down vote up
@MessageMapping("/hello")//@MessageMapping保证如果一个消息被发送到"/hello",greeting()方法被调用
@SendTo("/topic/greetings")//@SendTo将返回值广播给所有"/topic/greetings"
public Greeting greeting(HelloMessage message) throws Exception {
    //Thread.sleep(1000); // simulated delay
    return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
 
Example 11
Source File: CollectionTagSearchUtil.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 4 votes vote down vote up
public String build(String tagName) {
    String stringBuilder = PRE +
            HtmlUtils.htmlEscape(tagName) +
            POS;
    return stringBuilder;
}
 
Example 12
Source File: GBActivityGridRowDTO.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public GBActivityGridRowDTO(Activity activity, String groupName, Long groupId, boolean escapeTitles) {

	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
	    if (escapeTitles) {
		this.rowName = HtmlUtils.htmlEscape(activity.getTitle()) + " (" + groupName + ")";
	    } else {
		this.rowName = activity.getTitle() + " (" + groupName + ")";
	    }
	} else {
	    this.id = activity.getActivityId().toString();

	    if (escapeTitles) {
		this.rowName = HtmlUtils.htmlEscape(activity.getTitle());
	    } else {
		this.rowName = 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;

    }
 
Example 13
Source File: BindStatus.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Create a new BindStatus instance, representing a field or object status.
 * @param requestContext the current RequestContext
 * @param path the bean and property path for which values and errors
 * will be resolved (e.g. "customer.address.street")
 * @param htmlEscape whether to HTML-escape error messages and string values
 * @throws IllegalStateException if no corresponding Errors object found
 */
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException {
	this.requestContext = requestContext;
	this.path = path;
	this.htmlEscape = htmlEscape;

	// determine name of the object and property
	String beanName;
	int dotPos = path.indexOf('.');
	if (dotPos == -1) {
		// property not set, only the object itself
		beanName = path;
		this.expression = null;
	}
	else {
		beanName = path.substring(0, dotPos);
		this.expression = path.substring(dotPos + 1);
	}

	this.errors = requestContext.getErrors(beanName, false);

	if (this.errors != null) {
		// Usual case: A BindingResult is available as request attribute.
		// Can determine error codes and messages for the given expression.
		// Can use a custom PropertyEditor, as registered by a form controller.
		if (this.expression != null) {
			if ("*".equals(this.expression)) {
				this.objectErrors = this.errors.getAllErrors();
			}
			else if (this.expression.endsWith("*")) {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
			}
			else {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
				this.value = this.errors.getFieldValue(this.expression);
				this.valueType = this.errors.getFieldType(this.expression);
				if (this.errors instanceof BindingResult) {
					this.bindingResult = (BindingResult) this.errors;
					this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
					this.editor = this.bindingResult.findEditor(this.expression, null);
				}
				else {
					this.actualValue = this.value;
				}
			}
		}
		else {
			this.objectErrors = this.errors.getGlobalErrors();
		}
		this.errorCodes = initErrorCodes(this.objectErrors);
	}

	else {
		// No BindingResult available as request attribute:
		// Probably forwarded directly to a form view.
		// Let's do the best we can: extract a plain target if appropriate.
		Object target = requestContext.getModelObject(beanName);
		if (target == null) {
			throw new IllegalStateException(
					"Neither BindingResult nor plain target object for bean name '" +
					beanName + "' available as request attribute");
		}
		if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
			BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
			this.value = bw.getPropertyValue(this.expression);
			this.valueType = bw.getPropertyType(this.expression);
			this.actualValue = this.value;
		}
		this.errorCodes = new String[0];
		this.errorMessages = new String[0];
	}

	if (htmlEscape && this.value instanceof String) {
		this.value = HtmlUtils.htmlEscape((String) this.value);
	}
}
 
Example 14
Source File: KmarkProcessor.java    From kaif with Apache License 2.0 4 votes vote down vote up
public static String escapeHtml(String input) {
  return HtmlUtils.htmlEscape(input);
}
 
Example 15
Source File: BindStatus.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Create a new BindStatus instance, representing a field or object status.
 * @param requestContext the current RequestContext
 * @param path the bean and property path for which values and errors
 * will be resolved (e.g. "customer.address.street")
 * @param htmlEscape whether to HTML-escape error messages and string values
 * @throws IllegalStateException if no corresponding Errors object found
 */
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException {
	this.requestContext = requestContext;
	this.path = path;
	this.htmlEscape = htmlEscape;

	// determine name of the object and property
	String beanName;
	int dotPos = path.indexOf('.');
	if (dotPos == -1) {
		// property not set, only the object itself
		beanName = path;
		this.expression = null;
	}
	else {
		beanName = path.substring(0, dotPos);
		this.expression = path.substring(dotPos + 1);
	}

	this.errors = requestContext.getErrors(beanName, false);

	if (this.errors != null) {
		// Usual case: A BindingResult is available as request attribute.
		// Can determine error codes and messages for the given expression.
		// Can use a custom PropertyEditor, as registered by a form controller.
		if (this.expression != null) {
			if ("*".equals(this.expression)) {
				this.objectErrors = this.errors.getAllErrors();
			}
			else if (this.expression.endsWith("*")) {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
			}
			else {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
				this.value = this.errors.getFieldValue(this.expression);
				this.valueType = this.errors.getFieldType(this.expression);
				if (this.errors instanceof BindingResult) {
					this.bindingResult = (BindingResult) this.errors;
					this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
					this.editor = this.bindingResult.findEditor(this.expression, null);
				}
				else {
					this.actualValue = this.value;
				}
			}
		}
		else {
			this.objectErrors = this.errors.getGlobalErrors();
		}
		this.errorCodes = initErrorCodes(this.objectErrors);
	}

	else {
		// No BindingResult available as request attribute:
		// Probably forwarded directly to a form view.
		// Let's do the best we can: extract a plain target if appropriate.
		Object target = requestContext.getModelObject(beanName);
		if (target == null) {
			throw new IllegalStateException(
					"Neither BindingResult nor plain target object for bean name '" +
					beanName + "' available as request attribute");
		}
		if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
			BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
			this.value = bw.getPropertyValue(this.expression);
			this.valueType = bw.getPropertyType(this.expression);
			this.actualValue = this.value;
		}
		this.errorCodes = new String[0];
		this.errorMessages = new String[0];
	}

	if (htmlEscape && this.value instanceof String) {
		this.value = HtmlUtils.htmlEscape((String) this.value);
	}
}
 
Example 16
Source File: FormTag.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resolve the value of the '{@code action}' attribute.
 * <p>If the user configured an '{@code action}' value then the result of
 * evaluating this value is used. If the user configured an
 * '{@code servletRelativeAction}' value then the value is prepended
 * with the context and servlet paths, and the result is used. Otherwise, the
 * {@link org.springframework.web.servlet.support.RequestContext#getRequestUri()
 * originating URI} is used.
 * @return the value that is to be used for the '{@code action}' attribute
 */
protected String resolveAction() throws JspException {
	String action = getAction();
	String servletRelativeAction = getServletRelativeAction();
	if (StringUtils.hasText(action)) {
		action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
		return processAction(action);
	}
	else if (StringUtils.hasText(servletRelativeAction)) {
		String pathToServlet = getRequestContext().getPathToServlet();
		if (servletRelativeAction.startsWith("/") &&
				!servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
			servletRelativeAction = pathToServlet + servletRelativeAction;
		}
		servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
		return processAction(servletRelativeAction);
	}
	else {
		String requestUri = getRequestContext().getRequestUri();
		String encoding = this.pageContext.getResponse().getCharacterEncoding();
		try {
			requestUri = UriUtils.encodePath(requestUri, encoding);
		}
		catch (UnsupportedEncodingException ex) {
			// shouldn't happen - if it does, proceed with requestUri as-is
		}
		ServletResponse response = this.pageContext.getResponse();
		if (response instanceof HttpServletResponse) {
			requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
			String queryString = getRequestContext().getQueryString();
			if (StringUtils.hasText(queryString)) {
				requestUri += "?" + HtmlUtils.htmlEscape(queryString);
			}
		}
		if (StringUtils.hasText(requestUri)) {
			return processAction(requestUri);
		}
		else {
			throw new IllegalArgumentException("Attribute 'action' is required. " +
					"Attempted to resolve against current request URI but request URI was null.");
		}
	}
}
 
Example 17
Source File: FederationService.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@GET
public Response get(@Context UriInfo uriInfo,
                    @Context SecurityContext securityContext) {

    StringBuilder out = new StringBuilder(275);
    out.append("<html>");
    out.append("<head><title>WS Federation Spring Security Example</title></head>");
    out.append("<body>");
    out.append("<h1>Hello World</h1>");
    out.append("Hello world<br>");
    out.append("Request url: ").append(uriInfo.getAbsolutePath()).append("<p>");

    out.append("<br><b>User</b><p>");
    Principal p = securityContext.getUserPrincipal();
    if (p != null) {
        out.append("Principal: ").append(p.getName()).append("<p>");
    }

    // Access Spring security context
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof FederationAuthenticationToken) {
        out.append("Roles of user:<p><ul>");
        FederationAuthenticationToken fedAuthToken = (FederationAuthenticationToken) auth;
        for (GrantedAuthority item : fedAuthToken.getAuthorities()) {
            out.append("<li>").append(item.getAuthority()).append("</li>");
        }
        out.append("</ul>");

        if (fedAuthToken.getUserDetails() instanceof FederationUser) {
            out.append("<br><b>Claims</b><p>");
            ClaimCollection claims = ((FederationUser) fedAuthToken.getUserDetails()).getClaims();
            for (Claim c : claims) {
                out.append(c.getClaimType().toString()).append(": ").append(c.getValue()).append("<p>");
            }
        } else {
            out.append("FederationAuthenticationToken found but not FederationUser");
        }

    } else {
        out.append("No FederationAuthenticationToken found in Spring Security Context.");
    }

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.append("<p>Bootstrap token...");
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(el), new StreamResult(buffer));
            String token = buffer.toString();
            String escapedXml = HtmlUtils.htmlEscape(token);
            out.append("<p>").append(escapedXml);
        } catch (Exception ex) {
            out.append("<p>Failed to transform cached element to string: ").append(ex.toString());
        }
    } else {
        out.append("<p>Bootstrap token not cached in thread local storage");
    }

    out.append("</body>");

    return Response.ok().type(MediaType.TEXT_HTML).entity(out.toString()).build();
}
 
Example 18
Source File: RequestContext.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Retrieve the message for the given code.
 * @param code code of the message
 * @param args arguments for the message, or {@code null} if none
 * @param defaultMessage the String to return if the lookup fails
 * @param htmlEscape if the message should be HTML-escaped
 * @return the message
 */
public String getMessage(String code, @Nullable Object[] args, String defaultMessage, boolean htmlEscape) {
	String msg = this.webApplicationContext.getMessage(code, args, defaultMessage, getLocale());
	if (msg == null) {
		return "";
	}
	return (htmlEscape ? HtmlUtils.htmlEscape(msg) : msg);
}
 
Example 19
Source File: RequestContext.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Retrieve the message for the given code.
 * @param code code of the message
 * @param args arguments for the message, or {@code null} if none
 * @param defaultMessage the String to return if the lookup fails
 * @param htmlEscape if the message should be HTML-escaped
 * @return the message
 */
public String getMessage(String code, @Nullable Object[] args, String defaultMessage, boolean htmlEscape) {
	String msg = this.webApplicationContext.getMessage(code, args, defaultMessage, getLocale());
	if (msg == null) {
		return "";
	}
	return (htmlEscape ? HtmlUtils.htmlEscape(msg) : msg);
}
 
Example 20
Source File: RequestContext.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance).
 * @param resolvable the MessageSourceResolvable
 * @param htmlEscape if the message should be HTML-escaped
 * @return the message
 * @throws org.springframework.context.NoSuchMessageException if not found
 */
public String getMessage(MessageSourceResolvable resolvable, boolean htmlEscape) throws NoSuchMessageException {
	String msg = this.webApplicationContext.getMessage(resolvable, getLocale());
	return (htmlEscape ? HtmlUtils.htmlEscape(msg) : msg);
}