001: /*
002: * HexBlobFormatter.java
003: *
004: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005: *
006: * Copyright 2002-2008, Thomas Kellerer
007: * No part of this code maybe reused without the permission of the author
008: *
009: * To contact the author please send an email to: support@sql-workbench.net
010: *
011: */
012: package workbench.storage;
013:
014: import java.sql.Blob;
015: import java.sql.SQLException;
016: import workbench.util.NumberStringCache;
017: import workbench.util.StringUtil;
018:
019: /**
020: * @author support@sql-workbench.net
021: */
022: public class DefaultBlobFormatter implements BlobLiteralFormatter {
023: private String prefix;
024: private String suffix;
025: private boolean upperCase = false;
026: private BlobLiteralType literalType = BlobLiteralType.hex;
027:
028: public DefaultBlobFormatter() {
029: }
030:
031: public void setLiteralType(BlobLiteralType type) {
032: this .literalType = (type == null ? BlobLiteralType.hex : type);
033: }
034:
035: public void setUseUpperCase(boolean flag) {
036: this .upperCase = flag;
037: }
038:
039: public void setPrefix(String p) {
040: this .prefix = p;
041: }
042:
043: public void setSuffix(String s) {
044: this .suffix = s;
045: }
046:
047: public String getBlobLiteral(Object value) throws SQLException {
048: if (value == null)
049: return null;
050:
051: int addSpace = (prefix != null ? prefix.length() : 0);
052: addSpace += (suffix != null ? suffix.length() : 0);
053:
054: StringBuilder result = null;
055:
056: if (value instanceof byte[]) {
057: byte[] buffer = (byte[]) value;
058: result = new StringBuilder(buffer.length * 2 + addSpace);
059: if (prefix != null)
060: result.append(prefix);
061: appendArray(result, buffer);
062: } else if (value instanceof Blob) {
063: Blob b = (Blob) value;
064: int len = (int) b.length();
065: result = new StringBuilder(len * 2 + addSpace);
066: if (prefix != null)
067: result.append(prefix);
068: for (int i = 0; i < len; i++) {
069: byte[] byteBuffer = b.getBytes(i, 1);
070: appendArray(result, byteBuffer);
071: }
072: } else {
073: String s = value.toString();
074: result = new StringBuilder(s.length() + addSpace);
075: if (prefix != null)
076: result.append(prefix);
077: result.append(s);
078: }
079: if (suffix != null)
080: result.append(suffix);
081: return result.toString();
082: }
083:
084: private void appendArray(StringBuilder result, byte[] buffer) {
085: for (int i = 0; i < buffer.length; i++) {
086: int c = (buffer[i] < 0 ? 256 + buffer[i] : buffer[i]);
087: CharSequence s = null;
088: if (literalType == BlobLiteralType.octal) {
089: result.append("\\");
090: s = StringUtil.getOctalString(c);
091: } else {
092: s = NumberStringCache.getHexString(c);
093: }
094:
095: if (upperCase) {
096: result.append(s.toString().toUpperCase());
097: } else {
098: result.append(s);
099: }
100: }
101: }
102:
103: }
|