org.opentestsystem.delivery.testreg.upload.TextFileUtils.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.upload.TextFileUtils.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System
 * Copyright (c) 2013 American Institutes for Research
 *
 * Distributed under the AIR Open Source License, Version 1.0
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/
package org.opentestsystem.delivery.testreg.upload;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

public class TextFileUtils {

    public interface TextFileProcessor<I, O> {

        O process(I input) throws Exception;
    }

    public interface LineMapper {

        boolean mapLine(String line, int lineNumber, String formatType);

    }

    public void processTextFile(final InputStream textFile, final String formatType, final LineMapper lineMapper)
            throws Exception {
        final String CHARSET = "UTF-8";

        final TextFileProcessor<InputStream, String> textFileProcessor = new TextFileProcessor<InputStream, String>() {
            @Override
            public String process(final InputStream input) throws Exception {
                LineIterator lineIterator = null;
                try {
                    lineIterator = IOUtils.lineIterator(textFile, CHARSET);

                    int lineNumber = 1; // First line starts at 1

                    while (lineIterator.hasNext()) {
                        String line = lineIterator.next();
                        if (lineNumber == 1) {
                            //worry about BOM chars (/ufeff)
                            line = line.replaceAll("[\uFEFF]", "");
                        }
                        if (!lineMapper.mapLine(line, lineNumber++, formatType)) {
                            break;
                        }
                    }

                } catch (RuntimeException | IOException ex) {
                    if (lineIterator != null) {
                        lineIterator.close();
                    }
                    IOUtils.closeQuietly(textFile);
                    throw ex;
                } finally {
                    if (lineIterator != null) {
                        lineIterator.close();
                    }
                    IOUtils.closeQuietly(textFile);
                }
                return null;
            }
        };
        textFileProcessor.process(textFile);
    }

}