Convert CQL query result file hex to ascii

Under Cassandra-2.0.17, I want to query a table by cqlsh

First of all, I put query in a file: ~/query.cql
select * from "myData" LIMIT 50000;

Then use cqlsh to execute command, output to file
cqlsh -k mykeyspace -f ~/query.cql > ~/query.out

or 

cqlsh -k wsg -e 'select * from "mykeyspace" LIMIT 50000;' > ~/query.out

Query result format looks like as follows
key                                                                        | 5f6261636b7570546167                                         
----------------------------------------------------------------------------+--------------------------------------------------------------
0x36346265303431622d376335652d346530332d393964352d373135613939306636666532 |  bbb
0x61666637623538372d643537632d346662662d613265662d666262363164626163363138 |  aaa

This table contains many hex string in column name and values, so I convert hex to ASCII code by following code.
(Not sure only start with 5f and 0x is hex, in my case I only need handle this two)
public void convert() throws IOException {
    StringBuilder copy = new StringBuilder();
    File file = new File("C:\\query.out");
    for (String line: FileUtils.readLines(file, "UTF-8")) {
        if (line.startsWith("--")) continue;
        String[] splitted = StringUtils.splitString(line, " ");
        if (splitted.length < 2) continue;
        for (int i = 0; i < splitted.length; i++) {
            if (splitted[i].startsWith("5f") || splitted[i].startsWith("0x")) {
                splitted[i] = hexToAscii(splitted[i].substring(2));
            }
        }
        copy.append(Arrays.stream(splitted).filter(s -> !s.equals("|")).collect(Collectors.joining(","))).append("\n");
    }
    FileUtils.write(new File("C:\\query.copy"), copy.toString(), "UTF-8");
}


private static String hexToAscii(String hexStr) {
    StringBuilder output = new StringBuilder("");

    try {
        for (int i = 0; i < hexStr.length(); i += 2) {
            String str = hexStr.substring(i, i + 2);
            output.append((char) Integer.parseInt(str, 16));
        }
    } catch (NumberFormatException ex) {
        return hexStr;
    }

    return output.toString();
}

沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...