use of com.predic8.membrane.core.http.Message in project service-proxy by membrane.
the class AdminRESTInterceptor method getRequestBody.
@Mapping("/admin/rest/exchanges/(-?\\d+)/(response|request)/body")
public Response getRequestBody(QueryParameter params, String relativeRootPath) throws Exception {
AbstractExchange exc = router.getExchangeStore().getExchangeById(params.getGroupInt(1));
if (exc == null) {
return Response.notFound().build();
}
Message msg = params.getGroup(2).equals("response") ? exc.getResponse() : exc.getRequest();
String ct = params.getGroup(2).equals("response") ? exc.getResponseContentType() : exc.getRequestContentType();
if (msg == null || msg.isBodyEmpty()) {
return Response.noContent().build();
}
ResponseBuilder rb = Response.ok().contentType(ct).body(msg.getBodyAsStream(), false);
String contentEncoding = msg.getHeader().getContentEncoding();
if (contentEncoding != null)
rb.header(Header.CONTENT_ENCODING, contentEncoding);
return rb.build();
}
use of com.predic8.membrane.core.http.Message in project service-proxy by membrane.
the class LoginDialog method handleLoginRequest.
public void handleLoginRequest(Exchange exc) throws Exception {
Session s = sessionManager.getSession(exc);
String uri = exc.getRequest().getUri().substring(path.length() - 1);
if (uri.indexOf('?') >= 0)
uri = uri.substring(0, uri.indexOf('?'));
exc.getDestinations().set(0, uri);
if (uri.equals("/logout")) {
if (s != null)
s.clear();
exc.setResponse(Response.redirect(path, false).body("").build());
} else if (uri.equals("/consent")) {
if (exc.getRequest().getMethod().equals("POST"))
processConsentPageResult(exc, s);
else
showConsentPage(exc, s);
} else if (uri.equals("/")) {
if (s == null || !s.isPreAuthorized()) {
if (exc.getRequest().getMethod().equals("POST")) {
Map<String, String> userAttributes;
Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
String username = params.get("username");
if (username == null) {
showPage(exc, 0, "error", "INVALID_PASSWORD");
return;
}
if (accountBlocker != null && accountBlocker.isBlocked(username)) {
showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
return;
}
try {
userAttributes = userDataProvider.verify(params);
} catch (NoSuchElementException e) {
List<String> params2 = Lists.newArrayList("error", "INVALID_PASSWORD");
if (accountBlocker != null) {
if (accountBlocker.fail(username))
params2.addAll(Lists.newArrayList("accountBlocked", "true"));
}
showPage(exc, 0, params2.toArray());
return;
} catch (Exception e) {
log.error("", e);
showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
return;
}
if (exposeUserCredentialsToSession) {
for (Map.Entry<String, String> param : params.entrySet()) if (!userAttributes.containsKey(param.getKey()))
userAttributes.put(param.getKey(), param.getValue());
}
if (tokenProvider != null)
showPage(exc, 1);
else {
String target = params.get("target");
if (StringUtils.isEmpty(target))
target = "/";
exc.setResponse(Response.redirectWithout300(target).build());
}
Session session = sessionManager.getOrCreateSession(exc);
session.preAuthorize(username, userAttributes);
if (tokenProvider != null)
tokenProvider.requestToken(session.getUserAttributes());
} else {
showPage(exc, 0);
}
} else {
if (accountBlocker != null && accountBlocker.isBlocked(s.getUserName())) {
showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
return;
}
if (exc.getRequest().getMethod().equals("POST")) {
String token = URLParamUtil.getParams(uriFactory, exc).get("token");
try {
if (tokenProvider != null)
tokenProvider.verifyToken(s.getUserAttributes(), token);
} catch (NoSuchElementException e) {
List<String> params = Lists.newArrayList("error", "INVALID_TOKEN");
if (accountBlocker != null)
if (accountBlocker.fail(s.getUserName()))
params.addAll(Lists.newArrayList("accountBlocked", "true"));
s.clear();
showPage(exc, 0, params.toArray());
return;
} catch (Exception e) {
log.error("", e);
s.clear();
showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
return;
}
if (accountBlocker != null)
accountBlocker.unblock(s.getUserName());
String target = URLParamUtil.getParams(uriFactory, exc).get("target");
if (StringUtils.isEmpty(target))
target = "/";
if (this.message != null)
exc.setResponse(Response.redirectWithout300(target, message).build());
else
exc.setResponse(Response.redirectWithout300(target).build());
s.authorize();
} else {
showPage(exc, 1);
}
}
} else {
wsi.handleRequest(exc);
}
}
use of com.predic8.membrane.core.http.Message in project service-proxy by membrane.
the class AMQuota method setResponseToServiceUnavailable.
private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
// TODO do a better response here
Header hd = new Header();
DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
ByteArrayOutputStream os = new ByteArrayOutputStream();
JsonGenerator jgen = null;
try {
jgen = new JsonFactory().createGenerator(os);
jgen.writeStartObject();
jgen.writeObjectField("Statuscode", 429);
jgen.writeObjectField("Message", "Quota Exceeded");
jgen.writeEndObject();
jgen.close();
} catch (IOException ignored) {
}
Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
exc.setResponse(resp);
}
use of com.predic8.membrane.core.http.Message in project service-proxy by membrane.
the class AMRateLimiter method setResponseToServiceUnavailable.
public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl) throws UnsupportedEncodingException {
Header hd = new Header();
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
hd.add("Date", dateFormatter.print(DateTime.now()));
hd.add("X-LimitDuration", PeriodFormat.getDefault().print(prl.getInterval().toPeriod()));
hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
String ip = exc.getRemoteAddrIp();
DateTime availableAgainDateTime = prl.getNextCleanup();
hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));
/*StringBuilder bodyString = new StringBuilder();
DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
bodyString.append(ip).append(" exceeded the rate limit of ").append(prl.getRequests())
.append(" requests per ")
.append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
.append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/
DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
ByteArrayOutputStream os = new ByteArrayOutputStream();
JsonGenerator jgen = null;
try {
jgen = new JsonFactory().createGenerator(os);
jgen.writeStartObject();
jgen.writeObjectField("Statuscode", 429);
jgen.writeObjectField("Message", "The rate limit of " + prl.getRequests() + " requests in " + prl.getInterval().getStandardSeconds() + " seconds is exceeded. The next requests can be made at " + dtFormatter.print(availableAgainDateTime));
jgen.writeEndObject();
jgen.close();
} catch (IOException ignored) {
}
Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
exc.setResponse(resp);
}
use of com.predic8.membrane.core.http.Message in project service-proxy by membrane.
the class XMLContentFilter method removeMatchingElements.
/**
* Removes parts of an XML document based on an XPath expression.
*
* If the message is not valid XML, it is left unchanged.
*/
public void removeMatchingElements(Message message) {
try {
Message xop = null;
try {
xop = xopReconstitutor.getReconstitutedMessage(message);
} catch (ParseException e) {
} catch (EndOfStreamException e) {
} catch (FactoryConfigurationError e) {
}
if (elementFinder != null && !elementFinder.matches(xop != null ? xop.getBodyAsStream() : message.getBodyAsStream())) {
return;
}
DocumentBuilder db = createDocumentBuilder();
Document d;
try {
d = db.parse(xop != null ? xop.getBodyAsStream() : message.getBodyAsStream());
} finally {
db.reset();
}
removeElementsIfNecessary(message, xop, d);
} catch (SAXException e) {
return;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (XMLStreamException e) {
return;
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
} catch (TransformerConfigurationException e) {
throw new RuntimeException(e);
} catch (TransformerException e) {
throw new RuntimeException(e);
} catch (TransformerFactoryConfigurationError e) {
throw new RuntimeException(e);
}
}
Aggregations