days old
+ * or older. This has the potential to be a heavy call - it has to do
+ * complete directory listing and then recursively delete the files and
+ * directories as needed.
+ *
+ * Note: this method has not been tested as it is rather hard to write a
+ * junit test for!
+ *
+ * @param directories
+ * @return number of directories deleted
+ */
+ public static int cleanupOldFiles(File[] directories) {
+ int numDeleted = 0;
+ if (directories != null) {
+ for (int i = 0; i < directories.length; i++) {
+ if (FileUtil.deleteDirectory(directories[i])) {
+ FileUtil.log.info("Directory " + directories[i].getPath()
+ + " deleted.");
+ } else {
+ FileUtil.log
+ .info("Directory "
+ + directories[i].getPath()
+ + " partially deleted - some directories/files could not be deleted.");
+ }
+ numDeleted++;
+ }
+ }
+ return numDeleted;
}
- // calculate comparison date
- long newestDateToKeep = System.currentTimeMillis() - numDays * FileUtil.numMilliSecondsInADay;
- Date date = new Date(newestDateToKeep);
- FileUtil.log.info("Getting all temp zipfile expanded directories before " + date.toString()
- + " (server time) (" + newestDateToKeep + ")");
+ /**
+ * List files in temp directory older than numDays.
+ *
+ * @param numDays
+ * Number of days old that the directory should be to be deleted.
+ * Must be greater than 0
+ * @return array of files older than input date
+ * @throws FileUtilException
+ * if numDays <= 0
+ */
+ public static File[] getOldTempFiles(int numDays) throws FileUtilException {
+ // Contract checking
+ if (numDays < 0) {
+ throw new FileUtilException(
+ "Invalid getOldTempFiles call - the parameter numDays is "
+ + numDays + ". Must not be less than 0.");
+ }
- File tempSysDir = new File(FileUtil.TEMP_DIR);
- File candidates[] = tempSysDir.listFiles(new TempDirectoryFilter(newestDateToKeep, FileUtil.log));
- return candidates;
- }
+ // calculate comparison date
+ long newestDateToKeep = System.currentTimeMillis() - numDays
+ * FileUtil.numMilliSecondsInADay;
+ Date date = new Date(newestDateToKeep);
+ FileUtil.log
+ .info("Getting all temp zipfile expanded directories before "
+ + date.toString() + " (server time) ("
+ + newestDateToKeep + ")");
- /**
- * Recursively calculates size in bytes of given file or directory.
- *
- * @param file
- * @return Size in bytes.
- */
- public static long calculateFileSize(File file) {
- if (file != null) {
- if (file.isFile()) {
- return file.length();
- } else if (file.isDirectory()) {
- File[] fileList = file.listFiles();
- long totalSize = 0;
- if (fileList != null) {
- for (int i = 0; i < fileList.length; i++) {
- totalSize += calculateFileSize(fileList[i]);
- }
- return totalSize;
+ File tempSysDir = new File(FileUtil.TEMP_DIR);
+ File candidates[] = tempSysDir.listFiles(new TempDirectoryFilter(
+ newestDateToKeep, FileUtil.log));
+ return candidates;
+ }
+
+ /**
+ * Recursively calculates size in bytes of given file or directory.
+ *
+ * @param file
+ * @return Size in bytes.
+ */
+ public static long calculateFileSize(File file) {
+ if (file != null) {
+ if (file.isFile()) {
+ return file.length();
+ } else if (file.isDirectory()) {
+ File[] fileList = file.listFiles();
+ long totalSize = 0;
+ if (fileList != null) {
+ for (int i = 0; i < fileList.length; i++) {
+ totalSize += calculateFileSize(fileList[i]);
+ }
+ return totalSize;
+ } else {
+ return 0;
+ }
+ }
} else {
- return 0;
+ return 0;
}
- }
- } else {
- return 0;
+ return 0;
}
- return 0;
- }
- /**
- * Remove chars from a file name that may be invalid on a file system.
- *
- * @param name
- * @return a filename that can be saved to a file system.
- */
- public static String stripInvalidChars(String name) {
- name = name.replaceAll("\\\\", "");
- name = name.replaceAll("\\/", "");
- name = name.replaceAll("\\:", "");
- name = name.replaceAll("\\*", "");
- name = name.replaceAll("\\?", "");
- name = name.replaceAll("\\>", "");
- name = name.replaceAll("\\<", "");
- name = name.replaceAll("\\|", "");
- name = name.replaceAll("\\#", "");
- name = name.replaceAll("\\%", "");
- name = name.replaceAll("\\$", "");
- name = name.replaceAll("\\;", "");
- return name;
- }
+ /**
+ * Remove chars from a file name that may be invalid on a file system.
+ *
+ * @param name
+ * @return a filename that can be saved to a file system.
+ */
+ public static String stripInvalidChars(String name) {
+ name = name.replaceAll("\\\\", "");
+ name = name.replaceAll("\\/", "");
+ name = name.replaceAll("\\:", "");
+ name = name.replaceAll("\\*", "");
+ name = name.replaceAll("\\?", "");
+ name = name.replaceAll("\\>", "");
+ name = name.replaceAll("\\<", "");
+ name = name.replaceAll("\\|", "");
+ name = name.replaceAll("\\#", "");
+ name = name.replaceAll("\\%", "");
+ name = name.replaceAll("\\$", "");
+ name = name.replaceAll("\\;", "");
+ return name;
+ }
- /**
- * Encode a filename in such a way that the UTF-8 characters won't be munged during the download by a browser. Need
- * the request to work out the user's browser type
- *
- * @return encoded filename
- * @throws UnsupportedEncodingException
- */
- public static String encodeFilenameForDownload(HttpServletRequest request, String unEncodedFilename)
- throws UnsupportedEncodingException {
+ /**
+ * Encode a filename in such a way that the UTF-8 characters won't be munged
+ * during the download by a browser. Need the request to work out the user's
+ * browser type
+ *
+ * @return encoded filename
+ * @throws UnsupportedEncodingException
+ */
+ public static String encodeFilenameForDownload(HttpServletRequest request,
+ String unEncodedFilename) throws UnsupportedEncodingException {
- // Different browsers handle stream downloads differently LDEV-1243
- String agent = request.getHeader("USER-AGENT");
- String filename = null;
+ // Different browsers handle stream downloads differently LDEV-1243
+ String agent = request.getHeader("USER-AGENT");
+ String filename = null;
- if (null != agent && -1 != agent.indexOf("MSIE")) {
- // if MSIE then urlencode it
- filename = URLEncoder.encode(unEncodedFilename, FileUtil.ENCODING_UTF_8);
+ if (null != agent && -1 != agent.indexOf("MSIE")) {
+ // if MSIE then urlencode it
+ filename = URLEncoder.encode(unEncodedFilename,
+ FileUtil.ENCODING_UTF_8);
- } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
- // if Mozilla then base64 url_safe encoding
- filename = MimeUtility.encodeText(unEncodedFilename, FileUtil.ENCODING_UTF_8, "B");
+ } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
+ // if Mozilla then base64 url_safe encoding
+ filename = MimeUtility.encodeText(unEncodedFilename,
+ FileUtil.ENCODING_UTF_8, "B");
- } else {
- // any others use same filename.
- filename = unEncodedFilename;
+ } else {
+ // any others use same filename.
+ filename = unEncodedFilename;
+ }
+
+ return filename;
}
- return filename;
- }
+ public static String generateUniqueContentFolderID() {
- public static String generateUniqueContentFolderID() {
+ String newUniqueContentFolderID = null;
+ Properties props = new Properties();
- String newUniqueContentFolderID = null;
- Properties props = new Properties();
+ IdentifierGenerator uuidGen = new UUIDHexGenerator();
+ ((Configurable) uuidGen).configure(Hibernate.STRING, props, null);
- IdentifierGenerator uuidGen = new UUIDHexGenerator();
- ((Configurable) uuidGen).configure(Hibernate.STRING, props, null);
+ // lowercase to resolve OS issues
+ newUniqueContentFolderID = ((String) uuidGen.generate(null, null))
+ .toLowerCase();
- // lowercase to resolve OS issues
- newUniqueContentFolderID = ((String) uuidGen.generate(null, null)).toLowerCase();
+ return newUniqueContentFolderID;
+ }
- return newUniqueContentFolderID;
- }
+ /**
+ * Call xstream to get the POJOs from the XML file. To make it backwardly
+ * compatible we catch any exceptions due to added fields, remove the field
+ * using the ToolContentVersionFilter functionality and try to reparse. We
+ * can't nominate the problem fields in advance as we are making XML created
+ * by newer versions of LAMS compatible with an older version.
+ *
+ * This logic depends on the exception message containing the text. When we
+ * upgrade xstream, we must check that this message doesn't change.
+ *
+ *
+ * com.thoughtworks.xstream.converters.ConversionException: unknownField : unknownField
+ * ---- Debugging information ----
+ * required-type : org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO
+ * cause-message : unknownField : unknownField
+ * class : org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO
+ * message : unknownField : unknownField
+ * line number : 15
+ * path : /org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO/unknownField
+ * cause-exception : com.thoughtworks.xstream.alias.CannotResolveClassException
+ * -------------------------------
+ *
+ */
+ public static Object getObjectFromXML(XStream xStream, String fullFilePath)
+ throws JDOMException, IOException {
- /**
- * Call xstream to get the POJOs from the XML file. To make it backwardly compatible we catch any exceptions due to
- * added fields, remove the field using the ToolContentVersionFilter functionality and try to reparse. We can't
- * nominate the problem fields in advance as we are making XML created by newer versions of LAMS compatible with an
- * older version.
- *
- * This logic depends on the exception message containing the text. When we upgrade xstream, we must check that this
- * message doesn't change.
- *
- *
- * com.thoughtworks.xstream.converters.ConversionException: unknownField : unknownField
- * ---- Debugging information ----
- * required-type : org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO
- * cause-message : unknownField : unknownField
- * class : org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO
- * message : unknownField : unknownField
- * line number : 15
- * path : /org.lamsfoundation.lams.learningdesign.dto.LearningDesignDTO/unknownField
- * cause-exception : com.thoughtworks.xstream.alias.CannotResolveClassException
- * -------------------------------
- *
- */
- public static Object getObjectFromXML(XStream xStream, String fullFilePath) throws JDOMException, IOException {
+ Reader file = null;
+ XStream conversionXml = xStream != null ? xStream : new XStream();
+ ConversionException finalException = null;
+ String lastFieldRemoved = "";
+ ToolContentVersionFilter contentFilter = null;
+ // cap the maximum number of retries to 30 - if we add more than 30 new
+ // fields then we need to rethink our
+ // strategy
+ int maxRetries = 30;
+ int numTries = 0;
- Reader file = null;
- XStream conversionXml = xStream != null ? xStream : new XStream();
- ConversionException finalException = null;
- String lastFieldRemoved = "";
- ToolContentVersionFilter contentFilter = null;
- // cap the maximum number of retries to 30 - if we add more than 30 new
- // fields then we need to rethink our
- // strategy
- int maxRetries = 30;
- int numTries = 0;
+ while (true) {
+ try {
- while (true) {
- try {
+ if (numTries > maxRetries) {
+ break;
+ }
+ numTries++;
- if (numTries > maxRetries) {
- break;
- }
- numTries++;
+ file = new InputStreamReader(new FileInputStream(fullFilePath),
+ FileUtil.ENCODING_UTF_8);
+ return conversionXml.fromXML(file);
- file = new InputStreamReader(new FileInputStream(fullFilePath), FileUtil.ENCODING_UTF_8);
- return conversionXml.fromXML(file);
+ } catch (ConversionException ce) {
+ FileUtil.log.debug("Failed import", ce);
+ finalException = ce;
+ file.close();
- } catch (ConversionException ce) {
- FileUtil.log.debug("Failed import", ce);
- finalException = ce;
- file.close();
+ if (ce.getMessage() == null) {
+ // can't retry, so get out of here!
+ break;
- if (ce.getMessage() == null) {
- // can't retry, so get out of here!
- break;
+ } else {
+ // try removing the field from our XML and retry
+ String message = ce.getMessage();
+ String classname = extractValue(message, "required-type");
+ String fieldname = extractValue(message, "message");
+ if (fieldname == null
+ || fieldname.equals("")
+ || lastFieldRemoved.equals(classname + "."
+ + fieldname)) {
+ // can't retry, so get out of here!
+ break;
+ } else {
+ if (contentFilter == null) {
+ contentFilter = new ToolContentVersionFilter();
+ }
- } else {
- // try removing the field from our XML and retry
- String message = ce.getMessage();
- String classname = extractValue(message, "required-type");
- String fieldname = extractValue(message, "message");
- if (fieldname == null || fieldname.equals("")
- || lastFieldRemoved.equals(classname + "." + fieldname)) {
- // can't retry, so get out of here!
- break;
- } else {
- if (contentFilter == null) {
- contentFilter = new ToolContentVersionFilter();
- }
+ Class problemClass = getClass(classname);
+ if (problemClass == null) {
+ // can't retry, so get out of here!
+ break;
+ }
- Class problemClass = getClass(classname);
- if (problemClass == null) {
- // can't retry, so get out of here!
- break;
+ contentFilter.removeField(problemClass, fieldname);
+ contentFilter.transformXML(fullFilePath);
+ lastFieldRemoved = classname + "." + fieldname;
+ FileUtil.log
+ .debug("Retrying import after removing field "
+ + fieldname);
+ continue;
+ }
+ }
+ } finally {
+ if (file != null) {
+ file.close();
+ }
}
-
- contentFilter.removeField(problemClass, fieldname);
- contentFilter.transformXML(fullFilePath);
- lastFieldRemoved = classname + "." + fieldname;
- FileUtil.log.debug("Retrying import after removing field " + fieldname);
- continue;
- }
}
- } finally {
- if (file != null) {
- file.close();
- }
- }
+ throw finalException;
}
- throw finalException;
- }
- /**
- * Extract the class name or field name from a ConversionException message
- */
- private static String extractValue(String message, String fieldToLookFor) {
- try {
- int startIndex = message.indexOf(fieldToLookFor);
- if (startIndex > -1) {
- startIndex = message.indexOf(":", startIndex + 1);
- if (startIndex > -1 && startIndex + 2 < message.length()) {
- startIndex = startIndex + 2;
- int endIndex = message.indexOf(" ", startIndex);
- String value = message.substring(startIndex, endIndex);
- return value.trim();
+ /**
+ * Extract the class name or field name from a ConversionException message
+ */
+ private static String extractValue(String message, String fieldToLookFor) {
+ try {
+ int startIndex = message.indexOf(fieldToLookFor);
+ if (startIndex > -1) {
+ startIndex = message.indexOf(":", startIndex + 1);
+ if (startIndex > -1 && startIndex + 2 < message.length()) {
+ startIndex = startIndex + 2;
+ int endIndex = message.indexOf(" ", startIndex);
+ String value = message.substring(startIndex, endIndex);
+ return value.trim();
+ }
+ }
+ } catch (ArrayIndexOutOfBoundsException e) {
}
- }
- } catch (ArrayIndexOutOfBoundsException e) {
+ return "";
}
- return "";
- }
- private static Class getClass(String classname) {
- try {
- return Class.forName(classname);
- } catch (ClassNotFoundException e) {
- FileUtil.log.error("Trying to remove unwanted fields from import but we can't find the matching class "
- + classname + ". Aborting retry.", e);
- return null;
+ private static Class getClass(String classname) {
+ try {
+ return Class.forName(classname);
+ } catch (ClassNotFoundException e) {
+ FileUtil.log
+ .error(
+ "Trying to remove unwanted fields from import but we can't find the matching class "
+ + classname + ". Aborting retry.", e);
+ return null;
+ }
}
- }
- /**
- * Exports data in MS Excel (.xls) format.
- *
- * @param out
- * output stream to which the file written; usually taken from HTTP response; it is not closed
- * afterwards
- * @param sheetName
- * name of first sheet in Excel workbook; data will be stored in this sheet
- * @param title
- * title printed in the first (0,0) cell
- * @param dateHeader
- * text describing current date; if NULL
then no date is printed; if not
- * NULL
then text is written out along with current date in the cell; the date is
- * formatted according to {@link #EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT}
- * @param columnNames
- * name of the columns that describe data
parameter
- * @param data
- * array of data to print out; first index of array describes a row, second a column; dates are
- * formatted according to {@link #EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT}
- * @throws IOException
- * @throws JXLException
- */
- public static void exportToolToExcel(OutputStream out, String sheetName, String title, String dateHeader,
- String[] columnNames, Object[][] data) throws IOException, JXLException {
- WritableWorkbook workbook = Workbook.createWorkbook(out);
- WritableSheet sheet = workbook.createSheet(sheetName, 0);
- // Prepare cell formatter used in all columns
- CellView stretchedCellView = new CellView();
- stretchedCellView.setAutosize(true);
- // Pring title in bold, if needed
- if (!StringUtils.isBlank(title)) {
- Label titleCell = new Label(0, 0, title);
- Font font = titleCell.getCellFormat().getFont();
- WritableFont titleFont = new WritableFont(font);
- titleFont.setBoldStyle(WritableFont.BOLD);
- WritableCellFormat titleCellFormat = new WritableCellFormat(titleFont);
- titleCell.setCellFormat(titleCellFormat);
- sheet.addCell(titleCell);
- }
- // Print current date, if needed
- if (!StringUtils.isBlank(dateHeader)) {
- sheet.addCell(new Label(0, 1, dateHeader));
- SimpleDateFormat titleDateFormat = new SimpleDateFormat(FileUtil.EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT);
- sheet.addCell(new Label(1, 1, titleDateFormat.format(new Date())));
- }
- // Print column names, if needed
- if (columnNames != null) {
- for (int columnIndex = 0; columnIndex < columnNames.length; columnIndex++) {
- sheet.addCell(new Label(columnIndex, 3, columnNames[columnIndex]));
- sheet.setColumnView(columnIndex, stretchedCellView);
- }
- }
- SimpleDateFormat cellDateFormat = new SimpleDateFormat(FileUtil.EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT);
- Calendar calendar = Calendar.getInstance();
- if (data != null) {
- // Print data
- for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
- int sheetRowIndex = rowIndex + 4;
- for (int columnIndex = 0; columnIndex < data[rowIndex].length; columnIndex++) {
- Object content = data[rowIndex][columnIndex];
- if (content != null) {
- WritableCell cell = null;
- if (content instanceof Date) {
- Date date = (Date) content;
- cell = new Label(columnIndex, sheetRowIndex, cellDateFormat.format(date));
- } else {
- cell = new Label(columnIndex, sheetRowIndex, content.toString());
+ /**
+ * Exports data in MS Excel (.xls) format.
+ *
+ * @param out
+ * output stream to which the file written; usually taken from
+ * HTTP response; it is not closed afterwards
+ * @param sheetName
+ * name of first sheet in Excel workbook; data will be stored in
+ * this sheet
+ * @param title
+ * title printed in the first (0,0) cell
+ * @param dateHeader
+ * text describing current date; if NULL
then no
+ * date is printed; if not NULL
then text is written
+ * out along with current date in the cell; the date is formatted
+ * according to {@link #EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT}
+ * @param columnNames
+ * name of the columns that describe data
parameter
+ * @param data
+ * array of data to print out; first index of array describes a
+ * row, second a column; dates are formatted according to
+ * {@link #EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT}
+ * @throws IOException
+ * @throws JXLException
+ */
+ public static void exportToolToExcel(OutputStream out, String sheetName,
+ String title, String dateHeader, String[] columnNames,
+ Object[][] data) throws IOException, JXLException {
+ WritableWorkbook workbook = Workbook.createWorkbook(out);
+ WritableSheet sheet = workbook.createSheet(sheetName, 0);
+ // Prepare cell formatter used in all columns
+ CellView stretchedCellView = new CellView();
+ stretchedCellView.setAutosize(true);
+ // Pring title in bold, if needed
+ if (!StringUtils.isBlank(title)) {
+ Label titleCell = new Label(0, 0, title);
+ Font font = titleCell.getCellFormat().getFont();
+ WritableFont titleFont = new WritableFont(font);
+ titleFont.setBoldStyle(WritableFont.BOLD);
+ WritableCellFormat titleCellFormat = new WritableCellFormat(
+ titleFont);
+ titleCell.setCellFormat(titleCellFormat);
+ sheet.addCell(titleCell);
+ }
+ // Print current date, if needed
+ if (!StringUtils.isBlank(dateHeader)) {
+ sheet.addCell(new Label(0, 1, dateHeader));
+ SimpleDateFormat titleDateFormat = new SimpleDateFormat(
+ FileUtil.EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT);
+ sheet.addCell(new Label(1, 1, titleDateFormat.format(new Date())));
+ }
+ // Print column names, if needed
+ if (columnNames != null) {
+ for (int columnIndex = 0; columnIndex < columnNames.length; columnIndex++) {
+ sheet.addCell(new Label(columnIndex, 3,
+ columnNames[columnIndex]));
+ sheet.setColumnView(columnIndex, stretchedCellView);
}
- sheet.addCell(cell);
- }
}
- }
+ SimpleDateFormat cellDateFormat = new SimpleDateFormat(
+ FileUtil.EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT);
+ Calendar calendar = Calendar.getInstance();
+ if (data != null) {
+ // Print data
+ for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
+ int sheetRowIndex = rowIndex + 4;
+ for (int columnIndex = 0; columnIndex < data[rowIndex].length; columnIndex++) {
+ Object content = data[rowIndex][columnIndex];
+ if (content != null) {
+ WritableCell cell = null;
+ if (content instanceof Date) {
+ Date date = (Date) content;
+ cell = new Label(columnIndex, sheetRowIndex,
+ cellDateFormat.format(date));
+ } else {
+ cell = new Label(columnIndex, sheetRowIndex,
+ content.toString());
+ }
+ sheet.addCell(cell);
+ }
+ }
+ }
+ }
+ workbook.write();
+ workbook.close();
}
- workbook.write();
- workbook.close();
- }
- /**
- * Exports data in CSV format. It uses UTF-8 character set and semicolon as separator.
- *
- * @param out
- * output stream to which the file written; usually taken from HTTP response; it is not closed
- * afterwards
- * @param title
- * title printed in the first (0,0) cell
- * @param dateHeader
- * text describing current date; if NULL
then no date is printed; if not
- * NULL
then text is written out along with current date in the cell; the date is
- * formatted according to {@link #EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT}
- * @param columnNames
- * name of the columns that describe data
parameter
- * @param data
- * array of data to print out; first index of array describes a row, second a column; dates are
- * formatted according to {@link #EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT}
- * @throws IOException
- */
- public static void exportToolToCSV(OutputStream out, String title, String dateHeader, String[] columnNames,
- Object[][] data) throws IOException {
- Writer writer = new OutputStreamWriter(out, FileUtil.ENCODING_UTF_8);
- CSVWriter csv = new CSVWriter(writer, ';');
- String[] line = null;
- // Print title, if needed
- if (!StringUtils.isBlank(title)) {
- line = new String[] { title };
- csv.writeNext(line);
- }
- // Print current date,if needed
- if (!StringUtils.isBlank(dateHeader)) {
- String date = new SimpleDateFormat(FileUtil.EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT).format(new Date());
- line = new String[] { dateHeader, date };
- csv.writeNext(line);
- }
- // Separator
- line = new String[] {};
- csv.writeNext(line);
+ /**
+ * Exports data in CSV format. It uses UTF-8 character set and semicolon as
+ * separator.
+ *
+ * @param out
+ * output stream to which the file written; usually taken from
+ * HTTP response; it is not closed afterwards
+ * @param title
+ * title printed in the first (0,0) cell
+ * @param dateHeader
+ * text describing current date; if NULL
then no
+ * date is printed; if not NULL
then text is written
+ * out along with current date in the cell; the date is formatted
+ * according to {@link #EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT}
+ * @param columnNames
+ * name of the columns that describe data
parameter
+ * @param data
+ * array of data to print out; first index of array describes a
+ * row, second a column; dates are formatted according to
+ * {@link #EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT}
+ * @throws IOException
+ */
+ public static void exportToolToCSV(OutputStream out, String title,
+ String dateHeader, String[] columnNames, Object[][] data)
+ throws IOException {
+ Writer writer = new OutputStreamWriter(out, FileUtil.ENCODING_UTF_8);
+ CSVWriter csv = new CSVWriter(writer, ';');
+ String[] line = null;
+ // Print title, if needed
+ if (!StringUtils.isBlank(title)) {
+ line = new String[] { title };
+ csv.writeNext(line);
+ }
+ // Print current date,if needed
+ if (!StringUtils.isBlank(dateHeader)) {
+ String date = new SimpleDateFormat(
+ FileUtil.EXPORT_TO_SPREADSHEET_TITLE_DATE_FORMAT)
+ .format(new Date());
+ line = new String[] { dateHeader, date };
+ csv.writeNext(line);
+ }
+ // Separator
+ line = new String[] {};
+ csv.writeNext(line);
- // Print column names, if needed
- if (columnNames != null) {
- csv.writeNext(columnNames);
- }
- SimpleDateFormat cellDateFormat = new SimpleDateFormat(FileUtil.EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT);
- // Print data
- if (data != null) {
- for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
- line = new String[data[rowIndex].length];
- for (int columnIndex = 0; columnIndex < line.length; columnIndex++) {
- Object content = data[rowIndex][columnIndex];
- if (content != null) {
- if (content instanceof Date) {
- Date date = (Date) content;
- line[columnIndex] = cellDateFormat.format(date);
- } else {
- line[columnIndex] = content.toString();
+ // Print column names, if needed
+ if (columnNames != null) {
+ csv.writeNext(columnNames);
+ }
+ SimpleDateFormat cellDateFormat = new SimpleDateFormat(
+ FileUtil.EXPORT_TO_SPREADSHEET_CELL_DATE_FORMAT);
+ // Print data
+ if (data != null) {
+ for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
+ line = new String[data[rowIndex].length];
+ for (int columnIndex = 0; columnIndex < line.length; columnIndex++) {
+ Object content = data[rowIndex][columnIndex];
+ if (content != null) {
+ if (content instanceof Date) {
+ Date date = (Date) content;
+ line[columnIndex] = cellDateFormat.format(date);
+ } else {
+ line[columnIndex] = content.toString();
+ }
+ }
+ }
+ csv.writeNext(line);
}
- }
}
- csv.writeNext(line);
- }
+ csv.close();
}
- csv.close();
- }
}
\ No newline at end of file