Professional Documents
Culture Documents
SOURCES
Table of Contents
General Information about Data Sources ......................................................................................... 5
Understanding Data Sources ................................................................................................ 6
Create New SQL Data Source .............................................................................................. 9
Create a New Plug-in Data Source ..................................................................................... 13
What does the Refresh Metadata button do? .................................................................... 17
Metric Insights' Plugins........................................................................................................ 18
Registering Your Server with Google to use their Plug-in Resources ................................. 21
Populate a Data Source with an uploaded List of Reports.................................................. 26
How to Link to External BI Tools..................................................................................................... 30
What are external reports? ................................................................................................. 31
How to link to External report content ................................................................................. 33
How to link to a Parameterized External report .................................................................. 41
Configuring Remote Data Collectors .............................................................................................. 48
Overview of Remote Data Collection ................................................................................. 49
Configure a Remote Data Collector ................................................................................... 50
Installing Insightd on Windows Servers ............................................................................ 55
Upgrading Insightd on Windows Servers ............................................................................ 62
Installing Insightd on Linux Servers .................................................................................. 68
Upgrading Insightd on Linux Servers .................................................................................. 70
Troubleshooting a Remote Data Collector .......................................................................... 72
JDBC Connections ......................................................................................................................... 80
Establishing a JDBC Connection ....................................................................................... 81
Add a new JDBC Driver ..................................................................................................... 86
Validation errors: "Value '0000-00-00' can not be represented as java.sql.Date" ............... 89
Sourcing data from 1010data ......................................................................................................... 92
Establish connectivity to 1010data ...................................................................................... 93
Collect data from 1010data ................................................................................................. 97
Creating 1010data macro code for your 1st Basic Metric ............................................... 102
Sourcing Data from Adaptive Planning ........................................................................................ 111
How to establish connectivity to Adaptive Planning plugin ................................................112
How to collect data from Adaptive Planning plugin ............................................................ 116
Sourcing Data from Basecamp .................................................................................................... 121
Establish Connectivity to Basecamp ................................................................................. 122
How to Collect Data using Basecamp Plug-in................................................................... 127
Sourcing data from Business Objects .......................................................................................... 131
Establish Connectivity to Business Objects
................................................................ 132
Collect Data from a Business Objects Document
.................................................. 138
Sourcing Data using Elastic Search ............................................................................................. 146
Establish Connectivity to Elastic Search ........................................................................... 147
How to Collect Data using Elastic Search Plug-in............................................................. 151
Sourcing Data from Facebook...................................................................................................... 154
Establish connectivity to Facebook ................................................................................... 155
How to Collect Data from Facebook ................................................................................. 156
Sourcing Data from Fogbugz ....................................................................................................... 159
Establish connectivity to FogBugz .................................................................................... 160
How to collect data from Fogbugz..................................................................................... 164
Sourcing data from Google Analytics ........................................................................................... 169
Establish connectivity to Google Analytics ........................................................................ 170
Connecting To Data Sources
Page 2
Page 3
350
351
354
355
356
363
368
369
374
377
378
Page 4
Page 5
Page 6
Once you have completed the Add Element pop-up and are directed to the Metric or Report
Editor, the browser automatically scrolls down to the Metric/Report Calculation section
1. The Data Source drop-down list contains all of the SQL and Plug in Data Sources that
have been defined for your instance as well as all non-configurable Data Sources
2. You still have to select a Data Collection Trigger that fetches the data
3. Based on your Data Source selection, you either see a Plug-in Command or SQL
Statement text box into which you enter the fetch command
Page 7
The Event, Dimension and Data Dependency Editors all have data collection settings similar to
those on the Element Editors
The example above shows the Dimension Editor
Page 8
Page 9
1. Select "SQL"
2. Click Next step
Page 10
Page 11
7. Select a JDBC Driver. (If you do not see the the driver that you wish to use in the drop-down
provided, contact Metric Insights for assistance.)
8. Optionally, specify the maximum number of concurrent Threads per Trigger Event to be used
in background processing when the system updates metrics and reports for this data source. If
you do not specify any value for this setting, batch data collection processing will be singlethreaded.
9. If you select "Yes" to specify that this Data Source is remote; i.e., behind a firewall, you will be
required to select a Connector or create a new one. See Define a Remote Data Collector for more
details.
10. Save.
11. Click Test Connection to ensure that settings are correct. (Some data sources, e.g., Hive,
cannot be tested this way.)
Note: The JDBC string will be created automatically based on your other inputs. In some cases,
however, it will not be possible to infer the correct string without additional inputs. If the Connection
Test fails, please check the documentation for your JDBC driver.
Page 12
Page 13
3. Choose type
1. Select "Plug-in"
2. Click Next step
Page 14
1. Select a Plug-in from the drop-down list of configured Plug-ins. If you do not find the one
you need, contact your system Administrator or support@metricinsights.com
2. Create a unique name for this data source
3. If you select "Yes" to Use Remote Data Collector?, you will be required to select a
collector or create a new one For more information, reference Define a Remote Data
Collector
4. When the supported plug-in is configured, the required Plug-in Connection Profile
Parameters are defined and are defaulted into the Parameters grid once you select the
Plug-in setting
5. Any of these parameters may be edited by clicking the Edit link
Page 15
Page 16
For SQL data sources, if using the visual editor (1), table/column metadata from the data base is
collected periodically and cached on the Metric Insights server. When users go into the Visual
Editor from an Editor, the cached metadata is used instead of making a database hit to pull up
table/column information.
The Refresh Metadata button (2) allows you to force the refresh of this metadata.
Page 17
Description
Insightd Required?
1010 Data
No
Adapative
Insights
No
Amazon
RedShift
No
BOBJ
CoolaData
No
Elasticsearch
No
Facebook plugin
No
Flat File
No
Google
Analytics
No
Page 18
Google
BigQuery
Google
Calendar
No
Google Calendar plugin for importing a google
calendar as an event calendar
Google
Spreadsheet
No
No
Graphite
Graphite Plugin
No
Hadoop Pig
IBM
Coremetrics
No
Marketo
Marketo plugin
No
MicroStrategy
No
Mixpanel
Mixpanel plugin
No
MongoDB
No
OLAP
No
Omniture
Reporting
No
QlikView
Yes
QlikSense
Yes
Salesforce
Splunk
SQL
Databases
No
No
No
SugarCRM
No
Tableau
No
Teradata
No
Page 19
TreasureData
No
Web Service
No
Page 20
Go to: https://code.google.com/apis/console/?api=plus
1. You can use the current Google console as seen here. However, the steps in this
document use the "old console".
2. Choose the Go back link (yellow section) to use the "old console".
Page 21
Provide
Page 22
1. Product name
2. Product logo
3. Home Page URL
3.2 Create a new Web Application client id for your Metric Insights server
3.3 Record Client ID and Client Secret for use in application configuration file
1. Record Client ID
Page 23
2. For Authorized JavaScript Origins, leave the default that it provides. In this example where
the hostname is document.metricinsights.com, the default is https://document.metricinsights.com
2. Enter the values provided above for the variables shown below:
Modify the lines below inserting values obtained from Google for your host:
Page 24
define('GOOGLE_OAUTH2_CLIENT_ID', '761272366824.apps.googleusercontent.com');
define('GOOGLE_OAUTH2_CLIENT_SECRET', 'yT4nDBBppanARIbWhU5WHNLG');
Page 25
Page 26
1.
2.
3.
4.
5.
Page 27
Page 28
4. Review Image
The image reflects the Report selected from the list stored in the Data Source
Page 29
Page 30
Overview
When creating a new metric, the last two choices allow you to link to reports you've already
developed in other BI platforms, like Tableau, Crystal Reports, or Microstrategy. The difference
between an 'External Report' and 'Other External Content' is that with an External Report you
can actually drill down from another Metric Insights tile into the specified external report. External
Content, however, is just any URL of your choosing that will not be passed in any dynamic
parameters from Metric Insights.
URL Templates
For Other External Content, any old static url is defined for each report. However, for External
Reports that you wish to drill down to, you can use a URL template that will use the following
variable place holders
:measurement_start_time
:measurement_end_time
and, if the metric is dimensioned, by the dimension's bind_variable. So, if the metric is
dimensioned by sales channel, for example, you might also have the :channel template
variable
Page 31
Thumbnails
Metric Insights tiles will actually auto update and generate values based on the value of the metric.
In contrast, external report thumbnails will just be a static icon that the report developer sets.
Sometimes report developers will actually take a screenshot of the external report and store it with
the external report definition to allow for a more realistic and seamless transition from Metric
Insights to the external BI tool.
End result
Once an external report is created, a business user will be able to seamlessly link to a variety of
relevant reports all from their own personal list of favorites or report categories they have access
to.
Page 32
Page 33
Page 34
Even though the report is already created in your external BI tool, for related metrics Metric
Insights still need to know a couple of things about this particular content.
To facilitate this, set
1.
2.
3.
4.
Measurement Interval,
Measure of,
Category,
and Topic
That way, if you're looking at another monthly report that happens to look at some measure, your
external content report will also show up to the user as a related report.
Page 35
1. In this case, we'll just use a static web page that we've created just for examples:
http://external.metricinsights.com/daily_sales_country.php .
2. Select 'SAVE' to display External Content Editor
Page 36
1. Select to display your content in either MetricInsights Viewer or on the External webpage
2. Select 'Upload Image File' to display pop-up where you can add a Preview Image
Page 37
Take a screenshot of your report and upload it as the preview image. This image should be a .png
file and to avoid distortion should have a width to height ratio of 1.8 (in other words, the width is
nearly twice the height).
Page 38
Page 39
Now that it's enabled, make sure the new external content tile properly shows up in the Home
Page. Double clicking on the report should take you to the url you expect.
Page 40
From the Add a new Element menu in Metric Insights, select External Report.
Page 41
Even though the report is already created in your external BI tool, for related metrics Metric
Insights still need to know a couple of things about this particular content.
To facilitate this, set the
1.
2.
3.
4.
Measurement Interval
Measure of
Category
Topic
That way, if you're looking at another monthly report that happens to look at some measure, your
external content report will also show up to the user as a related report.
Page 42
A report type is used for organizational purposes. In addition, though currently unimplemented, it
will allow administrators to associate an icon url for each report type that allows users to
differentiate between report types when scrolling through your list of favorites.
NOTE: This will be auto-populated in future releases.
Page 43
External report URLs can by default take special parameters to help get relevant information. For
example, a report may take a start_date and end_date parameters when running. To facilitate
this, Metric Insights has the following variables available to use in the report URL template.
:measurement_start_time - Metric Insights will automatically choose a reasonable start
and end times based on the report frequency and drill down path. For example, if you're
looking at a Monthly Sales report, and you click on January 2012, the
:measurement_start_time will be 'Jan 01, 2012 00:00:00' with :measurement_end_time =
'Jan 31, 2012 23:59:59'
:measurement_end_time - see above.
for dimensioned metrics only: a dimension name. For example, if your Dimension is
'Country' and you set up the Dimension to have a bind variable name of 'country_id', you
would be able to use :country_id in your URL template.
Page 44
Take a screenshot of your report and upload it as the preview image. This image should be a .png
file and to avoid distortion should have a width to height ratio of 1.8 (in other words, the width is
nearly twice the height)
Page 45
After you're satisfied, save and enable the external report so that it may be visible in the
dashboard.
Page 46
Now that it's enabled, make sure the new external content tile properly shows up in the Tile View
at Home Page. Double clicking on the report should take you to your external BI tool where you'll
need to login
Page 47
Page 48
Page 49
Page 50
Page 51
3.2 Add a SQL database or Plug-in data source to the remote data collector
Note: A single remote data collector can connect to multiple data sources if they are all accessible
through the same remote host.
Page 52
3.3 Choose the SQL database or Plug-in connection that you want to connect
to
Page 53
5. Install insightd
Now, copy the downloaded zip file to the server that will be running Insightd.
Please refer to the following sections to install insightd on Windows and Linux servers.
Page 54
Page 55
Page 56
Page 57
4.1
4.2
Page 58
Page 59
Page 60
Page 61
Page 62
Page 63
Page 64
Page 65
Page 66
Page 67
Page 68
Page 69
If it's not running then you might get the following message:
"The insightd can not be stopped because it is not currently running."
Page 70
In rare cases you might receive the remote data collector via a different means. For example, from
Metric Insights company directly. For example you might get a patched version or one with a new
feature. In that case just follow the directions given for that situation.
This will install the remote data collector (i.e., extract the contents of the zip file) into the
./datacollector directory. If you obtained this file via a different means then it might have a different
name.
If you downloaded this from your Metric Insights system described in the above steps, then this
step is not necessary. If you obtained the remote data collector via a different means then this step
is recommended.
Page 71
Page 72
Page 73
Page 74
3.1 Windows - Check error messages from the remote data collector on the
remote machine
Find the Event Viewer menu on the Windows machine and choose the events for the service
named 'Metric Insights Daemon'. Errors are flagged in red and provide information on problems
that the remote data collector encountered.
3.2 Linux - Check error messages from the remote data collector on the
remote machine
View the errors in the log.
cat /var/log/insight/insightd-error.log
Page 75
CentOS instance:
cat /var/log/httpd/pyinsight-error.log
Page 76
Page 77
1. View the configuration file "config.ini". You can view it with Notepad editor.
2. Compare the setting values for "hostname" with "Username" in previous step. Do the same
for "password". In this example the values are "tableau.metricinsights.com" and
"myPassword123".
3. Compare the setting value for "requestURL" with the domain in previous step. In this
example the value is "demo.metricinsights.com".
Page 78
[authentication]
hostname = tableau.metricinsights.com
password = myPassword123
requestURL = demo.metricinsights.com
[parameters]
FetchRestartWait = 300
PollingInterval = 1
PostingRestartWait = 300
PostingTimeoutInterval = 10
HeartbeatAlertInterval = 10
PostingRestartsAllow = 3
CacheDNSLookup = 0
FetchRestartsAllow = 3
FetchTimeoutInterval = 30
1. Compare the setting values for "hostname" with "Username" in previous step. Do the same
for "password". In this example the values are "tableau.metricinsights.com" and
"myPassword123".
2. Compare the setting value for "requestURL" with the domain in previous step. In this
example the value is "demo.metricinsights.com".
Page 79
JDBC Connections
Page 80
Page 81
Page 82
Page 83
7. Select a JDBC Driver. (If you do not see the the driver that you wish to use in the drop-down
provided, contact Metric Insights for assistance.)
8. Optionally, specify the maximum number of concurrent Threads per Trigger Event to be used
in background processing when the system updates metrics and reports for this data source. If
you do not specify any value for this setting, batch data collection processing will be singlethreaded.
9. Save.
Note: The JDBC string will be created automatically based on your other inputs. In some cases,
however, it will not be possible to infer the correct string without additional inputs. If the Connection
Test fails, please check the documentation for your JDBC driver.
Page 84
NOTE: the test feature does not currently work for testing connections to Apache Hive.
1. Click the Test Link to Verify connectivity to the data source.
2. If you need to further edit the connection, click on the name link of the datasource to access the
pop-up editor
7. Confirm success
Page 85
Page 86
2. Click the ADD icon to the right on the Data Sources grid field
Optionally, you can Edit an existing SQL Data Source on its editor by clicking its Name link and
add your new JDBC driver from there; if this is your approach, skip to Step 4
Page 87
1. Use the Browse button to find and Open the driver found the .jar file that you downloaded
and saved to your local hard drive
2. Once the Jar file is in the text box, click SAVE
Page 88
1. Problem examples:
1.1 Example: "Value '0000-00-00' can not be represented as java.sql.Date"
Page 89
2. Solution:
2.1 Navigate to the data source editor for the affected data source
Make sure the data source drop down is pointing to the appropriate data source, then click the
gear icon to the right to edit the data source.
Page 90
Page 91
Page 92
Page 93
Page 94
Page 95
Page 96
Page 97
Page 98
1.
2.
3.
4.
Page 99
5. Collect Data
1. If validation is finished successfully you will see how many records are fetched. Information
message is displayed in green font. If any error occurs during validation you will see error
message in red font.
2. Collect Data
Page 100
6. View Chart
Page 101
Page 102
Insert a willbe in the Edit Actions screen to reformat the date to a mm/dd/yyyy format. Here is the
example code: <willbe name="Date" value="date" format="type:date4y"/>
Page 103
1. Use is greater than in the drop down - this will be used on the Metric Insights side.
2. Regardless of the actual dates you are analyzing, choose a recent date to limit row count.
Page 104
2. Build a Tabulation
Page 105
Page 106
Metric Insights takes raw macro code from 1010data. Copy the 1010data macro code out of the
Edit Actions window to paste into Metric Insights.
To see how to build a Metric from scratch, click the following this link:
Page 107
Paste the code into the Macro Code box in the Metric Editor.
Page 108
6. Remove table name note at the beginning of the code, and paste
table into table name field.
1. Paste Table Name into Table Name field & remove table note from code.
2. Click the Validate Plug-In Command button to verify code.
7. Validated Code
Once validated, the macro code window will convert from red to green. You will also see the
number of records fetched from your code.
Page 109
Page 110
Page 111
Page 112
Page 113
Press Save
Page 114
1. Enter Username
2. Set Password
Save plug-in
Page 115
Page 116
2. Select Report
Choose Report
Page 117
Page 118
Page 119
Page 120
Page 121
Page 122
Page 123
Page 124
1. Enter Username
2. Set Password
3. Click on gear icon to set User ID parameter.
Page 125
Page 126
Page 127
Page 128
You can select fields in Included Fields section, filter selection or group fields based on Filter on
and Group By options.
Page 129
Page 130
Page 131
Page 132
1. Select Plug-in
Click Next Step
1. Select "BOBJ Data Collection Plugin" from the Plug-in pick list (NOTE: If this option is
not found, contact your Administrator or support@Metricinsights.com for assistance since
your instance has not been configured for BOBJ
2. Enter a meaningful Name
3. Optionally, enter the Username and Password required for this Plug-In
Page 133
Click Save
Page 134
Page 135
Page 136
Page 137
1. Create an element
Page 138
Page 139
Page 140
1.
2.
3.
4.
Page 141
You may select Field and set Expression for it, Fetch options are set below table with fields
Page 142
6. Collect Data
1. If validation is finished successfully, you will see how many records are fetched displayed
in green font; if an error occurs during validation, an error message is presented in red
font.
Click Collect Data
Page 143
7. Review results
Page 144
Page 145
Page 146
Page 147
Page 148
1. Click on gear icon to input your server's Endpoint (server can be local or remote).
2. Provide Index parameter - the name of your Database.
Page 149
3. Optionally, provide Type parameter - the name of the table in your Database.
Page 150
Page 151
Page 152
1.
2.
3.
4.
Page 153
Page 154
Required Variables
Include the following const.php variables:
1.
2.
3.
4.
FACEBOOK_OAUTH2_APP_ID
FACEBOOK_OAUTH2_APP_SECRET
FACEBOOK_OAUTH2_REDIRECT_URI
FACEBOOK_OAUTH2_PERMISSIONS
The above are standard OAuth2 parameters required by Facebook API and are described in
appropriate Facebook docs
http://developers.facebook.com/docs/reference/dialogs/oauth/
http://developers.facebook.com/docs/howtos/login/server-side-login/
Page 155
Page 156
Page 157
Page 158
Page 159
Page 160
Page 161
1.
2.
3.
4.
5.
Page 162
1. Click the gear icon to open the Edit Plug-in Data Source Parameter pop-up
2. domain: Enter the domain name of your FogBugz account
3. Click Save
Page 163
Page 164
1.
2.
3.
4.
Page 165
You can select fields in Included Fields section, filter selection or group fields based on Filter on
and Group By options.
Page 166
Page 167
Page 168
Page 169
Start by creating your new metric or report and performing the following actions in the Metric
Calculations section of the Metric Editor (or Report Editor):
1. Expand Data Source drop down list
2. Select Add New Data Source
Page 170
Next, perform the followings steps to define your new connection profile:
1.
2.
3.
4.
5.
Page 171
Save
Page 172
Login to your Google Analytics account and click the Admin link (top right-hand corner) to access
your Admin page. Then choose the profile that you want.
Click the Profile Settings tab and find your Profile ID near the top of the tab
Page 173
Page 174
Next, close the profile, back to Element Editor and set the newly defined profile as the source for
your metric/report.
Page 175
Page 176
The Query Builder provides an example for each entry. Just click on the desired box and the
example will appear on the right. The first three boxes (i.e., 'dimensions', 'metrics', and 'segment')
include drop-down menus that will enable you to select entries by clicking your mouse.
Note: The 'segment' box will enable you to select or define a Google Analytics 'advanced
segment', which is a type of filter. It should not be confused with the dimensions that are used in
dimensioned metrics and reports.
You can fetch data incrementally from Google Analytics by referencing :last_measurement_time
for the start-date in the Query Builder. In the example above, the system will fetch visitors by day
incrementally by substituting the last date for which data was collected for the start-time variable in
the query expression.
IMPORTANT: By default, Google Analytics returns data for a relatively brief date range. If you
want a larger date range, a start-date must be specified.
Page 177
As you know, Google identifies weeks and months by number, e.g., '11'. Metric Insights requires
dates, e.g., 11/1/2014. If you look in the 'Time' section of the Visual Editor, you will see three
special Metric Insights functions which are designed to address this issue:
mi:hour returns a datetime value that is computed by concatenating ga:date and ga:hour
(i.e., the native Google Analytics 'hour' function, which simply returns the hour of the day).
mi:week returns a date value corresponding to the first day of the week that is identified by
ga:week (i.e., the native Google Analytics 'week' function, which simply returns the week of
the year).
mi:month returns a date value corresponding to the first day of the month that is identified
by ga:month (i.e., the native Google Analytics 'month' function, which simply returns the
month of the year).
Page 178
Page 179
Page 180
Page 181
Before you can complete this step, you must have registered your server with Google. See
Registering Your Server with Google for more information.
1. Enter a BigQuery Job Id for the "job_id_prefix" parameter. This is simply a tag that you will
see in your BigQuery logs so that you can tell which queries are coming from Metric
Insights. You can leave that as the default value or change if you like. The value will not
affect your connection.
2. Click the Gear icon for "token" parameter
Page 182
1. Notice that a token ID appears in the Parameters grid in the Value column
2. Save changes
Page 183
Page 184
Page 185
Set Measurement interval (1) and Measure of (2) for metric. Then press Collect data (3).
If you don't already have a Measure, see Define Your First Measure
Page 186
Page 187
Page 188
7. Collect Data
1. If validation is finished successfully you will see how many records are fetched. Information
message is displayed in green font. If any error occurs during validation you will see error
message in red font.
2. Set Time point from what data should be collected.
3. Press Collect Data
Page 189
8. Fetch is completed
You will get message how many values are recorded. Press Next button to generate Preview
Page 190
Check "Make Visible" flag is set to true and click Enable metric to add tile on your Home Page
Page 191
Page 192
1. Select Data Sources from Admin menu to open the Data Sources grid
2. Click Add New Data Source
Page 193
1. Choose "Plug-in"
2. Click Next step to open the Add Plug-in Data Source pop-up
Page 194
1. Click the Edit icon for the token variable in the Parameters section.
2. On the Pop-up window that appears, view/choose your Google Calendar account and
sign in
Page 195
Click Accept
Page 196
1. Select More
Page 197
Page 198
1.
2.
3.
4.
Page 199
Page 200
Page 201
Page 202
Page 203
Select Data Sources from Admin menu to open the Data Sources grid
Page 204
Page 205
1. Choose "Plug-in"
2. Click Next step to open the Add Plug-in Data Source pop-up
Page 206
1. Click the Edit icon for the token variable in the Parameters section.
2. On the Pop-up window that appears, view/choose your Google account to get access to
Google Drive with your spreadsheets and sign in
Page 207
Click Accept
Page 208
Page 209
1. Create Report
Page 210
Page 211
Page 212
1.
2.
3.
4.
5.
Page 213
Page 214
Page 215
Page 216
Page 217
Page 218
After providing "host" parameter, your Plug-in Data Source will be ready to use in creation of new
Elements.
Page 219
Page 220
Start by creating your new metric or report and then clicking the List icon next to the 'Data Source'
field.
Page 221
Click on the 'Add New Data Source' button to define the new Data Source
Page 222
3. Specify the name and credentials for the new data source
Next, perform the followings steps to define your new Data Source:
1.
2.
3.
4.
Page 223
When you click the Save button in the previous step, you'll be taken to the Plug-in editor. You'll
need to provide your Coremetrics Client ID here. To do so, click the gear icon next to the 'Value'
field.
Page 224
Page 225
Page 226
Page 227
Save
Page 228
Page 229
Page 230
Page 231
1.1
Page 232
Click Select
1. Check to ensure that data was fetched during the Validation process
2. Use the Calendar to choose the start date for data collection
Click Collect Data
Page 233
Page 234
Page 235
Page 236
Page 237
1. Input Username
2. Provide Password
3. And click on Save button
Page 238
Page 239
Page 240
Page 241
Page 242
1. Validate your Plug-in Command. Upon successful validation you will see sample results
under 'Validate' button.
2. If you want to continue configuring of the Element, click on Save button and keep on
configuring.
3. If configuring of the Element finished, Enable & Publish it.
Page 243
Page 244
Page 245
Page 246
1. Enter Username
2. Set Password
Page 247
Page 248
Page 249
Page 250
Alternate Approach
Page 251
An alternate approach is to host the Metric Insights agent on another Windows server in the same
network as QlikView. In this configuration the agent communicates with QlikView server over ports
80 and 443 (http/https), and also port 4747 (using "qvp" - the QlikView protocol).
A port (8443) will need to be opened for communication back from the agent on the Windows
server to Metric Insights.
Collecting data
Finally, once setup, pulling data from QlikView is easy. You configure a data connection in Metric
Insights. Then begin collecting data.
Page 252
Page 253
Page 254
Page 255
The Parameters section is where you specify how to connect to QlikView. The parameters include:
1. Objects In Containers - specify the types of QlikView objects to pull data from (e.g.,
graph, table, text)
2. Objects In Sheets - specify the types of QlikView objects to pull data from (e.g., graph,
table, text)
3. Path to server folder - if pulling from the file system then specify which folder contains the
.qvw files. Not used if pulling via 'server'
4. QVW File Filter List (Comma-Separated) - narrow the list of QlikView documents. Wild
card (*) is allowed
5. URI Scheme - how to access the QlikView Server (either http or https)
6. server - the host name of the QlikView server (e.g., localhost, qlikview.metricinsights.com,
...). Leave blank if pulling .qvw documents via the file system
7. Click through server - the URL to use for creating UI links back to your QlikView server
Page 256
5.2 Enter the 'server' address - pull .qvw document data from file system
Pull QVW data from the file system instead of going through QlikView server
1. If you leave the 'server' parameter blank then the plugin pulls QVW data from the file system
instead of going through QlikView server.
Page 257
2. For this case, you will want to specify the location of the .qvw files via the Path to server folder
parameter.
7. Set user credentials when pulling .qvw file data via file system
Pull QVW data from the file system instead of going through QlikView server
If you specified the 'server' parameter with the QlikView server name, then you can skip this step.
If you left the 'server' parameter blank, so that you will pull .qvw document data via the file system,
then you will want to do this step.
You specify the user credentials in the the Remote Data Collector. This user is used for accessing
the .qvw documents on the file system.
On the machine where the Remote Data Collector is installed, open the 'Metric Insights Daemon'
Windows Service
1. Set the User in Log On menu. The default user is the local system account. You can enter a
different user here. You will then need to restart the Windows Service for it to take effect.
Page 258
Page 259
Page 260
You can select fields in Included Fields section, filter selection or sort fields based on Filter on
and Sort By options.
You can also select date field from the list, or construct your own by Construct Date Field option.
Page 261
Page 262
Page 263
Page 264
Page 265
Page 266
Page 267
Page 268
1.
2.
3.
4.
Notes on Syntax
A query builder will be available shortly to help you build queries. These are the fields that are
available:
'pubDate by Day', type='datetime'
'Number of records', type='numeric'
'title', type 'text',
'link', type 'text',
Page 269
Page 270
"select":["pubDate","COUNT(*)"],
"where":[{"column":"title","condition":"contains","value":"amazon"},
{"column":"title","condition":"contains","value":"customers"},
{"column":"description","condition":"contains","value":"netflix"}],
"group":["pubDate GRANULARITY DAY"]
}
Page 271
Page 272
1. SalesForce plug-in
SalesForce plug-in allows you to create elements using Visual editor.
The main distinctions of using SalesForce plug-in are:
You don't need to know SOQL (Salesforce Object Query Language) to create plug-in
commands;
You can use Visual editor;
BUT, you need to have existing reports in SalesForce as a source.
See more information here
Page 273
Page 274
Set plug-in type of data source and press Next Step button
Page 275
1. Enter Username
2. Set Password
3. Click at Gear icon for token parameter
Page 276
You will need a 'security token' in order to use the Salesforce plugin. You can get it from the
Salesforce browser interface. Instructions are available in Salesforce.
Page 277
Go to Metric Editor
1. Set Data Source - SalesForce plugin
2. Input simple command in the text box
3. Press Validate
If command is validated successfully, you will see message how many records are returned.
Page 278
Page 279
Set Measurement interval (1) and Measure of (2) for metric. Then press Collect data (3).
Page 280
Page 281
You may select Field and set Expression for it, Fetch options are set below table with fields
Page 282
Page 283
8. Collect Data
1. If validation is finished successfully you will see how many records are fetched. Information
message is displayed in green font. If any error occurs during validation you will see error
message in red font.
2. Set Time point from what data should be collected.
3. Press Collect Data
Page 284
9. Fetch is completed
You will get message how many values are recorded. Press Next button to generate Preview
Page 285
Check "Make Visible" flag is set to true and click Enable metric to add tile on your Home Page
Page 286
Page 287
Page 288
Page 289
Page 290
1. Click on gear icon to set token parameter. After you click on icon system will automatically
request SalesForce SOQL token, and upon successful validation the token will appear in
"Value" column. See our article on viewing and updating your SalesForce token here.
2. And then Save SalesForce SOQL plug-in.
Page 291
1. Login to Salesforce
Page 292
Page 293
When you click "Edit" you will see your Consumer Key (ID) and your Consumer Secret. You need
to add your SalesForce Secret and Client ID to the Const.php file (/var/www/iv/engine/config/
const.php).
define('SALESFORCE_OAUTH2_CLIENT_ID',
'3MVG9y6x0357Hlefte5xC92_J.LmfhKJ0Z_...5JydLTMG5bh6eosdfWERZjDOMbc_2FWeBclda5gD6');
define('SALESFORCE_OAUTH2_CLIENT_SECRET', '79282882...');
Note: These are client specific.
Page 294
Page 295
Page 296
Page 297
Page 298
1. SalesForce plug-in
SalesForce plug-in allows you to create elements using Visual editor.
The main distinctions of using SalesForce plug-in are:
You don't need to know SOQL (Salesforce Object Query Language) to create plug-in
commands;
You can use Visual editor;
BUT, you need to have existing reports in SalesForce as a source.
See more information here
Page 299
Page 300
Page 301
Once hosted, Metric Insights pulls your Tableau data directly from your Tableau server via your
web login credentials. Just follow the instructions in your Metric Insights application for setting up
the connection to your Tableau server.
Page 302
Page 303
1.
2.
3.
4.
Page 304
"Manually" only if you use a Data Collector or if you have a large list of reports and only
want a few of them. You can either enter them one at a time or in bulk via upload from a
csv file.
6. Save the new Data Source
NOTE: You can always access the Data Source Editor by clicking its Name link in the Data
Sources grid
Once you have added a Data Source, the Editor opens to allow you to complete additional
settings. Page down to the Parameters Section
1. Click the Edit (gear) icon on the "Tableau server" row and
2. Enter the name of your Tableau server on the pop-up
3. Save to place your entry in the Value column
Page 305
If your Tableau server has only one site or has multiple sites and you want to pull data from the
Default site, skip this step. Otherwise, if you want to pull data from one of the other (not the
Default) sites configured on a multi-site Tableau server:
1. Click the Edit icon on the the "Site ID" row
2. On the pop-up, enter the Site ID. NOTE: In the example above we are pulling data from
the "metricinsights" site configured on the Tableau server.
3. Save the Parameter
IMPORTANT: If your Tableau server has multiple sites, and you want to pull data from more than
one site, then you will need to configure a Tableau Data Source for each of the sites from which
you will extract data.
Page 306
Page 307
NOTE: The format for Report ID is "workbook/view" as illustrated in the example above with the
entry "Finance/Taleof100Start-ups"
Page 308
To confirm the value you entered for your Tableau reports, sign in to your Tableau server and
navigate to the view that contains your Tableau report. The "workbook/view" part of the url as seen
in the address bar of your web browser contains the value to enter for your Tableau report.
In this example, the "workbook/view" is "Finance/Taleof100Start-ups" (outlined in Red above).
This is the value that you enter as your Tableau Report ID
Page 309
Once you have entered or uploaded at least one Tableau Report, the External Reports grid
contains a row for each one
Page 310
Page 311
Once you have added a Data Source, the Editor opens to allow you to complete additional
settings. Page down to the Parameters Section
Page 312
If your Tableau server has only one site or has multiple sites and you want to pull data from the
Default site, skip this step. Otherwise, if you want to pull data from one of the other (not the
Default) sites configured on a multi-site Tableau server:
1. Click the Edit icon on the the "Site ID" row
2. On the pop-up, enter the Site ID value. NOTE: In the example above we are pulling data
from the "metricinsights" site configured on the Tableau server.
3. Save
IMPORTANT: If your Tableau server has multiple sites, and you want to pull data from more than
one site, then you will need to configure a Tableau Data Source for each of the sites from which
you will extract data.
Page 313
Page 314
NOTE: The format for Report ID is "workbook/view" as illustrated in the example above with the
entry "Finance/Taleof100Start-ups"
Page 315
To confirm the value you entered for your Tableau reports, sign in to your Tableau server and
navigate to the view that contains your Tableau report. The "workbook/view" part of the url as seen
in the address bar of your web browser contains the value to enter for your Tableau report.
In this example, the "workbook/view" is "Finance/Taleof100Start-ups" (outlined in Red above).
This is the value that you enter as your Tableau Report ID
Page 316
Once you have entered or uploaded at least one Tableau Report, the External Reports grid
contains a row for each one
Page 317
4.1 Add Tableau data source created in Step 1 to your Remote Data Collector
The instructions on setting up Remote Data Collectors will instruct you to add a new Plug-in
Connection Profile to your remote data collector. Please use the Tableau Plug-in Data Source that
you created in Step 1.
Page 318
Once you have installed Insightd on your Tableau server, you will need to start the Metric Insights
Daemon. Click the Start button and then open the Services panel.
6.1 Find the Metric Insights Daemon and start the service
Find the Metric Insights Daemon and start the service. Now you're ready to collect data from your
Tableau server!
Page 319
1.
2.
3.
4.
Page 320
5. External reports fetch method: Choose "Automatically" and Metric Insights will
automatically discover all Tableau reports on Tableau server and list them all. Choose
"Manually" if you want to manually establish the list of Tableau reports from which you want
to pull data. You can either enter them one at a time or in bulk via upload from a csv file.
6. Save
NOTE: You can always access the Data Source Editor by clicking its Name link in the Data
Sources grid
Once you have added a Data Source, the Editor opens to allow you to complete additional
settings. Page down to the Parameters Section
Page 321
As indicated above, Tableau Online does not support automatic retrieval of the Reports List. So for
your choice of Manually for External reports fetch method:
Page 322
Page 323
Once you have entered or uploaded at least one Tableau Report, the External Reports grid
contains a row for each one
Page 324
To confirm the value you entered for your Tableau reports, sign in to Tableau Online and navigate
to the view that contains your Tableau report. The "workbook/view" part of the url as seen in the
address bar of your web browser contains the value to enter for your Tableau report.
In this example, the "workbook/view" is "Finance/Taleof100Start-ups" (outlined in Red above). This
is the value that you enter as your Tableau Report ID
Page 325
Page 326
Click the Visual Editor link to bring up a list of available fields for your Metric or Report. (Once you
know the syntax and field names, you can just type them directly into the plug-in command box.)
Page 327
Page 328
Choose whether to show the report in the Metric Insights Viewer or in an External Web Page.
3.1 Enter a URL and upload a .png file if you want to use a static image
Page 329
3.2 Select your Tableau source report if you want a dynamically generated
image
When you have entered all of your selections, click 'Collect Image'.
Page 330
Once you've connected to Tableau and created some basic content in Metric Insights, you'll want
to create some users. The fastest way to do that is to select the Users link in the Admin menu and
then click the Add New User button at the bottom of the page.
Page 331
When you click Add New User, you'll be prompted for some basic information about the new user.
Enter the necessary items and click the Save button.
Page 332
You can also create new users by uploading a CSV file. The required fields are Username, Email,
Use LDAP to authenticate, Firstname, and Lastname. (The import page includes a link where you
can obtain a sample CSV file in the expected format.)
Page 333
New users will automatically be opted-in to receive alerts and email digests. Any administrator can
subsequently edit any user's preferences. Just select the Users link in the Admin menu and then
click the link for the user whose preferences you want to edit.
Page 334
Within a given workbook in Tableau Desktop, both dashboards and worksheets can be
published to Tableau Server, where they then become views in Tableau Server.
Dashboards: Pulling the data from a published dashboard does not work very well. It only
gives the data from the first (alphabetic order) worksheet in the dashboard.
3. Best practices
You will probably want to publish dashboards for your users to see and use.
But you will want to make the underlying data available so that Metric Insights can pull. So you
must also publish your worksheets.
1. OPTION 1: Publish all worksheets in same workbook: One approach is to publish all
the worksheets in addition to the dashboards under a given Tableau Desktop workbook.
Then if you don't want your users to see the worksheets you deny permissions on the
worksheets to all users. See section below for instructions.
2. OPTION 2: Publish all worksheets in separate workbook: Another approach is to
publish your one workbook from Tableau Desktop to two workbooks in Tableau Server.
The first workbook has just the dashboard views in Tableau Server that your users access.
And the second workbook has just the worksheet views in Tableau Server that only Metric
Insights accesses. See section below for instructions.
Page 335
Page 336
Then on Tableau Server, select the worksheet Views that you don't want your users to see, and
select Permissions link at top of screen to edit permission for the selected views.
1. Next, click the X button to remove access to all the users. This approach works if you are
signed in with the credentials that Metric Insights uses for pulling data.
2. An alternate approach is to select the edit link to the right of your workbook.
Page 337
If you chose to Edit the permissions instead of Removing the permissions in the previous step,
then follow these instructions.
Select Deny for View permissions for any or all of your users.
Do not deny view access for the Tableau user account that Metric Insights will use.
In this example, we deny view for All Users. We do that because we are currently signed in with
the Tableau user account that we use in Metric Insights for pulling the data from the views.
Page 338
Then, on Tableau Desktop choose to publish your worksheets to a separate workbook on Tableau
Server.
Note, if you choose "hide sheet" option in Tableau Desktop, then the worksheet is not an option
under Publish to Server to publish as a view. So you must "unhide sheet" before you can publish
the worksheet.
Page 339
When publishing this workbook with worksheets, choose Add / Edit permissions to select Deny for
View permissions to any or all of your users.
If you are not signed in as the same Tableau user account that Metric Insights uses, then make
sure that user has view permission too.
Page 340
If using a live data connection, or publishing an updated version of your Tableau workbook, then
setting the Caching to "Refresh more often" will ensure that Metric Insights always sees the latest
information.
Set Caching to "Refresh more often":
1. On the computer running Tableau Server, run the program: Configure Tableau Server
2. Navigate to Data Connections menu tab
3. Under Caching section, select 'Refresh more often'
Page 341
For more information see Tableau article on 'Data in a Tableau Server View is Out of Date':
http://kb.tableausoftware.com/articles/issue/view-out-of-date
Page 342
One way you will know that you should embed database credentials for a view is when you access
that view for the first time with web browser in Tableau Server. You get a message that prompts
you to enter the database credentials.
Page 343
Page 344
Metric Insights then infers the data type of each column in the exported CSV by interrogating the
values. For Metric Insights to interpret a column as containing date/time values, it needs to see
that the values conform to a particular date/time format.
Note: if some of the values in a column are in date/time format, but other values are not, then
Metric Insights will type the whole column as a Text field rather than a Date field. To prevent this
from happening you will need to ensure that all values in the column are of date/time format.
2. The various date/time formats that Metric Insights looks for from
Tableau
This is just a sample list of the date/time formats that Metric Insights looks for in the CSV file
exported from Tableau Server.
"yyyy-MMMMM-dd HH:mm:ss",// 2013-August-01 01:23:45
"yyyy-MM-dd HH:mm:ss", // 2012-01-01 01:23:45
"MM-dd-yyyy",
// 01-01-2012
"yyyy-MM-dd",
// 2012-01-01
"yyyy-MM",
// 2012-01 but not 2012-2013
"M/d/yyyy h:m:s a",
// "4/15/2013 1:00:00 AM" for hourly or minute Tableau
"MM/dd/yyyy",
// 01/01/2012
"MM/dd/yyyy HH:mm:ss", // 01/01/2012 01:23:45
"MMMMM d, yyyy h:mm a", // "April 15, 2013 1:00 AM" for minute Tableau
"MMMMM d, yyyy h a",
// "April 15, 2013 1 AM", "April 15, 2013 12 PM" for hourly Tableau
"MMMMM dd, yyyy",
// January 01, 2012
"MMMMM dd,yyyy",
"dd MMM yyyy",
// "05 Nov 2013" for Tableau
"MMMMM, yyyy",
// January, 2012
--- also catches January, 12 -> January 0012
"MMMMM,yyyy",
"MMMMM yyyy",
// January 2012
--- also catches January 12 -> January 0012
"MMM, yyyy",
// Jan, 2012
--- also catches Jan, 12 -> Jan, 0012
"MMM,yyyy",
"MMM yyyy",
// Jan 2012
--- also catches Jan 12 -> Jan 0012
Page 345
"yyyy-MMM-dd",
// 2012-FEB-01
Oracle style. 12-FEB-12 -> Jan 12, 0012
"EEE MMM dd HH:mm:ss z yyyy", // Wed Aug 21 15:50:21 UTC 2013
2.1 Metric Insights needs at a minimum the Year and Month for a Date/Time
field
Metric Insights requires at a minimum a Year and a Month in the Date/Time field. In the previous
list of formats you can see that Year and Month are required. The following is a list of the date/time
parts that are needed as you expand into days, hours and minutes.
1.
2.
3.
4.
Year, Month
Year, Month, Day
Year, Month, Day, Hour
Year, Month, Day, Hour, Minute
If you see a column value in this displayed format then you know that Metric Insights has
interpreted the column as a Date.
Page 346
Use the Visual Editor link in the Element Editor (Metric or Report) to bring up the Query Builder.
The Query Builder screen shows the column interpreted as date/time with Type DATE.
Use the button to Validate your Tableau plug-in command query in the Metric editor, and the
sample returned data shows the column interpreted as date/time in YYYY-MM-DD hh:mm:ss
format
Page 347
Use the button to Validate your Tableau plug-in command query in the Report editor, and the
sample returned data shows the column interpreted as date/time in YYYY-MM-DD hh:mm:ss
format
3.4 In Report editor Data Columns section, the Display Format tells you that it
is a Date
For Reports, you can also use the Save button and then explore the Display Format for the
column. For a Date column it will give you Date/Time formats to choose.
Page 348
4.1 Publish your Tableau worksheet so that the Date/Time columns conform to
one of the date/time formats that Metric Insights understands
This might be an iterative approach, but based on the examples provided earlier in this article you
can format your column in Tableau desktop as one of the recognized date/time formats and
publish to Tableau server.
If your date/time value is spread over several columns, then you can build a Composite date/time
column. In the above example, use the control in the Visual Editor to construct a Composite date
from the individual year, month, day columns in the Tableau view.
You can create a Report from the Tableau view, and then create other Metrics (or Reports) from
this newly created Report. Because the report saves the data pulled from Tableau in an underlying
SQL table, you can simply write SQL against the report and apply any SQL functions you want for
converting or formatting data from the report into date/time columns as appropriate. See the help
documents on making an Existing Report.
Page 349
Page 350
root@sandbox:~# ifconfig
eth0
Link encap:Ethernet HWaddr
inet addr:10.192.61.233
Page 351
In the curl request, supply the username (e.g., 'admin') and the url of Tableau server (e.g.,
https://tableau-test.metricinsights.com/trusted/). Any of the above curl request arguments should
work.
The above curl request returns -1 from Tableau server if not trusted, and returns non-negative
ticket value if trusted. For example,
Not trusted:
root@sandbox:~# curl -3 -k -dusername=admin https://tableau-test.metricinsights.com/trusted/
-1
Trusted:
root@sandbox:~# curl -3 -k -dusername=admin https://tableau-test.metricinsights.com/trusted/
Co_GwPDEfUzAuj1mDO2MH-FE
Page 352
Add External Report Type for Tableau SSO. You can do this when adding a new External Report.
In the drop down for Report Type, choose Add New Report Type. Then choose Tableau SingleSign for Drill Down Authentication. If you already have an existing External Report Type
defined for Tableau, you can enable SSO authentication for all reports associated with this type by
modifying the Drill Down Authentication setting.
Page 353
Page 354
Page 355
Page 356
Page 357
Page 358
1. Click on the gear icon next to the API key column in the Parameters grid.
Page 359
Page 360
Go to Metric Editor
Page 361
Page 362
Page 363
1. Select the Measurement Interval that applies to your first metric (i.e. the aggregation
interval for your data)
2. Specify what this metric is measuring. If you do not see the measure that you want to use,
you can create one from this drop-down
3. Click on the Collect Data button
Page 364
Page 365
6. Collect Data
1. If validation is finished successfully you will see how many records are fetched. Information
message is displayed in green font. If any error occurs during validation you will see error
message in red font.
2. Set Time point from what data should be collected.
Page 366
7. Fetch is completed
You will get message how many values are recorded. Press Next button to generate Preview
Check "Make Visible" flag is set to true and click Enable metric to add tile on your Home Page
Page 367
Page 368
Page 369
Page 370
Page 371
Page 372
Page 373
Page 374
Page 375
1.
2.
3.
4.
Page 376
Page 377
Architecture Overview
The diagram above illustrates graphically the Metric Insights (MI) Web Services architecture and
high-level process flow; the numbering on the chart corresponds to the list below:
1. The Web Service URL and parameter data its obtained from the MI database; if required
for the call, Web Service credential data (username and password) is also retrieved and
decrypted, if necessary
2. An HTTP POST request is made using the parameters described in the 'Web Service
POST Data' section below and uses the unencrypted credentials (that were retrieved in
Step 1) to authenticate to the Web Service, using HTTPS, if requested
3. The Web Service performs a data fetch process as defined by the developer of that service
4. The Web Service returns the results from the data fetch process to Metric Insights in JSON
format as described in the 'Data Returned from Web Service' section
Page 378
5. MI parses JSON data and updates its database with the returned Metric data or Report
instance data
6. Data received from the Web Service is used by MI to generate new/updated tables and
charts according to the parameters defined for the Metric or Report associated with the
Web Service call
Page 379
The table above illustrates the information that is appended to the POST that is performed to the
Web Service URL
As shown in the table in the preceding section, the dimension_name information is passed to the
Web Service URL for Metrics and Reports that are dimensioned.
Page 380
A separate Web Service call is performed for every 'dimension Value' defined for the 'dimension'.
Each individual 'Key Value' of that dimension is passed in the dimension_value parameter. This
value may either be an integer or text, depending upon the definition of the dimension.
The POSTed parameters shown above are re-formatted prior to substitution, based on the date
format mask specified in the Web Service credentials associated with the Insight Element:
Page 381
2.6 Date Formats if the 'MySQL to Web Service Format' is not specified
3. Authentication Credentials
If Username and/or password data is present for the credentials associated with the Insight
Element, these parameters are passed to the web service using HTTP Basic authentication.
NOTE: It is important that an Element's developer understand that authentication credential
information that the Web Service requires in order to perform the data fetch, including Usernames
and passwords to other external services, must be managed by the Web Service since this
information is not stored or processed by Metric Insights. Authentication and data collection
processing performed by the Web Service occurs outside of this system.
Page 382
Metric Insights performs the following validation on the returned Metric data set before processing
the data to ensure that:
The Web Service always returns data sets that include one numeric (type of integer or
decimal ) and one date/time value (type of date) per row
If no date/time format is specified in the Web Service credentials for the Metric, all date/
time column values conform to the date format of
YYYY-MM-DD HH24:MI:SS
If a date/time format is provided as part of the Web Service credentials for the Metric, all
date/time column values conform to the specified format mask
Page 383
The example above has been arranged for readability but a Web Service JSON result set does not
have to be formatted and would typically look like the following example:
{"header":[{"name":"Calendar Date","type":"DATE"},{"name":"Total Sales","type":"DECIMAL"}],
"data":[["2011-05-10 07:00:00",4730661.59],["2011-05-11 07:00:00",4602004.14],["2011-05-12
07:00:00",4635604.11],["2011-05-13 07:00:00",4873962.11],["2011-05-14 07:00:00",4614745.
529999999],["2011-05-15 07:00:00",4699752.8],["2011-05-16 07:00:00",4774199.8],["2011-05-17
07:00:00",4793545.17],["2011-05-18 07:00:00",4529600.81],["2011-05-19 07:00:00",4605180.
539999999]]}
If a date/time format is provided as part of the Web Service credentials for the Metric, all
date/time column values conform to the specified format mask
6.1 Expected JSON structure for a result set with four columns and three rows
{
"header": [
{
"type": "DATE",
"name": "Order Date"
Page 384
},
{
"type": "DECIMAL",
"name": "US order Volume (US$)"
},
{
"type": "DECIMAL",
"name": "Intl order Volume (US$)"
},
{
"type": "DECIMAL",
"name": "Total order Volume (US$)"
}
],
"data": [
[
"2011-04-06 00:00:00",
415037.54999999999,
758473.73999999999,
1173511.29
],
[
"2011-04-05 00:00:00",
346160.52000000002,
738350.46999999997,
1084510.99
]
]
}
7. Error Reporting
Any error encountered in Web Service processing are returned to Metric Insights so that the
Administrator can be notified of any problems. The following information must be included in the
JSON message (for both metric and report data fetches) when an error is encountered:
{
error: | error string
}
Page 385
9. Sample Code
The following sub-steps contain examples of Web Services for consumption of Metric and Report
data written in php and python:
9.1 PHP Web Service example for collecting metrics data. Note the use of
last_measurement_time.
Above is a Php
<?php
/**
* @see Devx_Model
*/
require_once 'Devx/Model.php';
/**
* DemoModel object
*
* @version 1.0
* @package Insight
*/
class DemoModel extends Devx_Model
{
public function getDemoData1($subst) {
$cfg = Zend_Registry::get('config');
$password = Custom_Model_External::decryptPassword($cfg->database->password);
$params = array('host'
=> $cfg->database->host,
'username' => $cfg->database->username,
'password' => $password,
'dbname'
=> 'demo',
'port'
=> 3306 );
try {
$db = new Devx_Db_Adapter_Pdo_Mysql($params);
$db->query('SET NAMES "utf8"');
$sql = "select sum(amount), date(order_time)
from customer_order ord, customer_order_detail ord_line
where ord.order_id = ord_line.order_id
and ord.order_time > :last_measurement_time
and date(ord.order_time) < now()
group by 2";
if (!isset($subst['last_measurement_time'])) return array('error' => 'No substitution
provided for \':last_measurement_time\' pattern');
Page 386
$pattern = ':last_measurement_time';
$sql = trim(str_ireplace($pattern, "'" . $subst['last_measurement_time'] . "'", $sql));
$rows = $db->query($sql)->fetchAll();
//print_r($rows);
if (is_array($rows)) {
return array(
'header' => array(
array('name' => 'sum(amount)', 'type' => 'decimal'),
array('name' => 'date(order_time)', 'type' => 'date')
),
'data' => $rows
);
} else return array('error' => 'Unexpected data structure is returned');
} catch (Exception $ex) {
return array('error' => $ex->getMessage());
}
}
}
?>
9.2 Python code example used to collect report data using a Web Service
#!/usr/bin/env python2.5
"""
Requirements: apache, mod_python, python2.5, MySQLdb
Sample of virtual host file:
<Directory /var/www/generator/>
Options MultiViews
Order allow,deny
allow from all
AddHandler mod_python .py
PythonHandler webservice
PythonAuthenHandler webservice
AuthType Basic
AuthName "Restricted Area"
require valid-user
AuthBasicAuthoritative Off
PythonDebug On
PythonOption mod_python.legacy.importer *
</Directory>
<VirtualHost *:80>
DocumentRoot /var/www/generator/
ServerName generator
ServerAlias www.generator
</VirtualHost>
Needed modules: apache, util (from mod_python)
Local modules: simplejson
"""
import os
import sys
import datetime
Page 387
import MySQLdb
path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(path)
import simplejson
import logging
import logging.handlers
import os, tempfile
from datetime import date
class MLogger:
def __init__(self, name):
self._logger = logging.getLogger(name)
self._logger.setLevel(logging.INFO)
log_name = 'log-%s-.txt' % date.today()
full_log_dir = '/var/www/generator/log/'#os.path.join(os.path.split(os.path.split(os.
path.split(os.path.abspath( __file__ ))[0])[0])[0], 'log')
full_log_name = os.path.join(full_log_dir, log_name)
try:
os.chmod(full_log_name, 0777)
except OSError:
pass
try:
self._ch = logging.FileHandler(full_log_name)
except IOError:
tmp = tempfile.mkstemp(prefix='log_', dir = full_log_dir)
self._ch = logging.FileHandler(tmp[1])
self._formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s %(message)s","%Y-%m-%d %H:%M:%S")
self._ch.setFormatter(self._formatter)
self._logger.addHandler(self._ch)
def get_logger(self):
return self._logger
"""
local testing data
"""
#main date format
datetime_format = '%Y-%m-%d %H:%M:%S'
date_format = '%Y-%m-%d'
def unformat_date(var):
"""
unformat string to datetime
"""
date = None
if var:
try:
date = datetime.datetime.strptime(var, datetime_format)
except:
try:
date = datetime.datetime.strptime(var, date_format)
except:
# cannot format it
pass
return date
def format_date(var):
"""
Page 388
Page 389
13: 'YEAR',
14: 'NEWDATE',
15: 'VARCHAR',
16: 'BIT',
246: 'NEWDECIMAL',
247: 'INTERVAL',
248: 'SET',
249: 'TINY_BLOB',
250: 'MEDIUM_BLOB',
251: 'LONG_BLOB',
252: 'BLOB',
253: 'VAR_STRING',
254: 'STRING',
255: 'GEOMETRY' }
simple_field_type = {
0: 'DECIMAL',
1: 'INTEGER',
2: 'INTEGER',
3: 'INTEGER',
4: 'DECIMAL',
5: 'DECIMAL',
6: 'TEXT',
7: 'DATE',
8: 'INTEGER',
9: 'INTEGER',
10: 'DATE',
11: 'DATE',
12: 'DATE',
13: 'DATE',
14: 'DATE',
15: 'NVARCHAR',
16: 'INTEGER',
246: 'DECIMAL',
247: 'TEXT',
248: 'TEXT',
249: 'TEXT',
250: 'TEXT',
251: 'TEXT',
252: 'TEXT',
253: 'NVARCHAR',
254: 'NVARCHAR',
255: 'TEXT' }
_NAME = 'channel'
class MysqlConnect(object):
error = ''
connection = None
headers = []
#headers_types = []
result = None
rows = []
def __init__(self, *args, **kargs):
self.info = {
'host': 'localhost',
'user': 'generators',
Page 390
'passwd': 'p0rtal',
'db': 'demo',
'port': 3306,
'use_unicode': True,
'charset': 'utf8'
}
if kargs.has_key('host'):
self.info['host'] = kargs['host']
if kargs.has_key('user'):
self.info['user'] = kargs['user']
if kargs.has_key('passwd'):
self.info['passwd'] = kargs['passwd']
if kargs.has_key('db'):
self.info['db'] = kargs['db']
if kargs.has_key('port'):
self.info['port'] = int(kargs['port'])
def connect(self):
try:
self.connection = MySQLdb.connect(*[], **self.info)
return True
except MySQLdb.Error, e:
self.error = "%d %s" % (e.args[0], e.args[1])
except Exception, e:
self.error = e
return False
def close(self):
if self.connection is not None:
try:
self.connection.close()
except Exception, e:
pass
def query(self, query, params):
try:
cursor = self.connection.cursor(MySQLdb.cursors.Cursor)
cursor.execute(query, params)
except MySQLdb.Error, e:
self.error = "%d %s" % (e.args[0], e.args[1])
return False
try:
self.result = {'header': [{'name': header[0], 'type':
simple_field_type[header[1]]} for header in cursor.description],
'data': []}
records = cursor.fetchall()
for record in records:
row = []
for i, item in enumerate(record):
if self.result['header'][i]['type'] == 'DATE':
item = item.strftime(datetime_format)
else:
item = unicode(item)
row.append(item)
self.result['data'].append(row)
#self.json_result = simplejson.dumps(result)
return True
Page 391
except Exception, e:
self.error = e
return False
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
def authenhandler(req):
pw = req.get_basic_auth_pw()
user = req.user
if user == web_service_credentials['username'] and (
(web_service_credentials['password'] and pw ==
web_service_credentials['password']) or not web_service_credentials['password']):
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
def handler(req):
"""
Binds handler routing
"""
req.log_error('handler')
req.content_type = 'application/json'
#req.content_type = 'text/html'
req.send_http_header()
form = util.FieldStorage(req, keep_blank_values=1)
process(form, req, ret_answer)
return apache.OK
def ret_answer(ret, req):
"""
Formats answer to json answer and returns to apache
"""
#req.write(simplejson.dumps(ret, indent=4))
req.write(simplejson.dumps(ret))
return apache.OK
def print_answer(ret, req):
"""
Print answer to stdout. For test purposes.
"""
print simplejson.dumps(ret,4)
pass
def process(form, req, ret_answer):
"""
Main routine
"""
# empty answer dict
#ret = {'error': ''}
ret = {}
# check for last_measurement_time field
if 'measurement_time' in form:
form['last_measurement_time'] = None
log = MLogger('webservice')
Page 392
logger = log.get_logger()
logger.info('before elem id checks')
# check for element_id field
if 'element_id' not in form:
ret['error'] = 'ERROR. element_id is not set'
ret_answer(ret, req)
return
# check if element_id is correct
if not is_int(form['element_id']) or int(form['element_id']) not in reports:
ret['error'] = 'ERROR. element_id is incorrect %s ' % form['element_id']
ret_answer(ret, req)
return
element_id = int(form['element_id'])
# get mysql connection
outer_conn = MysqlConnect()
if not outer_conn.connect():
ret['error'] = "ERROR. Cannot connect to db: %s" % outer_conn.error
ret_answer(ret, req)
return
if 'command' in form and form['command'] == 'get_measurement_times':
if 'last_measurement_time' in form and form['last_measurement_time']:
#
#
#
#
#
#
#
#
#
last_meas_time = unformat_date(form['last_measurement_time'])
else:
last_meas_time = datetime.datetime(1900, 1, 1, 0, 0, 0)
if not last_meas_time:
last_meas_time = datetime.datetime(1900, 1, 1, 0, 0, 0)
query = reports[element_id]['measurement_time_fetch_command_sql']
params = {'last_measurement_time': last_meas_time}
else:
# check for value substitution
_value = ''
if _NAME in form:
_value = unicode(form[_NAME])
if not _value:
ret['error'] = "ERROR. _value is not specified"
ret_answer(ret, req)
return
# check for names substitution
_name = ''
if '_name' in form:
_name = unicode(form['_name'])
if not _name:
ret['error'] = "ERROR. _name is not specified"
ret_answer(ret, req)
return
# check for measurement time
#if 'measurement_time' in form and form['measurement_time']:
#
meas_time = unformat_date(form['measurement_time'])
if 'last_measurement_time' in form and form['last_measurement_time']:
meas_time = unformat_date(form['last_measurement_time'])
else:
meas_time = None
Page 393
if not meas_time:
ret['error'] = "ERROR. Measurement time is required"
ret_answer(ret, req)
return
query = reports[element_id]['data_fetch_command_sql']
params = {'measurement_time': meas_time, _NAME: _value}
if not outer_conn.query(query, params):
ret['error'] = "ERROR. Cannot execute query: %s" % outer_conn.error
ret_answer(ret, req)
return
result = outer_conn.result
if not result:
ret['error'] = "ERROR. Source db returned empty result"
ret_answer(ret, req)
return
ret['header'] = result['header']
ret['data'] = result['data']
ret_answer(ret, req)
return
if __name__ == "__main__":
"""
for testing from bash
"""
form = {'element_id': 27, 'username': u'user', 'meas_time': '', '_value': u'corporate
sales', '_name': u'channel', 'last_measurement_time': None, 'password': ''}
if len(sys.argv) >= 3:
form['command'] = 'get_measurement_times'
form['last_measurement_time'] = sys.argv[2]
elif len(sys.argv) >= 2:
form['measurement_time'] = sys.argv[1]
process(form, sys.stdout, print_answer)
else:
from mod_python import apache, util
directory = os.path.dirname(__file__)
Page 394