use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.
the class XML2HTTP method unwrapMessageIfNecessary.
/**
* Checks, if the response contains an XML doc with NS {@link Constants#HTTP_NS}.
* If it does, the HTTP data (uri, method, status, headers, body) is extracted from the doc
* and set as the response.
*
* Reverse of {@link com.predic8.membrane.core.http.xml.Request#write(XMLStreamWriter)} and
* {@link com.predic8.membrane.core.http.xml.Response#write(XMLStreamWriter)}.
*/
public static void unwrapMessageIfNecessary(Message message) {
if (MimeType.TEXT_XML_UTF8.equals(message.getHeader().getContentType())) {
try {
if (message.getBody().getLength() == 0)
return;
XMLEventReader parser;
synchronized (xmlInputFactory) {
parser = xmlInputFactory.createXMLEventReader(message.getBodyAsStreamDecoded(), message.getCharset());
}
/* States:
* 0 = before root element,
* 1 = root element has HTTP_NS namespace
*/
int state = 0;
boolean keepSourceHeaders = false, foundHeaders = false, foundBody = false;
while (parser.hasNext()) {
XMLEvent event = parser.nextEvent();
switch(state) {
case 0:
if (event.isStartElement()) {
QName name = event.asStartElement().getName();
if (Constants.HTTP_NS.equals(name.getNamespaceURI())) {
state = 1;
if ("request".equals(name.getLocalPart())) {
Request req = (Request) message;
req.setMethod(requireAttribute(event.asStartElement(), "method"));
String httpVersion = getAttribute(event.asStartElement(), "http-version");
if (httpVersion == null)
httpVersion = "1.1";
req.setVersion(httpVersion);
}
} else {
return;
}
}
break;
case 1:
if (event.isStartElement()) {
String localName = event.asStartElement().getName().getLocalPart();
if ("status".equals(localName)) {
Response res = (Response) message;
res.setStatusCode(Integer.parseInt(requireAttribute(event.asStartElement(), "code")));
res.setStatusMessage(slurpCharacterData(parser, event.asStartElement()));
}
if ("uri".equals(localName)) {
Request req = (Request) message;
req.setUri(requireAttribute(event.asStartElement(), "value"));
// uri/... (port,host,path,query) structure is ignored, as value already contains everything
slurpXMLData(parser, event.asStartElement());
}
if ("headers".equals(localName)) {
foundHeaders = true;
keepSourceHeaders = "true".equals(getAttribute(event.asStartElement(), "keepSourceHeaders"));
}
if ("header".equals(localName)) {
String key = requireAttribute(event.asStartElement(), "name");
boolean remove = getAttribute(event.asStartElement(), "remove") != null;
if (remove && !keepSourceHeaders)
throw new XML2HTTPException("<headers keepSourceHeaders=\"false\"><header name=\"...\" remove=\"true\"> does not make sense.");
message.getHeader().removeFields(key);
if (!remove)
message.getHeader().add(key, slurpCharacterData(parser, event.asStartElement()));
}
if ("body".equals(localName)) {
foundBody = true;
String type = requireAttribute(event.asStartElement(), "type");
if ("plain".equals(type)) {
message.setBodyContent(slurpCharacterData(parser, event.asStartElement()).getBytes(Constants.UTF_8_CHARSET));
} else if ("xml".equals(type)) {
message.setBodyContent(slurpXMLData(parser, event.asStartElement()).getBytes(Constants.UTF_8_CHARSET));
} else {
throw new XML2HTTPException("XML-HTTP doc body type '" + type + "' is not supported (only 'plain' or 'xml').");
}
}
}
break;
}
}
if (!foundHeaders && !keepSourceHeaders)
message.getHeader().clear();
if (!foundBody)
message.setBodyContent(new byte[0]);
} catch (XMLStreamException e) {
log.error("", e);
} catch (XML2HTTPException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
}
}
}
use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.
the class AdminRESTInterceptor method getProxies.
@Mapping("/admin/rest/proxies(/?\\?.*)?")
public Response getProxies(final QueryParameter params, String relativeRootPath) throws Exception {
final List<AbstractServiceProxy> proxies = getServiceProxies();
if ("order".equals(params.getString("sort"))) {
if (params.getString("order", "asc").equals("desc"))
Collections.reverse(proxies);
} else {
Collections.sort(proxies, ComparatorFactory.getAbstractServiceProxyComparator(params.getString("sort", "name"), params.getString("order", "asc")));
}
final int offset = params.getInt("offset", 0);
int max = params.getInt("max", proxies.size());
final List<AbstractServiceProxy> paginated = proxies.subList(offset, Math.min(offset + max, proxies.size()));
return json(new JSONContent() {
public void write(JsonGenerator gen) throws Exception {
gen.writeStartObject();
gen.writeArrayFieldStart("proxies");
int i = offset;
if (params.getString("order", "asc").equals("desc"))
i = proxies.size() - i + 1;
for (AbstractServiceProxy p : paginated) {
gen.writeStartObject();
gen.writeNumberField("order", i += params.getString("order", "asc").equals("desc") ? -1 : 1);
gen.writeStringField("name", p.toString());
gen.writeBooleanField("active", p.isActive());
if (!p.isActive())
gen.writeStringField("error", p.getErrorState());
gen.writeNumberField("listenPort", p.getKey().getPort());
gen.writeStringField("virtualHost", p.getKey().getHost());
gen.writeStringField("method", p.getKey().getMethod());
gen.writeStringField("path", p.getKey().getPath());
gen.writeStringField("targetHost", p.getTargetHost());
gen.writeNumberField("targetPort", p.getTargetPort());
gen.writeNumberField("count", p.getCount());
gen.writeObjectFieldStart("actions");
if (!isReadOnly()) {
gen.writeStringField("delete", "/admin/service-proxy/delete?name=" + URLEncoder.encode(RuleUtil.getRuleIdentifier(p), "UTF-8"));
}
if (!p.isActive())
gen.writeStringField("start", "/admin/service-proxy/start?name=" + URLEncoder.encode(RuleUtil.getRuleIdentifier(p), "UTF-8"));
gen.writeEndObject();
gen.writeEndObject();
}
gen.writeEndArray();
gen.writeNumberField("total", proxies.size());
gen.writeEndObject();
}
});
}
use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.
the class AdminRESTInterceptor method getRaw.
@Mapping("/admin/rest/exchanges/(-?\\d+)/(response|request)/raw")
public Response getRaw(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();
if (msg == null) {
return Response.noContent().build();
}
// TODO uses body.toString that doesn't handle different encodings than utf-8
return Response.ok().contentType(MimeType.TEXT_PLAIN_UTF8).body(msg.toString()).build();
}
use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.
the class AdminRESTInterceptor method getClients.
@Mapping("/admin/rest/clients(/?\\?.*)?")
public Response getClients(QueryParameter params, String relativeRootPath) throws Exception {
final List<? extends ClientStatistics> clients = getRouter().getExchangeStore().getClientStatistics();
Collections.sort(clients, ComparatorFactory.getClientStatisticsComparator(params.getString("sort", "name"), params.getString("order", "asc")));
int offset = params.getInt("offset", 0);
int max = params.getInt("max", clients.size());
final int total = clients.size();
final List<? extends ClientStatistics> paginated = clients.subList(offset, Math.min(offset + max, clients.size()));
return json(new JSONContent() {
public void write(JsonGenerator gen) throws Exception {
gen.writeStartObject();
gen.writeArrayFieldStart("clients");
for (ClientStatistics s : paginated) {
gen.writeStartObject();
gen.writeStringField("name", s.getClient());
gen.writeNumberField("count", s.getCount());
gen.writeNumberField("min", s.getMinDuration());
gen.writeNumberField("max", s.getMaxDuration());
gen.writeNumberField("avg", s.getAvgDuration());
gen.writeEndObject();
}
gen.writeEndArray();
gen.writeNumberField("total", total);
gen.writeEndObject();
}
});
}
use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.
the class ResponseSnapshot method toResponse.
public Response toResponse() {
Response result = new Response();
result.setHeader(convertHeader());
result.setBody(convertBody());
result.setStatusCode(getStatusCode());
result.setStatusMessage(getStatusMessage());
return result;
}
Aggregations