没有从Servlet读取CSV文件

时间:2017-05-05 04:54:37

标签: servlets java-ee war

正如标题所说,我有一个CSV文件,不会从我的Web应用程序中加载。我正在使用Netbeans来构建项目。

每当我从Netbeans启动项目时,它都会像它应该的那样工作但是当我接受war文件并尝试从Glassfish界面中部署它时,它会将变量显示为undefined,告诉我它没有读取文件。下面的屏幕截图显示了正在发生的事情以及我的文件夹结构。

我在这里阅读了很多帖子,而@BalusC有一些很好的信息here,但它不适合我,我相信这是我的错,但我需要一些更具体的帮助,而不仅仅是阅读另一个交。

我已将我打算加载的CSV文件放入/ src / main / resources文件夹中,如BalusC所述here。我用来加载文件的代码如下。

作为旁注,我有一个用于检查文件位置和访问权限的JSP。当手动部署应用程序时,JSP可以毫无问题地访问和显示文件。

编辑:我运行了一个调试,找不到任何错误,所以我以详细模式运行glassfish并加载页面,一旦页面启动,它就开始从文件读取并发送数据但仍显示“未定义”在所有领域。

以下是详细模式下运行glassfish的输出数据。

[#|2017-05-05T16:34:37.609+0900|INFO|glassfish 4.1|DukeETFServlet|_ThreadID=33;_ThreadName=http-listener-1(3);_TimeMillis=1493969677609;_LevelValue=800;|
  Connection open.|#]

[#|2017-05-05T16:34:38.014+0900|INFO|glassfish 4.1|DukeETFServlet|_ThreadID=109;_ThreadName=__ejb-thread-pool3;_TimeMillis=1493969678014;_LevelValue=800;|
  Sent: ABRN / Arbor Realty Trust 7.375% Senior / 25.32 / 25.11 / 25.24 / 12000 / 24.27 / 26.15 / Fri May 05 16:34:38 JST 2017|#]

[#|2017-05-05T16:34:38.016+0900|INFO|glassfish 4.1|DukeETFServlet|_ThreadID=109;_ThreadName=__ejb-thread-pool3;_TimeMillis=1493969678016;_LevelValue=800;|
  Connection closed.|#]

[#|2017-05-05T16:34:38.024+0900|INFO|glassfish 4.1|DukeETFServlet|_ThreadID=34;_ThreadName=http-listener-1(4);_TimeMillis=1493969678024;_LevelValue=800;|
  Connection open.|#]

[#|2017-05-05T16:34:38.029+0900|INFO|glassfish 4.1|DukeETFServlet|_ThreadID=119;_ThreadName=__ejb-thread-pool4;_TimeMillis=1493969678029;_LevelValue=800;|
  Sent: ABT / Abbott Laboratories / 44.01 / 43.60 / 43.65 / 7487400 / 36.76 / 45.84 / Fri May 05 16:34:38 JST 2017|#]

以下是加载文件的数据。

的Servlet

@WebServlet(urlPatterns={"/dukeetf"}, asyncSupported=true)
public class DukeETFServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger("DukeETFServlet");
private static final long serialVersionUID = 2114153638027156979L;
private Queue<AsyncContext> requestQueue;
@EJB private PriceVolumeBean pvbean; 

@Override
public void init(ServletConfig config) {
    /* Queue for requests */
    requestQueue = new ConcurrentLinkedQueue<>();
    /* Register with the bean that provides price/volume updates */
    pvbean.registerServlet(this);
}

/* PriceVolumeBean calls this method every second to send updates */
public void send(String ticker, String name, float highPrice, float lowPrice,
float closingPrice, int volume, float fiftyTwoWeekHigh, float fiftyTwoWeekLow,
String currentTime) {
    /* Send update to all connected clients */
    for (AsyncContext acontext : requestQueue) {
        try {
            String msg = String.format("%s / %s / %.2f / %.2f / %.2f / %d /"
                    + " %.2f / %.2f / %s",
                    ticker, name, highPrice, lowPrice, closingPrice, volume, 
                    fiftyTwoWeekHigh, fiftyTwoWeekLow, currentTime);
            PrintWriter writer = acontext.getResponse().getWriter();
            writer.write(msg);
            logger.log(Level.INFO, "Sent: {0}", msg);
            /* Close the connection
             * The client (JavaScript) makes a new one instantly */
            acontext.complete();
        } catch (IOException ex) {
            logger.log(Level.INFO, ex.toString());
        }
    }
}

/* Service method */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {

    response.setContentType("text/html");

    /* Put request in async mode. */
    final AsyncContext acontext = request.startAsync();
    /* Remove from the queue when done */
    acontext.addListener(new AsyncListener() {
        @Override
        public void onComplete(AsyncEvent ae) throws IOException {
            requestQueue.remove(acontext);
            logger.log(Level.INFO, "Connection Being Closed.");
        }
        @Override
        public void onTimeout(AsyncEvent ae) throws IOException {
            requestQueue.remove(acontext);
            logger.log(Level.INFO, "Connection Has Timed Out.");
        }
        @Override
        public void onError(AsyncEvent ae) throws IOException {
            requestQueue.remove(acontext);
            logger.log(Level.INFO, "Connection error.");
        }
        @Override
        public void onStartAsync(AsyncEvent ae) throws IOException { }
    });
    /* Add to the queue */
    requestQueue.add(acontext);
    logger.log(Level.INFO, "Connection Being Opened.");
}

}

从CSV获取信息的类

//Get Stock Data From CSV File
public static ArrayList<Stock> getListOfStocks() throws IOException {


    ArrayList<Stock> stocks = new ArrayList();
    ClassLoader classLoader = 
    Thread.currentThread().getContextClassLoader();
    InputStream is = 
    StockService.class.getResourceAsStream("/stockdata.csv");

    // create an instance of BufferedReader
    // using try with resource, Java 7 feature to close resources
    try (CSVReader reader = new CSVReader(new InputStreamReader(is))) {

        // read the first line from the text file
        String[] nextLine;
        reader.readNext();

        // loop until all lines are read
        while ((nextLine = reader.readNext()) != null) {

            Stock newStock = new Stock(nextLine[0], nextLine[1], 
                Float.valueOf(nextLine[2]), Float.valueOf(nextLine[3]),
                Float.valueOf(nextLine[4]), Integer.valueOf(nextLine[5]),
                Float.valueOf(nextLine[6]), Float.valueOf(nextLine[7]));

            stocks.add(newStock);
        }

    }

  return stocks;

}

检索和发送信息的Bean

/* Updates price and volume information every second */
@Startup
@Singleton
public class PriceVolumeBean {
/* Use the container's timer service */
@Resource TimerService tservice;
private DukeETFServlet servlet;
//Set Variable for Counter
private int i = 0;
//Set date time variable

String currentTime;
//Set Variables for Stock Data
private String ticker;
private String name;
private float highPrice;
private float lowPrice;
private float closingPrice;
private int volume;
private float fiftyTwoWeekHigh;
private float fiftyTwoWeekLow;
private static final Logger logger = Logger.getLogger("PriceVolumeBean");

@PostConstruct
public void init() {
    /* Intialize the EJB and create a timer */
    logger.log(Level.INFO, "Initializing EJB.");
    servlet = null;
    tservice.createIntervalTimer(2000, 2000, new TimerConfig());
}

public void registerServlet(DukeETFServlet servlet) {
    /* Associate a servlet to send updates to */
    this.servlet = servlet;
}

@Timeout
public void timeout() throws IOException {

    // Update Date
    Date date = new Date();        

    // Set stock variables //
    ticker = StockService.getListOfStocks().get(i).getTicker();
    name = StockService.getListOfStocks().get(i).getName();
    highPrice = StockService.getListOfStocks().get(i).getHighPrice();
    lowPrice = StockService.getListOfStocks().get(i).getLowPrice();
    closingPrice = StockService.getListOfStocks().get(i).getClosingPrice();
    volume = StockService.getListOfStocks().get(i).getVolume();
    fiftyTwoWeekHigh = StockService.getListOfStocks().get(i).getFiftyTwoWeekHigh();
    fiftyTwoWeekLow = StockService.getListOfStocks().get(i).getFiftyTwoWeekLow();
    currentTime = date.toString();

    // Send updated information
    if (servlet != null)
        servlet.send(ticker, name, highPrice, lowPrice, closingPrice,
                volume, fiftyTwoWeekHigh, fiftyTwoWeekLow, currentTime);

    // Counter that keeps from going beyond size of arraylist
    i++;        
    if (i == 100) {
        i = 0;
    }

}
}

Working Screenshot Failing Screenshot Directory Structure

0 个答案:

没有答案
相关问题