public final class DebugLogger implements Http {
private static final Logger log = LoggerFactory.getLogger(DebugLogger.class);
private final Hashtable<String, String> propertyList = new Hashtable<String, String>();
private final StringBuffer message = new StringBuffer();
private final ArrayList<MimeAttachment> httpList = new ArrayList<MimeAttachment>();
private final ArrayList<String> fieldList = new ArrayList<String>();
private final ArrayList<String[]> rangeList = new ArrayList<String[]>();
private final PlaneStage stage;
/**
* Constructor
* @param stage
* @throws NullPointerException
*/
public DebugLogger(PlaneStage stage) throws NullPointerException {
if (stage == null) {
throw new NullPointerException();
}
this.stage = stage;
}
/**
* cleanup
*/
public void cleanup() {
propertyList.clear();
message.setLength(0);
httpList.clear();
fieldList.clear();
rangeList.clear();
}
//根据表单字段值过滤显示内容
/**
* mask form field content
* @param name
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void maskField(String name) throws NullPointerException, IllegalArgumentException {
if (name == null) {
throw new NullPointerException();
}
String fieldName = new String(name.trim().toLowerCase());
if (fieldName.length() == 0) {
throw new IllegalArgumentException("Illegal mask form field name /"" + name + "/"");
}
if (!fieldList.contains(fieldName)) {
fieldList.add(fieldName);
}
}
//根据起始关键字过滤一段内容中的内容
/**
* mask content inside delimiters range
* @param begin
* @param end
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void maskRange(String begin, String end) throws NullPointerException, IllegalArgumentException {
if (begin == null || end == null) {
throw new NullPointerException();
}
String beginDelimiter = new String(begin.toLowerCase());
String endDelimiter = new String(end.toLowerCase());
if (beginDelimiter.length() == 0) {
throw new IllegalArgumentException("Illegal mask range begin delimiter /"" + begin + "/"");
}
if (endDelimiter.length() == 0) {
throw new IllegalArgumentException("Illegal mask range end delimiter /"" + end + "/"");
}
if (beginDelimiter.trim().length() == 0 && endDelimiter.trim().length() == 0) {
throw new IllegalArgumentException("Illegal mask range delimiters");
}
for (String[] range : rangeList) {
System.err.println("===========");
System.err.println(begin+" "+range[0]);
System.err.println(endDelimiter+" "+range[1]);
if (range[0].equals(beginDelimiter) && range[1].equals(endDelimiter)) {
System.err.println("----------Yes-------------");
System.err.println(begin+end);
return;
}
}
rangeList.add(new String[]{beginDelimiter, endDelimiter});
}
//向这个log日志文件中添加内容并在 特殊位置显示
/**
* log property
* @param key
* @param value
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void logProperty(String key, String value) throws NullPointerException, IllegalArgumentException {
if (key == null) {
throw new NullPointerException();
}
String propertyKey = new String(key.trim().toUpperCase());
if (propertyKey.length() == 0) {
throw new IllegalArgumentException("Illegal property key /"" + key + "/"");
}
propertyList.put(propertyKey, ((value != null) ? new String(value) : ""));
}
//向log日志中添加普通信息
/**
* log message
* @param buffer
* @param title
* @throws NullPointerException
*/
public final void logMessage(String buffer, String title) throws NullPointerException {
if (buffer == null || title == null) {
throw new NullPointerException();
}
logMessage(new StringBuffer(buffer), title, false);
}
//向头部插入普通信息
/**
* log message
* @param buffer
* @param title
* @param insert
*/
private final void logMessage(StringBuffer buffer, String title, boolean insert) {
StringBuffer log = new StringBuffer();
log.append("[" + new UtilDate().toString("dd/MM/yyyy-HH:mm:ss") + "]/t{" + title + "}/n");
log.append("/n" + buffer + "/n");
log.append("/n[EOF]/t{" + title + "}/n/n");
if (insert) {
message.insert(0, log.toString());
} else {
message.append(log.toString());
}
}
//截取request信息并放在log日志中
/**
* log http message
* @param buffer
* @param title
* @param request
*/
private final void logHttp(StringBuffer buffer, String title, boolean request) {
String fileName = ((request) ? "request" : "response") + "-" + title.replaceAll("[^0-9a-zA-Z_-]", "");
try {
byte[] content = new Gzip().compressString(buffer.toString(), Charsets.UTF_8);
httpList.add(new MimeAttachment(fileName + ".gz", MimeTypes.APPLICATION_X_GZIP, content));
} catch (Throwable t) {
log.error("Exception raised while gzip compressing the http message buffer", t);
httpList.add(new MimeAttachment(fileName + ".txt", MimeTypes.TEXT_PLAIN, buffer.toString().getBytes()));
}
}
//过滤内容根据起始唯一字符串
/**
* filter content
* @param buffer
* @param begin
* @param content
*/
private final void filterContent(StringBuffer buffer, int begin, String content) {
int index = 0;
int length = content.length();
if (content.matches("[0-9]{12,16}")) {
index += 4;
length -= 4;
}
for (int x = index; x < length; x++) {
buffer.setCharAt(begin + x, '*');
}
}
//过滤表单字段
/**
* filter fields content
* @param buffer
* @param query
*/
private final void filterFields(StringBuffer buffer, StringBuffer query) {
StringBuffer queryLowerCase = new StringBuffer(query.toString().toLowerCase());
for (String fieldName : fieldList) {
String begin = fieldName + "=";
int position = 0;
int index = -1;
while ((index = queryLowerCase.indexOf(begin, position)) != -1) {
int bIndex = index + begin.length();
int eIndex = query.indexOf("&", bIndex);
String value;
if (eIndex != -1) {
value = query.substring(bIndex, eIndex);
} else {
value = query.substring(bIndex);
}
filterContent(query, bIndex, value);
position = bIndex;
}
}
buffer.append(query);
}
//过滤字符串 针对某个内容对象
/**
* filter content inside delimiters range
* @param buffer
*/
private final void filterRanges(StringBuffer buffer) {
StringBuffer bufferLowerCase = new StringBuffer(buffer.toString().toLowerCase());
for (String[] range : rangeList) {
int position = 0;
int index = -1;
while ((index = bufferLowerCase.indexOf(range[0], position)) != -1) {
int bIndex = index + range[0].length();
int eIndex = bufferLowerCase.indexOf(range[1], bIndex);
if (eIndex != -1) {
filterContent(buffer, bIndex, buffer.substring(bIndex, eIndex));
} else {
break;
}
position = bIndex;
}
}
}
//过滤 request 的header信息
/**
* filter http message
* @param buffer
* @param message
* @param request
*/
private final void filterHttp(StringBuffer buffer, HttpMessage message, boolean request) {
HttpHeaderList headers = message.getHeaderList();
for (int i = 0; i < headers.size(); i++) {
HttpHeader header = headers.getHeader(i);
buffer.append(header.getName());
buffer.append(COLON);
buffer.append(SPACE);
buffer.append(header.getValue());
buffer.append(NEW_LINE);
}
buffer.append(NEW_LINE);
if (request) {
filterFields(buffer, new StringBuffer().append(message.getContent()));
} else {
buffer.append(message.getContent());
}
filterRanges(buffer);
}
//记录请求信息
/**
* log request
* @param title
* @throws NullPointerException
*/
public final void logRequest(String title) throws NullPointerException {
if (title == null) {
throw new NullPointerException();
}
if (stage.getDownloader() == null) {
return;
}
HttpRequest request = stage.getDownloader().getRequest();
if (request == null) {
return;
}
try {
StringBuffer buffer = new StringBuffer();
buffer.append(request.getMethod());
buffer.append(SPACE);
filterFields(buffer, new StringBuffer().append(request.getUrl()));
buffer.append(SPACE);
buffer.append(request.getVersion());
buffer.append(NEW_LINE);
filterHttp(buffer, request, true);
logHttp(buffer, title, true);
} catch (Throwable t) {
log.error("Exception raised while logging http request", t);
}
}
//记录返回结果信息
/**
* log response
* @param title
* @throws NullPointerException
*/
public final void logResponse(String title) throws NullPointerException {
if (title == null) {
throw new NullPointerException();
}
if (stage.getDownloader() == null) {
return;
}
HttpResponse response = stage.getDownloader().getResponse();
if (response == null) {
return;
}
try {
StringBuffer buffer = new StringBuffer();
buffer.append(response.getVersion());
buffer.append(SPACE);
buffer.append(response.getCode());
buffer.append(SPACE);
buffer.append(response.getReason());
buffer.append(NEW_LINE);
filterHttp(buffer, response, false);
logHttp(buffer, title, false);
} catch (Throwable t) {
log.error("Exception raised while logging http response", t);
}
}
//记录抛出的异常信息
/**
* log throwable
* @param throwable
* @throws NullPointerException
*/
public final void logThrowable(Throwable throwable) throws NullPointerException {
if (throwable == null) {
throw new NullPointerException();
}
logMessage(new StringBuffer().append(Text.getStackTrace(throwable)), "EXCEPTION STACK", true);
}
//发送log到某个邮箱
/**
* send debugging logs over email
* @param recipient
* @param title
* @throws NullPointerException
*/
public final void send(String recipient, String title) throws NullPointerException {
if (recipient == null || title == null) {
throw new NullPointerException();
}
send(new String[]{recipient}, title);
}
//发送log到邮箱
/**
* send debugging logs over email
* @param recipients
* @param title
* @throws NullPointerException
*/
public final void send(String[] recipients, String title) throws NullPointerException {
if (recipients == null || title == null) {
throw new NullPointerException();
}
StringBuffer subject = new StringBuffer();
subject.append(stage.getSupplierName().getCaseSensitive()).append(" ").append(title);
if (stage instanceof PlaneStageBooking) {
subject.append(" [");
try {
subject.append(((PlaneStageBooking) stage).getBookingRequest().getTFBookingReference());
} catch (Exception e) {
subject.append("TFREF_ERROR");
}
subject.append("]");
}
subject.append(" [" + IpAddress.getLocalAddress() + "]");
try {
StringBuffer body = new StringBuffer();
if (propertyList.size() > 0) {
body.append("[PROPERTIES]/n/n");
Enumeration<String> propertyKeys = propertyList.keys();
while (propertyKeys.hasMoreElements()) {
String propertyKey = propertyKeys.nextElement();
String propertyValue = propertyList.get(propertyKey);
if (propertyValue.length() > 0) {
body.append("/"" + propertyKey + "/" = /"" + propertyValue + "/"/n");
}
}
body.append("/n/n");
}
if (message.length() > 0) {
body.append("[MESSAGES]/n/n").append(message);
}
MimeAttachment[] attachments = new MimeAttachment[httpList.size()];
for (int x = 0; x < httpList.size(); x++) {
attachments[x] = httpList.get(x);
}
for (int x = 0; x < recipients.length; x++) {
if (recipients[x] != null) {
Email.send(EmailConfig.getDefaultSender(), recipients[x], subject.toString(), body.toString().trim(), false, MimeTypes.TEXT_PLAIN, attachments);
}
}
} catch (Throwable t) {
log.error("Exception raised while sending logger debugging email(s)", t);
}
}
}
private static final Logger log = LoggerFactory.getLogger(DebugLogger.class);
private final Hashtable<String, String> propertyList = new Hashtable<String, String>();
private final StringBuffer message = new StringBuffer();
private final ArrayList<MimeAttachment> httpList = new ArrayList<MimeAttachment>();
private final ArrayList<String> fieldList = new ArrayList<String>();
private final ArrayList<String[]> rangeList = new ArrayList<String[]>();
private final PlaneStage stage;
/**
* Constructor
* @param stage
* @throws NullPointerException
*/
public DebugLogger(PlaneStage stage) throws NullPointerException {
if (stage == null) {
throw new NullPointerException();
}
this.stage = stage;
}
/**
* cleanup
*/
public void cleanup() {
propertyList.clear();
message.setLength(0);
httpList.clear();
fieldList.clear();
rangeList.clear();
}
//根据表单字段值过滤显示内容
/**
* mask form field content
* @param name
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void maskField(String name) throws NullPointerException, IllegalArgumentException {
if (name == null) {
throw new NullPointerException();
}
String fieldName = new String(name.trim().toLowerCase());
if (fieldName.length() == 0) {
throw new IllegalArgumentException("Illegal mask form field name /"" + name + "/"");
}
if (!fieldList.contains(fieldName)) {
fieldList.add(fieldName);
}
}
//根据起始关键字过滤一段内容中的内容
/**
* mask content inside delimiters range
* @param begin
* @param end
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void maskRange(String begin, String end) throws NullPointerException, IllegalArgumentException {
if (begin == null || end == null) {
throw new NullPointerException();
}
String beginDelimiter = new String(begin.toLowerCase());
String endDelimiter = new String(end.toLowerCase());
if (beginDelimiter.length() == 0) {
throw new IllegalArgumentException("Illegal mask range begin delimiter /"" + begin + "/"");
}
if (endDelimiter.length() == 0) {
throw new IllegalArgumentException("Illegal mask range end delimiter /"" + end + "/"");
}
if (beginDelimiter.trim().length() == 0 && endDelimiter.trim().length() == 0) {
throw new IllegalArgumentException("Illegal mask range delimiters");
}
for (String[] range : rangeList) {
System.err.println("===========");
System.err.println(begin+" "+range[0]);
System.err.println(endDelimiter+" "+range[1]);
if (range[0].equals(beginDelimiter) && range[1].equals(endDelimiter)) {
System.err.println("----------Yes-------------");
System.err.println(begin+end);
return;
}
}
rangeList.add(new String[]{beginDelimiter, endDelimiter});
}
//向这个log日志文件中添加内容并在 特殊位置显示
/**
* log property
* @param key
* @param value
* @throws NullPointerException
* @throws IllegalArgumentException
*/
public final void logProperty(String key, String value) throws NullPointerException, IllegalArgumentException {
if (key == null) {
throw new NullPointerException();
}
String propertyKey = new String(key.trim().toUpperCase());
if (propertyKey.length() == 0) {
throw new IllegalArgumentException("Illegal property key /"" + key + "/"");
}
propertyList.put(propertyKey, ((value != null) ? new String(value) : ""));
}
//向log日志中添加普通信息
/**
* log message
* @param buffer
* @param title
* @throws NullPointerException
*/
public final void logMessage(String buffer, String title) throws NullPointerException {
if (buffer == null || title == null) {
throw new NullPointerException();
}
logMessage(new StringBuffer(buffer), title, false);
}
//向头部插入普通信息
/**
* log message
* @param buffer
* @param title
* @param insert
*/
private final void logMessage(StringBuffer buffer, String title, boolean insert) {
StringBuffer log = new StringBuffer();
log.append("[" + new UtilDate().toString("dd/MM/yyyy-HH:mm:ss") + "]/t{" + title + "}/n");
log.append("/n" + buffer + "/n");
log.append("/n[EOF]/t{" + title + "}/n/n");
if (insert) {
message.insert(0, log.toString());
} else {
message.append(log.toString());
}
}
//截取request信息并放在log日志中
/**
* log http message
* @param buffer
* @param title
* @param request
*/
private final void logHttp(StringBuffer buffer, String title, boolean request) {
String fileName = ((request) ? "request" : "response") + "-" + title.replaceAll("[^0-9a-zA-Z_-]", "");
try {
byte[] content = new Gzip().compressString(buffer.toString(), Charsets.UTF_8);
httpList.add(new MimeAttachment(fileName + ".gz", MimeTypes.APPLICATION_X_GZIP, content));
} catch (Throwable t) {
log.error("Exception raised while gzip compressing the http message buffer", t);
httpList.add(new MimeAttachment(fileName + ".txt", MimeTypes.TEXT_PLAIN, buffer.toString().getBytes()));
}
}
//过滤内容根据起始唯一字符串
/**
* filter content
* @param buffer
* @param begin
* @param content
*/
private final void filterContent(StringBuffer buffer, int begin, String content) {
int index = 0;
int length = content.length();
if (content.matches("[0-9]{12,16}")) {
index += 4;
length -= 4;
}
for (int x = index; x < length; x++) {
buffer.setCharAt(begin + x, '*');
}
}
//过滤表单字段
/**
* filter fields content
* @param buffer
* @param query
*/
private final void filterFields(StringBuffer buffer, StringBuffer query) {
StringBuffer queryLowerCase = new StringBuffer(query.toString().toLowerCase());
for (String fieldName : fieldList) {
String begin = fieldName + "=";
int position = 0;
int index = -1;
while ((index = queryLowerCase.indexOf(begin, position)) != -1) {
int bIndex = index + begin.length();
int eIndex = query.indexOf("&", bIndex);
String value;
if (eIndex != -1) {
value = query.substring(bIndex, eIndex);
} else {
value = query.substring(bIndex);
}
filterContent(query, bIndex, value);
position = bIndex;
}
}
buffer.append(query);
}
//过滤字符串 针对某个内容对象
/**
* filter content inside delimiters range
* @param buffer
*/
private final void filterRanges(StringBuffer buffer) {
StringBuffer bufferLowerCase = new StringBuffer(buffer.toString().toLowerCase());
for (String[] range : rangeList) {
int position = 0;
int index = -1;
while ((index = bufferLowerCase.indexOf(range[0], position)) != -1) {
int bIndex = index + range[0].length();
int eIndex = bufferLowerCase.indexOf(range[1], bIndex);
if (eIndex != -1) {
filterContent(buffer, bIndex, buffer.substring(bIndex, eIndex));
} else {
break;
}
position = bIndex;
}
}
}
//过滤 request 的header信息
/**
* filter http message
* @param buffer
* @param message
* @param request
*/
private final void filterHttp(StringBuffer buffer, HttpMessage message, boolean request) {
HttpHeaderList headers = message.getHeaderList();
for (int i = 0; i < headers.size(); i++) {
HttpHeader header = headers.getHeader(i);
buffer.append(header.getName());
buffer.append(COLON);
buffer.append(SPACE);
buffer.append(header.getValue());
buffer.append(NEW_LINE);
}
buffer.append(NEW_LINE);
if (request) {
filterFields(buffer, new StringBuffer().append(message.getContent()));
} else {
buffer.append(message.getContent());
}
filterRanges(buffer);
}
//记录请求信息
/**
* log request
* @param title
* @throws NullPointerException
*/
public final void logRequest(String title) throws NullPointerException {
if (title == null) {
throw new NullPointerException();
}
if (stage.getDownloader() == null) {
return;
}
HttpRequest request = stage.getDownloader().getRequest();
if (request == null) {
return;
}
try {
StringBuffer buffer = new StringBuffer();
buffer.append(request.getMethod());
buffer.append(SPACE);
filterFields(buffer, new StringBuffer().append(request.getUrl()));
buffer.append(SPACE);
buffer.append(request.getVersion());
buffer.append(NEW_LINE);
filterHttp(buffer, request, true);
logHttp(buffer, title, true);
} catch (Throwable t) {
log.error("Exception raised while logging http request", t);
}
}
//记录返回结果信息
/**
* log response
* @param title
* @throws NullPointerException
*/
public final void logResponse(String title) throws NullPointerException {
if (title == null) {
throw new NullPointerException();
}
if (stage.getDownloader() == null) {
return;
}
HttpResponse response = stage.getDownloader().getResponse();
if (response == null) {
return;
}
try {
StringBuffer buffer = new StringBuffer();
buffer.append(response.getVersion());
buffer.append(SPACE);
buffer.append(response.getCode());
buffer.append(SPACE);
buffer.append(response.getReason());
buffer.append(NEW_LINE);
filterHttp(buffer, response, false);
logHttp(buffer, title, false);
} catch (Throwable t) {
log.error("Exception raised while logging http response", t);
}
}
//记录抛出的异常信息
/**
* log throwable
* @param throwable
* @throws NullPointerException
*/
public final void logThrowable(Throwable throwable) throws NullPointerException {
if (throwable == null) {
throw new NullPointerException();
}
logMessage(new StringBuffer().append(Text.getStackTrace(throwable)), "EXCEPTION STACK", true);
}
//发送log到某个邮箱
/**
* send debugging logs over email
* @param recipient
* @param title
* @throws NullPointerException
*/
public final void send(String recipient, String title) throws NullPointerException {
if (recipient == null || title == null) {
throw new NullPointerException();
}
send(new String[]{recipient}, title);
}
//发送log到邮箱
/**
* send debugging logs over email
* @param recipients
* @param title
* @throws NullPointerException
*/
public final void send(String[] recipients, String title) throws NullPointerException {
if (recipients == null || title == null) {
throw new NullPointerException();
}
StringBuffer subject = new StringBuffer();
subject.append(stage.getSupplierName().getCaseSensitive()).append(" ").append(title);
if (stage instanceof PlaneStageBooking) {
subject.append(" [");
try {
subject.append(((PlaneStageBooking) stage).getBookingRequest().getTFBookingReference());
} catch (Exception e) {
subject.append("TFREF_ERROR");
}
subject.append("]");
}
subject.append(" [" + IpAddress.getLocalAddress() + "]");
try {
StringBuffer body = new StringBuffer();
if (propertyList.size() > 0) {
body.append("[PROPERTIES]/n/n");
Enumeration<String> propertyKeys = propertyList.keys();
while (propertyKeys.hasMoreElements()) {
String propertyKey = propertyKeys.nextElement();
String propertyValue = propertyList.get(propertyKey);
if (propertyValue.length() > 0) {
body.append("/"" + propertyKey + "/" = /"" + propertyValue + "/"/n");
}
}
body.append("/n/n");
}
if (message.length() > 0) {
body.append("[MESSAGES]/n/n").append(message);
}
MimeAttachment[] attachments = new MimeAttachment[httpList.size()];
for (int x = 0; x < httpList.size(); x++) {
attachments[x] = httpList.get(x);
}
for (int x = 0; x < recipients.length; x++) {
if (recipients[x] != null) {
Email.send(EmailConfig.getDefaultSender(), recipients[x], subject.toString(), body.toString().trim(), false, MimeTypes.TEXT_PLAIN, attachments);
}
}
} catch (Throwable t) {
log.error("Exception raised while sending logger debugging email(s)", t);
}
}
}