org.supercsv.io.CsvBeanReader Java Examples

The following examples show how to use org.supercsv.io.CsvBeanReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AirlineCsvDeserializer.java    From Showcase with Apache License 2.0 6 votes vote down vote up
public List<Airline> deserialize(InputStream in) throws IOException {
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    ICsvBeanReader csvBeanReader = new CsvBeanReader(inputStreamReader, CsvPreference.STANDARD_PREFERENCE);
    final String[] header = {null, "name", "alias", "iataCode", "icaoCode", "callsign", "country", null};
    Airline airline = null;
    List<Airline> airlines = new ArrayList<>();
    try {

        while ((airline = csvBeanReader.read(Airline.class, header, getCellProcessors())) != null) {
            System.out.println("deserialized " + airline);
            airlines.add(airline);
        }
    } finally {
        if (csvBeanReader != null) {
            csvBeanReader.close();
        }
    }
    return airlines;
}
 
Example #2
Source File: AirportCsvDeserializer.java    From Showcase with Apache License 2.0 6 votes vote down vote up
public List<Airport> deserialize(InputStream in) throws IOException {
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    ICsvBeanReader csvBeanReader = new CsvBeanReader(inputStreamReader, CsvPreference.STANDARD_PREFERENCE);
    final String[] header = {null, "name", "city", "country", "iataCode", "icaoCode", "latitude", "longitude", null, null, null, null, null, null};
    Airport airport = null;
    List<Airport> airports = new ArrayList<>();
    try {

        while ((airport = csvBeanReader.read(Airport.class, header, getCellProcessors())) != null) {
            System.out.println("deserialized " + airport);
            airports.add(airport);
        }
    } finally {
        if (csvBeanReader != null) {
            csvBeanReader.close();
        }
    }
    return airports;
}
 
Example #3
Source File: ConnectionCsvDeserializer.java    From Showcase with Apache License 2.0 6 votes vote down vote up
public List<FlightConnection> deserialize(InputStream in) throws IOException {
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    ICsvBeanReader csvBeanReader = new CsvBeanReader(inputStreamReader, CsvPreference.STANDARD_PREFERENCE);
    final String[] header = {"airlineIataCode", null, "sourceAirportIataCode", null, "destinationAirportIataCode", null, "codeshare", "stops", null};
    FlightConnection flightConnection = null;
    List<FlightConnection> flightConnections = new ArrayList<>();
    try {

        while ((flightConnection = csvBeanReader.read(FlightConnection.class, header, getCellProcessors())) != null) {
            System.out.println("deserialized " + flightConnection);
            flightConnections.add(flightConnection);
        }
    } finally {
        if (csvBeanReader != null) {
            csvBeanReader.close();
        }
    }
    return flightConnections;
}
 
Example #4
Source File: SuperCsvBOMTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
public void ReadTestCSVFile(Reader reader) throws IOException {
	ICsvBeanReader beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);
	final String[] header = beanReader.getHeader(true);
	assertEquals("customerNo", header[0]);
	CustomerBean customer = null;
	final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust!
	StrRegEx.registerMessage(emailRegex, "must be a valid email address");
	final CellProcessor[] processors = new CellProcessor[]{new UniqueHashCode(), // customerNo (must be unique)
			new NotNull(), // firstName
			new NotNull(), // lastName
			new ParseDate("dd/MM/yyyy"), // birthDate
			new ParseSqlTime("HH:mm:ss"), // birthTime
			new NotNull(), // mailingAddress
			new Optional(new ParseBool()), // married
			new Optional(new ParseInt()), // numberOfKids
			new NotNull(), // favouriteQuote
			new StrRegEx(emailRegex), // email
			new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
	};
	customer = beanReader.read(CustomerBean.class, header, processors);
	assertEquals("1", customer.getCustomerNo());
	assertEquals("John", customer.getFirstName());
	assertEquals("[email protected]", customer.getEmail());
	assertEquals(0, customer.getLoyaltyPoints());
	beanReader.close();
}
 
Example #5
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertsToBasicObjects() throws Exception {
	String csv = "Connor|John|16|1999-07-12|6" + decimalFormatSymbols.getDecimalSeparator() + "65\r\n";
	String[] mapping = { "lastName", "firstName", "age", "birthDate", "savings" };
	CellProcessor[] processors = { new NotNull(), new NotNull(), new ParseInt(), new ParseDate("yyyy-MM-dd"),
		new ParseBigDecimal(decimalFormatSymbols) };
	
	CsvPreference customPreference = new Builder('"', '|', "\r\n").build();
	CsvBeanReader beanReader = new CsvBeanReader(new StringReader(csv), customPreference);
	FeatureBean character = beanReader.read(FeatureBean.class, mapping, processors);
	
	Assert.assertNotNull(character);
	Assert.assertEquals("John", character.getFirstName());
	Assert.assertEquals("Connor", character.getLastName());
	Assert.assertEquals(16, character.getAge());
	Assert.assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse("1999-07-12"), character.getBirthDate());
	Assert.assertEquals(new BigDecimal(6.65, new MathContext(3)), character.getSavings());
}
 
Example #6
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
@Test
public void testConverterSupport() throws Exception {
	String csv = "Connor|John|16|1999-07-12|6" + decimalFormatSymbols.getDecimalSeparator() + "65\r\n";
	String[] mapping = { "lastName", "firstName", "age", "birthDate", "savings" };
	CellProcessor[] processors = { new NotNull(), new NotNull(), new ParseInt(), new ParseDate("yyyy-MM-dd"),
		new ParseBigDecimal(decimalFormatSymbols) };
	
	CsvPreference customPreference = new Builder('"', '|', "\r\n").build();
	CsvBeanReader beanReader = new CsvBeanReader(new StringReader(csv), customPreference);
	FeatureBean character = beanReader.read(FeatureBean.class, mapping, processors);
	
	Assert.assertNotNull(character);
	Assert.assertEquals("John", character.getFirstName());
	Assert.assertEquals("Connor", character.getLastName());
	Assert.assertEquals(16, character.getAge());
	Assert.assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse("1999-07-12"), character.getBirthDate());
	Assert.assertEquals(new BigDecimal(6.65, new MathContext(3)), character.getSavings());
}
 
Example #7
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
@Test
public void testReturnsTypedBean() throws Exception {
	int methodCounter = 0;
	Method[] methods = CsvBeanReader.class.getMethods();
	for( Method method : methods ) {
		if( method.getName().equals("read") ) {
			try {
				Type genericReturnType = method.getGenericReturnType();
				Assert.assertNotNull(genericReturnType);
				Assert.assertEquals("T", genericReturnType.getTypeName());
				methodCounter++;
			}
			catch(Exception e) {
				Assert.fail(e.getMessage());
			}
		}
	}
	Assert.assertTrue(methodCounter > 0);
}
 
Example #8
Source File: Utilities.java    From pegasus with Apache License 2.0 6 votes vote down vote up
/**
 * Read file sizes from CSV file.
 *
 * @param csvName CSV file name.
 * @throws IOException
 */
public static void loadHashMap(String csvName) throws IOException {
    final CellProcessor[] processors =
            new CellProcessor[] {null, null, null, null, new ParseLong()};
    CsvBeanReader beanReader =
            new CsvBeanReader(new FileReader(csvName), CsvPreference.STANDARD_PREFERENCE);
    final String[] header = beanReader.getHeader(true);
    FileDataBean fileDataBean;
    sizes = new HashMap<String, Long>();
    while ((fileDataBean = beanReader.read(FileDataBean.class, header, processors)) != null) {
        Long currentSize = sizes.get(fileDataBean.filename);
        if (currentSize != null) {
            assert (fileDataBean.length == currentSize);
        }
        sizes.put(fileDataBean.filename, fileDataBean.length);
    }
}
 
Example #9
Source File: CacheLoader.java    From geode-demo-application with Apache License 2.0 5 votes vote down vote up
private void initalizeBeanReader(String file) {
	beanReader = new CsvBeanReader(new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(file))),CsvPreference.STANDARD_PREFERENCE);
	try {
		@SuppressWarnings("unused")
		final String[] header = beanReader.getHeader(true);
	} catch (IOException e1) {
		e1.printStackTrace();
	}
}
 
Example #10
Source File: CacheLoader.java    From geode-demo-application with Apache License 2.0 5 votes vote down vote up
private void initalizeBeanReader(String file) {
	beanReader = new CsvBeanReader(new BufferedReader(
			new InputStreamReader(getClass().getClassLoader()
					.getResourceAsStream(file))),
			CsvPreference.STANDARD_PREFERENCE);
	try {
		@SuppressWarnings("unused")
		final String[] header = beanReader.getHeader(true);
	} catch (IOException e1) {
		errorLog.add(e1.toString());
	}
}
 
Example #11
Source File: CsvParser.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  delimitedParserSchema = new DelimitedSchema(schema);
  preference = new CsvPreference.Builder(delimitedParserSchema.getQuoteChar(),
      delimitedParserSchema.getDelimiterChar(), delimitedParserSchema.getLineDelimiter()).build();
  nameMapping = delimitedParserSchema.getFieldNames().toArray(
      new String[delimitedParserSchema.getFieldNames().size()]);
  header = StringUtils.join(nameMapping, (char)delimitedParserSchema.getDelimiterChar() + "");
  processors = getProcessor(delimitedParserSchema.getFields());
  csvStringReader = new ReusableStringReader();
  csvMapReader = new CsvMapReader(csvStringReader, preference);
  csvBeanReader = new CsvBeanReader(csvStringReader, preference);
}
 
Example #12
Source File: CSVImporter.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void importStream(InputStream inputStream, OnItemHandler handler, String charSetName) throws Exception {

    Reader reader = new InputStreamReader(inputStream, charSetName);

    ICsvBeanReader csvBeanReader = new CsvBeanReader(reader, this.preference);
    Object obj;
    while ((obj = csvBeanReader.<T>read(getDataClass(), this.fieldNames, this.processors)) != null) {
        handler.onItem(obj);
    }

}
 
Example #13
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 5 votes vote down vote up
@Test
public void testColumnNameBasedMapping() throws IOException {
	String csv = "Connor,John\r\n";
	String[] mapping = { "lastName", "firstName" };
	
	CsvBeanReader beanReader = new CsvBeanReader(new StringReader(csv), STANDARD_PREFERENCE);
	FeatureBean character = beanReader.read(FeatureBean.class, mapping);
	
	Assert.assertNotNull(character);
	Assert.assertEquals("John", character.getFirstName());
	Assert.assertEquals("Connor", character.getLastName());
}
 
Example #14
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertsToPrimitives() throws IOException {
	String csv = "Connor,John,16\r\n";
	String[] mapping = { "lastName", "firstName", "age" };
	CellProcessor[] processors = { new NotNull(), new NotNull(), new ParseInt() };
	
	CsvBeanReader beanReader = new CsvBeanReader(new StringReader(csv), STANDARD_PREFERENCE);
	FeatureBean character = beanReader.read(FeatureBean.class, mapping, processors);
	
	Assert.assertNotNull(character);
	Assert.assertEquals("John", character.getFirstName());
	Assert.assertEquals("Connor", character.getLastName());
	Assert.assertEquals(16, character.getAge());
}
 
Example #15
Source File: ReadingFeaturesTest.java    From super-csv with Apache License 2.0 5 votes vote down vote up
@Test
public void testDateSupport() throws Exception {
	String csv = "1999-07-12";
	String[] mapping = { "birthDate" };
	CellProcessor[] processors = { new ParseDate("yyyy-MM-dd") };
	
	CsvBeanReader beanReader = new CsvBeanReader(new StringReader(csv), STANDARD_PREFERENCE);
	FeatureBean character = beanReader.read(FeatureBean.class, mapping, processors);
	
	Assert.assertNotNull(character);
	Assert.assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse("1999-07-12"), character.getBirthDate());
}