Package ch.tatool.app.export

Source Code of ch.tatool.app.export.CSVSessionDataExport

/*******************************************************************************
* Copyright (c) 2011 Michael Ruflin, Andr� Locher, Claudia von Bastian.
*
* This file is part of Tatool.
*
* Tatool is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tatool is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Tatool. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ch.tatool.app.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVWriter;

import ch.tatool.data.DataService;
import ch.tatool.data.Module;
import ch.tatool.data.ModuleSession;
import ch.tatool.data.DataContainer.Entry;

/**
* Exports session data into a CSV file. This is a helper class used by the
* various exporters
*
* @author Andre Locher
*/
public class CSVSessionDataExport {

  Logger logger = LoggerFactory.getLogger(CSVSessionDataExport.class);

  private DataService dataService;

  private List<String> baseProperties;
  private int basePropertiesSize;
  private List<String> sessionProperties;
  private int sessionPropertiesSize;

  public CSVSessionDataExport(DataService dataService) {
    this.dataService = dataService;

    // this won't change
    initBaseProperties();
  }

  /**
   * Exports the session data and stores the results in the provided Writer
   *
   * @param module
   * @param file
   *            the file to write the data to
   * @return a file containing the module data or null in case an error
   *         occured
   */
  public File exportData(Module module, int fromSessionIndex) {
    // initialize the trial properties
    initSessionProperties(module);

    // create a writer
    try {
      File tmpFile = File.createTempFile("sessionData", "csv");
      FileOutputStream fos = new FileOutputStream(tmpFile, false);
      CSVWriter writer = new CSVWriter(new OutputStreamWriter(fos,
          "ISO-8859-1"), ';');

      // write the csv file header
      List<String> headers = new ArrayList<String>(baseProperties);
      headers.addAll(sessionProperties);
      writer.writeNext(headers.toArray(new String[headers.size()]));

      // fetch each session and trial, write one line for each trial
      List<ModuleSession> sessions = dataService.getSessions(module);
      for (ModuleSession session : sessions) {
        // skip if we only export some of the session
        if (fromSessionIndex >= 0
            && session.getIndex() < fromSessionIndex) {
          continue;
        }
        List<String[]> sessionData = getDataForSession(session);
        writer.writeAll(sessionData);
      }

      // close the writer and return the file
      writer.close();
      return tmpFile;
    } catch (IOException ioe) {
      logger.error("Unable to write csv file", ioe);
      return null;
    }
  }

  /** Returns a list with all to be written values for a given trial object. */
  private List<String[]> getDataForSession(ModuleSession session) {
    List<String[]> data = new ArrayList<String[]>(basePropertiesSize
        + sessionPropertiesSize);

    // add trial properties
    addSessionProperties(session, data);

    // done already
    return data;
  }

  // Base properties management

  /** Basic properties which are always written. */
  private void initBaseProperties() {
    baseProperties = new ArrayList<String>();

    // Module related
    baseProperties.add("Module id");
    baseProperties.add("Module name");

    // Session related
    baseProperties.add("Session id");
    baseProperties.add("Session index");
    baseProperties.add("Session start time");
    baseProperties.add("Session end time");
    baseProperties.add("Session completed");

    basePropertiesSize = baseProperties.size();
  }

  private String[] getBaseProperties(ModuleSession session) {
    // session related
    String[] baseProps = new String[7];
    baseProps[0] = session.getModule().getId().toString();
    baseProps[1] = session.getModule().getName();
    baseProps[2] = session.getId().toString();
    baseProps[3] = session.getIndex() + "";

    SimpleDateFormat dateformat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");
    StringBuilder sessionStartTime = new StringBuilder("");
    StringBuilder sessionEndTime = new StringBuilder("");
    if (session.getStartTime() != null) {
      sessionStartTime = new StringBuilder(dateformat.format(session
          .getStartTime()));
    }
    if (session.getEndTime() != null) {
      sessionEndTime = new StringBuilder(dateformat.format(session
          .getEndTime()));
    }

    baseProps[4] = sessionStartTime.toString();
    baseProps[5] = sessionEndTime.toString();
   
    baseProps[6] = String.valueOf(session.getCompleted());

    return baseProps;
  }

  private void addToData(List<String[]> data, String[] values) {
    if (values != null) {
      data.add(values);
    }
  }

  // Session properties management

  private void initSessionProperties(Module module) {
    // add additional headers for session properties
    sessionProperties = new ArrayList<String>();
    sessionProperties.add("ELEMENT_ID");
    sessionProperties.add("PROPERTY_NAME");
    sessionProperties.add("PROPERTY_VALUE");
    sessionPropertiesSize = sessionProperties.size();
  }

  /**
   * Adds the session properties to the data object
   */
  private void addSessionProperties(ModuleSession session, List<String[]> data) {
    List<String> sessionProps = null;
    if (session.getEntries().isEmpty()) {
      sessionProps = new ArrayList<String>();
      sessionProps.addAll(Arrays.asList(getBaseProperties(session)));
      addToData(data, sessionProps.toArray(new String[sessionProps.size()]));
    } else {
      for (Entry p : session.getEntries()) {
        sessionProps = new ArrayList<String>();
        sessionProps.addAll(Arrays.asList(getBaseProperties(session)));
        sessionProps.add(p.getNodeId());
        sessionProps.add(p.getName());
        sessionProps.add(p.getValue());
        addToData(data, sessionProps.toArray(new String[sessionProps
            .size()]));
      }
    }
  }
}
TOP

Related Classes of ch.tatool.app.export.CSVSessionDataExport

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.