0

Based on the example mentioned in - https://gist.github.com/canthony/3655917 I have created a new Vaadin example to upload an Excel/CSV file.

Based on the comments mentioned, I even downloaded opencsv-3.0 from the http://opencsv.sourceforge.net and added them into the project.

Below is how I added them

Right Click on Vaadin project created --> Properties --> Java Build Path --> Add Library (Created new User Library) --> New User Library --> User Libraries --> New (In User Libraries page) --> Created New Library with name CSV --> Included the OpenCSV3.0-jar

Finally this is how my setup looks like:

Libraries set up

No errors or warnings are present, but when I publish on tomcat I get below error. This error comes up when I Browse a file and click on Upload button. Can some one please help?

SEVERE: 
java.lang.NoClassDefFoundError: au/com/bytecode/opencsv/CSVReader
at com.example.uploadexcel.UploadexcelUI.buildContainerFromCSV(UploadexcelUI.java:101)
at com.example.uploadexcel.UploadexcelUI$2.uploadFinished(UploadexcelUI.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:979)
at com.vaadin.ui.Upload.fireUploadInterrupted(Upload.java:875)
at com.vaadin.ui.Upload$2.streamingFailed(Upload.java:1166)
at com.vaadin.server.communication.FileUploadHandler.streamToReceiver(FileUploadHandler.java:615)
at com.vaadin.server.communication.FileUploadHandler.handleFileUploadValidationAndData(FileUploadHandler.java:447)
at com.vaadin.server.communication.FileUploadHandler.doHandleSimpleMultipartFileUpload(FileUploadHandler.java:397)
at com.vaadin.server.communication.FileUploadHandler.handleRequest(FileUploadHandler.java:282)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1402)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:305)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

I don't understand why I get java.lang.NoClassDefFoundError when I have added the required jar into the Java build path.

Full code:

public class UploadexcelUI extends UI {
protected File tempFile;
protected Table table;
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = UploadexcelUI.class)
public static class Servlet extends VaadinServlet {
}

@SuppressWarnings("deprecation")
@Override
protected void init(VaadinRequest request) {
    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
 */
@SuppressWarnings("resource")
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
 */
@SuppressWarnings("unchecked")
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);
    }
}


}

3
  • Is there an entry for this csv.jar present in your project's classpath? Is it having the proper path? Commented Sep 18, 2014 at 11:26
  • No, the CSV.jar is not getting added to Run time classpath. I now manually added in the Runtime - Run --> Run configurations --> Classpath --> Add External Jars Please let me know if there is a way I can add the csv.jar into Runtime Classpath other than above method I have used? I had always been adding external jars as explained in my Question. Commented Sep 18, 2014 at 11:48
  • is it fixed after CSV.jar? Commented Apr 10, 2015 at 18:40

2 Answers 2

1

Probably, it is a dependency issue. You need to add commons-lang3 as dependency. You can find the required .jar file here.

Check this answer.

P.S.- May be I should have put this in comment but as my reputation is quite low, I can't.

Sign up to request clarification or add additional context in comments.

Comments

0

Here are the satisfactory enough dependencies of net.sf.opencsv:opencsv:2.3:

$HOME/.m2/repository/net/sf/opencsv/opencsv/2.3/opencsv-2.3.jar,$HOME/.m2/repository/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar,$HOME/.m2/repository/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar,$HOME/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.