Skip to content

Commit

Permalink
Added basic csv parser
Browse files Browse the repository at this point in the history
  • Loading branch information
benfortuna committed Nov 29, 2024
1 parent 773e0c2 commit 32eec35
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package net.fortuna.ical4j.extensions.data;

import net.fortuna.ical4j.data.CalendarParser;
import net.fortuna.ical4j.data.ContentHandler;
import net.fortuna.ical4j.data.ParserException;

import java.io.*;

/**
* Support parsing CSV files to produce {@link net.fortuna.ical4j.model.Calendar} objects.
*/
public class CalendarCSVParser implements CalendarParser {

private final String componentName;

public CalendarCSVParser(String componentName) {
this.componentName = componentName;
}

@Override
public void parse(InputStream inputStream, ContentHandler contentHandler) throws IOException, ParserException {
parse(new InputStreamReader(inputStream), contentHandler);
}

@Override
public void parse(Reader reader, ContentHandler contentHandler) throws IOException, ParserException {
try (BufferedReader in = new BufferedReader(reader)) {
contentHandler.startCalendar();

String[] properties = in.readLine().split(",");
String line;
while ((line = in.readLine()) != null) {
contentHandler.startComponent(componentName);
String[] values = line.split(",");
for (int i = 0; i < properties.length; i++) {
contentHandler.startProperty(properties[i]);
contentHandler.propertyValue(values[i]);
contentHandler.endProperty(properties[i]);
}
contentHandler.endComponent(componentName);
}

contentHandler.endCalendar();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package net.fortuna.ical4j.extensions.data

import net.fortuna.ical4j.data.DefaultContentHandler
import net.fortuna.ical4j.model.TimeZoneRegistryFactory
import spock.lang.Specification

class CalendarCSVParserTest extends Specification {

def 'test parsing csv'() {
given: 'a csv string'
def csv = '''summary,dtstart
summary 1,20030808
summary 2,20030809
summary 3,20030810
'''
when: 'string is parsed'
def calendar = null
def contentHandler = new DefaultContentHandler((it) -> calendar = it,
TimeZoneRegistryFactory.instance.createRegistry())
new CalendarCSVParser('vevent').parse(new StringReader(csv), contentHandler)

then: 'result matched expected'
calendar as String == '''BEGIN:VCALENDAR\r
BEGIN:VEVENT\r
SUMMARY:summary 1\r
DTSTART:20030808\r
END:VEVENT\r
BEGIN:VEVENT\r
SUMMARY:summary 2\r
DTSTART:20030809\r
END:VEVENT\r
BEGIN:VEVENT\r
SUMMARY:summary 3\r
DTSTART:20030810\r
END:VEVENT\r
END:VCALENDAR\r\n'''
}
}

0 comments on commit 32eec35

Please sign in to comment.