use of com.predic8.membrane.core.http.Body in project service-proxy by membrane.
the class AMStatisticsCollector method sendJsonToElasticSearch.
private void sendJsonToElasticSearch(String path, String json) throws Exception {
Response resp = null;
synchronized (client) {
Exchange exc = new Request.Builder().put(getElasticSearchPath(path)).body(json).buildExchange();
if (clientId != null && clientSecret != null)
exc.getRequest().getHeader().add(Header.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes("UTF-8")), "UTF-8"));
resp = client.call(exc).getResponse();
}
if (!resp.isOk())
log.warn("Could not send statistics to elastic search instance. Response: " + resp.getStatusCode() + " - " + resp.getStatusMessage() + " - " + resp.getBodyAsStringDecoded());
}
use of com.predic8.membrane.core.http.Body in project service-proxy by membrane.
the class TelekomSMSTokenProvider method sendSMS.
@Override
protected void sendSMS(String text, String recipientNumber) {
recipientNumber = recipientNumber.replaceAll("^00", "\\+");
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jg = jsonFactory.createGenerator(baos, JsonEncoding.UTF8);
jg.writeStartObject();
jg.writeObjectFieldStart("outboundSMSMessageRequest");
jg.writeArrayFieldStart("address");
jg.writeString("tel:" + recipientNumber);
jg.writeEndArray();
jg.writeStringField("senderAddress", senderAddress);
jg.writeObjectFieldStart("outboundSMSTextMessage");
jg.writeStringField("message", text);
jg.writeEndObject();
jg.writeStringField("outboundEncoding", "7bitGSM");
jg.writeStringField("clientCorrelator", "" + ((long) (Math.random() * Long.MAX_VALUE)));
if (senderName != null)
jg.writeStringField("senderName", senderName);
jg.writeEndObject();
jg.writeEndObject();
jg.close();
Exchange exc = new Request.Builder().post("https://gateway.developer.telekom.com/plone/sms/rest/" + environment.name().toLowerCase() + "/smsmessaging/v1/outbound/" + URLEncoder.encode(senderAddress, "UTF-8") + "/requests").header("Host", "gateway.developer.telekom.com").header("Authorization", "OAuth realm=\"developergarden.com\",oauth_token=\"" + getAccessToken() + "\"").header("Accept", "application/json").header("Content-Type", "application/json").body(baos.toByteArray()).buildExchange();
hc.call(exc, false, true);
if (exc.getResponse().getStatusCode() != 201)
throw new RuntimeException("Could not send SMS: " + exc.getResponse());
log.debug("sent SMS to " + recipientNumber);
} catch (Exception e2) {
throw new RuntimeException(e2);
}
}
use of com.predic8.membrane.core.http.Body in project service-proxy by membrane.
the class TelekomSMSTokenProvider method getAccessToken.
private synchronized String getAccessToken() throws Exception {
long now = System.currentTimeMillis();
if (token == null || tokenExpiration < now) {
Exchange exc = new Request.Builder().post("https://global.telekom.com/gcp-web-api/oauth").header(Header.HOST, "global.telekom.com").header(Header.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes("UTF-8")), "UTF-8")).header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.PRODUCT_NAME + " " + Constants.VERSION).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").body(new URLParamUtil.ParamBuilder().add("grant_type", "client_credentials").add("scope", scope).build()).buildExchange();
new HttpClient().call(exc, false, true);
if (exc.getResponse().getStatusCode() != 200)
throw new RuntimeException("Telekom Authentication Server returned: " + exc.getResponse());
HashMap<String, String> values = Util.parseSimpleJSONResponse(exc.getResponse());
if (!values.containsKey("access_token") || !values.containsKey("expires_in"))
throw new Exception("Telekom Authentication: Received 200 and JSON body, but no access_token or no expires_in.");
token = values.get("access_token");
tokenExpiration = Long.parseLong(values.get("expires_in")) + System.currentTimeMillis() - 2000;
}
return token;
}
use of com.predic8.membrane.core.http.Body in project service-proxy by membrane.
the class AbstractHttpHandler method generateErrorResponse.
private Response generateErrorResponse(Exception e) {
String msg;
boolean printStackTrace = transport.isPrintStackTrace();
if (printStackTrace) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
msg = sw.toString();
} else {
msg = e.toString();
}
String comment = "Stack traces can be " + (printStackTrace ? "dis" : "en") + "abled by setting the " + "@printStackTrace attribute on <a href=\"https://membrane-soa.org/service-proxy-doc/current/configuration/reference/transport.htm\">transport</a>. " + "More details might be found in the log.";
Response error = null;
ResponseBuilder b = null;
if (e instanceof URISyntaxException)
b = Response.badRequest();
if (b == null)
b = Response.internalServerError();
switch(ContentTypeDetector.detect(exchange.getRequest()).getEffectiveContentType()) {
case XML:
error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8)).body(("<error><message>" + StringEscapeUtils.escapeXml(msg) + "</message><comment>" + StringEscapeUtils.escapeXml(comment) + "</comment></error>").getBytes(Constants.UTF_8_CHARSET)).build();
break;
case JSON:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
JsonGenerator jg = new JsonFactory().createGenerator(baos);
jg.writeStartObject();
jg.writeFieldName("error");
jg.writeString(msg);
jg.writeFieldName("comment");
jg.writeString(comment);
jg.close();
} catch (Exception f) {
log.error("Error generating JSON error response", f);
}
error = b.header(HttpUtil.createHeaders(MimeType.APPLICATION_JSON_UTF8)).body(baos.toByteArray()).build();
break;
case SOAP:
error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8)).body(HttpUtil.getFaultSOAPBody("Internal Server Error", msg + " " + comment).getBytes(Constants.UTF_8_CHARSET)).build();
break;
case UNKNOWN:
error = HttpUtil.setHTMLErrorResponse(b, msg, comment);
break;
}
return error;
}
use of com.predic8.membrane.core.http.Body in project service-proxy by membrane.
the class HttpServerHandler method process.
private void process() throws Exception {
try {
DNSCache dnsCache = getTransport().getRouter().getDnsCache();
InetAddress remoteAddr = sourceSocket.getInetAddress();
String ip = dnsCache.getHostAddress(remoteAddr);
exchange.setRemoteAddrIp(ip);
exchange.setRemoteAddr(getTransport().isReverseDNS() ? dnsCache.getHostName(remoteAddr) : ip);
exchange.setRequest(srcReq);
exchange.setOriginalRequestUri(srcReq.getUri());
if (exchange.getRequest().getHeader().is100ContinueExpected()) {
final Request request = exchange.getRequest();
request.addObserver(new MessageObserver() {
public void bodyRequested(AbstractBody body) {
try {
if (request.getHeader().is100ContinueExpected()) {
// request body from client so that interceptors can handle it
Response.continue100().build().write(srcOut);
// remove "Expect: 100-continue" since we already sent "100 Continue"
request.getHeader().removeFields(Header.EXPECT);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void bodyComplete(AbstractBody body) {
}
});
}
invokeHandlers();
exchange.blockResponseIfNeeded();
} catch (AbortException e) {
log.debug("Aborted");
exchange.finishExchange(true, e.getMessage());
removeBodyFromBuffer();
writeResponse(exchange.getResponse());
log.debug("exchange set aborted");
return;
}
try {
removeBodyFromBuffer();
writeResponse(exchange.getResponse());
exchange.setCompleted();
log.debug("exchange set completed");
} catch (Exception e) {
exchange.finishExchange(true, e.getMessage());
throw e;
}
}
Aggregations