Table CSV Stringtokenizer

Hi guys. Im new to vaadin and I would like to know how to import data/contents from a csv file which is already tokenized and transfer each contents to a table. First row to be the table’s Properties. Here are my codes but without the table. could you please teach me how to do it. Thank you for your help.

 package com.example.tablelet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;

@SuppressWarnings("serial")
@Theme("tablelet")
public class TableletUI extends UI {
	@WebServlet(value = "/*", asyncSupported = true)
	@VaadinServletConfiguration(productionMode = false, ui = TableletUI.class)
	public static class Servlet extends VaadinServlet {
	}

	private InputStream is;
	private int ctr;

	@Override
	protected void init(VaadinRequest request) {
		System.out.println("got in init VaadinRequest request");
		String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); 

		String filePath = basepath + "/WEB-INF/files/input/file.csv";
		Scanner opnScanner = null; // correct
		try {
			opnScanner = new Scanner(new File(filePath)); 

			String strFiLe = filePath;

			BufferedReader br = new BufferedReader(new FileReader(strFiLe));
			String strLine = "";
			StringTokenizer st = null;
			int row = 0;
			int col = 0;
			String [] []
 numbers = new String[30]
 [30]
;
			int lineNumber = 0, tokenNumber = 0;


			while ((strLine = br.readLine()) != null) {
				lineNumber++;
				st = new StringTokenizer(strLine, ",");
				while (st.hasMoreTokens()){
					numbers[row]
[col]
 = st.nextToken();
					System.out.print(numbers[row]
[col]
+"\t");
					col++;
					tokenNumber++;
//					System.out.println("Token: " + st.nextToken());
				}
				System.out.println();
				row++;
				tokenNumber = 0;
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception while reading csv file: " + e);
		}
	}

	 }

I’ve previously
posted a gist
to github that takes an uploaded CSV file and populates a table/container with it’s contents.

It was written for Vaadin v6, but should be easily portable to v7 : the bit that builds a container from a CSV file is very clearly a separate method and will Just Work with v7.

HTH,

Cheers

Charles.

Thank you Charles! So much help.

Hi Charles, I have some questions to ask about the code in Vaadin 6, I came with an error

Type mismatch: Cannot convert from Boolean to String[]

in the while statement of the Indexed Container buildContainerFromCSV. How can I avoid this error. or any tips and tricks.
novice[i]

[/i]

Hi,

Erm - it’s a bit tricky to help without sample code/data/stacktrace - but I’m guessing that the problem is probably the loop statement while ((record = csvReader.readNext()) != null) { csvReader.readNext() should return a string array (or null at end-of-file), and is being cast to a String.

I’m wondering if you’ve copied the code exactly, or whether you’ve tweaked it a little.

Please post the code you are using, and the full stacktrace if you need some more help.

Cheers,

Charles.

Hi Charles,

It seems that I’ve done it now on Vaadin 7. Works smoothly and very nice codes by the way. I didn’t edited most of your codes so the comments are still present but the only thing I’ve done is by deleting the
Window
codes and added
setContent(layout);
Here’s the tweaked code.


Original codes from
Charles Anthony


Little tweak by Adi(Chi)


import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import javax.servlet.annotation.WebServlet;

import au.com.bytecode.opencsv.CSVReader;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.Upload;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
@Theme("tablelet")
public class TableletUI extends UI {
	@WebServlet(value = "/*", asyncSupported = true)
	@VaadinServletConfiguration(productionMode = false, ui = TableletUI.class)
	public static class Servlet extends VaadinServlet {
	}

	protected File tempFile;
	protected Table table;

	@SuppressWarnings("deprecation")
	@Override
	public void init(VaadinRequest request) {
		/* Create and configure the upload component */
		Upload upload = new Upload("Upload CSV File", new Upload.Receiver() {

			@Override
			public OutputStream receiveUpload(String filename, String mimeType) {
				try {
					/*
					 * Here, we'll stored the uploaded file as a temporary file.
					 * No doubt there's a way to use a ByteArrayOutputStream, a
					 * reader around it, use ProgressListener (and a progress
					 * bar) and a separate reader thread to populate a container
					 * *during* the update.
					 * 
					 * This is quick and easy example, though.
					 */
					tempFile = File.createTempFile("temp", ".csv");
					return new FileOutputStream(tempFile);
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
		});
		upload.addListener(new Upload.FinishedListener() {
			@Override
			public void uploadFinished(Upload.FinishedEvent finishedEvent) {
				try {
					/* Let's build a container from the CSV File */
					FileReader reader = new FileReader(tempFile);
					IndexedContainer indexedContainer = buildContainerFromCSV(reader);
					reader.close();
					tempFile.delete();

					/* Finally, let's update the table with the container */
					table.setCaption(finishedEvent.getFilename());
					table.setContainerDataSource(indexedContainer);
					table.setVisible(true);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		/* Table to show the contents of the file */
		table = new Table();
		table.setVisible(false);

		/* Main layout */
		VerticalLayout layout = new VerticalLayout();
		layout.setMargin(true);
		layout.setSpacing(true);
		layout.addComponent(table);
		layout.addComponent(upload);

		setContent(layout);
	}

	/**
	 * Uses http://opencsv.sourceforge.net/ to read the entire contents of a CSV
	 * file, and creates an IndexedContainer from it
	 * 
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	protected IndexedContainer buildContainerFromCSV(Reader reader)
			throws IOException {
		IndexedContainer container = new IndexedContainer();
		CSVReader csvReader = new CSVReader(reader);
		String[] columnHeaders = null;
		String[] record;
		while ((record = csvReader.readNext()) != null) {
			if (columnHeaders == null) {
				columnHeaders = record;
				addItemProperties(container, columnHeaders);
			} else {
				addItem(container, columnHeaders, record);
			}
		}
		return container;
	}

	/**
	 * Set's up the item property ids for the container. Each is a String (of
	 * course, you can create whatever data type you like, but I guess you need
	 * to parse the whole file to work it out)
	 * 
	 * @param container
	 *            The container to set
	 * @param columnHeaders
	 *            The column headers, i.e. the first row from the CSV file
	 */
	private static void addItemProperties(IndexedContainer container,
			String[] columnHeaders) {
		for (String propertyName : columnHeaders) {
			container.addContainerProperty(propertyName, String.class, null);
		}
	}

	/**
	 * Adds an item to the given container, assuming each field maps to it's
	 * corresponding property id. Again, note that I am assuming that the field
	 * is a string.
	 * 
	 * @param container
	 * @param propertyIds
	 * @param fields
	 */
	private static void addItem(IndexedContainer container,
			String[] propertyIds, String[]
 fields) {
		if (propertyIds.length != fields.length) {
			throw new IllegalArgumentException(
					"Hmmm - Different number of columns to fields in the record");
		}
		Object itemId = container.addItem();
		Item item = container.getItem(itemId);
		for (int i = 0; i < fields.length; i++) {
			String propertyId = propertyIds[i]
;
			String field = fields[i]
;
			item.getItemProperty(propertyId).setValue(field);
		}
	}
}

Thank you,
Adi (Chi)