All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mentalog.encoder.ThrowableEncoder Maven / Gradle / Ivy

There is a newer version: 2.1.2
Show newest version
package org.mentalog.encoder;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;

public class ThrowableEncoder implements Encoder {

	@Override
	public boolean encode(Object obj, ByteBuffer bb, int varargsPos, int varargsLen) {

		if (obj instanceof Throwable) {

			Throwable t = (Throwable) obj;

			if (varargsPos == varargsLen - 1) { // last argument...
				String s = getStackTrace(t); // sorry...
				bb.put((byte) '\n');
				transfer(s, bb);
			} else {
				transferToString(t, bb);
			}
			
			return true;
		}
		return false;
	}

	private final static void transfer(CharSequence s, ByteBuffer bb) {
		int len = s.length();
		for (int i = 0; i < len; i++) {
			bb.put((byte) s.charAt(i));
		}
	}

	private final static void transferToString(Throwable t, ByteBuffer bb) {
		transfer(t.getClass().getName(), bb);
		String msg = t.getLocalizedMessage();
		if (msg != null) {
			bb.put((byte) ':');
			bb.put((byte) ' ');
			transfer(msg, bb);
		}
	}

	public static String getStackTrace(Throwable throwable) {
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		throwable.printStackTrace(printWriter);
		return writer.toString();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy