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

org.yamcs.utils.CommandHistoryFormatter Maven / Gradle / Ivy

There is a newer version: 5.10.1
Show newest version
package org.yamcs.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.yamcs.protobuf.Commanding.CommandHistoryAttribute;
import org.yamcs.protobuf.Commanding.CommandHistoryEntry;

import com.csvreader.CsvWriter;


/**
 * Formats command history entries. 
 * WARNING: the header composed of the columns names is not known at the beginning. Therefore this class writes all the values into a temporary file,
 *  and only at the end it writes the header into the passed buffer and copies the temporary file in there as well.
 * 
 * @author nm
 *
 */
public class CommandHistoryFormatter {
    private BufferedWriter writer;
    private HashMap columns=new HashMap();
    File tmpFile;
    static char DEFAULT_COLUMN_SEPARATOR = '\t';
    CsvWriter tmpCsvWriter;
    char columnSeparator;
    
    public CommandHistoryFormatter(BufferedWriter writer, char columnSeparator) throws IOException {
        this.writer = writer;
        this.columnSeparator = columnSeparator;
        tmpFile = File.createTempFile("cmdhist-out", null);
        BufferedWriter tmpWriter=new BufferedWriter(new FileWriter(tmpFile));
        tmpCsvWriter = new CsvWriter(tmpWriter, columnSeparator);
    }
    
    public CommandHistoryFormatter(BufferedWriter writer) throws IOException {
        this(writer, DEFAULT_COLUMN_SEPARATOR);
    }
    
    /**
     *returns the size in characters of the written command (without the separators)
    */
    public int writeCommand(CommandHistoryEntry che) throws IOException {
     //   System.out.println("che: "+che);
        ArrayList values=new ArrayList(columns.size());
               
        //initialize the list with nulls so we can do set later
        for(int i=0; i e:columns.entrySet()) {
            colNames[e.getValue()]=e.getKey();
        }
        CsvWriter csvWriter = new CsvWriter(writer, columnSeparator);
        csvWriter.writeRecord(colNames);
        writer.newLine();
        tmpCsvWriter.close();
        
        
        BufferedReader br = new BufferedReader(new FileReader(tmpFile));
        String line;
        while((line=br.readLine())!=null) {
            writer.write(line);
            writer.newLine();
        }
        tmpFile.delete();
        br.close();
        csvWriter.close();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy