Java Code Examples for org.apache.commons.text.StringEscapeUtils

The following examples show how to use org.apache.commons.text.StringEscapeUtils. These examples are extracted from open source projects. 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
@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 2
Source Project: hub-detect   Source File: GradleScriptCreator.java    License: 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 3
Source Project: drftpd   Source File: HttpUtils.java    License: 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 Project: My-Blog-layui   Source File: MyBlogController.java    License: 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 5
Source Project: sailfish-core   Source File: TextileAdapter.java    License: 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("\\(", "&#40;").replaceAll("\\)", "&#41;"));
        }
    } catch (Exception e) {
        System.err.println("Error during link parsing. " + e.getMessage());
    }

    return sb.toString();
}
 
Example 6
Source Project: rdf4j   Source File: Select.java    License: 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 7
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 8
Source Project: RedReader   Source File: ImgurAPI.java    License: 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 9
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 10
Source Project: cxf-fediz   Source File: TokenSerializer.java    License: 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 11
Source Project: onedev   Source File: AssistPanel.java    License: 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 12
Source Project: sakai   Source File: ElasticSearchResult.java    License: 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 13
Source Project: spring-cloud-contract   Source File: GenericJsonBodyThen.java    License: 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 14
Source Project: StatsAgg   Source File: InfluxdbStandardizedMetric.java    License: 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 15
Source Project: sakai   Source File: OptionValidator.java    License: Educational Community License v2.0 5 votes vote down vote up
public void validate(Object obj, Errors errors) {

		Option option = (Option) obj;
		
		// SAK-14725 : BugFix
		String stripText = null;
		
		if(null != option.getText()) {
			stripText = externalLogic.convertFormattedTextToPlaintext(option.getText()).trim();
		}
		
		log.debug("validating Option with id {} and status {}.", option.getOptionId(), option.getStatus());
		if (option.getStatus()!=null && (option.getStatus().equals("cancel") || option.getStatus().equals("delete") || option.getStatus().equals("batch")))
			return;

		if (option.getText() == null || option.getText().trim().length()==0 ||
				stripText == null || stripText.length()==0) {
			log.debug("OptionText is empty!");
			errors.reject("option_empty","option empty");
			return;
		}

		//if where here option is not null or empty but could be something like "&nbsp;&nbsp;"
		String text = option.getText();
		text = PollUtils.cleanupHtmlPtags(text);
		text = text.replace("&nbsp;", "");
		text = StringEscapeUtils.unescapeHtml4(text).trim();
		log.debug("text to validate is: " + text);
		if (text.trim().length()==0) {
			log.debug("OptionText is empty! (after excaping html)");
			errors.reject("option_empty","option empty");
			return;
		}
	}
 
Example 16
Source Project: sakai   Source File: FormattedTextImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public String escapeHtml(String value, boolean escapeNewlines) {
    /*
     * Velocity tools depend on this returning empty string (and never null),
     * they also depend on this handling a null input and converting it to null
     */
    String val = "";
    if (StringUtils.isNotEmpty(value)){
        val = StringEscapeUtils.escapeHtml4(value);
        if (escapeNewlines && val != null) {
            val = val.replace("\n", "<br/>\n");
        }
    }
    return val;
}
 
Example 17
/**
 * Append a node to the writer, indented according to a specific level.
 */
private void printNode(final PrintWriter out, final int indentLevel, final ImmutableNode node)
{
    final String padding = StringUtils.repeat(" ", indentLevel * INDENT_SIZE);

    if (node.getNodeName() != null)
    {
        out.println(padding + "<key>" + StringEscapeUtils.escapeXml10(node.getNodeName()) + "</key>");
    }

    final List<ImmutableNode> children = node.getChildren();
    if (!children.isEmpty())
    {
        out.println(padding + "<dict>");

        final Iterator<ImmutableNode> it = children.iterator();
        while (it.hasNext())
        {
            final ImmutableNode child = it.next();
            printNode(out, indentLevel + 1, child);

            if (it.hasNext())
            {
                out.println();
            }
        }

        out.println(padding + "</dict>");
    }
    else if (node.getValue() == null)
    {
        out.println(padding + "<dict/>");
    }
    else
    {
        final Object value = node.getValue();
        printValue(out, indentLevel, value);
    }
}
 
Example 18
Source Project: bamboobsc   Source File: MenuSupportUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getTwitterAccordionPane(String systemId) throws ServiceException, Exception {
	if ( StringUtils.isBlank(systemId) ) {
		return "";
	}
	SysTwitterVO sysTwitter = new SysTwitterVO();
	sysTwitter.setSystem( systemId );
	DefaultResult<SysTwitterVO> result = sysTwitterService.findByUK(sysTwitter);
	if ( result.getValue()==null ) {
		return "";
	}
	sysTwitter = result.getValue();
	if ( !YesNo.YES.equals(sysTwitter.getEnableFlag()) ) {
		return "";
	}
	String content = new String( sysTwitter.getContent(), "utf8" );
	if ( StringUtils.isBlank(content) ) {
		return "";
	}
	StringBuilder sb = new StringBuilder();
	String title = StringEscapeUtils.escapeHtml4( sysTwitter.getTitle() );
	String id = "_" + systemId + "_twitter_AccordionPane";
	sb.append("<div data-dojo-type=\"dijit/layout/AccordionPane\" title=\"<img src='./icons/twitter.png' border='0'/>&nbsp;" + title + "\" id=\"" + id + "\"> \n");
	sb.append(content);
	sb.append("\n");
	sb.append("</div>");
	return sb.toString();		
}
 
Example 19
Source Project: rdf4j   Source File: GroupByCount.java    License: BSD 3-Clause "New" or "Revised" License 5 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");
	stringBuilder.append(parent.getId() + " -> " + getId()).append("\n");
	parent.getPlanAsGraphvizDot(stringBuilder);
}
 
Example 20
public static String getOutputTableInfoContentLine(String contentItemName, String contentItemValue) {
	return new StringBuilder()
		.append("	<tr>\n")
		.append("		<td width=\"140\" class=\"stack-column\"><b>").append(StringUtils.isNotEmpty(contentItemName) ? StringEscapeUtils.escapeHtml4(contentItemName) + ":" : "").append("</b></td>\n")
		.append("		<td class=\"stack-column\">").append(StringEscapeUtils.escapeHtml4(contentItemValue)).append("</td>\n")
		.append("	</tr>\n")
		.toString();
}
 
Example 21
@Override
public String getFullUrlWithExtensions() {
   	try {
		String directLink = createDirectLinkWithOptionalExtensionsWithoutUserData();
		return StringEscapeUtils.escapeHtml4(directLink);
	} catch (UnsupportedEncodingException e) {
		logger.warn("Error creation directory link with optional extension without user data, cause: " + e.getMessage());
		return "";
	}
}
 
Example 22
Source Project: parquet-mr   Source File: CSVProperties.java    License: Apache License 2.0 5 votes vote down vote up
private static String unescapeJava(String str) {
  // StringEscapeUtils removes the single escape character
  if (str == "\\") {
    return str;
  }
  return StringEscapeUtils.unescapeJava(str);
}
 
Example 23
@Test
public void shouldAlertIfPhpEchoTagsWereDisclosedInResponseBody() throws Exception {
    // Given
    String test = "/shouldAlertIfPhpEchoTagsWereDisclosedInResponseBody/";
    nano.addHandler(
            new NanoServerHandler(test) {

                @Override
                protected Response serve(IHTTPSession session) {
                    String encodedPhpCode = StringEscapeUtils.escapeHtml4(PHP_SOURCE_ECHO_TAG);
                    return newFixedLengthResponse(
                            "<html><body>" + encodedPhpCode + "</body></html>");
                }
            });
    HttpMessage message = getHttpMessage(test);
    rule.init(message, parent);
    // 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 24
Source Project: cerberus-source   Source File: SoapService.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public SOAPMessage createSoapRequest(String envelope, String method, List<AppServiceHeader> header, String token) throws SOAPException, IOException, SAXException, ParserConfigurationException {
    String unescapedEnvelope = StringEscapeUtils.unescapeXml(envelope);
    boolean is12SoapVersion = SOAP_1_2_NAMESPACE_PATTERN.matcher(unescapedEnvelope).matches();

    MimeHeaders headers = new MimeHeaders();
    for (AppServiceHeader appServiceHeader : header) {
        headers.addHeader(appServiceHeader.getKey(), appServiceHeader.getValue());
    }

    InputStream input = new ByteArrayInputStream(unescapedEnvelope.getBytes("UTF-8"));
    MessageFactory messageFactory = MessageFactory.newInstance(is12SoapVersion ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL);
    return messageFactory.createMessage(headers, input);
}
 
Example 25
Source Project: openemm   Source File: AgnMessageTag.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private String escape(String message) throws JspException {
	switch (resolveEscapeMode()) {
		case ESCAPE_MODE_HTML:
			return Functions.escapeXml(message);

		case ESCAPE_MODE_JS:
			return StringEscapeUtils.escapeEcmaScript(message);

		default:
			return message;
	}
}
 
Example 26
Source Project: youtube-comment-suite   Source File: YouTubeChannel.java    License: MIT License 5 votes vote down vote up
/**
 * Comment objects usually have enough detail about the poster to create our object.
 */
public YouTubeChannel(Comment item) {
    this(getChannelIdFromObject(item.getSnippet().getAuthorChannelId()),
            StringEscapeUtils.unescapeHtml4(item.getSnippet().getAuthorDisplayName()),
            item.getSnippet().getAuthorProfileImageUrl());
    setTypeId(YType.CHANNEL);
}
 
Example 27
@Test
public void appDockerResource() throws IOException {
	byte[] bytes = StreamUtils.copyToByteArray(new ClassPathResource(
			"apps/no-whitelist/META-INF/spring-configuration-metadata.json", getClass()).getInputStream());
	when(containerImageMetadataResolver.getImageLabels("test/test:latest"))
			.thenReturn(Collections.singletonMap("org.springframework.cloud.dataflow.spring-configuration-metadata.json", StringEscapeUtils.escapeJson(new String(bytes))));
	List<ConfigurationMetadataProperty> properties = resolver.listProperties(new DockerResource("test/test:latest"));
	assertThat(properties.size(), is(3));
}
 
Example 28
Source Project: o2oa   Source File: BaseAction.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
protected String initPassword(Business business, Person person) throws Exception {
	String str = Config.person().getPassword();
	Pattern pattern = Pattern.compile(com.x.base.core.project.config.Person.REGULAREXPRESSION_SCRIPT);
	Matcher matcher = pattern.matcher(str);
	if (matcher.matches()) {
		String eval = ScriptFactory.functionalization(StringEscapeUtils.unescapeJson(matcher.group(1)));
		ScriptContext scriptContext = new SimpleScriptContext();
		Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
		bindings.put("person", person);
		Object o = ScriptFactory.scriptEngine.eval(eval, scriptContext);
		return o.toString();
	} else {
		return str;
	}
}
 
Example 29
Source Project: Openfire   Source File: SystemPropertiesServlet.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void encryptProperty(final HttpServletRequest request, final WebManager webManager) {
    final String key = request.getParameter("key");
    if (JiveGlobals.getProperty(key) == null) {
        // We can't encrypt a property that doesn't yet exist
        SystemProperty.getProperty(key).ifPresent(property -> property.setValue(property.getDefaultValue()));
    }
    JiveGlobals.setPropertyEncrypted(key, true);
    webManager.logEvent("Encrypted server property " + key, null);
    request.getSession().setAttribute("successMessage",
        String.format("The property %s was encrypted", StringEscapeUtils.escapeXml11(key)));
}
 
Example 30
Source Project: Openfire   Source File: SystemPropertiesServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final HttpSession session = request.getSession();
    final Cookie csrfCookie = CookieUtils.getCookie(request, "csrf");
    if (csrfCookie == null || !csrfCookie.getValue().equals(request.getParameter("csrf"))) {
        session.setAttribute("errorMessage", LocaleUtils.getLocalizedString("global.csrf.failed"));
    } else {
        final WebManager webManager = new WebManager();
        webManager.init(request, response, session, session.getServletContext());
        final String action = ParamUtils.getStringParameter(request, "action", "");
        switch (action) {
            case "save":
                saveProperty(request, webManager);
                break;
            case "cancel":
                session.setAttribute("warningMessage",
                    String.format("No changes were made to the property %s",
                        StringEscapeUtils.escapeXml11(request.getParameter("key"))));
                break;
            case "encrypt":
                encryptProperty(request, webManager);
                break;
            case "delete":
                deleteProperty(request, webManager);
                break;
            default:
                session.setAttribute("warningMessage",
                    String.format("Unexpected request action '%s'",
                        StringEscapeUtils.escapeXml11(action)));
                break;
        }
    }
    response.sendRedirect(request.getRequestURI() + ListPager.getQueryString(request, '?', SEARCH_FIELDS));
}