org.apache.commons.text.StringEscapeUtils Java Examples

The following examples show how to use org.apache.commons.text.StringEscapeUtils. 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: TextileAdapter.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private static String replaceLinks(String rawString) {
    StringBuilder sb = new StringBuilder(rawString);

    try {
        while (sb.indexOf("[[") > -1) {
            int from = sb.indexOf("[[");
            int to = sb.indexOf("]]");

            String rawLink = sb.substring(from + 2, to);
            int dividerIndex = rawLink.indexOf("|");
            String name = StringEscapeUtils.escapeHtml4(rawLink.substring(dividerIndex + 1));
            String link = StringEscapeUtils.escapeHtml4(!rawLink.substring(0, dividerIndex + 1).isEmpty() ? rawLink.substring(0, dividerIndex) : name);

            String newLink = "\"" + name + "\":" + link.replaceAll(" ", "_");
            sb.replace(from, to + 2, newLink.replaceAll("\\(", "(").replaceAll("\\)", ")"));
        }
    } catch (Exception e) {
        System.err.println("Error during link parsing. " + e.getMessage());
    }

    return sb.toString();
}
 
Example #2
Source File: RedditParsedComment.java    From RedReader with GNU General Public License v3.0 6 votes vote down vote up
public RedditParsedComment(
		final RedditComment comment,
		final AppCompatActivity activity) {

	mSrc = comment;

	mBody = HtmlReader.parse(
			StringEscapeUtils.unescapeHtml4(comment.body_html),
			activity);

	if(comment.author_flair_text != null) {
		mFlair = StringEscapeUtils.unescapeHtml4(comment.author_flair_text);
	} else {
		mFlair = null;
	}
}
 
Example #3
Source File: HttpUtils.java    From drftpd with GNU General Public License v2.0 6 votes vote down vote up
public static String htmlToString(String input) {
    String str = input.replaceAll("\n", "");
    str = StringEscapeUtils.unescapeHtml4(str);
    str = Normalizer.normalize(str, Normalizer.Form.NFD);
    str = str.replaceAll("\\P{InBasic_Latin}", "");
    while (str.contains("<")) {
        int startPos = str.indexOf("<");
        int endPos = str.indexOf(">", startPos);
        if (endPos > startPos) {
            String beforeTag = str.substring(0, startPos);
            String afterTag = str.substring(endPos + 1);
            str = beforeTag + afterTag;
        }
    }
    return str;
}
 
Example #4
Source File: GradleScriptCreator.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
private String generateGradleScript(File scriptFile, String airGapLibs, String inspectorVersion) throws IOException, TemplateException {
    logger.debug("Generating the gradle script file.");
    final Map<String, String> gradleScriptData = new HashMap<>();
    gradleScriptData.put("airGapLibsPath", StringEscapeUtils.escapeJava(airGapLibs));
    gradleScriptData.put("gradleInspectorVersion", StringEscapeUtils.escapeJava(inspectorVersion));
    gradleScriptData.put("excludedProjectNames", detectConfiguration.getProperty(DetectProperty.DETECT_GRADLE_EXCLUDED_PROJECTS, PropertyAuthority.None));
    gradleScriptData.put("includedProjectNames", detectConfiguration.getProperty(DetectProperty.DETECT_GRADLE_INCLUDED_PROJECTS, PropertyAuthority.None));
    gradleScriptData.put("excludedConfigurationNames", detectConfiguration.getProperty(DetectProperty.DETECT_GRADLE_EXCLUDED_CONFIGURATIONS, PropertyAuthority.None));
    gradleScriptData.put("includedConfigurationNames", detectConfiguration.getProperty(DetectProperty.DETECT_GRADLE_INCLUDED_CONFIGURATIONS, PropertyAuthority.None));
    final String configuredGradleInspectorRepositoryUrl = detectConfiguration.getProperty(DetectProperty.DETECT_GRADLE_INSPECTOR_REPOSITORY_URL, PropertyAuthority.None);
    String customRepository = ArtifactoryConstants.GRADLE_INSPECTOR_MAVEN_REPO;
    if (StringUtils.isNotBlank(configuredGradleInspectorRepositoryUrl)) {
        logger.warn("Using a custom gradle repository will not be supported in the future.");
        customRepository = configuredGradleInspectorRepositoryUrl;
    }
    gradleScriptData.put("customRepositoryUrl", customRepository);

    populateGradleScriptWithData(scriptFile, gradleScriptData);
    logger.trace(String.format("Successfully created gradle script: %s", scriptFile.getCanonicalPath()));
    return scriptFile.getCanonicalPath();
}
 
Example #5
Source File: ImgurAPI.java    From RedReader with GNU General Public License v3.0 6 votes vote down vote up
public static AlbumInfo parse(final String id, final JsonBufferedObject object)
		throws IOException, InterruptedException {

	String title = object.getString("title");
	String description = object.getString("description");

	if(title != null) {
		title = StringEscapeUtils.unescapeHtml4(title);
	}

	if(description != null) {
		description = StringEscapeUtils.unescapeHtml4(description);
	}

	final JsonBufferedArray imagesJson = object.getArray("images");
	final ArrayList<ImageInfo> images = new ArrayList<>();

	for(final JsonValue imageJson : imagesJson) {
		images.add(ImageInfo.parseImgur(imageJson.asObject()));
	}

	return new AlbumInfo(id, title, description, images);
}
 
Example #6
Source File: TokenSerializer.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public String serialize(RequestContext context, Element rpToken) {
    if (rpToken != null) {
        StringWriter sw = new StringWriter();
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            try {
                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
            } catch (IllegalArgumentException ex) {
                // ignore
            }

            Transformer t = tf.newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.transform(new DOMSource(rpToken), new StreamResult(sw));
        } catch (TransformerException te) {
            LOG.warn("nodeToString Transformer Exception");
        }
        String serializedToken = sw.toString();

        return StringEscapeUtils.escapeXml11(serializedToken);
    }

    return null;
}
 
Example #7
Source File: AssistPanel.java    From onedev with MIT License 6 votes vote down vote up
private Component newSuggestionItem(String itemId, InputCompletion suggestion) {
	WebMarkupContainer item = new WebMarkupContainer(itemId);
	LinearRange match = suggestion.getMatch();
	String label = suggestion.getLabel();
	if (match != null) {
		String prefix = StringEscapeUtils.escapeHtml4(label.substring(0, match.getFrom()));
		String suffix = StringEscapeUtils.escapeHtml4(label.substring(match.getTo()));
		String matched = StringEscapeUtils.escapeHtml4(label.substring(match.getFrom(), match.getTo()));
		item.add(new Label("content", prefix + "<b>" + matched + "</b>" + suffix).setEscapeModelStrings(false));
	} else {
		item.add(new Label("content", label));
	}
	
	if (suggestion.getDescription() != null)
		item.add(new Label("description", suggestion.getDescription()));
	else
		item.add(new Label("description"));
	
	String content = suggestion.getContent();
	item.add(AttributeAppender.append("data-content", content));
	item.add(AttributeAppender.append("data-caret", suggestion.getCaret()));
	item.setOutputMarkupId(true);
	return item;
}
 
Example #8
Source File: ElasticSearchResult.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void toXMLString(StringBuilder sb) {
    sb.append("<result");
    sb.append(" index=\"").append(getIndex()).append("\" ");
    sb.append(" score=\"").append(getScore()).append("\" ");
    sb.append(" sid=\"").append(StringEscapeUtils.escapeXml11(getId())).append("\" ");
    sb.append(" site=\"").append(StringEscapeUtils.escapeXml11(getSiteId())).append("\" ");
    sb.append(" reference=\"").append(StringEscapeUtils.escapeXml11(getReference())).append("\" ");
    try {
        sb.append(" title=\"").append(new String(Base64.encodeBase64(getTitle().getBytes("UTF-8")), "UTF-8")).append("\" ");
    } catch (UnsupportedEncodingException e) {
        sb.append(" title=\"").append(StringEscapeUtils.escapeXml11(getTitle())).append("\" ");
    }
    sb.append(" tool=\"").append(StringEscapeUtils.escapeXml11(getTool())).append("\" ");
    sb.append(" url=\"").append(StringEscapeUtils.escapeXml11(getUrl())).append("\" />");
}
 
Example #9
Source File: UnorderedSelect.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void getPlanAsGraphvizDot(StringBuilder stringBuilder) {
	if (printed) {
		return;
	}
	printed = true;
	stringBuilder.append(getId() + " [label=\"" + StringEscapeUtils.escapeJava(this.toString()) + "\"];")
			.append("\n");

	if (connection instanceof MemoryStoreConnection) {
		stringBuilder
				.append(System.identityHashCode(((MemoryStoreConnection) connection).getSail()) + " -> " + getId())
				.append("\n");
	} else {
		stringBuilder.append(System.identityHashCode(connection) + " -> " + getId()).append("\n");
	}

}
 
Example #10
Source File: GenericJsonBodyThen.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
	BodyMatchers bodyMatchers = this.bodyParser.responseBodyMatchers(metadata);
	Object convertedResponseBody = this.bodyParser.convertResponseBody(metadata);
	ContentType contentType = metadata.getOutputTestContentType();
	if (TEXT != contentType && FORM != contentType && DEFINED != contentType) {
		boolean dontParseStrings = contentType == JSON
				&& convertedResponseBody instanceof Map;
		Function parsingClosure = dontParseStrings ? Function.identity()
				: MapConverter.JSON_PARSING_FUNCTION;
		convertedResponseBody = MapConverter.getTestSideValues(convertedResponseBody,
				parsingClosure);
	}
	else {
		convertedResponseBody = StringEscapeUtils
				.escapeJava(convertedResponseBody.toString());
	}
	addJsonBodyVerification(metadata, convertedResponseBody, bodyMatchers);
	return this;
}
 
Example #11
Source File: SlimFixtureException.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
private static String createMessage(boolean stackTraceInWiki, String message) {
    String result = message;
    if (!stackTraceInWiki) {
        // Until https://github.com/unclebob/fitnesse/issues/731 is fixed
        if (message.contains("\n")) {
            if (!message.startsWith("<") || !message.endsWith(">")) {
                // it is not yet HTML, make it HTML so we can use <br/>
                message = StringEscapeUtils.escapeHtml4(message);
                message = String.format("<div>%s</div>", message);
            }
            message = message.replaceAll("(\\r)?\\n", "<br/>");
        }
        result = String.format("message:<<%s>>", message);
    }
    return result;
}
 
Example #12
Source File: MyBlogController.java    From My-Blog-layui with Apache License 2.0 6 votes vote down vote up
/**
 * 提交评论
 * @return com.site.blog.dto.Result
 * @date 2019/9/6 17:40
 */
@PostMapping(value = "/blog/comment")
@ResponseBody
public Result<String> comment(HttpServletRequest request,
                      @Validated BlogComment blogComment) {
    String ref = request.getHeader("Referer");
    // 对非法字符进行转义,防止xss漏洞
    blogComment.setCommentBody(StringEscapeUtils.escapeHtml4(blogComment.getCommentBody()));
    if (StringUtils.isEmpty(ref)) {
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR,"非法请求");
    }
    boolean flag = blogCommentService.save(blogComment);
    if (flag){
        return ResultGenerator.getResultByHttp(HttpStatusEnum.OK);
    }
    return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
}
 
Example #13
Source File: Select.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void getPlanAsGraphvizDot(StringBuilder stringBuilder) {
	if (printed) {
		return;
	}
	printed = true;
	stringBuilder.append(getId() + " [label=\"" + StringEscapeUtils.escapeJava(this.toString()) + "\"];")
			.append("\n");

	if (connection instanceof MemoryStoreConnection) {
		stringBuilder
				.append(System.identityHashCode(((MemoryStoreConnection) connection).getSail()) + " -> " + getId())
				.append("\n");
	} else {
		stringBuilder.append(System.identityHashCode(connection) + " -> " + getId()).append("\n");
	}

}
 
Example #14
Source File: CommentPropertiesDialog.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void prepare(AppCompatActivity context, LinearLayout items) {

	final RedditComment comment = getArguments().getParcelable("comment");

	items.addView(propView(context, "ID", comment.name, true));

	items.addView(propView(context, R.string.props_author, comment.author, false));

	if(comment.author_flair_text != null && comment.author_flair_text.length() > 0) {
		items.addView(propView(context, R.string.props_author_flair, comment.author_flair_text, false));
	}

	items.addView(propView(context, R.string.props_created, RRTime.formatDateTime(comment.created_utc * 1000, context), false));

	if(comment.edited instanceof Long) {
		items.addView(propView(context, R.string.props_edited, RRTime.formatDateTime((Long) comment.edited * 1000, context), false));
	} else {
		items.addView(propView(context, R.string.props_edited, R.string.props_never, false));
	}

	items.addView(propView(context, R.string.props_score, String.valueOf(comment.ups - comment.downs), false));

	items.addView(propView(context, R.string.props_subreddit, comment.subreddit, false));

	if(comment.body != null && comment.body.length() > 0) {
		items.addView(propView(context, R.string.props_body_markdown, StringEscapeUtils.unescapeHtml4(comment.body), false));

		if(comment.body_html != null) {
			items.addView(propView(
					context,
					R.string.props_body_html,
					StringEscapeUtils.unescapeHtml4(comment.body_html),
					false));
		}
	}
}
 
Example #15
Source File: SourceCodeDisclosureCVE20121823UnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAlertIfJavaScriptFilesAtLowThreshold() throws Exception {
    // Given
    String test = "/shouldAlertIfJavaScriptFilesAtLowThreshold/";
    nano.addHandler(
            new NanoServerHandler(test) {

                @Override
                protected Response serve(IHTTPSession session) {
                    String encodedPhpCode = StringEscapeUtils.escapeHtml4(PHP_SOURCE_ECHO_TAG);
                    return newFixedLengthResponse(
                            Response.Status.OK,
                            "text/javascript",
                            "/* javascript comment blah blah " + encodedPhpCode + "*/");
                }
            });
    HttpMessage message = getHttpMessage(test, "text/javascript");
    rule.init(message, parent);
    rule.setAlertThreshold(AlertThreshold.LOW);
    // When
    rule.scan();
    // Then
    assertThat(alertsRaised, hasSize(1));
    assertThat(alertsRaised.get(0).getEvidence(), is(equalTo("")));
    assertThat(alertsRaised.get(0).getParam(), is(equalTo("")));
    assertThat(alertsRaised.get(0).getAttack(), is(equalTo("")));
    assertThat(alertsRaised.get(0).getRisk(), is(equalTo(Alert.RISK_HIGH)));
    assertThat(alertsRaised.get(0).getConfidence(), is(equalTo(Alert.CONFIDENCE_MEDIUM)));
    assertThat(alertsRaised.get(0).getOtherInfo(), is(equalTo(PHP_SOURCE_ECHO_TAG)));
}
 
Example #16
Source File: FontTBL.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  return new ToStringBuilder(this)
      .append("id", StringEscapeUtils.escapeJava(id))
      .append("one", Integer.toHexString(one))
      .append("locale", Integer.toHexString(locale))
      .append("height", height)
      .append("width", width)
      .toString();
}
 
Example #17
Source File: GradebookServiceHelperImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Add a published assessment to gradebook.
 * @param publishedAssessment the published assessment
 * @param g  the Gradebook Service
 * @return false: cannot add to gradebook
 * @throws java.lang.Exception
 */
public boolean addToGradebook(PublishedAssessmentData publishedAssessment, Long categoryId, 
  GradebookExternalAssessmentService g) throws
  Exception
{
  boolean added = false;
  String gradebookUId = GradebookFacade.getGradebookUId();
  if (gradebookUId == null)
  {
    return false;
  }

  if (g.isGradebookDefined(gradebookUId))
  {
    String title = StringEscapeUtils.unescapeHtml4(publishedAssessment.getTitle());
    if(!g.isAssignmentDefined(gradebookUId, title))
    {
        g.addExternalAssessment(gradebookUId,
                publishedAssessment.getPublishedAssessmentId().toString(),
                null,
                title,
                publishedAssessment.getTotalScore(),
                publishedAssessment.getAssessmentAccessControl().getDueDate(),
                getAppName(), // Use the app name from sakai
                null,
                false,
                categoryId);
      added = true;
    }
  }
  return added;
}
 
Example #18
Source File: XMLPropertiesConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Escapes a property value before it is written to disk.
 *
 * @param value the value to be escaped
 * @return the escaped value
 */
private String escapeValue(final Object value)
{
    final String v = StringEscapeUtils.escapeXml10(String.valueOf(value));
    return String.valueOf(getListDelimiterHandler().escape(v,
            ListDelimiterHandler.NOOP_TRANSFORMER));
}
 
Example #19
Source File: BufferedPlanNode.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void getPlanAsGraphvizDot(StringBuilder stringBuilder) {
	if (printed) {
		return;
	}
	printed = true;
	parent.getPlanAsGraphvizDot(stringBuilder);

	stringBuilder.append(getId() + " [label=\"" + StringEscapeUtils.escapeJava(this.toString()) + "\"];")
			.append("\n");
}
 
Example #20
Source File: XMLPropertiesConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
private void writeProperty(final Document document, final Node properties, final String key, final Object value)
{
    final Element entry = document.createElement("entry");
    properties.appendChild(entry);

    // escape the key
    final String k = StringEscapeUtils.escapeXml10(key);
    entry.setAttribute("key", k);

    if (value != null)
    {
        final String v = escapeValue(value);
        entry.setTextContent(v);
    }
}
 
Example #21
Source File: ProfileController.java    From oauth2-server with MIT License 5 votes vote down vote up
@PostMapping("/user/profile")
public String handleProfile(Principal principal,
                            @RequestParam(value = "nickName", required = false) String nickName,
                            @RequestParam(value = "avatarUrl", required = false) String avatarUrl,
                            @RequestParam(value = "email", required = false) String email,
                            @RequestParam(value = "mobile", required = false) String mobile,
                            @RequestParam(value = "province", required = false) String province,
                            @RequestParam(value = "city", required = false) String city,
                            @RequestParam(value = "address", required = false) String address,
                            @JsonFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd")
                            @RequestParam(value = "birthday", required = false) LocalDate birthday,
                            Model model) {

    try {
        UserAccount userAccount = userAccountService.findByUsername(principal.getName());
        userAccount.setNickName(StringEscapeUtils.escapeHtml4(nickName));
        userAccount.setAvatarUrl(StringEscapeUtils.escapeHtml4(avatarUrl));
        userAccount.setEmail(StringEscapeUtils.escapeHtml4(email));
        userAccount.setMobile(StringEscapeUtils.escapeHtml4(mobile));
        userAccount.setProvince(StringEscapeUtils.escapeHtml4(province));
        userAccount.setCity(StringEscapeUtils.escapeHtml4(city));
        userAccount.setAddress(StringEscapeUtils.escapeHtml4(address));
        userAccount.setBirthday(birthday);
        userAccount = userAccountService.updateById(userAccount);
        model.addAttribute("userAccount", userAccount);
        model.addAttribute("updated", true);
    } catch (EntityNotFoundException e) {
        if (log.isErrorEnabled()) {
            log.error("findByUsername exception", e);
        }
    }
    return "profile";
}
 
Example #22
Source File: SourceCodeDisclosureCVE20121823UnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void
        shouldNotAlertIfResponseIsNotSuccessfulEvenIfPhpSourceTagsWereDisclosedInResponseBody()
                throws Exception {
    // Given
    String test =
            "/shouldNotAlertIfResponseIsNotSuccessfulEvenIfPhpSourceTagsWereDisclosedInResponseBody/";
    nano.addHandler(
            new NanoServerHandler(test) {

                @Override
                protected Response serve(IHTTPSession session) {
                    String encodedPhpCode = StringEscapeUtils.escapeHtml4(PHP_SOURCE_TAGS);
                    return newFixedLengthResponse(
                            Response.Status.INTERNAL_ERROR,
                            "text/html",
                            "<html><body>" + encodedPhpCode + "</body></html>");
                }
            });
    HttpMessage message = getHttpMessage(test);
    rule.init(message, parent);
    // When
    rule.scan();
    // Then
    assertThat(httpMessagesSent, hasSize(1));
    assertThat(alertsRaised, hasSize(0));
}
 
Example #23
Source File: InfluxdbStandardizedMetric.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
private String getOpenTsdbTagsJsonFromInfluxColumnsAndPoints(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {
    
    if ((columns_ == null) || (point_ == null) || (columns_.size() != point_.size()) || point_.isEmpty()) {
        return null;
    }
    
    StringBuilder openTsdbTagsJson = new StringBuilder();
    boolean didWriteAnyTag = false;

    for (int i = 0; i < columns_.size(); i++) {
        String column = columns_.get(i);
        Object pointColumnValue = point_.get(i);
                    
        if ((pointColumnValue != null) && (pointColumnValue instanceof String)) {
            String pointString = (String) pointColumnValue;
            
            openTsdbTagsJson.append("\"");
            if (sanitizeMetric) openTsdbTagsJson.append(StringEscapeUtils.escapeJson(OpenTsdbMetric.getOpenTsdbSanitizedString(column)));
            else openTsdbTagsJson.append(StringEscapeUtils.escapeJson(column));
            
            openTsdbTagsJson.append("\":\"");
            
            if (sanitizeMetric) openTsdbTagsJson.append(StringEscapeUtils.escapeJson(OpenTsdbMetric.getOpenTsdbSanitizedString(pointString)));
            else openTsdbTagsJson.append(StringEscapeUtils.escapeJson(pointString));
            openTsdbTagsJson.append("\"");
            
            didWriteAnyTag = true;
            if ((i + 1) != columns_.size()) openTsdbTagsJson.append(",");
        }
    }

    if (!didWriteAnyTag && (defaultOpenTsdbTagKey != null)) openTsdbTagsJson.append("\"").append(defaultOpenTsdbTagKey).append("\":\"").append(defaultOpenTsdbTagValue).append("\"");
    else if (!didWriteAnyTag) openTsdbTagsJson.append("\"Format\":\"InfluxDB\"");
                    
    return openTsdbTagsJson.toString();
}
 
Example #24
Source File: HostHeaderHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an error message to the response and marks the request as handled if the host header is not valid.
 * Otherwise passes the request on to the next scoped handler.
 *
 * @param target      the target (not relevant here)
 * @param baseRequest the original request object
 * @param request     the request as an HttpServletRequest
 * @param response    the current response
 */
@Override
public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final String hostHeader = request.getHeader("Host");
    logger.debug("Received request [" + request.getRequestURI() + "] with host header: " + hostHeader);
    if (!hostHeaderIsValid(hostHeader)) {
        logger.warn("Request host header [" + hostHeader + "] different from web hostname [" +
                serverName + "(:" + serverPort + ")]. Overriding to [" + serverName + ":" +
                serverPort + request.getRequestURI() + "]");

        response.setContentType("text/html; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        PrintWriter out = response.getWriter();

        out.println("<h1>System Error</h1>");
        // TODO: Change to org.apache.commons.text.StringEscapeUtils
        out.println("<h2>The request contained an invalid host header [<code>" + StringEscapeUtils.escapeHtml4(hostHeader) +
                "</code>] in the request [<code>" + StringEscapeUtils.escapeHtml4(request.getRequestURI()) +
                "</code>]. Check for request manipulation or third-party intercept.</h2>");
        out.println("<h3>Valid host headers are [<code>empty</code>] or: <br/><code>");
        out.println(printValidHosts());
        out.println("</code></h3>");

        baseRequest.setHandled(true);
    }
}
 
Example #25
Source File: Strings.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Escape XML entities and illegal characters in the given string. This
 * enhances the functionality of
 * org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping
 * low-valued unprintable characters, which are not permitted by the W3C XML
 * 1.0 specification.
 *
 * @param s
 *            a string
 * @return the same string with characters not permitted by the XML
 *         specification escaped
 * @see <a href="http://www.w3.org/TR/REC-xml/#charsets">Extensible Markup
 *      Language (XML) 1.0 (Fifth Edition)</a>
 * @see <a
 *      href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils
 *      javadoc</a>
 */
public static String escapeXml(String s) {
    initializeEscapeMap();

    if (s == null || s.length() == 0) {
        return s;
    }

    char[] sChars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    int lastReplacement = 0;
    for (int i = 0; i < sChars.length; i++) {
        if (isInvalidXMLCharacter(sChars[i])) {
            // append intermediate string to string builder
            sb.append(sChars, lastReplacement, i - lastReplacement);
            // substitute control character with escape sequence
            sb.append(sChars[i] == 0xFFFE ? "\\ufffe" : xmlLowValueEscapeStrings[sChars[i]]);
            // advance last pointer past this character
            lastReplacement = i + 1;
        }
    }
    if (lastReplacement < sChars.length) {
        sb.append(sChars, lastReplacement, sChars.length - lastReplacement);
    }

    return StringEscapeUtils.escapeXml11(sb.toString());
}
 
Example #26
Source File: SamigoExport.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public boolean outputEntity(CCConfig ccConfig, String samigoId, ZipPrintStream out, PrintWriter resultsWriter, CCResourceItem CCResourceItem, CCVersion ccVersion) {
    String publishedAssessmentString = samigoId.substring(samigoId.indexOf("/") + 1);
    PublishedAssessmentFacade assessment = pubService.getPublishedAssessment(publishedAssessmentString, true);
    List<ItemDataIfc> publishedItemList = preparePublishedItemList(assessment);
    String assessmentTitle = formattedText.convertFormattedTextToPlaintext(assessment.getTitle());

    out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");

    switch (ccVersion) {
        case V11:
            out.println("<questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\"");
            out.println("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p1/ccv1p1_qtiasiv1p2p1_v1p0.xsd\">");
            break;
        case V13:
            out.println("<questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\"");
            out.println("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p3/ccv1p3_qtiasiv1p2p1_v1p0.xsd\">");
            break;
        default:
            out.println("<questestinterop xmlns=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2\"");
            out.println("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/profile/cc/ccv1p2/ccv1p2_qtiasiv1p2p1_v1p0.xsd\">");
            break;
    }

    out.println("  <assessment ident=\"QDB_1\" title=\"" + StringEscapeUtils.escapeXml11(assessmentTitle) + "\">");
    out.println("    <section ident=\"S_1\">");

    outputQuestions(ccConfig, publishedItemList, null, assessmentTitle, out, resultsWriter, CCResourceItem, ccVersion);

    out.println("    </section>");
    out.println("  </assessment>");
    out.println("</questestinterop>");

    return true;
}
 
Example #27
Source File: AnimeCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private void characterData(GuildMessageReceivedEvent event, I18nContext lang, CharacterData character) {
    try {
        final CharacterData.Attributes attributes = character.getAttributes();

        final String japName = attributes.getNames().getJa_jp();
        final String charName = attributes.getName();
        final String imageUrl = attributes.getImage().getOriginal();

        final String characterDescription = StringEscapeUtils.unescapeHtml4(attributes.getDescription().replace("<br>", "\n").replaceAll("\\<.*?>", "")); //This is silly.

        final String charDescription = attributes.getDescription() == null || attributes.getDescription().isEmpty() ? lang.get("commands.character.no_info")
                : StringUtils.limit(characterDescription, 1016);

        Player p = MantaroData.db().getPlayer(event.getAuthor());
        Badge badge = APIUtils.getHushBadge(charName.replace(japName, "").trim(), Utils.HushType.CHARACTER);

        if (badge != null) {
            p.getData().addBadgeIfAbsent(badge);
            p.save();
        }

        EmbedBuilder embed = new EmbedBuilder();
        embed.setColor(Color.LIGHT_GRAY)
                .setThumbnail(imageUrl)
                .setAuthor(String.format(lang.get("commands.character.information_header"), charName), null, imageUrl)
                .addField(lang.get("commands.character.information"), charDescription, true)
                .setFooter(lang.get("commands.anime.information_notice"), null);

        event.getChannel().sendMessage(embed.build()).queue(success -> {
        }, failure -> failure.printStackTrace());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: LinkTrackerProducer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
	TrackerViewParameters params = (TrackerViewParameters) viewparams;

               if (!simplePageBean.canReadPage())
	    return;

               UIOutput.make(tofill, "html").decorate(new UIFreeAttributeDecorator("lang", localeGetter.get().getLanguage()))
	    .decorate(new UIFreeAttributeDecorator("xml:lang", localeGetter.get().getLanguage()));        

	Long itemId = params.getItemId();

	SimplePageItem i = simplePageToolDao.findItem(itemId);

	SimplePage page = simplePageBean.getCurrentPage();

	if (i.getPageId() != page.getPageId()) {
	    log.info("LinkTracker asked to track item not in current page");
	    return;
	}

	if (i != null && simplePageBean.isItemAvailable(i)) {

	    simplePageBean.track(itemId, null);

	    String URL = params.getURL();
	    if (lessonBuilderAccessService.needsCopyright(i.getSakaiId()))
		URL = "/access/require?ref=" + URLEncoder.encode("/content" + i.getSakaiId()) + "&url=" + URLEncoder.encode(URL.substring(7));

	    String js = "window.location = \"" + StringEscapeUtils.escapeEcmaScript(URL) + "\"";
	    if (params.getRefresh())
		js = "window.top.opener.location.reload(true);" + js;
	    UIVerbatim.make(tofill, "redirect", js);

	} else {

	    UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.error"));
	    UIOutput.make(tofill, "errormsg", messageLocator.getMessage("simplepage.complete_required"));
	}
}
 
Example #29
Source File: FriendInvitationContentTest.java    From jeeves with MIT License 5 votes vote down vote up
@Test
public void TestDeserializing() throws IOException {
    String xmlString = "&lt;msg fromusername=\"wxid_emf5glqo1tlf22\" encryptusername=\"v1_632d08f0036f3610315c0aeb1db8825f6392c4b5755ad2c99214ad2c447fa1ea7f7dff79999c6e64bfe2d69578c8eeb0@stranger\" fromnickname=\"鹧鸪仔\" content=\"我是鹧鸪仔\"  shortpy=\"ZGZ\" imagestatus=\"3\" scene=\"30\" country=\"\" province=\"\" city=\"\" sign=\"\" percard=\"1\" sex=\"0\" alias=\"daishuxiaogege\" weibo=\"\" weibonickname=\"\" albumflag=\"0\" albumstyle=\"0\" albumbgimgid=\"\" snsflag=\"1\" snsbgimgid=\"\" snsbgobjectid=\"0\" mhash=\"86ed45196ad6ee51f69661a68ab4e689\" mfullhash=\"86ed45196ad6ee51f69661a68ab4e689\" bigheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/5TrzicKwZW9a9Rc7YhJrRhnw5ZO46eEvvNhE8xicqwmubcTrtg9Dowp6b8BQKiaEO3JLWViarLPib2Zfic9VA2ETUZokucgFvhy6aaQNcVjAk3mBM/0\" smallheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/5TrzicKwZW9a9Rc7YhJrRhnw5ZO46eEvvNhE8xicqwmubcTrtg9Dowp6b8BQKiaEO3JLWViarLPib2Zfic9VA2ETUZokucgFvhy6aaQNcVjAk3mBM/132\" ticket=\"v2_52ca9d554ec220ad0882373288b6e14cc717dd91ad8db6bb38c64df1774e933c6d026f4168cadf877a38f6c4ec1cf3e79088eef110f53ae8d57474d6665c1497@stranger\" opcode=\"2\" googlecontact=\"\" qrticket=\"\" chatroomusername=\"\" sourceusername=\"\" sourcenickname=\"\"&gt;&lt;brandlist count=\"0\" ver=\"693400187\"&gt;&lt;/brandlist&gt;&lt;/msg&gt;";
    ObjectMapper xmlMapper = new XmlMapper();
    FriendInvitationContent content = xmlMapper.readValue(StringEscapeUtils.unescapeXml(xmlString), FriendInvitationContent.class);
    Assert.assertTrue(content.getFromusername().equals("wxid_emf5glqo1tlf22"));
}
 
Example #30
Source File: HtmlReport.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private void createNode(Writer writer, String nodeTitle, String nodeDescription, NodeType nodeType,
                        StatusType statusType, MessageLevel messageLevel, int indentSize, CheckPoint checkPoint,
                        Long msgId, List<String> verificationsOrder, String jsonVerificationResult,
                        boolean hasChild) {
    logger.debug("createNode - context: {}, title: {}, type: {}", currentContext, nodeTitle, nodeType);

    String nodeClass = getNodeClass(nodeType, statusType, messageLevel);

    try {
        TemplateWrapper nodeOpenTemplate = templateWrapperFactory.createWrapper("node_create.ftlh");

        nodeOpenTemplate.setData("id", ++nodeId);
        nodeOpenTemplate.setData("node_class", nodeClass);
        nodeOpenTemplate.setData("title", nodeTitle);
        nodeOpenTemplate.setData("description", StringEscapeUtils.escapeHtml4(StringUtils.stripToNull(nodeDescription)));
        nodeOpenTemplate.setData("action", nodeType == NodeType.ACTION);
        nodeOpenTemplate.setData("status_type", statusType);
        nodeOpenTemplate.setData("checkPoint", checkPoint);
        nodeOpenTemplate.setData("hasChild", hasChild);
        nodeOpenTemplate.setData("msgId", msgId);
        nodeOpenTemplate.setData("verificationsOrder", String.join(",", verificationsOrder));
        nodeOpenTemplate.setData("jsonVerificationResult", jsonVerificationResult);
        nodeOpenTemplate.write(writer, indentSize);
    } catch(IOException | TemplateException e) {
        throw new ScriptRunException("Failed to open node: " + nodeTitle, e);
    }

}