/**
* A demo servlet for serving a simple, constant data table.
* This servlet extends DataSourceServlet, but does not override the default
* empty implementation of method getCapabilities(). This servlet therefore ignores the
* user query (as passed in the 'tq' url parameter), leaving the
* query engine to apply it to the data table created here.
*
* @author Nimrod T.
*/
public class CsvDataSourceServlet extends DataSourceServlet {
/**
* Log.
*/
private static final Log log = LogFactory.getLog(CsvDataSourceServlet.class.getName());
/**
* The name of the parameter that contains the url of the CSV to load.
*/
private static final String URL_PARAM_NAME = "url";
/**
* Generates the data table.
* This servlet assumes a special parameter that contains the CSV URL from which to load
* the data.
*/
@Override
public DataTable generateDataTable(Query query, HttpServletRequest request)
throws DataSourceException {
String url = request.getParameter(URL_PARAM_NAME);
if (StringUtils.isEmpty(url)) {
log.error("url parameter not provided.");
throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided");
}
Reader reader;
try {
reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
} catch (MalformedURLException e) {
log.error("url is malformed: " + url);
throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url);
} catch (IOException e) {
log.error("Couldn't read from url: " + url, e);
throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
}
DataTable dataTable = null;
ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request);
try {
// Note: We assume that all the columns in the CSV file are text columns. In cases where the
// column types are known in advance, this behavior can be overridden by passing a list of
// ColumnDescription objects specifying the column types. See CsvDataSourceHelper.read() for
// more details.
dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale);
} catch (IOException e) {
log.error("Couldn't read from url: " + url, e);
throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
}
return dataTable;
}
}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2024-07-10 (世界標準時間)。"],[[["\u003cp\u003e\u003ccode\u003eCsvDataSourceServlet\u003c/code\u003e uses a CSV file as an external data store and must be run within a servlet container.\u003c/p\u003e\n"],["\u003cp\u003eTo use \u003ccode\u003eCsvDataSourceServlet\u003c/code\u003e, you need to create a CSV file, update your web application, and set up a visualization that queries the data source.\u003c/p\u003e\n"],["\u003cp\u003eThe provided example demonstrates how to display the data from your CSV file using an organization chart visualization.\u003c/p\u003e\n"],["\u003cp\u003eYou can explore advanced features like defining capabilities and passing parameters to the data source in the documentation's next steps.\u003c/p\u003e\n"]]],[],null,["# Using an External Data Store\n\nThis section\nintroduces `CsvDataSourceServlet`. `CsvDataSourceServlet`\nis an example implementation that uses a CSV file as an external data\nstore. This section also provides step-by-step instructions on how to\nrun and test `CsvDataSourceServlet`.\n\n- [Introducing `CsvDataSourceServlet`](#intro)\n- [Running and testing `CsvDataSourceServlet`](#running)\n\n**Note** : You should complete the [Getting\nStarted with Data Sources](/chart/interactive/docs/dev/dsl_get_started) section before you begin this section.\n\nIntroducing `CsvDataSourceServlet`\n----------------------------------\n\nThe `CsvDataSourceServlet` class is located in the `examples`\npackage. This class provides an example implementation\nthat uses a CSV file as an external data store. `CsvDataSourceServlet` inherits\nfrom `DataSourceServlet`,\nimplements `generateDataTable()`, and must be run within a servlet\ncontainer.\n\nA snippet of `CsvDataSourceServlet` is provided below. The `generateDataTable` function\nexposes data to the library. This function creates a data table description,\ndefines the data table columns, and populates the data table with data\nobtained from a CSV file. The CSV file is read from\na URL specified in a requesting visualization's query. The library handles\nall other actions required to return the data table to the querying visualization. \n\n```gdscript\n/**\n * A demo servlet for serving a simple, constant data table.\n * This servlet extends DataSourceServlet, but does not override the default\n * empty implementation of method getCapabilities(). This servlet therefore ignores the\n * user query (as passed in the 'tq' url parameter), leaving the\n * query engine to apply it to the data table created here.\n *\n * @author Nimrod T.\n */\npublic class CsvDataSourceServlet extends DataSourceServlet {\n\n /**\n * Log.\n */\n private static final Log log = LogFactory.getLog(CsvDataSourceServlet.class.getName());\n\n /**\n * The name of the parameter that contains the url of the CSV to load.\n */\n private static final String URL_PARAM_NAME = \"url\";\n\n /**\n * Generates the data table.\n * This servlet assumes a special parameter that contains the CSV URL from which to load\n * the data.\n */\n @Override\n public DataTable generateDataTable(Query query, HttpServletRequest request)\n throws DataSourceException {\n String url = request.getParameter(URL_PARAM_NAME);\n if (StringUtils.isEmpty(url)) {\n log.error(\"url parameter not provided.\");\n throw new DataSourceException(ReasonType.INVALID_REQUEST, \"url parameter not provided\");\n }\n\n Reader reader;\n try {\n reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));\n } catch (MalformedURLException e) {\n log.error(\"url is malformed: \" + url);\n throw new DataSourceException(ReasonType.INVALID_REQUEST, \"url is malformed: \" + url);\n } catch (IOException e) {\n log.error(\"Couldn't read from url: \" + url, e);\n throw new DataSourceException(ReasonType.INVALID_REQUEST, \"Couldn't read from url: \" + url);\n }\n DataTable dataTable = null;\n ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request);\n try {\n // Note: We assume that all the columns in the CSV file are text columns. In cases where the\n // column types are known in advance, this behavior can be overridden by passing a list of\n // ColumnDescription objects specifying the column types. See CsvDataSourceHelper.read() for\n // more details.\n dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale);\n } catch (IOException e) {\n log.error(\"Couldn't read from url: \" + url, e);\n throw new DataSourceException(ReasonType.INVALID_REQUEST, \"Couldn't read from url: \" + url);\n }\n return dataTable;\n }\n}\n```\n\nRunning and testing `CsvDataSourceServlet`\n------------------------------------------\n\nThis section provides instructions on how to run and test `CsvDataSourceServlet`.\n\nTo run and test `CsvDataSourceServlet`, create a CSV file,\nupdate your web application, and set up a visualization that queries the\ndata source, as described in the following sections:\n\n- [Creating a CSV File](#create_csv)\n- [Updating Your Web Application on Apache Tomcat](#webapp)\n- [Using a Visualization to View the Data](#visualization)\n\n### Creating a CSV File\n\nThe file `csv_example.csv` is provided in the `\u003cdata_source_library_install\u003e/examples/src/html` directory.\nIt contains the following values: \n\n```\nEmployee,Manager\nRoger,John\nRobert,John\nJane,Roger\nJack,Jane\nBob,Jane\n```\n\nCopy this file to the `\u003ctomcat_home\u003e/webapps/myWebApp` directory\nyou created in the [Getting Started](/chart/interactive/docs/dev/dsl_get_started) section.\n\n### Updating Your Web Application on Apache\nTomcat\n\nFollow or adapt the instructions below to update your web application\non Apache Tomcat. These instructions are specific to Apache Tomcat on a\nWindows system:\n\n1. The `web.xml` file you previously copied to the `WEB-INF` directory already contains the definition and mapping required for this example. The lines that define this are: \n\n ```text\n \u003cservlet\u003e\n \u003cservlet-name\u003eCSV Example\u003c/servlet-name\u003e\n \u003cdescription\u003e\n CsvDataSourceServlet\n \u003c/description\u003e\n \u003cservlet-class\u003eCsvDataSourceServlet\u003c/servlet-class\u003e\n \u003c/servlet\u003e\n\n \u003cservlet-mapping\u003e\n \u003cservlet-name\u003eCSV Example\u003c/servlet-name\u003e\n \u003curl-pattern\u003e/csv\u003c/url-pattern\u003e\n \u003c/servlet-mapping\u003e\n ```\n2. Start Tomcat, or restart Tomcat if it is already running. \n3. Click the following link: \u003chttp://localhost:8080/myWebApp/csv?url=http://localhost:8080/myWebApp/csv_example.csv\u003e \n\n The screen displays 6-7 lines of text, depending on your screen width. \n The text begins with `google.visualization.Query.setResponse ` \n and ends with `{c:[{v:'Bob'},{v:'Jane'}]}]}});` \n\n This is the response that the example CSV data source sends to a visualization.\n\n### Using a Visualization\nto View the Data\n\nThe `all_examples.html` file in the `\u003cdata_source_library_install\u003e/examples/src/html` directory\ncan be used to view a visualization of the data.\n\nIf you view the source of the `all_examples.html` file,\nyou will see there are three visualizations included in the file. The following\nsnippets reproduce the specification of these visualizations.\n\n- The following line specifies the `csv` example covered in this section: \n\n ```css+lasso\n query = new google.visualization.Query('csv?url=http://localhost:8080/myWebApp/csv_example.csv');\n ```\n The following line specifies an organization chart visualization: \n\n ```gdscript\n var chart = new google.visualization.OrgChart(document.getElementById('csv_div'));\n ```\n- The following line specifies the `simpleexample` covered in the [Getting Started](/chart/interactive/docs/dev/dsl_get_started) section: \n\n ```gdscript\n var query = new google.visualization.Query('simpleexample?tq=select name,population');\n ```\n The following line specifies a pie chart visualization: \n\n ```gdscript\n var chart = new google.visualization.PieChart(document.getElementById('simple_div'));\n ```\n- The following line specifies the `advanced` example that is covered in the [Defining Capabilities\n and the Flow of Events](/chart/interactive/docs/dev/dsl_httpservlet) section: \n\n ```text\n query = new google.visualization.Query('advanced?tableId=planets&tq=select planet,mass');\n ```\n The following line specifies a bar chart visualization: \n\n ```gdscript\n var chart = new google.visualization.BarChart(document.getElementById('advanced_div'));\n ```\n\nFor more information on how to specify a chart and use the query\nlanguage, see [Introduction to Using Chart Tools](/chart/interactive/docs) and\nthe [Query Language Reference](/chart/interactive/docs/querylanguage).\n\nFollow, or adapt, the instructions below to view a visualization of\nthe data served by `CsvDataSourceServlet`:\n\n1. Copy the `all_examples.html` file from the `\u003cdata_source_library_install\u003e/examples/src/html` directory to the `\u003ctomcat_home\u003e/webapps/myWebApp/` directory. \n2. Click the following link: \u003chttp://localhost:8080/myWebApp/all_examples.html\u003e, you should see the following visualization. \n\n \u003cbr /\u003e\n\nThe Advanced Data Source example is discussed in [Defining\nCapabilities and the Flow of Events](/chart/interactive/docs/dev/dsl_httpservlet).\n\nNext Steps\n----------\n\nThe next example is described in the [Defining\nCapabilities and the Flow of Events](/chart/interactive/docs/dev/dsl_httpservlet)section.\nAlternatively, explore the following links:\n\n- For an introduction to the library's most commonly used classes, see [Key Classes](/chart/interactive/docs/dev/dsl_packages#keyclasses).\n- Instead of having the data source inherit from `DataSourceServlet`, you can have it inherit from another class. For more information, see [Using\n Your Own Servlet](/chart/interactive/docs/dev/dsl_key_concepts#servlet).\n- To learn about how to pass parameters from an application to a data source, see [Passing Parameters to `DataTableGenerator.generateDataTable`](/chart/interactive/docs/dev/dsl_key_concepts#params)."]]