Skip to content

Commit

Permalink
Merge branch 'master' into snyk-upgrade-ce692b96cbff5942cd77394b2ab30024
Browse files Browse the repository at this point in the history
  • Loading branch information
t-burch authored Aug 26, 2024
2 parents 2d78721 + 7581b02 commit 16f81d3
Show file tree
Hide file tree
Showing 6 changed files with 421 additions and 184 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package com.predic8.membrane.core.interceptor.templating;

import com.predic8.membrane.annot.MCAttribute;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.annot.MCTextContent;
import com.predic8.membrane.core.beautifier.JSONBeautifier;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.Message;
import com.predic8.membrane.core.interceptor.AbstractInterceptor;
import com.predic8.membrane.core.interceptor.Outcome;
import com.predic8.membrane.core.util.TextUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;

import static com.predic8.membrane.core.http.MimeType.*;
import static com.predic8.membrane.core.interceptor.Outcome.CONTINUE;
import static com.predic8.membrane.core.util.TextUtil.unifyIndent;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;

@MCElement(name = "static", mixed = true)
public class StaticInterceptor extends AbstractInterceptor {

protected String location;

protected String textTemplate;

protected String contentType = TEXT_PLAIN;

protected Boolean pretty = false;

protected final JSONBeautifier jsonBeautifier = new JSONBeautifier();

protected static final Logger log = LoggerFactory.getLogger("StaticInterceptor");

public StaticInterceptor() {
name = "Static";
}

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
return handleInternal(exc.getRequest());
}

@Override
public Outcome handleResponse(Exchange exc) throws Exception {
return handleInternal(exc.getResponse());
}

private Outcome handleInternal(Message msg) {
msg.setBodyContent(getTemplateBytes());
msg.getHeader().setContentType(getContentType());
return CONTINUE;
}

private byte @NotNull [] getTemplateBytes() {
if (!pretty)
return textTemplate.getBytes(UTF_8);

return switch (contentType) {
case APPLICATION_JSON -> prettifyJson(textTemplate).getBytes(UTF_8);
case APPLICATION_XML, APPLICATION_SOAP, TEXT_HTML, TEXT_XML, TEXT_HTML_UTF8, TEXT_XML_UTF8 -> prettifyXML(textTemplate).getBytes(UTF_8);
default -> unifyIndent(textTemplate).getBytes(UTF_8);
};
}

private String prettifyXML(String text) {
try {
return TextUtil.formatXML(new StringReader(text));
} catch (Exception e) {
log.warn("Failed to format XML", e);
return text;
}
}

String prettifyJson(String text) {
try {
return jsonBeautifier.beautify(text);
} catch (IOException e) {
log.warn("Failed to format JSON", e);
return text;
}
}

@Override
public void init() throws Exception {
if (this.getLocation() != null && (getTextTemplate() != null && !getTextTemplate().isBlank())) {
throw new IllegalStateException("On <" + getName() + ">, ./text() and ./@location cannot be set at the same time.");
}
}

public String getLocation() {
return location;
}

@MCAttribute
public void setLocation(String location){
this.location = location;
}

public String getTextTemplate() {
return textTemplate;
}

@MCTextContent
public void setTextTemplate(String textTemplate) {
this.textTemplate = textTemplate;
}

protected String getName() {
return getClass().getAnnotation(MCElement.class).name();
}

public String getContentType() {
return contentType;
}

@MCAttribute
public void setContentType(String contentType) {
this.contentType = contentType;
}

public Boolean getPretty() {
return pretty;
}

@MCAttribute
public void setPretty(String pretty) {
this.pretty = Boolean.valueOf(pretty);
}

private String formatAsHtml(String plaintext) {
return String.join("<br />", escapeHtml4(plaintext).split("\n"));
}

@Override
public String getShortDescription() {
return formatAsHtml(textTemplate);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,27 @@

package com.predic8.membrane.core.interceptor.templating;

import com.predic8.membrane.annot.*;
import com.predic8.membrane.core.beautifier.*;
import com.predic8.membrane.core.exceptions.*;
import com.predic8.membrane.core.exchange.*;
import com.predic8.membrane.core.http.*;
import com.predic8.membrane.core.interceptor.*;
import com.predic8.membrane.core.lang.*;
import com.predic8.membrane.core.resolver.*;
import groovy.text.*;
import org.apache.commons.io.*;
import org.apache.commons.lang3.*;
import org.slf4j.*;

import java.io.*;
import java.util.*;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.core.exceptions.ProblemDetails;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.Message;
import com.predic8.membrane.core.interceptor.Outcome;
import com.predic8.membrane.core.lang.ScriptingUtils;
import com.predic8.membrane.core.resolver.ResolverMap;
import groovy.text.StreamingTemplateEngine;
import groovy.text.Template;
import groovy.text.TemplateExecutionException;
import groovy.text.XmlTemplateEngine;
import org.apache.commons.io.FilenameUtils;

import java.io.InputStreamReader;
import java.util.HashMap;

import static com.predic8.membrane.core.http.MimeType.*;
import static com.predic8.membrane.core.interceptor.Interceptor.Flow.*;
import static com.predic8.membrane.core.interceptor.Outcome.*;
import static java.nio.charset.StandardCharsets.*;
import static org.apache.commons.text.StringEscapeUtils.*;
import static com.predic8.membrane.core.interceptor.Interceptor.Flow.REQUEST;
import static com.predic8.membrane.core.interceptor.Interceptor.Flow.RESPONSE;
import static com.predic8.membrane.core.interceptor.Outcome.CONTINUE;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
* @description Renders the body content of a message from a template. The template can
Expand All @@ -48,25 +48,12 @@


@MCElement(name="template", mixed = true)
public class TemplateInterceptor extends AbstractInterceptor{

/**
* @description Path of template file
*/
private String location;

private String textTemplate;

private Template template;

private String contentType = TEXT_PLAIN;

private Boolean pretty = false;

private final JSONBeautifier jsonBeautifier = new JSONBeautifier();
public class TemplateInterceptor extends StaticInterceptor {

private boolean scriptAccessesJson;

protected Template template;

public TemplateInterceptor() {
name = "Template";
}
Expand Down Expand Up @@ -97,14 +84,6 @@ private Outcome handleInternal(Message msg, Exchange exc, Flow flow) {
return CONTINUE;
}

String prettifyJson(String text) {
try {
return jsonBeautifier.beautify(text);
} catch (IOException e) {
return text;
}
}

@SuppressWarnings("RedundantThrows") // Declaration of exception is needed. However, Groovy does not declare it.
private String fillTemplate(Exchange exc, Message msg, Flow flow) throws TemplateExecutionException {

Expand Down Expand Up @@ -155,78 +134,11 @@ public void init() throws Exception {
throw new IllegalStateException("You have to set either ./@location or ./text()");
}

public String getLocation() {
return location;
}

/**
* @description path of xml template file.
* @example template.xml
*/
@MCAttribute
public void setLocation(String location){
this.location = location;
}

public String getTextTemplate() {
return textTemplate;
}

@MCTextContent
public void setTextTemplate(String textTemplate) throws IOException, ClassNotFoundException {
this.textTemplate = textTemplate;

if(textTemplate != null && !StringUtils.isBlank(textTemplate)){
template = new StreamingTemplateEngine().createTemplate(this.getTextTemplate());
}
}

public Template getTemplate() {
return template;
}

public void setTemplate(Template template) {
this.template = template;
}


private String getName() {
return getClass().getAnnotation(MCElement.class).name();
}

public String getContentType() {
return contentType;
}

/**
* @description content type for body
* @example application/json
*/
@MCAttribute
public void setContentType(String contentType) {
this.contentType = contentType;
}

public Boolean getPretty() {
return pretty;
}

/**
* @description Format JSON documents.
* @example yes
* @default no
*/
@MCAttribute
public void setPretty(String pretty) {
this.pretty = Boolean.valueOf(pretty);
}

private String formatAsHtml(String plaintext) {
return String.join("<br />", escapeHtml4(plaintext).split("\n"));
}

@Override
public String getShortDescription() {
return formatAsHtml(textTemplate);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import java.util.List;
import java.util.regex.Pattern;

import static com.predic8.membrane.core.util.TextUtil.unifyIndent;

public abstract class PEMSupport {

private static final Logger log = LoggerFactory.getLogger(PEMSupport.class.getName());
Expand Down Expand Up @@ -64,21 +66,8 @@ public PEMSupportImpl() {
Security.addProvider(new BouncyCastleProvider());
}

private String cleanupPEM(String pemBlock) {
String lines[] = pemBlock.split("\r?\n");
StringBuilder block = new StringBuilder();
for (String line : lines) {
String l = line.replaceAll("^\\s+", "");
if (l.length() > 0) {
block.append(l);
block.append("\n");
}
}
return block.toString();
}

public X509Certificate parseCertificate(String pemBlock) throws IOException {
PEMParser p2 = new PEMParser(new StringReader(cleanupPEM(pemBlock)));
PEMParser p2 = new PEMParser(new StringReader(unifyIndent(pemBlock)));
Object o2 = p2.readObject();
if (o2 == null)
throw new InvalidParameterException("Could not read certificate. Expected the certificate to begin with '-----BEGIN CERTIFICATE-----'.");
Expand All @@ -94,7 +83,7 @@ public X509Certificate parseCertificate(String pemBlock) throws IOException {
}
public List<X509Certificate> parseCertificates(String pemBlock) throws IOException {
List<X509Certificate> res = new ArrayList<>();
PEMParser p2 = new PEMParser(new StringReader(cleanupPEM(pemBlock)));
PEMParser p2 = new PEMParser(new StringReader(unifyIndent(pemBlock)));
JcaX509CertificateConverter certconv = new JcaX509CertificateConverter().setProvider("BC");
while(true) {
Object o2 = p2.readObject();
Expand All @@ -115,7 +104,7 @@ public List<X509Certificate> parseCertificates(String pemBlock) throws IOExcepti
}

public Key getPrivateKey(String pemBlock) throws IOException {
PEMParser p = new PEMParser(new StringReader(cleanupPEM(pemBlock)));
PEMParser p = new PEMParser(new StringReader(unifyIndent(pemBlock)));
Object o = p.readObject();
if (o == null)
throw new InvalidParameterException("Could not read certificate. Expected the certificate to begin with '-----BEGIN CERTIFICATE-----'.");
Expand All @@ -131,7 +120,7 @@ public Key getPrivateKey(String pemBlock) throws IOException {
}

public Object parseKey(String pemBlock) throws IOException {
PEMParser p = new PEMParser(new StringReader(cleanupPEM(pemBlock)));
PEMParser p = new PEMParser(new StringReader(unifyIndent(pemBlock)));
Object o = p.readObject();
if (o == null) {
log.error("Could not read PEM file. Check the contents of PEM file or configuration. Content is {}", pemBlock);
Expand Down
Loading

0 comments on commit 16f81d3

Please sign in to comment.