diff --git a/modules/components/org.wso2.iot.core.admin.styles/pom.xml b/modules/components/org.wso2.iot.core.admin.styles/pom.xml new file mode 100644 index 00000000..94c7b4a4 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/pom.xml @@ -0,0 +1,63 @@ + + + + + + org.wso2.iot + wso2iot-components + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.iot.core.admin.styles + bundle + WSO2 IoT - Core - UI Styles + http://wso2.org + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + + org.osgi.framework, + org.osgi.service.http, + org.wso2.carbon.ui, + javax.servlet.*;version="2.4.0", + *;resolution:=optional + + org.wso2.carbon.ui + UIBundle + + + + + + diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/META-INF/product.xml b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/META-INF/product.xml new file mode 100644 index 00000000..a1b86897 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/META-INF/product.xml @@ -0,0 +1,25 @@ + + + + http://stackoverflow.com/questions/tagged/wso2/ + https://docs.wso2.org/display/IOT100/WSO2+IoT+Server + http://wso2.org/mail + https://wso2.org/jira/browse/IoT + + diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/product/about.html b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/product/about.html new file mode 100644 index 00000000..d472d18b --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/product/about.html @@ -0,0 +1,49 @@ + + + + + WSO2 IoT 1.0.0 + + + + +

WSO2 IoT 1.0.0

+ +

+ With its modular, extensible, and customizable capabilities, + WSO2 Internet of Things Server (IoT Server) offers a complete, secure, + open source, enterprise-grade IoT device management solution. + + Built by re-using WSO2 middleware platform capabilities, + WSO2 IoT Server provides the server-side of IoT device management architecture for device manufacturers; + the extensibility of the underlying WSO2 Connected Device Management Framework enables WSO2 IoT Server + to be extended to any device type and support other protocols and data formats. + Moreover, it’s in-built tooling capability allows developers to extend WSO2 IoT Server’s functionality. + + It offers customizable and advanced IoT device analytics via WSO2 Data Analytics Server + that include predictive analytics using machine learning capabilities. + It also supports edge computing devices and policy-based edge analytics as well + as pre-built instant visualization for sensor readings using live data streams gathered from devices. +

+ +

Features

+ + + diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/css/main.css b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/css/main.css new file mode 100644 index 00000000..324f8dc9 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/css/main.css @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* ---------------- template styles ------------------------- */ + +table#main-table td#header { + background-image: none !important; + border-bottom: 1px solid #CCC; +} + +table#main-table td#menu-panel { + border-right: solid 1px #6F97CD; + /*background-image: url(../images/app-server-menu-panel-bg.gif);*/ + background-position: right top; + background-repeat: repeat-y; +} + +/* ---------------- header styles ------------------ */ +div#header-div { + background-color: #222222; + background-image: none !important; +} + +div#header-div div.left-logo { + background-image: url(../images/logo.png); + width: 138px; + margin: 12px 20px !important; +} + +div#header-div div.right-logo { + /*background-image: url( ../images/wsas-mgt-logo.gif);*/ + color: #FFF; + font-family: Arial; + font-size: 12px; + padding: 0px !important; + margin: 18px !important; + +} + +div#header-div div.header-links { + margin-top: 0px; + float: right !important; +} + +div#header-div div.header-links div.right-links { + margin-right: 0px; + height: 35px; + padding-top: 0px; +} + +div#header-div div.header-links div.right-links ul { + + background-position: left top; + background-repeat: repeat-x; + padding-top: 9px; + padding-bottom: 7px; +} + +/* ------------- menu styles ---------------------- */ +div#menu { +} + +div#menu ul.main { +} + +div#menu ul.main li { +} + +div#menu ul.main li.normal { +} + +div#menu ul.main li a.menu-home { + color: #0067B1; + background-image: none; + height: 30px; + line-height: 30px; +} + +div#menu ul.main li a.menu-home:hover { + color: #f47b20; + background-image: none; + background-color: #ffffff; +} + +div#menu ul.main li.menu-header { + /*background-image: url(../images/app-server-menu-header.png);*/ + background-image: none !important; + background-position: left bottom; + background-repeat: repeat-x; + + border-top: 1px solid #CCC; + border-bottom: 1px solid #CCC; + color: #502D16 !important; + height: 32px; + line-height: 32px; + background-color: #F3f3f3; + font-weight: bold; + text-transform: uppercase; +} + +div#menu ul.main li.menu-header img { + margin-right: -14px; + margin-top: 7px; +} + +div#menu ul.main li a.menu-default { + +} + +div#menu ul.main li a.menu-default:hover { + background-color: #ffffff; + border-bottom: solid 1px #CCC; + border-top: solid 1px #CCC; + color: #00447C; + +} + +div#menu ul.sub { +} + +div#menu ul.main li.menu-disabled-link { + background-color: #E9EDF7; +} + +/* -------------- child no-01 styles -------------- */ + +div#menu ul.sub li.normal { + +} + +div#menu ul.sub li a.menu-default { +} + +/* ----------- child no-01 (disabled) styles ------------------- */ + +div#menu ul.sub li a.menu-disabled-link { +} + +div#menu ul.sub li a.menu-disabled-link:hover { +} + +/* -------------- child no-02 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li a.menu-default { + +} + +/* -------------- child no-03 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li.normal ul.sub li a.menu-default { +} + +/* ------------- footer styles -------------------- */ + +div#footer-div div.footer-content div.poweredby { + /*background-image: url( ../images/axis2-powered.gif);*/ +} + +/* ---- login styles ----- */ + +/* --------------- table styles -------------------- */ + +.tableOddRow { + background-color: white; +} + +.tableEvenRow { + background-color: #eeeffb; +} + +.button:hover { + /*background-image:url(../images/wsas-button-bg-hover.gif); + border:solid 1px #9D9FA1;*/ +} + +/* -------------- work area ---------------------- */ + +table#main-table td#middle-content { + background-color: none !important; + background: transparent !important; +} + +div#middle { + background-color: #ffffff; +} + +div#middle h2 { + margin-top: 5px; +} + +div#middle div#workArea { + background-color: none !important; + background: transparent !important; + padding: 10px; +} + +div#workArea table.styledLeft thead th { + /*background-image:url("../images/app-server-table-header.gif");*/ + background-image: none; + background-color: #efd7a5; + border-bottom: 1px solid #CCC; + border-left: 1px solid #CCC; + border-right: 1px solid #CCC; + border-top: 1px solid #CCC; + height: 27px; + line-height: 25px; + text-transform: uppercase; + font-weight: bold; +} + +div#workArea table.styledLeft .tableOddRow { + background-color: none !important; +} + +div#workArea table.styledLeft .tableEvenRow { + background-color: none !important; + background: none; +} + +div#workArea table.styledLeft tbody tr td.middle-header { + /*background-image:url("../images/app-server-table-header.gif");*/ + border-bottom: 1px solid #A7A9AC; + border-left: 1px solid #cccccc; + border-right: 1px solid #cccccc; + border-top: 1px solid #cccccc; + height: 22px; + line-height: 22px; +} + +div#workArea table.styledLeft tbody tr td.buttonRow { + /*background-image:url("../images/app-server-buttonRow-bg.gif");*/ + background-color: #F5F5F6; + padding-bottom: 5px; + padding-top: 5px; +} + +.button { + /*background-image:url("../images/app-server-button-bg.gif");*/ + background-position: left bottom; + border: 1px solid #666666; + padding: 2px 5px; +} + +/** TEAGUE EDITS FOR JAGGERY SERVER ADMIN **/ + +div#header-div { + height: 52px !important; +} + +.left-logo img { + display: none !important; +} + +body { + /*background-image:url("../images/bg.png");*/ + font-family: Arial !important; +} + +div.right-links ul a { + +} + +a { + color: #502D16 !important; +} + +a:hover { + color: #784421 !important; +} + +table#main-table td#menu-panel { + border-right: 1px solid #784421; +} + +div#middle h2 { + color: #502D16 !important; + font-weight: bold; + padding-bottom: 10px; + border-bottom: 1px solid #CCC !important; +} + +div#features tr.feature td { + border-top: 1px solid #CCC; +} + +div#features tr.feature-top td { + border-top: 0px; +} + +#main-table { + background-color: none !important; + +} + +#middle { + background: transparent !important; + background-color: none !important; +} + +/* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/images/logo.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/images/logo.png new file mode 100644 index 00000000..deb024cd Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/styles/images/logo.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/dashboard-common.css b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/dashboard-common.css new file mode 100644 index 00000000..8b161f28 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/dashboard-common.css @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +.tip-table { + border-collapse: collapse; + width: 868px; +} + +.tip-table tr td.tip-empty { + width: 20px; +} + +.tip-top { + width: 202px; + height: 85px; + z-index: 90; +} + +.tip-content-lifter { + margin-top: -20px; + position: relative; + font-size: 11px; +} + +.tip-content a.dashboard-subtitle { + line-height: 30px; +} + +.tip-content { + background: transparent url(../images/tip-back.png) repeat-y left top; + padding: 10px !important; + width: 182px; + z-index: 100; +} + +.tip-bottom { + background: transparent url(../images/tip-bottom.png) no-repeat left top; + height: 11px; + width: 202px; +} + +a.tip-title, h3.tip-title { + color: #333333 !important; + font-size: 18px !important; + text-decoration: none; + margin-bottom: 0 !important; + margin-top: 0 !important; + display: block; +} + +a.tip-title { + cursor: pointer; +} + +a.tip-title:hover { + color: #930000 !important; +} + +div#workArea h2.dashboard-title { + background-image: url(../images/dashboard-title-bg.gif); + background-position: left bottom; + background-repeat: repeat-x; + border-bottom: 0 none; + color: #000000; + font-size: 150%; + font-weight: bold; + line-height: 25px; + margin-bottom: 20px; + padding-bottom: 10px; +} + +.tip-table-div { + height: 10px; +} \ No newline at end of file diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/main.css b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/main.css new file mode 100644 index 00000000..8a230ce0 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/css/main.css @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* ---------------- template styles ------------------------- */ + +table#main-table td#header { + background-image: none !important; + border-bottom: 1px solid #CCC; +} + +table#main-table td#menu-panel { + border-right: solid 1px #6F97CD; + /*background-image: url(../images/app-server-menu-panel-bg.gif);*/ + background-position: right top; + background-repeat: repeat-y; +} + +/* ---------------- header styles ------------------ */ +div#header-div { + background-color: #222222; + background-image: none !important; +} + +div#header-div div.left-logo { + background-image: url(../images/logo.png); + width: 200px; + margin: 12px 20px !important; +} + +div#header-div div.right-logo { + /*background-image: url( ../images/wsas-mgt-logo.gif);*/ + color: #FFF; + font-family: Arial; + font-size: 12px; + padding: 0px !important; + margin: 18px !important; + +} + +div#header-div div.header-links { + margin-top: 0px; + float: right !important; +} + +div#header-div div.header-links div.right-links { + margin-right: 0px; + height: 35px; + padding-top: 0px; +} + +div#header-div div.header-links div.right-links ul { + + background-position: left top; + background-repeat: repeat-x; + padding-top: 9px; + padding-bottom: 7px; +} + +/* ------------- menu styles ---------------------- */ +div#menu { +} + +div#menu ul.main { +} + +div#menu ul.main li { +} + +div#menu ul.main li.normal { +} + +div#menu ul.main li a.menu-home { + color: #0067B1; + background-image: none; + height: 30px; + line-height: 30px; +} + +div#menu ul.main li a.menu-home:hover { + color: #f47b20; + background-image: none; + background-color: #ffffff; +} + +div#menu ul.main li.menu-header { + /*background-image: url(../images/app-server-menu-header.png);*/ + background-image: none !important; + background-position: left bottom; + background-repeat: repeat-x; + + border-top: 1px solid #CCC; + border-bottom: 1px solid #CCC; + color: #502D16 !important; + height: 32px; + line-height: 32px; + background-color: #F3f3f3; + font-weight: bold; + text-transform: uppercase; +} + +div#menu ul.main li.menu-header img { + margin-right: -14px; + margin-top: 7px; +} + +div#menu ul.main li a.menu-default { + +} + +div#menu ul.main li a.menu-default:hover { + background-color: #ffffff; + border-bottom: solid 1px #CCC; + border-top: solid 1px #CCC; + color: #00447C; + +} + +div#menu ul.sub { +} + +div#menu ul.main li.menu-disabled-link { + background-color: #E9EDF7; +} + +/* -------------- child no-01 styles -------------- */ + +div#menu ul.sub li.normal { + +} + +div#menu ul.sub li a.menu-default { +} + +/* ----------- child no-01 (disabled) styles ------------------- */ + +div#menu ul.sub li a.menu-disabled-link { +} + +div#menu ul.sub li a.menu-disabled-link:hover { +} + +/* -------------- child no-02 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li a.menu-default { + +} + +/* -------------- child no-03 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li.normal ul.sub li a.menu-default { +} + +/* ------------- footer styles -------------------- */ + +div#footer-div div.footer-content div.poweredby { + /*background-image: url( ../images/axis2-powered.gif);*/ +} + +/* ---- login styles ----- */ + +/* --------------- table styles -------------------- */ + +.tableOddRow { + background-color: white; +} + +.tableEvenRow { + background-color: #eeeffb; +} + +.button:hover { + /*background-image:url(../images/wsas-button-bg-hover.gif); + border:solid 1px #9D9FA1;*/ +} + +/* -------------- work area ---------------------- */ + +table#main-table td#middle-content { + background-color: none !important; + background: transparent !important; +} + +div#middle { + background-color: #ffffff; +} + +div#middle h2 { + margin-top: 5px; +} + +div#middle div#workArea { + background-color: none !important; + background: transparent !important; + padding: 10px; +} + +div#workArea table.styledLeft thead th { + /*background-image:url("../images/app-server-table-header.gif");*/ + background-image: none; + background-color: #efd7a5; + border-bottom: 1px solid #CCC; + border-left: 1px solid #CCC; + border-right: 1px solid #CCC; + border-top: 1px solid #CCC; + height: 27px; + line-height: 25px; + text-transform: uppercase; + font-weight: bold; +} + +div#workArea table.styledLeft .tableOddRow { + background-color: none !important; +} + +div#workArea table.styledLeft .tableEvenRow { + background-color: none !important; + background: none; +} + +div#workArea table.styledLeft tbody tr td.middle-header { + /*background-image:url("../images/app-server-table-header.gif");*/ + border-bottom: 1px solid #A7A9AC; + border-left: 1px solid #cccccc; + border-right: 1px solid #cccccc; + border-top: 1px solid #cccccc; + height: 22px; + line-height: 22px; +} + +div#workArea table.styledLeft tbody tr td.buttonRow { + /*background-image:url("../images/app-server-buttonRow-bg.gif");*/ + background-color: #F5F5F6; + padding-bottom: 5px; + padding-top: 5px; +} + +.button { + /*background-image:url("../images/app-server-button-bg.gif");*/ + background-position: left bottom; + border: 1px solid #666666; + padding: 2px 5px; +} + +/** TEAGUE EDITS FOR JAGGERY SERVER ADMIN **/ + +div#header-div { + height: 52px !important; +} + +.left-logo img { + display: none !important; +} + +body { + /*background-image:url("../images/bg.png");*/ + font-family: Arial !important; +} + +div.right-links ul a { + +} + +a { + color: #502D16 !important; +} + +a:hover { + color: #784421 !important; +} + +table#main-table td#menu-panel { + border-right: 1px solid #784421; +} + +div#middle h2 { + color: #502D16 !important; + font-weight: bold; + padding-bottom: 10px; + border-bottom: 1px solid #CCC !important; +} + +div#features tr.feature td { + border-top: 1px solid #CCC; +} + +div#features tr.feature-top td { + border-top: 0px; +} + +#main-table { + background-color: none !important; + +} + +#middle { + background: transparent !important; + background-color: none !important; +} + +/* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/images/dashboard.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/images/dashboard.png new file mode 100644 index 00000000..9b2886e5 Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/images/dashboard.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/userguide.html b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/userguide.html new file mode 100644 index 00000000..9a1c62f0 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/docs/userguide.html @@ -0,0 +1,43 @@ + + + + + + + Cloud Application Server Home - User Guide + + + + +

Cloud Application Server Home

+ +

+ The WSO2 Application Server supports the development, deployment, and management of Web services + through a lean, simple and inter-operable platform for hosting Java-based services. With + capabilities such as clustering and high availability, Eclipse IDE integration, and full support + for key WS-* and REST standards, AppServer is becoming the platform of choice for developers and + SOA architects. +

+ + + +

Figure1: Cloud Application Server Home

+ + + diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif new file mode 100644 index 00000000..15a54065 Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/dashboard-title-bg.gif differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/java2wsdl.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/java2wsdl.png new file mode 100644 index 00000000..12ecb14b Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/java2wsdl.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/message-tracing.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/message-tracing.png new file mode 100644 index 00000000..4ccd15db Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/message-tracing.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/modules.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/modules.png new file mode 100644 index 00000000..9e4b5d2b Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/modules.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-hosting.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-hosting.png new file mode 100644 index 00000000..ee0a4a40 Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-hosting.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-testing.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-testing.png new file mode 100644 index 00000000..d04d57c4 Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/service-testing.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-back.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-back.png new file mode 100644 index 00000000..b19ac2f8 Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-back.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-bottom.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-bottom.png new file mode 100644 index 00000000..3159c0ec Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/tip-bottom.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/web-applications.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/web-applications.png new file mode 100644 index 00000000..91e82aca Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/web-applications.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png new file mode 100644 index 00000000..10b7d91d Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl-validator.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl2java.png b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl2java.png new file mode 100644 index 00000000..b825d36b Binary files /dev/null and b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/images/wsdl2java.png differ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index-old.jsp b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index-old.jsp new file mode 100644 index 00000000..163e5444 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index-old.jsp @@ -0,0 +1,105 @@ +<%-- + ~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + ~ + ~ WSO2 Inc. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + + +<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> + +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> + + + + + + + + +<%@include file="../admin/index.jsp" %> + + + + +
+
+
+ +
+
+
+ diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index.jsp b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index.jsp new file mode 100644 index 00000000..9c34f653 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/index.jsp @@ -0,0 +1,147 @@ +<%-- + ~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + ~ + ~ WSO2 Inc. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + + +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> +<%@ page import="org.wso2.carbon.utils.ServerConstants" %> +<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> + +<% + Object param = session.getAttribute("authenticated"); + String passwordExpires = (String) session.getAttribute(ServerConstants.PASSWORD_EXPIRATION); + boolean hasModMgtPermission = CarbonUIUtil.isUserAuthorized(request, + "/permission/admin/manage/add/module"); + boolean hasServiceMgtPermission = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/add/service"); + boolean hasWebAppMgtPermission = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/manage/webapp"); + boolean loggedIn = false; + if (param != null) { + loggedIn = (Boolean) param; + } +%> + +
+ <% + if (loggedIn && passwordExpires != null) { + %> +

Your password expires at <%=passwordExpires%>. Please change by + visiting here +

+ <% + } + %> +
+
+
+ +

WSO2 Enterprise Mobility Server quick start dashboard

+ + + + + + + + + + + + + + + + +
+
+ <% + if (hasWebAppMgtPermission) { + %> + Web + Applications +
+ <% + } else { + %> +

Web Applications


+ <% + } + %> +

Web Application hosting features in AppServer supports deployment of + Tomcat compliant Webapps. Deployed Webapps can be easily managed using + the Webapp management facilities available in the management console.

+ +
+
+
+ + +

+
+

+
diff --git a/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp new file mode 100644 index 00000000..6f48f8a9 --- /dev/null +++ b/modules/components/org.wso2.iot.core.admin.styles/src/main/resources/web/tenant-dashboard/system_stats_ajaxprocessor.jsp @@ -0,0 +1,146 @@ +<%-- + ~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + ~ + ~ WSO2 Inc. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --%> + + +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ page import="org.apache.axis2.context.ConfigurationContext" %> +<%@ page import="org.wso2.carbon.CarbonConstants" %> +<%@ page import="org.wso2.carbon.statistics.ui.StatisticsAdminClient" %> +<%@ page import="org.wso2.carbon.statistics.ui.types.carbon.SystemStatistics" %> +<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> +<%@ page import="org.wso2.carbon.utils.ServerConstants" %> +<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> + +<% + response.setHeader("Cache-Control", "no-cache"); + + String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); + ConfigurationContext configContext = + (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); + + String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); + StatisticsAdminClient client = new StatisticsAdminClient(cookie, backendServerURL, + configContext, request.getLocale()); + + SystemStatistics systemStats; + try { + systemStats = client.getSystemStatistics(); + } catch (Exception e) { + response.setStatus(500); + CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e); + session.setAttribute(CarbonUIMessage.ID, uiMsg); +%> + +<% + return; + } +%> + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
<%= ((float) Math.round(systemStats.getAvgResponseTime() * 1000)) / 1000 %> + ms +
+ <% if (systemStats.getMinResponseTime() <= 0) {%> + < 1.00 ms + <% } else {%> + <%= systemStats.getMinResponseTime()%> ms + <% }%> +
<%= systemStats.getMaxResponseTime()%> ms
<%= systemStats.getRequestCount()%> +
<%= systemStats.getResponseCount()%> +
<%= systemStats.getFaultCount()%> +
<%= systemStats.getServices()%> +
+
  + + + + + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/modules/components/pom.xml b/modules/components/pom.xml new file mode 100644 index 00000000..dfc023a0 --- /dev/null +++ b/modules/components/pom.xml @@ -0,0 +1,40 @@ + + + + + + + + org.wso2.iot + wso2iot-parent + 3.1.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + wso2iot-components + pom + WSO2 IoT Server - Components Module + http://wso2.org + + + org.wso2.iot.core.admin.styles + + + diff --git a/modules/distribution/pom.xml b/modules/distribution/pom.xml new file mode 100644 index 00000000..551f2746 --- /dev/null +++ b/modules/distribution/pom.xml @@ -0,0 +1,766 @@ + + + + + + + org.wso2.iot + wso2iot-parent + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + wso2iot + pom + WSO2 IoT - Distribution + WSO2 IoT Distribution + + + + com.h2database.wso2 + h2-database-engine + + + + + + + org.codehaus.mojo + buildnumber-maven-plugin + ${maven-buildnumber-plugin.version} + + {0,date,dd MMM yyyy} + + timestamp + + false + false + + + + validate + + create + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + false + + + 2-unpack-wso2carbon + prepare-package + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.kernel.version} + zip + true + target + + + + + + + + + com.google.code.maven-replacer-plugin + replacer + 1.5.2 + + + + replace-for-identity + package + + replace + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/identity.xml + + + /Server/JDBCPersistenceManager/DataSource/Name + (jdbc/WSO2CarbonDB) + jdbc/WSO2AM_DB + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedAuthorizationCodeGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedPasswordGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedClientCredentialsGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler) + org.wso2.carbon.apimgt.keymgt.handlers.ExtendedSAML2BearerGrantHandler + + + /Server/OAuth/SupportedGrantTypes/SupportedGrantType + (org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandler) + org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandlerWithHandshake + + + /Server/OAuth/OAuthCallbackHandlers + (org.wso2.carbon.identity.oauth.callback.DefaultCallbackHandler) + org.wso2.carbon.apimgt.keymgt.util.APIManagerOAuthCallbackHandler + + + /Server/SSOService/UseAuthenticatedUserDomainCrypto + (false) + true + + + + + + + + + replace-for-thrift + prepare-package + + replace + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/thrift-authentication.xml + + + /Server/JDBCPersistenceManager/DataSource/Name + (jdbc/WSO2CarbonDB) + jdbc/WSO2AM_DB + + + + + + + + + + com.google.code.maven-config-processor-plugin + config-processor-maven-plugin + 2.6 + + + init-input-adapter-config + prepare-package + + process + + + false + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/input-event-adapters.xml + ../../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/input-event-adapters.xm + src/core/conf/input-adapter-change.xml + + + + + + init-output-adapter-config + prepare-package + + process + + + false + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/output-event-adapters.xml + ../../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/output-event-adapters.xml + src/core/conf/output-adapter-change.xml + + + + + + add-scope-validator + prepare-package + + process + + + false + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/identity.xml + ../../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/identity.xml + src/core/conf/identity_config_change.xml + + + + http://wso2.org/projects/carbon/carbon.xml + + + + + init-claim-manager + prepare-package + + process + + + false + + + ${basedir}/../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/user-mgt.xml + ../../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/user-mgt.xml + src/core/conf/user_mgt_config_change.xml + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + + copy-con + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + create-device-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + create-certificate-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + create-api-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + create-app-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + create-JAGH2-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + create-social-db-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + create-mobile-android-plugin-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + create-mobile-windows-plugin-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + 3-extract-docs-from-components + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + copy_modules_apps + package + + + + + + + run + + + + + + + clean_target + install + + + + + + + + + + + + + + + + + + + + run + + + + modify_entitlement_properties + prepare-package + + + + + + + + + run + + + + + + replace-web-xmls-in-war-files + prepare-package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + 1-pre-dist + test + + + single + + + false + UTF-8 + + ${basedir}/src/assembly/filter.properties + + + ${basedir}/src/assembly/dist.xml + + + + + 2-dist + package + + single + + + false + UTF-8 + + ${basedir}/src/assembly/filter.properties + + \ + + ${basedir}/src/assembly/bin.xml + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + diff --git a/modules/distribution/src/assembly/bin.xml b/modules/distribution/src/assembly/bin.xml new file mode 100755 index 00000000..3051f910 --- /dev/null +++ b/modules/distribution/src/assembly/bin.xml @@ -0,0 +1,1513 @@ + + + + + + + + + + + + + + + + + + + + + + + + ]> + + bin + + zip + + false + + + + target/wso2carbon-core-${carbon.kernel.version} + ${pom.artifactId}-${pom.version} + + **/*.sh + **/README* + **/LICENSE* + **/INSTALL* + **/release-notes.html + **/*.sh + **/repository/conf/** + **/repository/components/** + **/wso2 + **/lib/** + **/bin/** + **/axis2services/sample01.aar + **/axis2services/echo/** + **/axis2services/version/** + **/version.txt + **/master-datasources.xml + **/carbon.xml + **/registry.xml + **/client-truststore.jks + **/wso2carbon.jks + **/WSO2AM_DB.h2.db + **/WSO2DM_DB.h2.db + **/lib/httpmime* + **/lib/encoder* + **/plugins/jaxb* + **/repository/conf/* + **/user-mgt.xml + + **/asm-all_4.1.0.wso2v1.jar + **/java-property-utils_1.9.0.wso2v1.jar + **/axis2-transport-jms_1.1.0.wso2v13.jar + **/axis2-transport-mail_1.1.0.wso2v13.jar + **/commons-digester_1.8.1.wso2v1.jar + **/org.apache.commons.configuration_1.10.0.jar + **/commons-configuration_1.6.0.wso2v1.jar + **/net.minidev.json-smart_1.2.0.jar + **/libthrift_0.7.0.wso2v2.jar + **/com.google.gson_2.3.1.jar + **/com.google.gson_2.2.4.jar + **/com.google.gson_2.1.0.jar + **/com.jayway.jsonpath_0.8.1.wso2v1.jar + **/json_1.0.0.wso2v1.jar + **/json_2.0.0.wso2v1.jar + **/bcprov-jdk15on_1.49.0.wso2v1.jar + **/xmlbeans_2.3.0.wso2v1.jar + **/nimbus-jose-jwt_2.26.1.wso2v2.jar + **/org.wso2.carbon.hostobjects.sso_4.4.3.jar + **/org.wso2.carbon.hostobjects.sso_4.3.2.jar + **/conf/log4j.properties + **/repository/conf/security/Owasp.CsrfGuard.Carbon.properties + **/conf/tomcat/carbon/WEB-INF/web.xml + **/bin/wso2server.sh + **/bin/wso2server.bat + **/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handler-utils.js + **/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handlers.js + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/lib + + ${pom.artifactId}-${pom.version}/wso2/lib/ + + */** + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/ + + ${pom.artifactId}-${pom.version}/conf/ + + + **/* + + true + + + + + + + + + + + + src/core/resources/styles/css + ${pom.artifactId}-${pom.version}/resources/allthemes/Default/admin + + + **/**.css + + + + src/core/resources/styles/images + ${pom.artifactId}-${pom.version}/resources/allthemes/Default/images + + + **/**.gif + **/**.png + + + + + + target/site + ${pom.artifactId}-${pom.version}/docs + 755 + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/modules + + ${pom.artifactId}-${pom.version}/wso2/modules/ + + **/carbon/ + **/jaggery-test/ + **/process/ + **/uuid/ + **/i18n/ + **/ws/ + **/appmgtpublisher/ + **/appstore/ + **/store/ + **/lifecycle/ + **/utils/ + **/caramel/ + **/markdown/ + **/handlebars/ + **/event/ + **/claims/ + **/permission/ + **/registration/ + + + + src/core/conf + ${pom.artifactId}-${pom.version}/conf + + **/api-manager.xml + **/sso-idp-config.xml + **/application-authentication.xml + **/log4j.properties + **/nhttp.properties + **/passthru-http.properties + **/user-mgt.xml + + + + + + + + + + + + + + + + + + + + + src/core/conf/datasources + ${pom.artifactId}-${pom.version}/conf/datasources + + + **/master-datasources.xml + **/cdm-datasources.xml + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/datasources + + ${pom.artifactId}-${pom.version}/conf/datasources + + + */** + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/device-types + + ${pom.artifactId}-${pom.version}/conf/device-types + + + */** + + + + src/core/resources + ${pom.artifactId}-${pom.version}/repository/resources + + */** + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/dbscripts/ + + ${pom.artifactId}-${pom.version}/dbscripts/ + + */** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/modules + ${pom.artifactId}-${pom.version}/wso2/modules/ + + */** + + + + + + + + + + + + + + + + + + + + + + src/core/modules + ${pom.artifactId}-${pom.version}/wso2/modules + + */** + + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/carbonapps + ${pom.artifactId}-${pom.version}/repository/deployment/server/carbonapps + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/resources + + ${pom.artifactId}-${pom.version}/repository/resources + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/devicetypes + + ${pom.artifactId}-${pom.version}/repository/deployment/server/devicetypes + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/devicemgt/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/devicemgt + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/devicemgt-cdmf/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/devicemgt + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/uuf-template-app/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/devicemgt + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/windows-web-agent/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/windows-web-agent + + + **/jaggery.conf + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/uuf-template-app/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/windows-web-agent + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/android-web-agent/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/android-web-agent + + + **/jaggery.conf + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps/uuf-template-app/ + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/android-web-agent + + + **/jaggery.conf + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/webapps/ + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps/ + + + appmoauth2.war + am#sample#calculator#v1.war + api.war + + false + 644 + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/publisher/ + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/publisher + + + publisherLogo/** + publisherTheme/** + publisherSite/** + footer/** + localstyles.css + **/jaggery.conf + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/store/ + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/store + + + storeLogo/** + storeSite/** + base-page/** + login/** + styles-layout.css + **/jaggery.conf + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/api-store/ + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/api-store + + + storeLogo/** + storeSite/** + base-page/** + login/** + styles-layout.css + **/site/conf/site.json + **/jaggery.conf + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/synapse-configs/default/api/ + + ${pom.artifactId}-${pom.version}/repository/deployment/server/synapse-configs/default/api/ + + + + + + + src/core/api-resources/customsequences + ${pom.artifactId}-${pom.version}/repository/resources/customsequences + + **/**.xml + + + + src/core/api-resources/default-tiers + ${pom.artifactId}-${pom.version}/repository/resources/default-tiers + + **/**.xml + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/social/ + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/social + + **/jaggery.conf + + + + + src/core/api-resources/synapse-configs/default/sequences + ${pom.artifactId}-${pom.version}/repository/resources/apim-synapse-config/ + + + + src/core/api-resources/synapse-configs + ${pom.artifactId}-${pom.version}/repository/deployment/server/synapse-configs/ + + + + src/core/api-resources/api_templates + ${pom.artifactId}-${pom.version}/repository/resources/api_templates + + **/**.xml + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/rxts + + ${pom.artifactId}-${pom.version}/repository/resources/rxts + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity + + ${pom.artifactId}-${pom.version}/conf/identity + + + **/saml1-assertion-config + **/msg-mgt.properties + **/entitlement.properties + **/EndpointConfig.properties + **/identity.xml + **/thrift-authentication.xml + + + + src/core/conf/identity/service-providers + ${pom.artifactId}-${pom.version}/conf/identity/service-providers + + */** + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/identity-providers + + + ${pom.artifactId}-${pom.version}/conf/identity/identity-providers + + + **/default.xml + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/service-providers + + + ${pom.artifactId}-${pom.version}/conf/identity/service-providers + + + **/default.xml + + + + + + + + + + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/deployment/server/jaggeryapps/portal + + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal + + + **/* + + + **/configs/designer.json + **/jaggery.conf + + + + + + + src/core/jaggeryapps/portal/themes + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/extensions/themes + + **/* + + + + + + ../scripts/mobile-qsg/resources + + ${pom.artifactId}-${pom.version}/samples/mobile-qsg + + + **/** + + + + + ../scripts/mobile-qsg/target + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + + **/** + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/components/dropins + + ${pom.artifactId}-${pom.version}/dropins + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/components/lib + + ${pom.artifactId}-${pom.version}/lib + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/components/patches + + ${pom.artifactId}-${pom.version}/patches + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/components/servicepacks + + ${pom.artifactId}-${pom.version}/servicepacks + + + + + + + + + + + + + + + + + + + + + + + + + + + src/core/conf/tomcat/carbon/WEB-INF/web.xml + ${pom.artifactId}-${pom.version}/conf/tomcat/carbon/WEB-INF + 755 + + + + src/core/bin/wso2server.sh + ${pom.artifactId}-${pom.version}/bin + 755 + + + src/core/bin/wso2server.bat + ${pom.artifactId}-${pom.version}/bin + 755 + + + src/core/jaggeryapps/portal/configs/designer.json + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/configs + + 755 + + + src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth + + 755 + + + src/core/jaggeryapps/portal/modules/oauth/token-handlers.js + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth + + 755 + + + + + + src/core/jaggeryapps/api-store/site/conf/site.json + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/api-store/site/conf + + 755 + + + + + src/core/conf/synapse.properties + ${pom.artifactId}-${pom.version}/conf + synapse.properties + true + 644 + + + src/core/conf/etc/device-analytics-config.xml + ${pom.artifactId}-${pom.version}/conf/etc + device-analytics-config.xml + true + 644 + + + + src/core/conf/synapse-handlers.xml + ${pom.artifactId}-${pom.version}/conf + synapse-handlers.xml + true + 644 + + + src/core/conf/tomcat/context.xml + ${pom.artifactId}-${pom.version}/conf/tomcat + true + 644 + + + + src/core/conf/security/Owasp.CsrfGuard.Carbon.properties + ${pom.artifactId}-${pom.version}/conf/security + + + src/core/conf/security/Owasp.CsrfGuard.dashboard.properties + ${pom.artifactId}-${pom.version}/conf/security + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/event-broker.xml + + ${pom.artifactId}-${pom.version}/conf/ + true + 644 + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/registry-event-broker.xml + + ${pom.artifactId}-${pom.version}/conf/ + true + 644 + + + src/core/INSTALL.txt + ${pom.artifactId}-${pom.version} + true + 644 + + + src/core/README.txt + ${pom.artifactId}-${pom.version} + true + 644 + + + src/core/LICENSE.txt + ${pom.artifactId}-${pom.version} + true + 644 + + + src/core/release-notes.html + ${pom.artifactId}-${pom.version} + true + 644 + + + target/wso2carbon-core-${carbon.kernel.version}/bin/README.txt + ${pom.artifactId}-${pom.version}/bin/ + true + 644 + + + target/wso2carbon-core-${carbon.kernel.version}/bin/version.txt + ${pom.artifactId}-${pom.version}/bin/ + true + 644 + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/etc/logging-config.xml + + ${pom.artifactId}-${pom.version}/conf/etc + true + 644 + + + + src/core/conf/application-authenticators.xml + ${pom.artifactId}-${pom.version}/conf/security/ + + true + 644 + + + target/wso2carbon-core-${carbon.kernel.version}/repository/conf/README + ${pom.artifactId}-${pom.version}/conf/ + true + 644 + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/identity/oidc-scope-config.xml + ${pom.artifactId}-${pom.version}/conf/identity/ + true + 644 + + + src/core/conf/identity/application-authentication.xml + ${pom.artifactId}-${pom.version}/conf/identity + + 644 + + + + src/core/conf/identity/identity-providers/iot_default.xml + + ${pom.artifactId}-${pom.version}/conf/identity/identity-providers + true + 644 + + + + src/core/conf/identity/sso-idp-config.xml + ${pom.artifactId}-${pom.version}/conf/identity + 644 + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/governance.xml + + ${pom.artifactId}-${pom.version}/conf + 644 + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/conf/apim-integration.xml + + ${pom.artifactId}-${pom.version}/conf + 644 + + + + src/core/conf/api-manager.xml + ${pom.artifactId}-${pom.version}/conf + 644 + + + + + src/core/resources/lifecycles/APILifeCycle.xml + ${pom.artifactId}-${pom.version}/repository/resources/lifecycles + 644 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/database/WSO2METRICS_DB.h2.db + ${pom.artifactId}-${pom.version}/repository/database/ + 644 + + + + + + + + + + + + src/core/conf/app-manager.xml + ${pom.artifactId}-${pom.version}/conf + true + 644 + + + src/core/resources/appm-tenant-conf.xml + ${pom.artifactId}-${pom.version}/repository/resources + true + 644 + + + + + src/core/conf/license-config.xml + + ${pom.artifactId}-${pom.version}/conf/etc + true + 644 + + + + + + + + + + + + + + + src/core/conf/registry.xml + + ${pom.artifactId}-${pom.version}/conf/ + true + 644 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + target/wso2carbon-core-${carbon.kernel.version}/repository/database/WSO2AM_DB.h2.db + + ${pom.artifactId}-${pom.version}/repository/database + WSO2AM_DB.h2.db + 644 + + + + + target/wso2carbon-core-${carbon.kernel.version}/repository/database/WSO2APPM_DB.h2.db + + ${pom.artifactId}-${pom.version}/repository/database + WSO2APPM_DB.h2.db + 644 + + + + + target/wso2carbon-core-${carbon.kernel.version}/repository/database/WSO2DM_DB.h2.db + + ${pom.artifactId}-${pom.version}/repository/database + WSO2DM_DB.h2.db + 644 + + + src/core/conf/carbon.xml + + ${pom.artifactId}-${pom.version}/conf/ + true + + + + + + + + + + + + + + + + src/core/conf/axis2/axis2.xml + ${pom.artifactId}-${pom.version}/conf/axis2 + + true + 644 + + + src/core/conf/etc/launch.ini + ${pom.artifactId}-${pom.version}/conf/etc/ + + true + 644 + + + + + src/core/conf/security/authenticators.xml + + ${pom.artifactId}-${pom.version}/conf/security/ + + true + 644 + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/bin/ciphertool.sh + + ${pom.artifactId}-${pom.version}/bin + 755 + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/bin/ciphertool.bat + + ${pom.artifactId}-${pom.version}/bin + 644 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + src/core/conf/analytics/analytics-data-config.xml + ${pom.artifactId}-${pom.version}/conf/analytics/ + true + 644 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + src/core/conf/identity/identity-providers/iot_default.xml + + ${pom.artifactId}-${pom.version}/conf/identity/identity-providers + true + 644 + + + + + + + + + + + + src/core/conf/log4j.properties + + ${pom.artifactId}-${pom.version}/conf + true + 644 + + + + + + + + + + + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/resources/devicetypes/device_management/org_wso2_carbon_analytics_cdmf-1.0.0.car + + ${pom.artifactId}-${pom.version}/repository/resources/devicetypes/device_management/ + 644 + + + + src/core/conf/etc/webapp-publisher-config.xml + ${pom.artifactId}-${pom.version}/conf/etc + webapp-publisher-config.xml + true + 644 + + + + + + + + + + + + + src/core/jaggeryapps/android-web-agent/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/android-web-agent/ + + 755 + + + src/core/jaggeryapps/api-store/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/api-store/ + + 755 + + + src/core/jaggeryapps/portal/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/ + + 755 + + + src/core/jaggeryapps/publisher/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/publisher/ + + 755 + + + src/core/jaggeryapps/social/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/social/ + + 755 + + + src/core/jaggeryapps/store/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/store/ + + 755 + + + src/core/jaggeryapps/windows-web-agent/jaggery.conf + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/windows-web-agent/ + + 755 + + + + target/webapp-temp/api-application-registration.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/api#scep-mgt#v1.0.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/client-registration#v0.11.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/secured-websocket.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/api#certificate-mgt#v1.0.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/api#identity#entitlement.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/authenticationendpoint.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/oauth2.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + target/webapp-temp/shindig.war + + ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps + + 755 + + + + src/core/cloud/portal/common.css + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/css + + + + + + src/core/cloud/portal/portal.js + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/js + + + + + + src/core/cloud/portal/global-navigation.jag + + ${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/theme/templates + + + + + + ../scripts/mobile-qsg/target/mobile-qsg.jar + + ${pom.artifactId}-${pom.version}/samples/mobile-qsg + + + + ../scripts/mobile-qsg/target/org.wso2.carbon.appmgt.oauth.core-1.2.5.jar + + ${pom.artifactId}-${pom.version}/dropins + + + + + diff --git a/modules/distribution/src/assembly/dist.xml b/modules/distribution/src/assembly/dist.xml new file mode 100644 index 00000000..bdeadb9e --- /dev/null +++ b/modules/distribution/src/assembly/dist.xml @@ -0,0 +1,39 @@ + + + wso2-iot-dist + + zip + + + false + + + + ../p2-profile/iot-core-profile/target/wso2carbon-core-${carbon.kernel.version}/wso2/components + ${pom.artifactId}-${pom.version}/wso2/components + + **/eclipse.ini + **/*.lock + **/.data + **/.settings + features/** + + + + diff --git a/modules/distribution/src/assembly/filter.properties b/modules/distribution/src/assembly/filter.properties new file mode 100644 index 00000000..4a97a77f --- /dev/null +++ b/modules/distribution/src/assembly/filter.properties @@ -0,0 +1,26 @@ +# +# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +# +# WSO2 Inc. licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +product.name=WSO2 IoT Server +product.key=IoT +product.version=6.0.0 + +carbon.version=4.4.14 +ei.version=3.1.0 +default.server.role=IoTServer +bundle.creators=org.wso2.carbon.mediator.bridge.MediatorBundleCreator diff --git a/modules/distribution/src/core/INSTALL.txt b/modules/distribution/src/core/INSTALL.txt new file mode 100644 index 00000000..0aacac7b --- /dev/null +++ b/modules/distribution/src/core/INSTALL.txt @@ -0,0 +1,44 @@ +Installing WSO2 IoT Server 3.0.0 + +Running the server +----------------- +1. The directory containing this INSTALL file will be the root and it is treated as the IoTS home directory, and is referred to as . + +2. WSO2 IoT Server comes as a composition of three components namely broker, core, and analytics. + +3. The starting order of the WSO2 IoTS components should be broker, core, analytics. + +4. To start/stop/restart the IoTS components, run wso2server.sh for *nix systems and wso2server.bat for Windows systems, which can be found in following locations. + /broker/bin + /core/bin + /analytics/bin + +5. The wso2server.sh and wso2server.bat startup scripts have the following commands: + + i) ./wso2server.sh {console|start|stop|restart|status|dump|version} + ii) wso2server.bat {start|stop|version} + + Usage: wso2server.sh [command] + command: + --debug Start the server in remote debugging mode + The remote debugging port + --run Run the server + --start Start the server as a Unix daemon in the background + --console Start the server as a Unix daemon in the foreground + --stop Stop the server Unix daemon + --status Get the status of the Carbon Unix daemon + --dump Print a thread dump of the Carbon Unix daemon + --restart Restart the Carbon Unix daemon + --version The version of the Carbon server are you running + --n Start multiple instances of the same server after you + have successfully installed the Multiple-instances feature + from a feature repository + +System Requirements +------------------- +1. Minimum memory - 4GB +2. The WSO2 IOTS Management Console requires full Javascript enablement in the Web browser + NOTE: + On Windows Server 2003, it is not allowed to go below the medium security + level when using Internet Explorer 6.x. + diff --git a/modules/distribution/src/core/LICENSE.txt b/modules/distribution/src/core/LICENSE.txt new file mode 100644 index 00000000..c1b97982 --- /dev/null +++ b/modules/distribution/src/core/LICENSE.txt @@ -0,0 +1,787 @@ + +This product is licensed by WSO2 Inc. under Apache License 2.0. The license +can be downloaded from the following locations: + http://www.apache.org/licenses/LICENSE-2.0.html + http://www.apache.org/licenses/LICENSE-2.0.txt + +This product also contains software under different licenses. This table below +all the contained libraries (jar files) and the license under which they are +provided to you. + +At the bottom of this file is a table that shows what each license indicated +below is and where the actual text of the license can be found. + +Name Type License +--------------------------------------------------------------------------------------------------------- +abdera_1.0.0.wso2v3.jar bundle apache2 907 +addressing-1.6.1-wso2v20.mar bundle apache2 9597 +ajaxtags_1.3.0.beta-rc7-wso2v1.jar bundle apache2 905 +annogen_0.1.0.wso2v1.jar bundle apache2 942 +ant-contrib-1.0b3.jar jar apache2 549 +antlr-runtime_3.2.0.wso2v1.jar bundle bsd 817 +antlr_3.2.0.wso2v1.jar bundle bsd 838 +ant_1.7.0.wso2v1.jar bundle apache2 1012 +aopalliance-1.0.jar jar apache2 512 +apache-zookeeper_3.3.4.wso2v1.jar bundle apache2 4219 +asm-3.3.1.jar jar bsd 1268 +axiom_1.2.11.wso2v11.jar bundle apache2 8489 +axis2-json_1.6.1.wso2v20.jar bundle apache2 9596 +axis2-transport-mail_1.1.0.wso2v17.jar bundle apache2 5260 +axis2-transport-tcp_1.1.0.wso2v17.jar bundle apache2 5257 +axis2_1.6.1.wso2v20.jar bundle apache2 9595 +backport-util-concurrent_3.1.0.wso2v1.jar bundle apache2 1007 +bcpkix-jdk15on-1.52.jar jarinbundle bouncy 1343 +bcpkix-jdk15on_1.52.0.wso2v2.jar bundle bouncy 10221 +bcprov-jdk15on-1.52.jar jarinbundle bouncy 1819 +bcprov-jdk15on_1.52.0.wso2v1.jar bundle bouncy 8485 +bcprov-jdk15-132.jar jar bouncy 285 +bsf-all_3.0.0.wso2v5.jar bundle apache2 5254 +com.fasterxml.jackson.core.jackson-annotations_2.8.2.jar bundle apache2 2057 +com.fasterxml.jackson.core.jackson-core_2.8.2.jar bundle apache2 2056 +com.fasterxml.jackson.core.jackson-databind_2.8.2.jar bundle apache2 2055 +com.fasterxml.jackson.dataformat.jackson-dataformat-yaml_2.8.2.jar bundle apache2 2054 +com.google.gson_2.7.0.jar bundle apache2 1853 +com.google.guava_18.0.0.jar bundle apache2 1511 +com.google.guava_19.0.0.jar bundle apache2 1627 +com.googlecode.plist.dd-plist_1.8.0.jar bundle mit 913 +com.jayway.jsonpath.json-path_0.9.1.jar bundle apache2 798 +com.samskivert.jmustache_1.13.0.jar bundle bsd 2053 +com.sun.jersey.jersey-core_1.9.0.jar bundle cddl+gpl 1307 +commons-beanutils-1.7.0.jar jarinbundle apache2 383 +commons-cli_1.2.0.wso2v1.jar bundle apache2 922 +commons-codec_1.4.0.wso2v1.jar bundle apache2 980 +commons-collections-3.2.2.jar bundle apache2 2042 +commons-collections_3.2.2.wso2v1.jar bundle apache2 6268 +commons-dbcp_1.4.0.wso2v1.jar bundle apache2 962 +commons-digester-1.8.jar jarinbundle apache2 384 +commons-fileupload_1.3.2.wso2v1.jar bundle apache2 9594 +commons-httpclient_3.1.0.wso2v3.jar bundle apache2 8483 +commons-io_2.4.0.wso2v1.jar bundle apache2 4217 +commons-lang-2.6.0.wso2v1.jar bundle apache2 664 +commons-lang-2.6.jar bundle apache2 506 +commons-lang3_3.4.0.wso2v1.jar bundle apache2 8739 +commons-lang_2.6.0.wso2v1.jar bundle apache2 940 +commons-logging-1.1.1.jar jar apache2 274 +commons-pool_1.5.6.wso2v1.jar bundle apache2 1009 +commons-scxml-0.9.jar jarinbundle apache2 401 +commons-scxml_0.9.0.wso2v1.jar bundle apache2 1070 +compass_2.0.1.wso2v2.jar bundle apache2 897 +cors-filter_1.7.0.wso2v1.jar bundle apache2 2106 +csrfguard_3.1.0.wso2v2.jar bundle bsd 8482 +cxf-bundle-2.7.16.jar bundle apache2 1154 +cxf-xjc-boolean-3.0.2.jar jar apache2 1153 +cxf-xjc-bug671-3.0.2.jar jar apache2 1152 +cxf-xjc-dv-3.0.2.jar jar apache2 1151 +cxf-xjc-runtime-3.0.2.jar bundle apache2 1150 +cxf-xjc-ts-3.0.2.jar jar apache2 1149 +disruptor_3.3.2.wso2v2.jar bundle apache2 4377 +ehcache-core-2.5.1.jar jar apache2 267 +ehcache_1.5.0.wso2v3.jar bundle apache2 852 +encoder_1.2.0.wso2v1.jar bundle apache2 4030 +feign-jaxrs-9.3.1.jar jarinbundle apache2 2058 +fontbox_1.8.10.wso2v2.jar bundle bsd 6702 +gdata-core_1.47.0.wso2v1.jar bundle apache2 1481 +geronimo-jaxws_2.2_spec-1.0.jar bundle apache2 395 +geronimo-jms_1.1_spec-1.1.0.wso2v1.jar bundle apache2 661 +geronimo-jta_1.1_spec-1.1.jar jar apache2 1066 +geronimo-saaj_1.3_spec_1.0.0.wso2v3.jar bundle apache2 893 +guava_12.0.0.wso2v1.jar apache2 +guice_3.0.0.wso2v1.jar bundle apache2 1505 +h2-1.3.175.jar jarinbundle epl1 1999 +h2_1.3.175.wso2v1.jar bundle apache2 9731 +handy-uri-templates_1.1.7.wso2v1.jar bundle apache2 1989 +hapi_2.1.0.wso2v1.jar bundle mpl10 5251 +hazelcast_3.5.4.wso2v2.jar bundle apache2 8481 +hector-core_1.1.4.wso2v1.jar bundle apache2 2878 +high-scale-lib_1.0.0.wso2v1.jar bundle apache2 4216 +httpasyncclient-4.0-beta3.jar jar apache2 280 +httpclient-4.2.5.jar jar apache2 548 +httpclient_4.3.1.wso2v2.jar bundle apache2 4214 +httpcore-4.2.4.jar jar apache2 533 +httpcore-nio-4.2.4.jar jar apache2 534 +httpcore-nio_4.3.3.wso2v4.jar bundle apache2 8736 +httpcore_4.3.3.wso2v1.jar bundle apache2 3638 +httpmime-4.3.6.jar jarinbundle apache2 1139 +httpmime_4.3.1.wso2v2.jar bundle apache2 4375 +icu4j-3.8.jar jarinbundle icu 321 +io.dropwizard.metrics.core_3.1.2.jar bundle apache2 1305 +io.dropwizard.metrics.jvm_3.1.2.jar bundle apache2 1302 +io.github.openfeign.feign-core_9.3.1.jar bundle apache2 2060 +io.github.openfeign.feign-gson_9.3.1.jar bundle apache2 2059 +io.netty.buffer_4.0.30.Final.jar bundle apache2 1544 +io.netty.codec-http_4.0.30.Final.jar bundle apache2 1543 +io.netty.codec_4.0.30.Final.jar bundle apache2 1542 +io.netty.common_4.0.30.Final.jar bundle apache2 1541 +io.netty.handler_4.0.30.Final.jar bundle apache2 1540 +io.netty.transport_4.0.30.Final.jar bundle apache2 1539 +io.swagger.annotations_1.5.10.jar bundle apache2 2052 +io.swagger.core_1.5.10.jar bundle apache2 2051 +io.swagger.models_1.5.10.jar bundle apache2 2050 +jackson-annotations_2.6.1.wso2v1.jar bundle apache2 7757 +jackson-core_2.6.1.wso2v1.jar bundle apache2 7756 +jackson-databind_2.6.1.wso2v3.jar bundle apache2 8735 +javassist-3.12.1.GA.jar jarinbundle lgpl2 1768 +javasysmon_0.3.3.wso2v1.jar bundle bsd 721 +javax.cache.wso2_4.4.11.jar bundle apache2 2045 +javax.servlet.jsp-api_2.2.1.jar bundle cddl+gpl 1301 +javax.validation.api_1.1.0.Final.jar bundle apache2 1840 +javax.ws.rs-api-2.0-m10.jar bundle cddl+gpl 263 +javax.ws.rs-api-2.0.1.jar jarinbundle cddl+gpl 1452 +jaxb-impl-2.2.6.jar jarinbundle cddl+gpl 1823 +jaxb-impl-2.2.6.jar jar cddl1 1148 +jaxb-xjc-2.2.6.jar jarinbundle cddl+gpl 1822 +jaxb-xjc-2.2.6.jar jar cddl1 1147 +jdbc-pool_7.0.34.wso2v2.jar bundle apache2 3637 +jdom_1.0.0.wso2v1.jar bundle apache2 693 +jericho-html-2.4.jar jarinbundle epl1 363 +jersey-client-1.12.jar jarinbundle cddl+gpl 1821 +jettison-1.3.4.jar bundle apache2 542 +jettison_1.3.4.wso2v1.jar bundle apache2 2162 +joda-time_2.8.2.wso2v1.jar bundle apache2 6879 +jscep_2.3.0.wso2v2.jar bundle mit 10220 +json-schema-validator-all_2.2.6.wso2v2.jar bundle apache2 10931 +json-simple_1.1.0.wso2v1.jar bundle apache2 828 +json_3.0.0.wso2v1.jar bundle apache2 6503 +jsoup-1.8.1.jar jarinbundle mit 1138 +jsr311-api-1.1.1.jar jarinbundle cddl1 553 +jstl_1.2.1.wso2v2.jar bundle cddl1 2204 +js_1.7.0.R4wso2v1.jar bundle mpl10 2199 +kaptcha_2.3.0.wso2v1.jar bundle apache2 854 +kryo_2.24.0.wso2v1.jar bundle bsd 4692 +libphonenumber_7.4.2.wso2v1.jar bundle apache2 8733 +libthrift_0.8.0.wso2v1.jar bundle apache2 1117 +libthrift_0.9.2.wso2v1.jar bundle apache2 5912 +localizer-1.0.jar jarinbundle apache2 551 +lucene_5.2.1.wso2v1.jar bundle apache2 4502 +maven-scm_1.7.0.wso2v2.jar bundle apache2 1331 +neethi-3.0.3.jar bundle apache2 1146 +neethi_2.0.4.wso2v5.jar bundle apache2 6267 +nekohtml-1.9.10.jar jarinbundle apache2 1576 +net.minidev.json-smart_1.3.0.jar bundle apache2 1337 +nimbus-jose-jwt_2.26.1.wso2v3.jar bundle apache2 4885 +noggit_0.6.0.wso2v1.jar bundle apache2 4211 +objenesis_2.1.0.wso2v1.jar bundle mit 4688 +oltu_1.0.0.wso2v3.jar bundle apache2 6502 +opencsv-1.8.jar jarinbundle apache2 368 +opencsv_1.8.0.wso2v1.jar bundle apache2 928 +openid4java_1.0.0.wso2v2.jar bundle apache2 6216 +opensaml_2.6.4.wso2v3.jar bundle apache2 8480 +openxri-client-1.2.0.jar jarinbundle apache2 433 +openxri-syntax-1.2.0.jar jarinbundle apache2 434 +org.apache.aries.blueprint_1.1.0.jar bundle apache2 1346 +org.apache.aries.proxy_1.0.1.jar bundle apache2 1345 +org.apache.aries.util_1.1.0.jar bundle apache2 1344 +org.apache.felix.gogo.command_0.10.0.v201209301215.jar bundle apache2 1134 +org.apache.felix.gogo.runtime_0.10.0.v201209301036.jar bundle apache2 1133 +org.apache.felix.gogo.shell_0.10.0.v201212101605.jar bundle apache2 1132 +org.apache.velocity_1.7.0.jar bundle apache2 1839 +org.eclipse.core.contenttype_3.4.200.v20130326-1255.jar bundle epl1 1131 +org.eclipse.core.expressions_3.4.500.v20130515-1343.jar bundle epl1 1130 +org.eclipse.core.jobs_3.5.300.v20130429-1813.jar bundle epl1 1129 +org.eclipse.core.runtime_3.9.0.v20130326-1255.jar bundle epl1 1128 +org.eclipse.ecf.filetransfer_5.0.0.v20130604-1622.jar bundle epl1 1127 +org.eclipse.ecf.identity_3.2.0.v20130604-1622.jar bundle epl1 1126 +org.eclipse.ecf.provider.filetransfer.httpclient_4.0.200.v20120319-0616.jar bundle epl1 289 +org.eclipse.ecf.provider.filetransfer_3.2.0.v20130604-1622.jar bundle epl1 1125 +org.eclipse.ecf_3.2.0.v20130604-1622.jar bundle epl1 1124 +org.eclipse.equinox.app_1.3.100.v20130327-1442.jar bundle epl1 1123 +org.eclipse.equinox.common_3.6.200.v20130402-1505.jar bundle epl1 1122 +org.eclipse.equinox.concurrent_1.1.0.v20130327-1442.jar bundle epl1 1121 +org.eclipse.equinox.console_1.0.100.v20130429-0953.jar bundle epl1 1120 +org.eclipse.equinox.ds_1.4.101.v20130813-1853.jar bundle epl1 1119 +org.eclipse.equinox.frameworkadmin.equinox_1.0.500.v20130327-2119.jar bundle epl1 1118 +org.eclipse.equinox.frameworkadmin_2.0.100.v20130327-2119.jar bundle epl1 1117 +org.eclipse.equinox.http.helper_1.1.0.wso2v1.jar bundle epl1 839 +org.eclipse.equinox.http.servlet_1.1.400.v20130418-1354.jar bundle epl1 1116 +org.eclipse.equinox.jsp.jasper_1.0.400.v20120522-2049.jar bundle epl1 388 +org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar bundle epl1 1115 +org.eclipse.equinox.p2.artifact.repository_1.1.100.v20110519.jar bundle epl1 337 +org.eclipse.equinox.p2.console_1.0.300.v20130327-2119.jar bundle epl1 1114 +org.eclipse.equinox.p2.core_2.3.0.v20130327-2119.jar bundle epl1 1113 +org.eclipse.equinox.p2.director.app_1.0.300.v20130819-1621.jar bundle epl1 1112 +org.eclipse.equinox.p2.directorywatcher_1.0.300.v20130327-2119.jar bundle epl1 1110 +org.eclipse.equinox.p2.director_2.3.0.v20130526-0335.jar bundle epl1 1111 +org.eclipse.equinox.p2.engine_2.3.0.v20130526-2122-wso2v1.jar bundle epl1 3873 +org.eclipse.equinox.p2.extensionlocation_1.2.100.v20130327-2119.jar bundle epl1 1109 +org.eclipse.equinox.p2.garbagecollector_1.0.200.v20130327-2119.jar bundle epl1 1108 +org.eclipse.equinox.p2.jarprocessor_1.0.300.v20130327-2119.jar bundle epl1 1107 +org.eclipse.equinox.p2.metadata.repository_1.2.100.v20130327-2119.jar bundle epl1 1106 +org.eclipse.equinox.p2.metadata_2.2.0.v20130523-1557.jar bundle epl1 1105 +org.eclipse.equinox.p2.publisher_1.2.0.v20110511.jar bundle epl1 306 +org.eclipse.equinox.p2.repository.tools_2.1.0.v20130327-2119.jar bundle epl1 1104 +org.eclipse.equinox.p2.repository_2.3.0.v20130412-2032.jar bundle epl1 1103 +org.eclipse.equinox.p2.touchpoint.eclipse_2.1.0.v20110511-wso2v1.jar bundle epl1 703 +org.eclipse.equinox.p2.touchpoint.natives_1.1.100.v20130327-2119.jar bundle epl1 1102 +org.eclipse.equinox.p2.transport.ecf_1.0.100.v20110902-0807.jar bundle epl1 369 +org.eclipse.equinox.p2.updatechecker_1.1.200.v20130327-2119.jar bundle epl1 1101 +org.eclipse.equinox.p2.updatesite_1.0.400.v20130515-2028.jar bundle epl1 1100 +org.eclipse.equinox.preferences_3.5.100.v20130422-1538.jar bundle epl1 1099 +org.eclipse.equinox.registry_3.5.301.v20130717-1549.jar bundle epl1 1098 +org.eclipse.equinox.security_1.2.0.v20130424-1801.jar bundle epl1 1097 +org.eclipse.equinox.simpleconfigurator.manipulator_2.0.0.v20130327-2119.jar bundle epl1 1096 +org.eclipse.equinox.simpleconfigurator_1.0.400.v20130327-2119.jar bundle epl1 1095 +org.eclipse.equinox.util_1.0.500.v20130404-1337.jar bundle epl1 1094 +org.eclipse.jdt.core.compiler.batch_3.10.2.v20150120-1634.jar bundle epl1 1141 +org.eclipse.osgi.services_3.3.100.v20130513-1956.jar bundle epl1 1093 +org.eclipse.osgi_3.9.1.v20130814-1242.jar bundle epl1 1092 +org.eclipse.paho.client.mqttv3_1.0.2.jar bundle epl1 1769 +org.eclipse.wst.jsdt.debug.rhino.debugger_1.0.300.v201109150503.jar bundle epl1 558 +org.eclipse.wst.jsdt.debug.transport_1.0.100.v201109150330.jar bundle epl1 557 +org.jaggeryjs.hostobjects.db_0.12.8.jar bundle apache2 1998 +org.jaggeryjs.hostobjects.feed_0.12.8.jar bundle apache2 1997 +org.jaggeryjs.hostobjects.file_0.12.8.jar bundle apache2 1996 +org.jaggeryjs.hostobjects.jaggeryparser_0.12.8.jar bundle apache2 1995 +org.jaggeryjs.hostobjects.log_0.12.8.jar bundle apache2 1994 +org.jaggeryjs.hostobjects.registry_0.12.8.jar bundle apache2 1993 +org.jaggeryjs.hostobjects.stream_0.12.8.jar bundle apache2 1992 +org.jaggeryjs.hostobjects.uri_0.12.8.jar bundle apache2 1991 +org.jaggeryjs.hostobjects.web_0.12.8.jar bundle apache2 1990 +org.jaggeryjs.hostobjects.xhr_0.12.8.jar bundle apache2 1989 +org.jaggeryjs.hostobjects.xslt_0.12.8.jar bundle apache2 1988 +org.jaggeryjs.jaggery.app.mgt.stub_0.12.8.jar bundle apache2 1987 +org.jaggeryjs.jaggery.app.mgt.ui_0.12.8.jar bundle apache2 1986 +org.jaggeryjs.jaggery.app.mgt_0.12.8.jar bundle apache2 1985 +org.jaggeryjs.jaggery.core_0.12.8.jar bundle apache2 1984 +org.jaggeryjs.jaggery.deployer_0.12.8.jar bundle apache2 1983 +org.jaggeryjs.jaggery.tools_0.12.8.jar bundle apache2 1982 +org.jaggeryjs.modules.process_1.5.5.jar bundle apache2 1953 +org.jaggeryjs.modules.sso_1.5.5.jar bundle apache2 1952 +org.jaggeryjs.modules.uuid_1.5.5.jar bundle apache2 1951 +org.jaggeryjs.modules.ws_1.5.5.jar bundle apache2 1981 +org.jaggeryjs.scriptengine_0.12.8.jar bundle apache2 1980 +org.restlet_2.3.0.wso2v1.jar bundle apache2 4501 +org.sat4j.core_2.3.5.v201308161310.jar bundle epl1+lgpl21091 +org.sat4j.pb_2.3.5.v201308161310.jar bundle epl1+lgpl21090 +org.wso2.balana_1.1.2.jar bundle apache2 10593 +org.wso2.caching_4.0.3.jar bundle apache2 2919 +org.wso2.carbon.addressing_4.4.11.jar bundle apache2 10386 +org.wso2.carbon.analytics.api_1.3.3.jar bundle apache2 10830 +org.wso2.carbon.analytics.dataservice.commons_1.3.3.jar bundle apache2 10828 +org.wso2.carbon.analytics.datasource.commons_1.3.3.jar bundle apache2 10825 +org.wso2.carbon.analytics.io.commons_1.3.3.jar bundle apache2 10819 +org.wso2.carbon.apimgt.annotations_2.0.8.jar bundle apache2 11056 +org.wso2.carbon.apimgt.api_6.1.35.jar bundle apache2 11055 +org.wso2.carbon.apimgt.application.extension_2.0.8.jar bundle apache2 11054 +org.wso2.carbon.apimgt.authenticator.oidc.stub_6.1.35.jar bundle apache2 11053 +org.wso2.carbon.apimgt.authenticator.oidc.ui_6.1.35.jar bundle apache2 11052 +org.wso2.carbon.apimgt.authenticator.oidc_6.1.35.jar bundle apache2 11051 +org.wso2.carbon.apimgt.core_6.1.35.jar bundle apache2 11050 +org.wso2.carbon.apimgt.gateway.stub_6.1.35.jar bundle apache2 11049 +org.wso2.carbon.apimgt.gateway_6.1.35.jar bundle apache2 11048 +org.wso2.carbon.apimgt.handlers.security.stub_6.1.35.jar bundle apache2 11047 +org.wso2.carbon.apimgt.handlers_2.0.8.jar bundle apache2 11046 +org.wso2.carbon.apimgt.hostobjects.oidc_6.1.35.jar bundle apache2 11045 +org.wso2.carbon.apimgt.hostobjects_6.1.35.jar bundle apache2 11044 +org.wso2.carbon.apimgt.impl_6.1.35.jar bundle apache2 11043 +org.wso2.carbon.apimgt.keymgt.client_6.1.35.jar bundle apache2 11042 +org.wso2.carbon.apimgt.keymgt.stub_6.1.35.jar bundle apache2 11041 +org.wso2.carbon.apimgt.keymgt_6.1.35.jar bundle apache2 11040 +org.wso2.carbon.apimgt.registry.cache.stub_6.1.35.jar bundle apache2 11039 +org.wso2.carbon.apimgt.statsupdate.stub_6.1.35.jar bundle apache2 11038 +org.wso2.carbon.apimgt.tier.cache.stub_6.1.35.jar bundle apache2 11037 +org.wso2.carbon.apimgt.usage.client_6.1.35.jar bundle apache2 11036 +org.wso2.carbon.apimgt.usage.publisher_6.1.35.jar bundle apache2 11035 +org.wso2.carbon.apimgt.webapp.publisher_2.0.8.jar bundle apache2 11034 +org.wso2.carbon.application.deployer.synapse_4.6.9.jar bundle apache2 10902 +org.wso2.carbon.application.deployer.webapp_4.7.2.jar bundle apache2 11033 +org.wso2.carbon.application.deployer_4.4.11.jar bundle apache2 10385 +org.wso2.carbon.application.mgt.stub_4.5.4.jar bundle apache2 8688 +org.wso2.carbon.application.mgt.synapse_4.6.9.jar bundle apache2 10901 +org.wso2.carbon.application.mgt.ui_4.5.4.jar bundle apache2 8686 +org.wso2.carbon.application.mgt_4.5.4.jar bundle apache2 8685 +org.wso2.carbon.application.upload_4.5.4.jar bundle apache2 8684 +org.wso2.carbon.appmgt.api_1.2.10.jar bundle apache2 11032 +org.wso2.carbon.appmgt.core_1.2.10.jar bundle apache2 11031 +org.wso2.carbon.appmgt.gateway.stub_1.2.10.jar bundle apache2 11030 +org.wso2.carbon.appmgt.hostobjects_1.2.10.jar bundle apache2 11029 +org.wso2.carbon.appmgt.impl_1.2.10.jar bundle apache2 11028 +org.wso2.carbon.appmgt.mdm.osgiconnector_3.0.7.jar bundle apache2 11027 +org.wso2.carbon.appmgt.mdm.restconnector_1.2.10.jar bundle apache2 11026 +org.wso2.carbon.appmgt.mdm.wso2emm_1.1.4.jar bundle apache2 8176 +org.wso2.carbon.appmgt.mobile_1.2.10.jar bundle apache2 11025 +org.wso2.carbon.appmgt.publisher_1.2.10.jar bundle apache2 11024 +org.wso2.carbon.appmgt.sample.deployer_1.2.10.jar bundle apache2 11023 +org.wso2.carbon.appmgt.usage.client_1.2.10.jar bundle apache2 11022 +org.wso2.carbon.appmgt.usage.publisher_1.2.10.jar bundle apache2 11021 +org.wso2.carbon.authenticator.proxy_4.4.11.jar bundle apache2 10384 +org.wso2.carbon.authenticator.stub_4.4.11.jar bundle apache2 10383 +org.wso2.carbon.bam.presentation.stub_4.2.0.jar bundle apache2 2165 +org.wso2.carbon.base_4.4.11.jar bundle apache2 10382 +org.wso2.carbon.bootstrap-4.4.11.jar bundle apache2 10337 +org.wso2.carbon.captcha.mgt_4.2.0.jar bundle apache2 2154 +org.wso2.carbon.certificate.mgt.core_2.0.8.jar bundle apache2 11020 +org.wso2.carbon.claim.mgt.stub_5.7.5.jar bundle apache2 10773 +org.wso2.carbon.claim.mgt.ui_5.7.5.jar bundle apache2 10772 +org.wso2.carbon.claim.mgt_5.7.5.jar bundle apache2 10771 +org.wso2.carbon.cluster.mgt.core_4.4.11.jar bundle apache2 10381 +org.wso2.carbon.connector.core_4.6.9.jar bundle apache2 10900 +org.wso2.carbon.core.bootup.validator_4.4.11.jar bundle apache2 10380 +org.wso2.carbon.core.commons.stub_4.4.11.jar bundle apache2 10378 +org.wso2.carbon.core.common_4.4.11.jar bundle apache2 10379 +org.wso2.carbon.core.services_4.4.11.jar bundle apache2 10377 +org.wso2.carbon.core_4.4.11.jar bundle apache2 10376 +org.wso2.carbon.cxf.ext-4.7.2.jar bundle apache2 10222 +org.wso2.carbon.dashboard.deployment_2.0.5.jar bundle apache2 11019 +org.wso2.carbon.dashboard.store.filter_2.0.5.jar bundle apache2 11018 +org.wso2.carbon.databridge.agent_5.1.5.jar bundle apache2 11017 +org.wso2.carbon.databridge.commons.binary_5.1.5.jar bundle apache2 11016 +org.wso2.carbon.databridge.commons.thrift_5.1.5.jar bundle apache2 11015 +org.wso2.carbon.databridge.commons_5.1.5.jar bundle apache2 11014 +org.wso2.carbon.databridge.core_5.1.5.jar bundle apache2 11013 +org.wso2.carbon.databridge.streamdefn.filesystem_5.1.5.jar bundle apache2 11012 +org.wso2.carbon.deployment.synchronizer.subversion_4.5.4.jar bundle apache2 8451 +org.wso2.carbon.deployment.synchronizer_4.5.4.jar bundle apache2 8450 +org.wso2.carbon.device.mgt.analytics.dashboard_2.0.8.jar bundle apache2 11011 +org.wso2.carbon.device.mgt.analytics.data.publisher_2.0.8.jar bundle apache2 11010 +org.wso2.carbon.device.mgt.common_2.0.8.jar bundle apache2 11009 +org.wso2.carbon.device.mgt.core_2.0.8.jar bundle apache2 11008 +org.wso2.carbon.device.mgt.extensions.device.type.deployer_2.0.8.jar bundle apache2 11007 +org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt_2.0.8.jar bundle apache2 11006 +org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp_2.0.8.jar bundle apache2 11005 +org.wso2.carbon.device.mgt.extensions_2.0.8.jar bundle apache2 11004 +org.wso2.carbon.device.mgt.input.adapter.extension_3.0.7.jar bundle apache2 11003 +org.wso2.carbon.device.mgt.input.adapter.http_3.0.7.jar bundle apache2 11002 +org.wso2.carbon.device.mgt.input.adapter.mqtt_3.0.7.jar bundle apache2 11001 +org.wso2.carbon.device.mgt.input.adapter.xmpp_3.0.7.jar bundle apache2 11000 +org.wso2.carbon.device.mgt.oauth.extensions_2.0.8.jar bundle apache2 10999 +org.wso2.carbon.device.mgt.output.adapter.mqtt_3.0.7.jar bundle apache2 10998 +org.wso2.carbon.device.mgt.output.adapter.websocket_3.0.7.jar bundle apache2 10997 +org.wso2.carbon.device.mgt.output.adapter.xmpp_3.0.7.jar bundle apache2 10996 +org.wso2.carbon.device.mgt.url.printer_2.0.10.jar bundle apache2 10995 +org.wso2.carbon.directory.server.manager.common_5.7.5.jar bundle apache2 10770 +org.wso2.carbon.directory.server.manager.stub_5.7.5.jar bundle apache2 10769 +org.wso2.carbon.directory.server.manager.ui_5.7.5.jar bundle apache2 10768 +org.wso2.carbon.directory.server.manager_5.7.5.jar bundle apache2 10767 +org.wso2.carbon.discovery.cxf_4.7.2.jar bundle apache2 10308 +org.wso2.carbon.dynamic.client.registration_2.0.10.jar bundle apache2 10994 +org.wso2.carbon.dynamic.client.web.app.registration_2.0.10.jar bundle apache2 10993 +org.wso2.carbon.email.sender.core_2.0.10.jar bundle apache2 10992 +org.wso2.carbon.email.verification.stub_4.5.4.jar bundle apache2 8678 +org.wso2.carbon.email.verification.ui_4.5.4.jar bundle apache2 8677 +org.wso2.carbon.email.verification_4.5.4.jar bundle apache2 8676 +org.wso2.carbon.endpoint.stub_4.6.9.jar bundle apache2 10991 +org.wso2.carbon.endpoint_4.6.9.jar bundle apache2 10899 +org.wso2.carbon.event.admin_4.5.4.jar bundle apache2 8444 +org.wso2.carbon.event.application.deployer_5.1.5.jar bundle apache2 10990 +org.wso2.carbon.event.client.stub_4.5.4.jar bundle apache2 8442 +org.wso2.carbon.event.client_4.5.4.jar bundle apache2 8441 +org.wso2.carbon.event.common_4.5.4.jar bundle apache2 8440 +org.wso2.carbon.event.core_4.5.4.jar bundle apache2 8439 +org.wso2.carbon.event.input.adapter.core_5.1.5.jar bundle apache2 10989 +org.wso2.carbon.event.output.adapter.core_5.1.5.jar bundle apache2 10988 +org.wso2.carbon.event.processor.stub_2.1.6.jar bundle apache2 10648 +org.wso2.carbon.event.stream.admin_5.1.5.jar bundle apache2 10987 +org.wso2.carbon.event.stream.core_5.1.5.jar bundle apache2 10986 +org.wso2.carbon.event.stream.persistence.stub_5.1.5.jar bundle apache2 10985 +org.wso2.carbon.event.stream.stub_5.1.5.jar bundle apache2 10984 +org.wso2.carbon.event.stream.ui_5.1.5.jar bundle apache2 10983 +org.wso2.carbon.event.template.manager.stub_5.1.7.jar bundle apache2 10625 +org.wso2.carbon.event.ws_4.5.4.jar bundle apache2 8417 +org.wso2.carbon.feature.mgt.core_4.4.11.jar bundle apache2 10375 +org.wso2.carbon.feature.mgt.services_4.4.11.jar bundle apache2 10374 +org.wso2.carbon.feature.mgt.stub_4.4.11.jar bundle apache2 10373 +org.wso2.carbon.feature.mgt.ui_4.4.11.jar bundle apache2 10372 +org.wso2.carbon.forum_6.1.35.jar bundle apache2 10982 +org.wso2.carbon.framework.exporter_4.4.11.jar bundle apache2 10371 +org.wso2.carbon.ganalytics.publisher_4.5.4.jar bundle apache2 8630 +org.wso2.carbon.governance.api_4.7.0.jar bundle apache2 9505 +org.wso2.carbon.governance.client_4.7.0.jar bundle apache2 9504 +org.wso2.carbon.governance.common_4.7.0.jar bundle apache2 9503 +org.wso2.carbon.governance.custom.lifecycles.checklist.stub_4.7.0.jar bundle apache2 9502 +org.wso2.carbon.governance.custom.lifecycles.checklist.ui_4.7.0.jar bundle apache2 9501 +org.wso2.carbon.governance.custom.lifecycles.checklist_4.7.0.jar bundle apache2 9500 +org.wso2.carbon.governance.custom.lifecycles.history.ui_4.7.0.jar bundle apache2 9499 +org.wso2.carbon.governance.generic.stub_4.7.0.jar bundle apache2 9498 +org.wso2.carbon.governance.generic.ui_4.7.0.jar bundle apache2 9497 +org.wso2.carbon.governance.generic_4.7.0.jar bundle apache2 9496 +org.wso2.carbon.governance.lcm.stub_4.7.0.jar bundle apache2 9495 +org.wso2.carbon.governance.lcm.ui_4.7.0.jar bundle apache2 9494 +org.wso2.carbon.governance.lcm_4.7.0.jar bundle apache2 9493 +org.wso2.carbon.governance.list_4.7.0.jar bundle apache2 9492 +org.wso2.carbon.governance.registry.eventing_4.7.0.jar bundle apache2 9491 +org.wso2.carbon.governance.registry.extensions_4.7.0.jar bundle apache2 9490 +org.wso2.carbon.governance.wsdltool.stub_4.7.0.jar bundle apache2 9486 +org.wso2.carbon.governance.wsdltool.ui_4.7.0.jar bundle apache2 9485 +org.wso2.carbon.governance.wsdltool_4.7.0.jar bundle apache2 9484 +org.wso2.carbon.hostobjects.sso_4.5.4.jar bundle apache2 10161 +org.wso2.carbon.hostobjects.sso_6.1.35.jar bundle apache2 10981 +org.wso2.carbon.i18n_4.4.11.jar bundle apache2 10370 +org.wso2.carbon.identity.application.authentication.endpoint.util_5.7.5.jar bundle apache2 10766 +org.wso2.carbon.identity.application.authentication.framework_5.7.5.jar bundle apache2 10765 +org.wso2.carbon.identity.application.authenticator.basicauth_5.2.4.jar bundle apache2 10980 +org.wso2.carbon.identity.application.authenticator.requestpath.oauth_5.1.1.jar bundle apache2 8394 +org.wso2.carbon.identity.application.authenticator.samlsso_5.1.4.jar bundle apache2 10979 +org.wso2.carbon.identity.application.common_5.7.5.jar bundle apache2 10764 +org.wso2.carbon.identity.application.mgt.stub_5.7.5.jar bundle apache2 10763 +org.wso2.carbon.identity.application.mgt.ui_5.7.5.jar bundle apache2 10762 +org.wso2.carbon.identity.application.mgt_5.7.5.jar bundle apache2 10761 +org.wso2.carbon.identity.authentication_4.5.4.jar bundle apache2 8609 +org.wso2.carbon.identity.authenticator.backend.oauth_2.0.10.jar bundle apache2 10978 +org.wso2.carbon.identity.authenticator.saml2.sso.common_5.1.6.jar bundle apache2 10977 +org.wso2.carbon.identity.authenticator.saml2.sso.stub_5.1.6.jar bundle apache2 10976 +org.wso2.carbon.identity.authenticator.saml2.sso.ui_5.1.6.jar bundle apache2 10975 +org.wso2.carbon.identity.authenticator.saml2.sso_5.1.6.jar bundle apache2 10974 +org.wso2.carbon.identity.authenticator.thrift_5.7.5.jar bundle apache2 10760 +org.wso2.carbon.identity.base_5.6.89.jar bundle apache2 10973 +org.wso2.carbon.identity.base_5.7.5.jar bundle apache2 10759 +org.wso2.carbon.identity.claim.metadata.mgt.stub_5.7.5.jar bundle apache2 10758 +org.wso2.carbon.identity.claim.metadata.mgt.ui_5.7.5.jar bundle apache2 10757 +org.wso2.carbon.identity.claim.metadata.mgt_5.7.5.jar bundle apache2 10756 +org.wso2.carbon.identity.core.ui_5.7.5.jar bundle apache2 10755 +org.wso2.carbon.identity.core_5.7.5.jar bundle apache2 10754 +org.wso2.carbon.identity.discovery_5.3.4.jar bundle apache2 10946 +org.wso2.carbon.identity.entitlement.common_5.7.5.jar bundle apache2 10752 +org.wso2.carbon.identity.entitlement.proxy_5.1.3.jar bundle apache2 10972 +org.wso2.carbon.identity.entitlement.stub_5.6.89.jar bundle apache2 10971 +org.wso2.carbon.identity.entitlement_5.7.5.jar bundle apache2 10749 +org.wso2.carbon.identity.governance.stub_5.7.5.jar bundle apache2 10747 +org.wso2.carbon.identity.inbound.metadata.saml2_0.1.1.jar bundle apache2 10970 +org.wso2.carbon.identity.jwt.client.extension_2.0.10.jar bundle apache2 10969 +org.wso2.carbon.identity.notification.mgt_5.7.5.jar bundle apache2 10742 +org.wso2.carbon.identity.oauth.common_5.3.4.jar bundle apache2 10944 +org.wso2.carbon.identity.oauth.dcr_5.3.4.jar bundle apache2 10943 +org.wso2.carbon.identity.oauth.stub_5.3.1.jar bundle apache2 10505 +org.wso2.carbon.identity.oauth.stub_5.3.4.jar bundle apache2 10942 +org.wso2.carbon.identity.oauth.ui_5.3.4.jar bundle apache2 10941 +org.wso2.carbon.identity.oauth2.grant.jwt_1.0.2.jar bundle apache2 8152 +org.wso2.carbon.identity.oauth_5.3.4.jar bundle apache2 10940 +org.wso2.carbon.identity.oidc.dcr_5.3.4.jar bundle apache2 10939 +org.wso2.carbon.identity.oidc.session_5.3.4.jar bundle apache2 10938 +org.wso2.carbon.identity.provider_5.1.1.jar bundle apache2 8360 +org.wso2.carbon.identity.query.saml_5.3.0.jar bundle apache2 10496 +org.wso2.carbon.identity.sp.metadata.saml2_0.1.6.jar bundle apache2 10968 +org.wso2.carbon.identity.sp.metadata.saml2_1.0.0.jar bundle apache2 10491 +org.wso2.carbon.identity.sso.agent_5.1.0.jar bundle apache2 8353 +org.wso2.carbon.identity.sso.saml.stub_5.1.3.jar bundle apache2 10490 +org.wso2.carbon.identity.sso.saml.stub_5.3.0.jar bundle apache2 10489 +org.wso2.carbon.identity.sso.saml.ui_5.3.0.jar bundle apache2 10488 +org.wso2.carbon.identity.sso.saml_5.3.0.jar bundle apache2 10487 +org.wso2.carbon.identity.user.profile.stub_5.7.5.jar bundle apache2 10732 +org.wso2.carbon.identity.user.profile.ui_5.7.5.jar bundle apache2 10731 +org.wso2.carbon.identity.user.profile_5.7.5.jar bundle apache2 10730 +org.wso2.carbon.identity.user.registration.stub_5.6.89.jar bundle apache2 10967 +org.wso2.carbon.identity.user.registration.stub_5.7.5.jar bundle apache2 10729 +org.wso2.carbon.identity.user.registration_5.7.5.jar bundle apache2 10728 +org.wso2.carbon.identity.user.store.configuration.deployer_5.7.5.jar bundle apache2 10727 +org.wso2.carbon.identity.user.store.configuration.stub_5.7.5.jar bundle apache2 10726 +org.wso2.carbon.identity.user.store.configuration.ui_5.7.5.jar bundle apache2 10725 +org.wso2.carbon.identity.user.store.configuration_5.7.5.jar bundle apache2 10724 +org.wso2.carbon.identity.user.store.count.stub_5.7.5.jar bundle apache2 10723 +org.wso2.carbon.identity.user.store.count_5.7.5.jar bundle apache2 10722 +org.wso2.carbon.identity.webfinger_5.3.4.jar bundle apache2 10932 +org.wso2.carbon.idp.mgt.stub_5.7.5.jar bundle apache2 10713 +org.wso2.carbon.idp.mgt.ui_5.7.5.jar bundle apache2 10712 +org.wso2.carbon.idp.mgt_5.7.5.jar bundle apache2 10711 +org.wso2.carbon.inbound.endpoint.osgi_4.6.9.jar bundle apache2 10893 +org.wso2.carbon.inbound.endpoint.persistence_4.6.9.jar bundle apache2 10892 +org.wso2.carbon.inbound.endpoint_4.6.9.jar bundle apache2 10891 +org.wso2.carbon.inbound.stub_4.6.9.jar bundle apache2 10966 +org.wso2.carbon.inbound_4.6.9.jar bundle apache2 10890 +org.wso2.carbon.localentry.stub_4.6.9.jar bundle apache2 10965 +org.wso2.carbon.localentry_4.6.9.jar bundle apache2 10889 +org.wso2.carbon.logging-4.4.11.jar bundle apache2 10339 +org.wso2.carbon.logging.admin.stub_4.5.4.jar bundle apache2 8313 +org.wso2.carbon.logging.admin.ui_4.5.4.jar bundle apache2 8312 +org.wso2.carbon.logging.service_4.5.4.jar bundle apache2 8311 +org.wso2.carbon.logging.view.stub_4.5.4.jar bundle apache2 8310 +org.wso2.carbon.logging.view.ui_4.5.4.jar bundle apache2 8309 +org.wso2.carbon.logging_4.4.11.jar bundle apache2 10369 +org.wso2.carbon.mashup.javascript.hostobjects.registry_4.7.0.jar bundle apache2 9483 +org.wso2.carbon.mashup.utils_4.2.0.jar bundle apache2 2216 +org.wso2.carbon.mediation.artifactuploader.stub_4.6.9.jar bundle apache2 10964 +org.wso2.carbon.mediation.artifactuploader_4.6.9.jar bundle apache2 10888 +org.wso2.carbon.mediation.configadmin.stub_4.6.9.jar bundle apache2 10887 +org.wso2.carbon.mediation.configadmin.ui_4.6.9.jar bundle apache2 10886 +org.wso2.carbon.mediation.configadmin_4.6.9.jar bundle apache2 10885 +org.wso2.carbon.mediation.dependency.mgt_4.6.9.jar bundle apache2 10884 +org.wso2.carbon.mediation.initializer.ui_4.6.9.jar bundle apache2 10883 +org.wso2.carbon.mediation.initializer_4.6.9.jar bundle apache2 10882 +org.wso2.carbon.mediation.library.stub_4.6.9.jar bundle apache2 10963 +org.wso2.carbon.mediation.library_4.6.9.jar bundle apache2 10881 +org.wso2.carbon.mediation.message.processor_4.6.9.jar bundle apache2 10880 +org.wso2.carbon.mediation.ntaskadmin_4.6.9.jar bundle apache2 10878 +org.wso2.carbon.mediation.ntask_4.6.9.jar bundle apache2 10879 +org.wso2.carbon.mediation.registry_4.6.9.jar bundle apache2 10877 +org.wso2.carbon.mediation.security.stub_4.6.1.jar bundle apache2 8589 +org.wso2.carbon.mediation.security.stub_4.6.9.jar bundle apache2 10876 +org.wso2.carbon.mediation.security_4.6.9.jar bundle apache2 10875 +org.wso2.carbon.mediation.startup_4.6.9.jar bundle apache2 10874 +org.wso2.carbon.mediation.templates.common_4.6.9.jar bundle apache2 10873 +org.wso2.carbon.mediation.templates.service_4.6.9.jar bundle apache2 10872 +org.wso2.carbon.mediation.templates.stub_4.6.9.jar bundle apache2 10962 +org.wso2.carbon.mediation.templates_4.6.9.jar bundle apache2 10871 +org.wso2.carbon.mediation.transport.handlers_4.6.9.jar bundle apache2 10870 +org.wso2.carbon.mediator.cache.ui_4.6.9.jar bundle apache2 10961 +org.wso2.carbon.mediator.cache_4.6.9.jar bundle apache2 10869 +org.wso2.carbon.mediator.clazz.services_4.6.9.jar bundle apache2 10868 +org.wso2.carbon.mediator.command.services_4.6.9.jar bundle apache2 10867 +org.wso2.carbon.mediator.event_4.6.9.jar bundle apache2 10866 +org.wso2.carbon.mediator.fastXSLT_4.6.9.jar bundle apache2 10865 +org.wso2.carbon.mediator.router.impl_4.6.9.jar bundle apache2 10862 +org.wso2.carbon.mediator.service_4.6.9.jar bundle apache2 10861 +org.wso2.carbon.message.processor.stub_4.6.9.jar bundle apache2 10960 +org.wso2.carbon.message.processor_4.6.9.jar bundle apache2 10860 +org.wso2.carbon.message.store.stub_4.6.9.jar bundle apache2 10959 +org.wso2.carbon.message.store_4.6.9.jar bundle apache2 10859 +org.wso2.carbon.messageflows.stub_4.5.4.jar bundle apache2 8574 +org.wso2.carbon.messageflows.ui_4.5.4.jar bundle apache2 8573 +org.wso2.carbon.messageflows_4.5.4.jar bundle apache2 8572 +org.wso2.carbon.metrics.common_1.2.2.jar bundle apache2 8818 +org.wso2.carbon.metrics.das.reporter_1.2.2.jar bundle apache2 8817 +org.wso2.carbon.metrics.data.common_1.2.2.jar bundle apache2 8816 +org.wso2.carbon.metrics.data.service.stub_1.2.2.jar bundle apache2 8815 +org.wso2.carbon.metrics.data.service_1.2.2.jar bundle apache2 8814 +org.wso2.carbon.metrics.impl_1.2.2.jar bundle apache2 8813 +org.wso2.carbon.metrics.jdbc.reporter_1.2.2.jar bundle apache2 8812 +org.wso2.carbon.metrics.manager_1.2.2.jar bundle apache2 8811 +org.wso2.carbon.metrics.view.ui_1.2.2.jar bundle apache2 8810 +org.wso2.carbon.module.mgt.stub_4.7.2.jar bundle apache2 10282 +org.wso2.carbon.module.mgt.ui_4.7.2.jar bundle apache2 10281 +org.wso2.carbon.module.mgt_4.7.2.jar bundle apache2 10280 +org.wso2.carbon.ndatasource.capp.deployer_4.5.4.jar bundle apache2 8772 +org.wso2.carbon.ndatasource.common_4.4.11.jar bundle apache2 10368 +org.wso2.carbon.ndatasource.core_4.4.11.jar bundle apache2 10367 +org.wso2.carbon.ndatasource.datasources_4.5.4.jar bundle apache2 8571 +org.wso2.carbon.ndatasource.rdbms_4.4.11.jar bundle apache2 10366 +org.wso2.carbon.ndatasource.stub_4.5.4.jar bundle apache2 8570 +org.wso2.carbon.ndatasource.ui_4.5.4.jar bundle apache2 8569 +org.wso2.carbon.ntask.common_4.5.4.jar bundle apache2 8568 +org.wso2.carbon.ntask.core_4.5.4.jar bundle apache2 8567 +org.wso2.carbon.ntask.solutions_4.5.4.jar bundle apache2 8566 +org.wso2.carbon.operation.mgt_4.7.2.jar bundle apache2 10279 +org.wso2.carbon.osgi.security_4.4.11.jar bundle apache2 10365 +org.wso2.carbon.policy.decision.point_2.0.10.jar bundle apache2 10958 +org.wso2.carbon.policy.information.point_2.0.10.jar bundle apache2 10957 +org.wso2.carbon.policy.mgt.common_2.0.10.jar bundle apache2 10956 +org.wso2.carbon.policy.mgt.core_2.0.10.jar bundle apache2 10955 +org.wso2.carbon.priority.executors.stub_4.6.9.jar bundle apache2 10954 +org.wso2.carbon.priority.executors_4.6.9.jar bundle apache2 10858 +org.wso2.carbon.proxyadmin.common_4.6.9.jar bundle apache2 10857 +org.wso2.carbon.proxyadmin.stub_4.6.9.jar bundle apache2 10953 +org.wso2.carbon.proxyadmin_4.6.9.jar bundle apache2 10856 +org.wso2.carbon.qpid.stub_4.5.4.jar bundle apache2 8298 +org.wso2.carbon.queuing_4.4.11.jar bundle apache2 10364 +org.wso2.carbon.registry.admin.api_4.6.0.jar bundle apache2 8904 +org.wso2.carbon.registry.api_4.4.11.jar bundle apache2 10363 +org.wso2.carbon.registry.common.ui_4.6.0.jar bundle apache2 8903 +org.wso2.carbon.registry.common_4.6.0.jar bundle apache2 8902 +org.wso2.carbon.registry.core_4.4.11.jar bundle apache2 10362 +org.wso2.carbon.registry.event.core_4.6.0.jar bundle apache2 8901 +org.wso2.carbon.registry.event.ws_4.6.0.jar bundle apache2 8900 +org.wso2.carbon.registry.eventing_4.6.0.jar bundle apache2 8899 +org.wso2.carbon.registry.extensions.stub_4.6.0.jar bundle apache2 8898 +org.wso2.carbon.registry.extensions.ui_4.6.0.jar bundle apache2 8897 +org.wso2.carbon.registry.extensions_4.6.0.jar bundle apache2 8896 +org.wso2.carbon.registry.indexing_4.6.0.jar bundle apache2 8895 +org.wso2.carbon.registry.info.stub_4.6.0.jar bundle apache2 8894 +org.wso2.carbon.registry.info.ui_4.6.0.jar bundle apache2 8893 +org.wso2.carbon.registry.info_4.6.0.jar bundle apache2 8892 +org.wso2.carbon.registry.properties.stub_4.6.0.jar bundle apache2 8891 +org.wso2.carbon.registry.properties.ui_4.6.0.jar bundle apache2 8890 +org.wso2.carbon.registry.properties_4.6.0.jar bundle apache2 8889 +org.wso2.carbon.registry.relations.stub_4.6.0.jar bundle apache2 8888 +org.wso2.carbon.registry.relations.ui_4.6.0.jar bundle apache2 8887 +org.wso2.carbon.registry.relations_4.6.0.jar bundle apache2 8886 +org.wso2.carbon.registry.resource.stub_4.6.0.jar bundle apache2 8885 +org.wso2.carbon.registry.resource.ui_4.6.0.jar bundle apache2 8884 +org.wso2.carbon.registry.resource_4.6.0.jar bundle apache2 8883 +org.wso2.carbon.registry.search.stub_4.6.0.jar bundle apache2 8882 +org.wso2.carbon.registry.search.ui_4.6.0.jar bundle apache2 8881 +org.wso2.carbon.registry.search_4.6.0.jar bundle apache2 8880 +org.wso2.carbon.registry.server_4.4.11.jar bundle apache2 10361 +org.wso2.carbon.registry.servlet_4.6.0.jar bundle apache2 8879 +org.wso2.carbon.registry.task_4.6.0.jar bundle apache2 8878 +org.wso2.carbon.registry.ws.api_4.6.0.jar bundle apache2 8877 +org.wso2.carbon.registry.ws.client_4.6.0.jar bundle apache2 8876 +org.wso2.carbon.registry.ws.stub_4.6.0.jar bundle apache2 8875 +org.wso2.carbon.relay.mediators.builder_4.6.9.jar bundle apache2 10855 +org.wso2.carbon.relay.module_4.6.9.jar bundle apache2 10854 +org.wso2.carbon.relay_4.6.9.jar bundle apache2 10853 +org.wso2.carbon.remote-tasks.stub_4.5.4.jar bundle apache2 8529 +org.wso2.carbon.rest.api.stub_4.6.9.jar bundle apache2 10852 +org.wso2.carbon.rest.api_4.6.9.jar bundle apache2 10851 +org.wso2.carbon.roles.mgt.stub_4.4.11.jar bundle apache2 10360 +org.wso2.carbon.roles.mgt.ui_4.4.11.jar bundle apache2 10359 +org.wso2.carbon.roles.mgt_4.4.11.jar bundle apache2 10358 +org.wso2.carbon.securevault_4.4.11.jar bundle apache2 10357 +org.wso2.carbon.security.mgt.stub_5.7.5.jar bundle apache2 10708 +org.wso2.carbon.security.mgt.ui_5.7.5.jar bundle apache2 10707 +org.wso2.carbon.security.mgt_5.7.5.jar bundle apache2 10706 +org.wso2.carbon.sequences.common_4.6.9.jar bundle apache2 10850 +org.wso2.carbon.sequences.stub_4.6.0.jar bundle apache2 10102 +org.wso2.carbon.sequences.stub_4.6.9.jar bundle apache2 10849 +org.wso2.carbon.sequences_4.6.9.jar bundle apache2 10848 +org.wso2.carbon.server-4.4.11.jar bundle apache2 10338 +org.wso2.carbon.server.admin.common_4.4.11.jar bundle apache2 10356 +org.wso2.carbon.server.admin.stub_4.4.11.jar bundle apache2 10355 +org.wso2.carbon.server.admin.ui_4.4.11.jar bundle apache2 10354 +org.wso2.carbon.server.admin_4.4.11.jar bundle apache2 10353 +org.wso2.carbon.service.mgt_4.7.2.jar bundle apache2 10245 +org.wso2.carbon.social.core_1.4.4.jar bundle apache2 10098 +org.wso2.carbon.social.db.adapter_1.4.4.jar bundle apache2 10097 +org.wso2.carbon.social.sql_1.4.4.jar bundle apache2 10096 +org.wso2.carbon.statistics.stub_4.5.4.jar bundle apache2 8264 +org.wso2.carbon.statistics.ui_4.5.4.jar bundle apache2 8263 +org.wso2.carbon.statistics_4.5.4.jar bundle apache2 8262 +org.wso2.carbon.store.jaggery-scxml-executors_1.4.4.jar bundle apache2 10095 +org.wso2.carbon.task.services_4.6.9.jar bundle apache2 10847 +org.wso2.carbon.task.stub_4.6.9.jar bundle apache2 10952 +org.wso2.carbon.task_4.6.9.jar bundle apache2 10846 +org.wso2.carbon.tenant.common.stub_4.5.4.jar bundle apache2 8258 +org.wso2.carbon.tenant.common_4.5.4.jar bundle apache2 8257 +org.wso2.carbon.tenant.deployment_4.6.1.jar bundle apache2 10243 +org.wso2.carbon.tenant.dispatcher_4.6.1.jar bundle apache2 10242 +org.wso2.carbon.tenant.keystore.mgt_4.6.1.jar bundle apache2 10241 +org.wso2.carbon.tenant.mgt.core_4.6.1.jar bundle apache2 10240 +org.wso2.carbon.tenant.mgt.stub_4.6.1.jar bundle apache2 10239 +org.wso2.carbon.tenant.mgt.ui_4.6.1.jar bundle apache2 10238 +org.wso2.carbon.tenant.mgt_4.6.1.jar bundle apache2 10237 +org.wso2.carbon.tenant.redirector.servlet.stub_4.6.1.jar bundle apache2 10236 +org.wso2.carbon.tenant.redirector.servlet.ui_4.6.1.jar bundle apache2 10235 +org.wso2.carbon.tenant.redirector.servlet_4.6.1.jar bundle apache2 10234 +org.wso2.carbon.tenant.sso.redirector.ui_4.6.1.jar bundle apache2 10233 +org.wso2.carbon.tenant.theme.mgt_4.6.1.jar bundle apache2 10232 +org.wso2.carbon.tenant.throttling.agent_4.6.1.jar bundle apache2 10231 +org.wso2.carbon.tenant.usage.agent_4.6.1.jar bundle apache2 10230 +org.wso2.carbon.throttling.agent.stub_4.5.4.jar bundle apache2 8505 +org.wso2.carbon.tomcat.ext_4.4.11.jar bundle apache2 10351 +org.wso2.carbon.tomcat.patch_4.7.2.jar bundle apache2 10229 +org.wso2.carbon.tomcat_4.4.11.jar bundle apache2 10350 +org.wso2.carbon.ui.menu.general_4.4.11.jar bundle apache2 10349 +org.wso2.carbon.ui.menu.governance_4.4.7.jar bundle apache2 8504 +org.wso2.carbon.ui.menu.registry_4.4.7.jar bundle apache2 8503 +org.wso2.carbon.ui_4.4.11.jar bundle apache2 10348 +org.wso2.carbon.um.ws.api.stub_5.1.4.jar bundle apache2 10421 +org.wso2.carbon.um.ws.api_5.1.4.jar bundle apache2 10420 +org.wso2.carbon.um.ws.service_5.1.4.jar bundle apache2 10419 +org.wso2.carbon.user.api_4.4.11.jar bundle apache2 10347 +org.wso2.carbon.user.core_4.4.11.jar bundle apache2 10346 +org.wso2.carbon.user.mgt.common_5.7.5.jar bundle apache2 10705 +org.wso2.carbon.user.mgt.stub_5.7.5.jar bundle apache2 10704 +org.wso2.carbon.user.mgt.ui_5.7.5.jar bundle apache2 10703 +org.wso2.carbon.user.mgt.workflow.stub_5.7.5.jar bundle apache2 10702 +org.wso2.carbon.user.mgt_5.7.5.jar bundle apache2 10701 +org.wso2.carbon.utils_4.4.11.jar bundle apache2 10345 +org.wso2.carbon.webapp.authenticator.framework_2.0.10.jar bundle apache2 10951 +org.wso2.carbon.webapp.deployer_4.7.2.jar bundle apache2 10227 +org.wso2.carbon.webapp.list.ui_4.7.2.jar bundle apache2 10226 +org.wso2.carbon.webapp.mgt.stub_4.2.0.jar bundle apache2 2083 +org.wso2.carbon.webapp.mgt.stub_4.7.2.jar bundle apache2 10225 +org.wso2.carbon.webapp.mgt.ui_4.7.2.jar bundle apache2 10224 +org.wso2.carbon.webapp.mgt_4.7.2.jar bundle apache2 10223 +org.wso2.ciphertool-1.0.0-wso2v3.jar bundle apache2 4038 +org.wso2.iot.core.admin.styles_3.0.0.RC.jar bundle apache2 10950 +org.wso2.securevault_1.0.0.wso2v2.jar bundle apache2 768 +org.wso2.store.admin.styles_1.4.4.jar bundle apache2 10090 +org.wso2.store.sso.common_1.4.4.jar bundle apache2 10089 +org.yaml.snakeyaml_1.17.0.jar bundle apache2 2027 +patch.jar jarinbundle epl1 1137 +pdepublishing-ant.jar jar epl1 524 +pdepublishing.jar jar epl1 525 +pdfbox_1.8.10.wso2v2.jar bundle apache2 6514 +perf4j_0.9.12.wso2v1.jar bundle apache2 832 +poi-ooxml_3.14.0.wso2v1.jar bundle apache2 8218 +poi-scratchpad_3.14.0.wso2v1.jar bundle apache2 8217 +poi_3.14.0.wso2v1.jar bundle apache2 8216 +quartz_2.1.1.wso2v1.jar bundle apache2 975 +rampart-core_1.6.1.wso2v24.jar bundle apache2 10409 +rampart-policy_1.6.1.wso2v24.jar bundle apache2 10408 +rampart-trust_1.6.1.wso2v24.jar bundle apache2 10407 +rome_0.9.0.wso2v1.jar bundle apache2 930 +saxon.bps_9.0.0.x-wso2v1.jar bundle mpl11 985 +saxon_8.9.0.wso2v2.jar bundle mpl10 2091 +scannotation_1.0.3.wso2v1.jar bundle apache2 7869 +slf4j.api_1.6.1.jar bundle mit 354 +slf4j.api_1.7.13.jar bundle mit 1606 +slf4j.api_1.7.21.jar bundle mit 1852 +slf4j.log4j12_1.6.1.jar bundle mit 346 +slf4j.log4j12_1.7.13.jar bundle mit 1605 +slf4j.log4j12_1.7.21.jar bundle mit 1851 +slf4j_1.5.10.wso2v1.jar bundle mit 1429 +smackx_3.0.4.wso2v1.jar bundle apache2 1871 +smack_3.0.4.wso2v1.jar bundle apache2 1493 +snakeyaml_1.16.0.wso2v1.jar bundle apache2 6274 +solr_5.2.1.wso2v1.jar bundle apache2 4384 +spatial4j_0.4.1.wso2v1.jar bundle apache2 4045 +spring-aop-3.0.7.RELEASE.jar bundle apache2 279 +spring-asm-3.0.7.RELEASE.jar bundle apache2 261 +spring-beans-3.0.7.RELEASE.jar bundle apache2 275 +spring-context-3.0.7.RELEASE.jar bundle apache2 273 +spring-core-3.0.7.RELEASE.jar bundle apache2 270 +spring-expression-3.0.7.RELEASE.jar bundle apache2 272 +spring-web-3.0.7.RELEASE.jar bundle apache2 268 +spring.framework_3.2.9.wso2v1.jar bundle apache2 4044 +stax2-api-3.1.4.jar bundle bsd 1089 +step2-common-1.0.0-wso2v2.jar bundle apache2 2909 +step2-consumer-1.0.0-wso2v2.jar bundle apache2 2908 +step2_1.0.0.wso2v2.jar bundle apache2 2907 +svn-client-adapter_1.10.9.wso2v1.jar bundle apache2 4043 +swagger-codegen_2.2.0.wso2v2.jar bundle apache2 10843 +synapse-commons_2.1.7.wso2v9.jar bundle apache2 10842 +synapse-core_2.1.7.wso2v9.jar bundle apache2 10841 +synapse-extensions_2.1.7.wso2v9.jar bundle apache2 10840 +synapse-nhttp-transport_2.1.7.wso2v9.jar bundle apache2 10839 +synapse-samples_2.1.7.wso2v9.jar bundle apache2 10838 +synapse-tasks_2.1.7.wso2v9.jar bundle apache2 10837 +tcpmon-1.0.jar jar bsd 255 +tiles-jsp_2.0.5.wso2v1.jar bundle apache2 989 +tomcat-annotations-api-7.0.73.jar jar apache2 2044 +tomcat-catalina-ha_7.0.73.wso2v1.jar bundle apache2 10344 +tomcat-el-api_7.0.73.wso2v1.jar bundle apache2 10343 +tomcat-jsp-api_7.0.73.wso2v1.jar bundle apache2 10342 +tomcat-juli-7.0.73.jar jar apache2 2043 +tomcat-servlet-api_7.0.73.wso2v1.jar bundle apache2 10341 +tomcat_7.0.73.wso2v1.jar bundle apache2 10340 +uddi4j-1.0.1.jar jarinbundle ibmpl 406 +velocity-1.7.jar bundle apache2 509 +velocity_1.7.0.wso2v1.jar bundle apache2 10082 +wadl-core_1.1.6.wso2v1.jar bundle apache2 8492 +waffle-jna_1.6.0.wso2v5.jar bundle epl1 8207 +woden_1.0.0.M9-wso2v1.jar bundle apache2 3755 +woodstox-core-asl-4.4.1.jar bundle apache2 1087 +wsdl-validator_1.2.0.wso2v1.jar bundle epl1 1175 +wsdl4j-1.6.3.jar jar cpl1 276 +wsdl4j_1.6.2.wso2v4.jar bundle apache2 745 +wso2-uri-templates_1.6.5.jar bundle apache2 1073 +wss4j_1.5.11.wso2v16.jar bundle apache2 10406 +xalan-2.7.2.wso2v2.jar bundle apache2 8202 +xercesImpl-2.8.1.wso2v2.jar bundle apache2 663 +xml-apis-1.4.01.jar jar apache2 1793 +xml-resolver-1.2.jar jar apache2 278 +xmlbeans-2.3.0.jar jarinbundle apache2 344 +xmlschema-core-2.1.0.jar bundle apache2 1145 +XmlSchema_1.4.7.wso2v3.jar bundle apache2 3585 +xmlsec-1.5.8.jar bundle apache2 1144 + + + +The license types used by the above libraries and their information is given below: + +apache2 Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.html +ibmpl IBM Public License 1.0 + http://www.ibm.com/developerworks/library/os-ipl.html +cddl1 Common Development and Distribution License + http://www.opensource.org/licenses/cddl1.php +cddl+gpl CDDL + GPLv2 + https://glassfish.dev.java.net/public/CDDL+GPL.html +bouncy Bouncy Castle License + http://www.bouncycastle.org/licence.html +bsd Berkeley License + http://www.opensource.org/licenses/bsd-license.php +mit MIT License + http://www.opensource.org/licenses/mit-license.php +lgpl2 Lesser GPL v2.1 + http://www.opensource.org/licenses/lgpl-2.1.php +icu ICU License + http://source.icu-project.org/repos/icu/icu/trunk/license.html +mpl10 Mozilla Public License 1.0 + http://www.mozilla.org/MPL/ +cpl1 Common Public License + http://opensource.org/licenses/cpl1.0.php +epl1+lgpl2 EPL1 + LGPL2 + http://www.eclipse.org/legal/epl-v10.html + http://www.gnu.org/licenses/licenses.html +mpl11 Mozilla Public License 1.0 + http://www.mozilla.org/MPL/MPL-1.1.html +epl1 Eclipse Public License + http://www.eclipse.org/legal/epl-v10.html \ No newline at end of file diff --git a/modules/distribution/src/core/README.txt b/modules/distribution/src/core/README.txt new file mode 100644 index 00000000..d287efb0 --- /dev/null +++ b/modules/distribution/src/core/README.txt @@ -0,0 +1,167 @@ +WSO2 IoT Server +---------------------- +Welcome to the WSO2 IoT Server (IoTS) 3.0.0 release. +======= + +Key Features +------------ +Self-service device enrollment and management with an end-user IoTS console. + + +Installation & Running +---------------------- +1. Extract the downloaded ZIP file. +2. Follow the INSTALL.txt file for install instructions. +3. After the server starts, point your Web browser to https://localhost:9443/devicemgt in order to see the available device types and operations +4. Navigate to https://localhost:9443/api-store to see the available device APIs. You can subscribe to these APIs with the default application (or by creating a new application). + In the API Store, go to my subscriptions and locate the client ID and secret, which can be used to invoke these APIs. + +System Requirements +------------------- + +1. Minimum memory - 4GB +2. The portal app requires full Javascript enablement on the Web browser + + +WSO2 IoT Server (IoTS) Binary Distribution Directory Structure +----------------------------------------------------- + IoT_HOME + . + ├── core //core component + ├── analytics //Analytics component + ├── broker //Message Broker component + ├── samples //sample device types e.g., connectedcup + ├── plugins //pre-built device types + +The IoTS Core, Analytics, and Broker have similar directory structures. For example Core has the following structure: + IoT_HOME/core + . + ├── bin //executables + ├── dbscripts //DBScripts + ├── INSTALL.txt + ├── lib + ├── LICENSE.txt + ├── modules //Jaggery Modules + ├── README.txt + ├── release-notes.html + ├── repository // repository + ├── tmp + ├── webapp-mode + + + - bin + Contains various scripts (i.e., .sh & .bat scripts). + + - dbscripts + Contains the database creation & seed data population SQL scripts for + various supported databases. + + - lib + Contains the basic set of libraries required to startup WSO2 IoT Server + in standalone mode + + - repository + The repository where Carbon artifacts & Axis2 services and + modules deployed in WSO2 Carbon, and other custom deployers such as + dataservices and axis1services are stored. + + - carbonapps + Carbon Application hot deployment directory. + + - components + Contains all OSGi related libraries and configurations. + + - conf + Contains server configuration files. e.g., axis2.xml, carbon.xml + + - data + Contains internal LDAP related data. + + - database + Contains the WSO2 Registry & User Manager database. + + - deployment + Contains server side and client side Axis2 repositories. + All deployment artifacts should go into this directory. + + - logs + Contains all log files created during execution. + + - resources + Contains additional resources that may be required. + + - tenants + This directory will contain relevant tenant artifacts + in the case of a multi-tenant deployment. + + - tmp + Used for storing temporary files, and is pointed to by the + java.io.tmpdir system property. + + - webapp-mode + You have the option of running WSO2 Carbon in the webapp mode (hosted as a web-app in an application server). This directory contains files required to run Carbon in the webapp mode. + + - LICENSE.txt + Apache License 2.0 under which WSO2 Carbon is distributed. + + - README.txt + This document. + + - INSTALL.txt + This document contains information on installing WSO2 IoT Server. + + - release-notes.html + Release information for WSO2 IoT Server 3.0.0 + +Secure sensitive information in Carbon configuration files +---------------------------------------------------------- + +There is sensitive information such as passwords in the Carbon configuration. +You can secure them by using secure vault. Please go through the following steps to +secure them with the default mode. + +1. Configure secure vault with the default configurations by running the ciphertool + script from the bin directory. + +> ciphertool.sh -Dconfigure (in UNIX) + +This script automates the following configurations that you would normally need to do manually. + +(i) Replaces sensitive elements in configuration files that have been defined in + cipher-tool.properties, with alias token values. +(ii) Encrypts the plain text password which is defined in the cipher-text.properties file. +(iii) Updates the secret-conf.properties file with the default keystore and callback class. + +cipher-tool.properties, cipher-text.properties and secret-conf.properties files + can be found in the /repository/conf/security directory. + +2. Start the server by running the wso2server script, which is in the /bin directory. + +> wso2server.sh (in UNIX) + +When running the default mode, it asks you to enter the master password +(By default, the master password is the password of the Carbon keystore and private key) + +3. Change any password by running the ciphertool script, which is in the /bin directory. + +> ciphertool -Dchange (in UNIX) + +For more information, see +https://docs.wso2.com/display/ADMIN44x/Carbon+Secure+Vault+Implementation + +Training +-------- + +WSO2 Inc. offers a variety of professional Training Programs for WSO2 products. +For additional support on training information please goto http://wso2.com/training/ + + +Support +------- + +We are committed to ensuring that your enterprise middleware deployment is completely supported from evaluation to production. Our unique approach ensures that all support leverages our open development methodology and is provided by the very same engineers who build the technology. + +For additional support information please refer to http://wso2.com/support/ + +--------------------------------------------------------------------------- +(c) Copyright 2017 WSO2 Inc. \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/api_templates/default_api_template.xml b/modules/distribution/src/core/api-resources/api_templates/default_api_template.xml new file mode 100644 index 00000000..85b78243 --- /dev/null +++ b/modules/distribution/src/core/api-resources/api_templates/default_api_template.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + 500 + Status report + Internal Server Error + Faulty invoking through default API + + + + + + +
+ + + + + + + + +
+ #if( $transport == "https" ) + + #else + + #end + + + + #if( $transport == "https" ) + + #else + + #end + + 60000 + fault + + + 1.0 + + + 0 + 0 + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/api_templates/prototype_template.xml b/modules/distribution/src/core/api-resources/api_templates/prototype_template.xml new file mode 100644 index 00000000..05ffc526 --- /dev/null +++ b/modules/distribution/src/core/api-resources/api_templates/prototype_template.xml @@ -0,0 +1,262 @@ + + + ##################### Define the macros ###################### + +#macro ( print_if_exist $field $default) + #if($field && "$field" !="") + $field + #else + $default + #end +#end + +#macro ( print_string_if_exist $field $default) + #if($field && "$field" !="") + "$field" + #else + "$default" + #end +#end + +#macro ( print_if_exist_only $tagname $field) + #if($field && "$field" !="") + <$tagname>$field + #else + ## print nothing. + #end +#end + +#macro ( print_list $tagname $list) + #if($list && "$list" !="" && $list.size() > 0) + <$tagname> + #foreach($item in $list) + $item #if( $foreach.hasNext ), #end + #end + + #else + ## print nothing. + #end +#end + +#macro ( timeout $config) + #if( $config.get("actionSelect") == "neverTimeout" ) + ## print nothing. + #elseif($config.get("actionDuration")|| $config.get("actionSelect")) + + #print_if_exist_only("duration" $config.get("actionDuration")) + #print_if_exist_only("responseAction" $config.get("actionSelect")) + + #end + + #print_list( "errorCodes" $config.get("suspendErrorCode")) + #print_if_exist_only("initialDuration" $config.get("suspendDuration")) + #print_if_exist_only("maximumDuration" $config.get("suspendMaxDuration")) + #print_if_exist( $config.get("factor") 1.0) + + + #print_list("errorCodes" $config.get("retryErroCode")) + #print_if_exist( $config.get("retryTimeOut") 0) + #print_if_exist( $config.get("retryDelay") 0) + +#end + + #macro ( http_endpoint $name $ep ) + + +#timeout( $ep.get('config') ) + + #if($destinationBasedStatsEnabled) + + #end + + #end + + #macro ( draw_endpoint $type $endpoint_config ) + + #set( $endpointClass = $endpoint_config.get("endpoint_type") ) + #set( $endpoints = $endpoint_config.get("${type}_endpoints")) + #set( $ep_name = "${apiName}_API${type}Endpoint_${resourceNo}") + + ## IF endpoint secured + #if($isEndpointSecured) + #if($isSecureVaultEnabled) + + + + #else + + #end + #end + +#if ($endpointClass == "http") +#http_endpoint($ep_name $endpoints) +#elseif ($endpointClass == "address") + + #set( $advance_ep = $endpoints.get("config") ) +
+ #timeout( $endpoints.get('config') ) +
+#if($destinationBasedStatsEnabled) + +#end +
+ #elseif ($endpointClass == "wsdl") + + +#timeout() + + #if($destinationBasedStatsEnabled) + + #end + + #elseif ($endpointClass == "failover") + #set( $failover_endpoints = $endpoint_config.get("${type}_failovers")) + + + #http_endpoint("${ep_name}_0" $endpoints) + #set( $i = 1) + #foreach($endpoint in $failover_endpoints) + #http_endpoint("${ep_name}_$i" $endpoint) + #set( $i = $i + 1) + #end + + + #elseif ($endpointClass == "load_balance") + +#if($endpoint_config.get("sessionManagement") && $endpoint_config.get("sessionManagement") != "" && $endpoint_config.get("sessionManagement") != "none") + +#if($endpoint_config.get("sessionTimeOut") && $endpoint_config.get("sessionTimeOut") != "") +$endpoint_config.get("sessionTimeOut") +#end + + #end + + #set( $i = 0) + #foreach($endpoint in $endpoints) + #http_endpoint("${ep_name}_$i" $endpoint) + #set( $i = $i + 1) + #end + + + #end +
+ #if($destinationBasedStatsEnabled) + + + + + + #end + #end + + ######################## End of Macros ###################################### + + + +#if($apiIsBlocked) +## if API is blocked send the API Block message + + + + + + 700700 + API blocked + This API has been blocked temporarily. Please try again later or contact the system administrators. + + + + + + +
+ + + +#else +## api not blocked +#set ($resourceNo = 0) +#foreach($resource in $resources) + + + #if(!$resource.getMediationScript().equalsIgnoreCase("null")) + + + + + + + + + + #else + + #end + #if($resource.getMethodsAsString().contains("GET")||$resource.getMethodsAsString().contains("DELETE")) + + #end + + + + + + + #set ($resourceNo = $resourceNo + 1) + #end ## end of resource iterator + ## print the handlers + #if($handlers.size() > 0) + +#foreach($handler in $handlers) + + #if($handler.hasProperties()) + #set ($map = $handler.getProperties() ) + #foreach($property in $map.entrySet()) + + #end + #end + +#end + +#end +#if($apiStatus == 'PROTOTYPED') +#end +#end +## end of apiIsBlocked check + diff --git a/modules/distribution/src/core/api-resources/api_templates/velocity_template.xml b/modules/distribution/src/core/api-resources/api_templates/velocity_template.xml new file mode 100644 index 00000000..a331c9b9 --- /dev/null +++ b/modules/distribution/src/core/api-resources/api_templates/velocity_template.xml @@ -0,0 +1,375 @@ + + + ##################### Define the macros ###################### + + #macro ( print_if_exist $field $default) + #if($field && "$field" !="") + $field + #else + $default + #end + #end + + #macro ( print_string_if_exist $field $default) + #if($field && "$field" !="") + "$field" + #else + "$default" + #end + #end + + #macro ( print_if_exist_only $tagname $field) + #if($field && "$field" !="") +<$tagname>$field + #else + ## print nothing. + #end + #end + + #macro ( print_list $tagname $list) + #if($list && "$list" !="" && $list.size() > 0) +<$tagname> + #foreach($item in $list) + $item #if( $foreach.hasNext ), #end + #end + + #else + ## print nothing. + #end + #end + + #macro ( timeout $config) + #if( $config.get("actionSelect") == "neverTimeout" ) + ## print nothing. + #elseif($config.get("actionDuration")|| $config.get("actionSelect")) + +#print_if_exist_only("duration" $config.get("actionDuration")) +#print_if_exist_only("responseAction" $config.get("actionSelect")) + + #end + +#print_list( "errorCodes" $config.get("suspendErrorCode")) +#print_if_exist_only("initialDuration" $config.get("suspendDuration")) +#print_if_exist_only("maximumDuration" $config.get("suspendMaxDuration")) +#print_if_exist( $config.get("factor") 1.0) + + +#print_list("errorCodes" $config.get("retryErroCode")) +#print_if_exist( $config.get("retryTimeOut") 0) +#print_if_exist( $config.get("retryDelay") 0) + + #end + +#macro ( http_endpoint $name $ep ) + + + #timeout( $ep.get('config') ) + + + +#end + +#macro ( address_endpoint $name $ep ) + + #set( $advance_ep = $ep.get("config") ) +
+ #timeout( $ep.get('config') ) +
+ +
+#end + + + #macro ( draw_endpoint $type $endpoint_config ) + + #set( $endpointClass = $endpoint_config.get("endpoint_type") ) + #set( $endpoints = $endpoint_config.get("${type}_endpoints")) + #set( $ep_name = "${apiName}_API${type}Endpoint_${resourceNo}") + + ## IF endpoint secured + #if($isEndpointSecured) + #if($isSecureVaultEnabled) + + + + #else + #if($isEndpointAuthDigest) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #else + + #end + #end + #end + + +## If endpoint is http +#if ($endpointClass == "http") +#http_endpoint($ep_name $endpoints) +#elseif ($endpointClass == "address") + + #set( $advance_ep = $endpoints.get("config") ) +
+ #timeout( $endpoints.get('config') ) +
+ +
+ #elseif ($endpointClass == "wsdl") + +#if (${type} == "production") + +#timeout() + + #else + + #timeout() + + #end + + + #elseif ($endpointClass == "failover") + #set( $failover_endpoints = $endpoint_config.get("${type}_failovers")) + + + #if($endpoints.get("endpoint_type") == "address") + #address_endpoint("${ep_name}_0" $endpoints) + #else + #http_endpoint("${ep_name}_0" $endpoints) + #end + #set( $i = 1) + #foreach($endpoint in $failover_endpoints) + #if($endpoint.get("endpoint_type") == "address") + #address_endpoint("${ep_name}_$i" $endpoint) + #else + #http_endpoint("${ep_name}_$i" $endpoint) + #end + #set( $i = $i + 1) + #end + + + #elseif ($endpointClass == "load_balance") + +#if($endpoint_config.get("sessionManagement") && $endpoint_config.get("sessionManagement") != "" && $endpoint_config.get("sessionManagement") != "none") + +#if($endpoint_config.get("sessionTimeOut") && $endpoint_config.get("sessionTimeOut") != "") +$endpoint_config.get("sessionTimeOut") +#end + + #end + + #set( $i = 0) + #foreach($endpoint in $endpoints) + #if($endpoint.get("endpoint_type") == "address") + #address_endpoint("${ep_name}_$i" $endpoint) + #else + #http_endpoint("${ep_name}_$i" $endpoint) + #end + #set( $i = $i + 1) + #end + + +#elseif ($endpointClass == "default") + + + + + #end +
+ #end + + ######################## End of Macros ###################################### + + + +#if($apiIsBlocked) +## if API is blocked send the API Block message + + + + + + 700700 + API blocked + This API has been blocked temporarily. Please try again later or contact the system administrators. + + + + + + +
+ + + + #else + ## api not blocked + #set ($resourceNo = 0) + #foreach($resource in $resources) + + + + +## check and set response caching +#if($responseCacheEnabled) + + + +#end + +############## define the filter based on environment type production only, sandbox only , hybrid ############ + +#if(($environmentType == 'sandbox') || ($environmentType =='hybrid' && !$endpoint_config.get("production_endpoints") )) +#set( $filterRegex = "SANDBOX" ) +#else +#set( $filterRegex = "PRODUCTION" ) +#end +#if($apiStatus != 'PROTOTYPED') + + + #end + #if(($environmentType == 'sandbox') || ($environmentType =='hybrid' && ! $endpoint_config.get("production_endpoints") )) + #draw_endpoint( "sandbox" $endpoint_config ) + #else + #draw_endpoint( "production" $endpoint_config ) + #end + #if($apiStatus != 'PROTOTYPED') + + + #if($environmentType !='hybrid') + + + + #if($environmentType == 'production') + Sandbox Key Provided for Production Gateway + #elseif($environmentType == 'sandbox') + Production Key Provided for Sandbox Gateway + #end + + + + + +
+ + + + #else + #if($endpoint_config.get("production_endpoints") && $endpoint_config.get("sandbox_endpoints")) + #draw_endpoint( "sandbox" $endpoint_config ) + #elseif($endpoint_config.get("production_endpoints")) + + #elseif($endpoint_config.get("sandbox_endpoints")) + + #end + #end + + +#end + + + +## check and set response caching +#if($responseCacheEnabled) + +#end + + + + #set ($resourceNo = $resourceNo + 1) + #end ## end of resource iterator + ## print the handlers + #if($handlers.size() > 0) + +#foreach($handler in $handlers) + + #if($handler.hasProperties()) + #set ($map = $handler.getProperties() ) + #foreach($property in $map.entrySet()) + + #end + #end + +#end + + #end + #end + #if($apiStatus == 'PROTOTYPED') + #end + ## end of apiIsBlocked check + + + + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/fault/json_fault.xml b/modules/distribution/src/core/api-resources/customsequences/fault/json_fault.xml new file mode 100644 index 00000000..392990c2 --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/fault/json_fault.xml @@ -0,0 +1,41 @@ + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/customsequences/in/json_to_xml_in_message.xml b/modules/distribution/src/core/api-resources/customsequences/in/json_to_xml_in_message.xml new file mode 100644 index 00000000..ce9bc526 --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/in/json_to_xml_in_message.xml @@ -0,0 +1,3 @@ + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/in/log_in_message.xml b/modules/distribution/src/core/api-resources/customsequences/in/log_in_message.xml new file mode 100644 index 00000000..3975edfb --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/in/log_in_message.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/customsequences/in/preserve_accept_header.xml b/modules/distribution/src/core/api-resources/customsequences/in/preserve_accept_header.xml new file mode 100644 index 00000000..7c79d6aa --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/in/preserve_accept_header.xml @@ -0,0 +1,4 @@ + + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/in/xml_to_json_in_message.xml b/modules/distribution/src/core/api-resources/customsequences/in/xml_to_json_in_message.xml new file mode 100644 index 00000000..c37a9e84 --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/in/xml_to_json_in_message.xml @@ -0,0 +1,3 @@ + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/out/apply_accept_header.xml b/modules/distribution/src/core/api-resources/customsequences/out/apply_accept_header.xml new file mode 100644 index 00000000..dc07e24a --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/out/apply_accept_header.xml @@ -0,0 +1,5 @@ + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/out/json_to_xml_out_message.xml b/modules/distribution/src/core/api-resources/customsequences/out/json_to_xml_out_message.xml new file mode 100644 index 00000000..5c8a060f --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/out/json_to_xml_out_message.xml @@ -0,0 +1,3 @@ + + + diff --git a/modules/distribution/src/core/api-resources/customsequences/out/log_out_message.xml b/modules/distribution/src/core/api-resources/customsequences/out/log_out_message.xml new file mode 100644 index 00000000..65498564 --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/out/log_out_message.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/customsequences/out/xml_to_json_out_message.xml b/modules/distribution/src/core/api-resources/customsequences/out/xml_to_json_out_message.xml new file mode 100644 index 00000000..8fb99684 --- /dev/null +++ b/modules/distribution/src/core/api-resources/customsequences/out/xml_to_json_out_message.xml @@ -0,0 +1,3 @@ + + + diff --git a/modules/distribution/src/core/api-resources/default-tiers/default-app-tiers.xml b/modules/distribution/src/core/api-resources/default-tiers/default-app-tiers.xml new file mode 100644 index 00000000..989792d6 --- /dev/null +++ b/modules/distribution/src/core/api-resources/default-tiers/default-app-tiers.xml @@ -0,0 +1,119 @@ + + + + + Large + + + + 20 + 60000 + + + + FREE + true + + + + + + + + + Medium + + + + 5 + 60000 + + + + FREE + true + + + + + + + + + Small + + + + 1 + 60000 + + + + FREE + true + + + + + + + + + Unauthenticated + + + + 60 + 60000 + + + + + + + diff --git a/modules/distribution/src/core/api-resources/default-tiers/default-res-tiers.xml b/modules/distribution/src/core/api-resources/default-tiers/default-res-tiers.xml new file mode 100644 index 00000000..0e97ab4b --- /dev/null +++ b/modules/distribution/src/core/api-resources/default-tiers/default-res-tiers.xml @@ -0,0 +1,119 @@ + + + + + Ultimate + + + + 20 + 60000 + + + + FREE + true + + + + + + + + + Plus + + + + 5 + 60000 + + + + FREE + true + + + + + + + + + Basic + + + + 1 + 60000 + + + + FREE + true + + + + + + + + + Unauthenticated + + + + 60 + 60000 + + + + + + + diff --git a/modules/distribution/src/core/api-resources/default-tiers/default-tiers.xml b/modules/distribution/src/core/api-resources/default-tiers/default-tiers.xml new file mode 100644 index 00000000..e57bb553 --- /dev/null +++ b/modules/distribution/src/core/api-resources/default-tiers/default-tiers.xml @@ -0,0 +1,122 @@ + + + + + Gold + + + + 20 + 60000 + + + + FREE + true + + + + + + + + + + Silver + + + + 5 + 60000 + + + + FREE + true + + + + + + + + + + Bronze + + + + 1 + 60000 + + + + FREE + true + + + + + + + + + + Unauthenticated + + + + 60 + 60000 + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/api/_API_Application_Registration_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_API_Application_Registration_.xml new file mode 100644 index 00000000..7e25c013 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_API_Application_Registration_.xml @@ -0,0 +1,63 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/api/_AuthorizeAPI_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_AuthorizeAPI_.xml new file mode 100644 index 00000000..571c5b61 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_AuthorizeAPI_.xml @@ -0,0 +1,24 @@ + + + + + /> + + + + + 60000 + fault + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/api/_RevokeAPI_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_RevokeAPI_.xml new file mode 100644 index 00000000..f227eecf --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_RevokeAPI_.xml @@ -0,0 +1,25 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/api/_TokenAPI_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_TokenAPI_.xml new file mode 100644 index 00000000..74a0315b --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_TokenAPI_.xml @@ -0,0 +1,25 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/api/_UserInfoAPI_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_UserInfoAPI_.xml new file mode 100644 index 00000000..3e649879 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/api/_UserInfoAPI_.xml @@ -0,0 +1,24 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/proxy-services/WorkflowCallbackService.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/proxy-services/WorkflowCallbackService.xml new file mode 100644 index 00000000..722d81b0 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/proxy-services/WorkflowCallbackService.xml @@ -0,0 +1,145 @@ + + + + + + + + +
+ + + + + + + + + + + WorkflowCallbackService + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/registry.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/registry.xml new file mode 100644 index 00000000..b19a4c89 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/registry.xml @@ -0,0 +1,25 @@ + + + + + + + 15000 + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_api_registration_fault_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_api_registration_fault_.xml new file mode 100644 index 00000000..335a9aba --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_api_registration_fault_.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_auth_failure_handler_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_auth_failure_handler_.xml new file mode 100644 index 00000000..5a5213d8 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_auth_failure_handler_.xml @@ -0,0 +1,4 @@ + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_build_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_build_.xml new file mode 100644 index 00000000..64e8fe39 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_build_.xml @@ -0,0 +1,26 @@ + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_cors_request_handler_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_cors_request_handler_.xml new file mode 100644 index 00000000..d8d043aa --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_cors_request_handler_.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_dcr_fault_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_dcr_fault_.xml new file mode 100644 index 00000000..64e0ffc1 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_dcr_fault_.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_production_key_error_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_production_key_error_.xml new file mode 100644 index 00000000..77199419 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_production_key_error_.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_resource_mismatch_handler_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_resource_mismatch_handler_.xml new file mode 100644 index 00000000..402c0835 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_resource_mismatch_handler_.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_sandbox_key_error_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_sandbox_key_error_.xml new file mode 100644 index 00000000..12906f2e --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_sandbox_key_error_.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_throttle_out_handler_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_throttle_out_handler_.xml new file mode 100644 index 00000000..710ee276 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_throttle_out_handler_.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_token_fault_.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_token_fault_.xml new file mode 100644 index 00000000..1e4a9825 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/_token_fault_.xml @@ -0,0 +1,40 @@ + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + +
+ + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/fault.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/fault.xml new file mode 100644 index 00000000..b1e45ccc --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/fault.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + $1 + Status report + Runtime Error + $2 + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/main.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/main.xml new file mode 100644 index 00000000..2f6f39eb --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/sequences/main.xml @@ -0,0 +1,99 @@ + + + + + + The default main sequence for API manager - Returns 404 Not Found + + + + + + + + + + 403 + Status report + Forbidden + Unsupported Transport [ $2 ]. The requested resource (/$1) is not available. + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + 404 + Status report + Not Found + The requested resource (/$1) is not available. + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/api-resources/synapse-configs/default/synapse.xml b/modules/distribution/src/core/api-resources/synapse-configs/default/synapse.xml new file mode 100644 index 00000000..d7f60ec4 --- /dev/null +++ b/modules/distribution/src/core/api-resources/synapse-configs/default/synapse.xml @@ -0,0 +1,25 @@ + + + + + + + + diff --git a/modules/distribution/src/core/bin/wso2server.bat b/modules/distribution/src/core/bin/wso2server.bat new file mode 100644 index 00000000..6a5b22e8 --- /dev/null +++ b/modules/distribution/src/core/bin/wso2server.bat @@ -0,0 +1,177 @@ +@echo off + +REM --------------------------------------------------------------------------- +REM Copyright 2005-2009 WSO2, Inc. http://www.wso2.org +REM +REM Licensed under the Apache License, Version 2.0 (the "License"); +REM you may not use this file except in compliance with the License. +REM You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +rem --------------------------------------------------------------------------- +rem Main Script for WSO2 Carbon +rem +rem Environment Variable Prequisites +rem +rem CARBON_HOME Home of CARBON installation. If not set I will try +rem to figure it out. +rem +rem JAVA_HOME Must point at your Java Development Kit installation. +rem +rem JAVA_OPTS (Optional) Java runtime options used when the commands +rem is executed. +rem --------------------------------------------------------------------------- + +rem ----- if JAVA_HOME is not set we're not happy ------------------------------ +:checkJava + +if "%JAVA_HOME%" == "" goto noJavaHome +if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome +goto checkServer + +:noJavaHome +echo "You must set the JAVA_HOME variable before running CARBON." +goto end + +rem ----- Only set CARBON_HOME if not already set ---------------------------- +:checkServer +rem %~sdp0 is expanded pathname of the current script under NT with spaces in the path removed +if "%CARBON_HOME%"=="" set CARBON_HOME=%~sdp0.. +SET curDrive=%cd:~0,1% +SET wsasDrive=%CARBON_HOME:~0,1% +if not "%curDrive%" == "%wsasDrive%" %wsasDrive%: + +rem find CARBON_HOME if it does not exist due to either an invalid value passed +rem by the user or the %0 problem on Windows 9x +if not exist "%CARBON_HOME%\bin\version.txt" goto noServerHome + +set AXIS2_HOME=%CARBON_HOME% +goto updateClasspath + +:noServerHome +echo CARBON_HOME is set incorrectly or CARBON could not be located. Please set CARBON_HOME. +goto end + +rem ----- update classpath ----------------------------------------------------- +:updateClasspath + +setlocal EnableDelayedExpansion +cd %CARBON_HOME% +set CARBON_CLASSPATH= +FOR %%C in ("%CARBON_HOME%\bin\*.jar") DO set CARBON_CLASSPATH=!CARBON_CLASSPATH!;".\bin\%%~nC%%~xC" + +set CARBON_CLASSPATH="%JAVA_HOME%\lib\tools.jar";%CARBON_CLASSPATH%; + +FOR %%D in ("%CARBON_HOME%\lib\commons-lang*.jar") DO set CARBON_CLASSPATH=!CARBON_CLASSPATH!;".\lib\%%~nD%%~xD" + +rem ----- Process the input command ------------------------------------------- + +rem Slurp the command line arguments. This loop allows for an unlimited number +rem of arguments (up to the command line limit, anyway). + + +:setupArgs +if ""%1""=="""" goto doneStart + +if ""%1""==""-run"" goto commandLifecycle +if ""%1""==""--run"" goto commandLifecycle +if ""%1""==""run"" goto commandLifecycle + +if ""%1""==""-restart"" goto commandLifecycle +if ""%1""==""--restart"" goto commandLifecycle +if ""%1""==""restart"" goto commandLifecycle + +if ""%1""==""debug"" goto commandDebug +if ""%1""==""-debug"" goto commandDebug +if ""%1""==""--debug"" goto commandDebug + +if ""%1""==""version"" goto commandVersion +if ""%1""==""-version"" goto commandVersion +if ""%1""==""--version"" goto commandVersion + +shift +goto setupArgs + +rem ----- commandVersion ------------------------------------------------------- +:commandVersion +shift +type "%CARBON_HOME%\bin\version.txt" +type "%CARBON_HOME%\bin\wso2carbon-version.txt" +goto end + +rem ----- commandDebug --------------------------------------------------------- +:commandDebug +shift +set DEBUG_PORT=%1 +if "%DEBUG_PORT%"=="" goto noDebugPort +if not "%JAVA_OPTS%"=="" echo Warning !!!. User specified JAVA_OPTS will be ignored, once you give the --debug option. +set JAVA_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=%DEBUG_PORT% +echo Please start the remote debugging client to continue... +goto findJdk + +:noDebugPort +echo Please specify the debug port after the --debug option +goto end + +rem ----- commandLifecycle ----------------------------------------------------- +:commandLifecycle +goto findJdk + +:doneStart +if "%OS%"=="Windows_NT" @setlocal +if "%OS%"=="WINNT" @setlocal + +rem ---------- Handle the SSL Issue with proper JDK version -------------------- +rem find the version of the jdk +:findJdk + +set CMD=RUN %* + +:checkJdk17 +"%JAVA_HOME%\bin\java" -version 2>&1 | findstr /r "1.[7|8]" >NUL +IF ERRORLEVEL 1 goto unknownJdk +goto jdk17 + +:unknownJdk +echo Starting WSO2 Carbon (in unsupported JDK) +echo [ERROR] CARBON is supported only on JDK 1.7 and 1.8 +goto jdk17 + +:jdk17 +goto runServer + +rem ----------------- Execute The Requested Command ---------------------------- + +:runServer +cd %CARBON_HOME% + +rem ------------------ Remove tmp folder on startup ----------------------------- +set TMP_DIR=%CARBON_HOME%\tmp +rmdir "%TMP_DIR%" /s /q + +rem ---------- Add jars to classpath ---------------- + +set CARBON_CLASSPATH=.\lib;%CARBON_CLASSPATH% + +set JAVA_ENDORSED=".\lib\endorsed";"%JAVA_HOME%\jre\lib\endorsed";"%JAVA_HOME%\lib\endorsed" + +set CMD_LINE_ARGS=-Xbootclasspath/a:%CARBON_XBOOTCLASSPATH% -Xms256m -Xmx1024m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath="%CARBON_HOME%\repository\logs\heap-dump.hprof" -Dcom.sun.management.jmxremote -classpath %CARBON_CLASSPATH% %JAVA_OPTS% -Djava.endorsed.dirs=%JAVA_ENDORSED% -Dcarbon.registry.root=/ -Dcarbon.home="%CARBON_HOME%" -Dlogger.server.name="IoT-Core" -Dwso2.server.standalone=true -Djava.command="%JAVA_HOME%\bin\java" -Djava.opts="%JAVA_OPTS%" -Djava.io.tmpdir="%CARBON_HOME%\tmp" -Dcatalina.base="%CARBON_HOME%\lib\tomcat" -Dwso2.carbon.xml=%CARBON_HOME%\repository\conf\carbon.xml -Dwso2.registry.xml="%CARBON_HOME%\repository\conf\registry.xml" -Dwso2.user.mgt.xml="%CARBON_HOME%\repository\conf\user-mgt.xml" -Dwso2.transports.xml="%CARBON_HOME%\repository\conf\mgt-transports.xml" -Djava.util.logging.config.file="%CARBON_HOME%\repository\conf\etc\logging-bridge.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Dcarbon.config.dir.path="%CARBON_HOME%\repository\conf" -Dcomponents.repo="%CARBON_HOME%\repository\components" -Dconf.location="%CARBON_HOME%\repository\conf" -Dcom.atomikos.icatch.file="%CARBON_HOME%\lib\transactions.properties" -Dcom.atomikos.icatch.hide_init_file_path="true" -Dorg.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false -Dorg.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true -Dcom.sun.jndi.ldap.connect.pool.authentication=simple -Dcom.sun.jndi.ldap.connect.pool.timeout=3000 -Dorg.terracotta.quartz.skipUpdateCheck=true -Dcarbon.classpath=%CARBON_CLASSPATH% -Dfile.encoding=UTF8 -Dorg.wso2.ignoreHostnameVerification=true -Dorg.opensaml.httpclient.https.disableHostnameVerification=true -Diot.analytics.host="localhost" -Diot.analytics.https.port="9445" -Diot.manager.host="localhost" -Diot.manager.https.port="9445" -Dmqtt.broker.host="localhost" -Dmqtt.broker.port="1886" -Diot.core.host="localhost" -Diot.core.https.port="9443" -Diot.keymanager.host="localhost" -Diot.keymanager.https.port="9443" -Diot.gateway.host="localhost" -Diot.gateway.https.port="8243" -Diot.gateway.http.port="8280" -Diot.apimpublisher.host="localhost" -Diot.apimpublisher.https.port="9443" -Diot.apimstore.host="localhost" -Diot.apimstore.https.port="8243" + +:runJava +echo JAVA_HOME environment variable is set to %JAVA_HOME% +echo CARBON_HOME environment variable is set to %CARBON_HOME% +"%JAVA_HOME%\bin\java" %CMD_LINE_ARGS% org.wso2.carbon.bootstrap.Bootstrap %CMD% +if "%ERRORLEVEL%"=="121" goto runJava +:end +goto endlocal + +:endlocal + +:END diff --git a/modules/distribution/src/core/bin/wso2server.sh b/modules/distribution/src/core/bin/wso2server.sh new file mode 100755 index 00000000..329a6ecf --- /dev/null +++ b/modules/distribution/src/core/bin/wso2server.sh @@ -0,0 +1,329 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Copyright 2005-2012 WSO2, Inc. http://www.wso2.org +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ---------------------------------------------------------------------------- +# Main Script for the WSO2 Carbon Server +# +# Environment Variable Prequisites +# +# CARBON_HOME Home of WSO2 Carbon installation. If not set I will try +# to figure it out. +# +# JAVA_HOME Must point at your Java Development Kit installation. +# +# JAVA_OPTS (Optional) Java runtime options used when the commands +# is executed. +# +# NOTE: Borrowed generously from Apache Tomcat startup scripts. +# ----------------------------------------------------------------------------- + +# OS specific support. $var _must_ be set to either true or false. +#ulimit -n 100000 + +cygwin=false; +darwin=false; +os400=false; +mingw=false; +case "`uname`" in +CYGWIN*) cygwin=true;; +MINGW*) mingw=true;; +OS400*) os400=true;; +Darwin*) darwin=true + if [ -z "$JAVA_VERSION" ] ; then + JAVA_VERSION="CurrentJDK" + else + echo "Using Java version: $JAVA_VERSION" + fi + if [ -z "$JAVA_HOME" ] ; then + JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Home + fi + ;; +esac + +# resolve links - $0 may be a softlink +PRG="$0" + +while [ -h "$PRG" ]; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '.*/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`/"$link" + fi +done + +# Get standard environment variables +PRGDIR=`dirname "$PRG"` + +# Only set CARBON_HOME if not already set +[ -z "$CARBON_HOME" ] && CARBON_HOME=`cd "$PRGDIR/.." ; pwd` + +# Set AXIS2_HOME. Needed for One Click JAR Download +AXIS2_HOME=$CARBON_HOME + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CARBON_HOME" ] && CARBON_HOME=`cygpath --unix "$CARBON_HOME"` + [ -n "$AXIS2_HOME" ] && CARBON_HOME=`cygpath --unix "$CARBON_HOME"` +fi + +# For OS400 +if $os400; then + # Set job priority to standard for interactive (interactive - 6) by using + # the interactive priority - 6, the helper threads that respond to requests + # will be running at the same priority as interactive jobs. + COMMAND='chgjob job('$JOBNAME') runpty(6)' + system $COMMAND + + # Enable multi threading + QIBM_MULTI_THREADED=Y + export QIBM_MULTI_THREADED +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$CARBON_HOME" ] && + CARBON_HOME="`(cd "$CARBON_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + [ -n "$AXIS2_HOME" ] && + CARBON_HOME="`(cd "$CARBON_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD=java + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." + echo " CARBON cannot execute $JAVACMD" + exit 1 +fi + +# if JAVA_HOME is not set we're not happy +if [ -z "$JAVA_HOME" ]; then + echo "You must set the JAVA_HOME variable before running CARBON." + exit 1 +fi + +if [ -e "$CARBON_HOME/wso2carbon.pid" ]; then + PID=`cat "$CARBON_HOME"/wso2carbon.pid` +fi + +# ----- Process the input command ---------------------------------------------- +args="" +for c in $* +do + if [ "$c" = "--debug" ] || [ "$c" = "-debug" ] || [ "$c" = "debug" ]; then + CMD="--debug" + continue + elif [ "$CMD" = "--debug" ]; then + if [ -z "$PORT" ]; then + PORT=$c + fi + elif [ "$c" = "--stop" ] || [ "$c" = "-stop" ] || [ "$c" = "stop" ]; then + CMD="stop" + elif [ "$c" = "--start" ] || [ "$c" = "-start" ] || [ "$c" = "start" ]; then + CMD="start" + elif [ "$c" = "--version" ] || [ "$c" = "-version" ] || [ "$c" = "version" ]; then + CMD="version" + elif [ "$c" = "--restart" ] || [ "$c" = "-restart" ] || [ "$c" = "restart" ]; then + CMD="restart" + elif [ "$c" = "--test" ] || [ "$c" = "-test" ] || [ "$c" = "test" ]; then + CMD="test" + else + args="$args $c" + fi +done + +if [ "$CMD" = "--debug" ]; then + if [ "$PORT" = "" ]; then + echo " Please specify the debug port after the --debug option" + exit 1 + fi + if [ -n "$JAVA_OPTS" ]; then + echo "Warning !!!. User specified JAVA_OPTS will be ignored, once you give the --debug option." + fi + CMD="RUN" + JAVA_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=$PORT" + echo "Please start the remote debugging client to continue..." +elif [ "$CMD" = "start" ]; then + if [ -e "$CARBON_HOME/wso2carbon.pid" ]; then + if ps -p $PID > /dev/null ; then + echo "Process is already running" + exit 0 + fi + fi + export CARBON_HOME=$CARBON_HOME +# using nohup sh to avoid erros in solaris OS.TODO + nohup sh $CARBON_HOME/bin/wso2server.sh $args > /dev/null 2>&1 & + exit 0 +elif [ "$CMD" = "stop" ]; then + export CARBON_HOME=$CARBON_HOME + kill -term `cat $CARBON_HOME/wso2carbon.pid` + exit 0 +elif [ "$CMD" = "restart" ]; then + export CARBON_HOME=$CARBON_HOME + kill -term `cat $CARBON_HOME/wso2carbon.pid` + process_status=0 + pid=`cat $CARBON_HOME/wso2carbon.pid` + while [ "$process_status" -eq "0" ] + do + sleep 1; + ps -p$pid 2>&1 > /dev/null + process_status=$? + done + +# using nohup sh to avoid erros in solaris OS.TODO + nohup sh $CARBON_HOME/bin/wso2server.sh $args > /dev/null 2>&1 & + exit 0 +elif [ "$CMD" = "test" ]; then + JAVACMD="exec "$JAVACMD"" +elif [ "$CMD" = "version" ]; then + cat $CARBON_HOME/bin/version.txt + cat $CARBON_HOME/bin/wso2carbon-version.txt + exit 0 +fi + +# ---------- Handle the SSL Issue with proper JDK version -------------------- +jdk_17=`$JAVA_HOME/bin/java -version 2>&1 | grep "1.[7|8]"` +if [ "$jdk_17" = "" ]; then + echo " Starting WSO2 Carbon (in unsupported JDK)" + echo " [ERROR] CARBON is supported only on JDK 1.7 and 1.8" +fi + +CARBON_XBOOTCLASSPATH="" +for f in "$CARBON_HOME"/lib/xboot/*.jar +do + if [ "$f" != "$CARBON_HOME/lib/xboot/*.jar" ];then + CARBON_XBOOTCLASSPATH="$CARBON_XBOOTCLASSPATH":$f + fi +done + +JAVA_ENDORSED_DIRS="$CARBON_HOME/lib/endorsed":"$JAVA_HOME/jre/lib/endorsed":"$JAVA_HOME/lib/endorsed" + +CARBON_CLASSPATH="" +if [ -e "$JAVA_HOME/lib/tools.jar" ]; then + CARBON_CLASSPATH="$JAVA_HOME/lib/tools.jar" +fi +for f in "$CARBON_HOME"/bin/*.jar +do + if [ "$f" != "$CARBON_HOME/bin/*.jar" ];then + CARBON_CLASSPATH="$CARBON_CLASSPATH":$f + fi +done +for t in "$CARBON_HOME"/lib/commons-lang*.jar +do + CARBON_CLASSPATH="$CARBON_CLASSPATH":$t +done +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"` + CARBON_HOME=`cygpath --absolute --windows "$CARBON_HOME"` + AXIS2_HOME=`cygpath --absolute --windows "$CARBON_HOME"` + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + JAVA_ENDORSED_DIRS=`cygpath --path --windows "$JAVA_ENDORSED_DIRS"` + CARBON_CLASSPATH=`cygpath --path --windows "$CARBON_CLASSPATH"` + CARBON_XBOOTCLASSPATH=`cygpath --path --windows "$CARBON_XBOOTCLASSPATH"` +fi + +# ----- Execute The Requested Command ----------------------------------------- + +echo JAVA_HOME environment variable is set to $JAVA_HOME +echo CARBON_HOME environment variable is set to $CARBON_HOME + +cd "$CARBON_HOME" + +TMP_DIR=$CARBON_HOME/tmp +if [ -d "$TMP_DIR" ]; then +rm -rf "$TMP_DIR" +fi + +START_EXIT_STATUS=121 +status=$START_EXIT_STATUS + +#To monitor a Carbon server in remote JMX mode on linux host machines, set the below system property. +# -Djava.rmi.server.hostname="your.IP.goes.here" + +while [ "$status" = "$START_EXIT_STATUS" ] +do + $JAVACMD \ + -Xbootclasspath/a:"$CARBON_XBOOTCLASSPATH" \ + -Xms256m -Xmx1024m -XX:MaxPermSize=512m \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:HeapDumpPath="$CARBON_HOME/repository/logs/heap-dump.hprof" \ + $JAVA_OPTS \ + -Dcom.sun.management.jmxremote \ + -classpath "$CARBON_CLASSPATH" \ + -Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" \ + -Djava.io.tmpdir="$CARBON_HOME/tmp" \ + -Dcatalina.base="$CARBON_HOME/lib/tomcat" \ + -Dwso2.server.standalone=true \ + -Dcarbon.registry.root=/ \ + -Djava.command="$JAVACMD" \ + -Dcarbon.home="$CARBON_HOME" \ + -Dlogger.server.name="IoT-Core" \ + -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager \ + -Dcarbon.config.dir.path="$CARBON_HOME/repository/conf" \ + -Djava.util.logging.config.file="$CARBON_HOME/repository/conf/etc/logging-bridge.properties" \ + -Dcomponents.repo="$CARBON_HOME/repository/components/plugins" \ + -Dconf.location="$CARBON_HOME/repository/conf"\ + -Dcom.atomikos.icatch.file="$CARBON_HOME/lib/transactions.properties" \ + -Dcom.atomikos.icatch.hide_init_file_path=true \ + -Dorg.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false \ + -Dorg.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true \ + -Dcom.sun.jndi.ldap.connect.pool.authentication=simple \ + -Dcom.sun.jndi.ldap.connect.pool.timeout=3000 \ + -Dorg.terracotta.quartz.skipUpdateCheck=true \ + -Djava.security.egd=file:/dev/./urandom \ + -Dfile.encoding=UTF8 \ + -Djava.net.preferIPv4Stack=true \ + -Dcom.ibm.cacheLocalHost=true \ + -DworkerNode=false \ + -Dorg.wso2.ignoreHostnameVerification=true \ + -Dorg.opensaml.httpclient.https.disableHostnameVerification=true \ + -Diot.analytics.host="localhost" \ + -Diot.analytics.https.port="9445" \ + -Diot.manager.host="localhost" \ + -Diot.manager.https.port="9443" \ + -Dmqtt.broker.host="localhost" \ + -Dmqtt.broker.port="1886" \ + -Diot.core.host="localhost" \ + -Diot.core.https.port="9443" \ + -Diot.keymanager.host="localhost" \ + -Diot.keymanager.https.port="9443" \ + -Diot.gateway.host="localhost" \ + -Diot.gateway.https.port="8243" \ + -Diot.gateway.http.port="8280" \ + -Diot.apimpublisher.host="localhost" \ + -Diot.apimpublisher.https.port="9443" \ + -Diot.apimstore.host="localhost" \ + -Diot.apimstore.https.port="9443" \ + org.wso2.carbon.bootstrap.Bootstrap $* + status=$? +done diff --git a/modules/distribution/src/core/cloud/portal/common.css b/modules/distribution/src/core/cloud/portal/common.css new file mode 100644 index 00000000..091a6501 --- /dev/null +++ b/modules/distribution/src/core/cloud/portal/common.css @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +.truncate { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/** + * Validation messages + */ +.required { + color: #e74c3c; +} + +.required-error { + background: #a94442; + border: 1px solid #a94442; + padding: 6px 12px; + color: #fff; +} + +/** + * Theme overrides + */ +.breadcrumb li .fw-home { + float: left; + padding-top: 2px; + margin-right: 5px; +} + +/** + * Auth menu + */ +.auth .hidden-xs { + line-height: 38px; +} + +.auth-xs { + color: #fff; +} + +.auth-xs ul { + list-style: none; + padding: 0; + margin: 0; + line-height: 28px; + background-color: #2a80b9; +} + +.auth-xs li { + color: #ccc; +} + +.auth-xs li a { + display: block; + color: #fff; +} + +.auth-xs li a:hover { + background-color: #499dd5; +} + +ul.dropdown-menu.more-actions-button { + list-style-type: none; + margin: 0; + padding: 0; + overflow: hidden; + width: 40px; + background: #F9F9F9; + border-bottom: 1px solid #EFEFEF; + min-width: 45px; + +} + +ul.dropdown-menu.more-actions-button > li { + height: 40px; + width: 40px; + border: 1px; +} + +ul.dropdown-menu.more-actions-button > li > button { + border-bottom: 1px solid #e4e4e4; + border-top: 1px solid darkred; +} + +.btn-group.open .dropdown-toggle { + -webkit-box-shadow: none; + box-shadow: none; + border: 0px; +} + +.btn-custom { + border-width: 1px; +} + + +.cloud-menu .popover { + border-radius: 0px; + width: 24em; + left: -21.1em !important; + max-width: 32em; + background-color: #006690 +} +.cloud-menu .popover-title,.navbar-header .popover-title { + background-color: #006690; + font-size: 16px; + border-bottom: none; + font-weight: 400; +} +.cloud-menu .popover.bottom>.arrow{ + margin-left:-2px; +} +.cloud-menu .popover.bottom>.arrow:after,.navbar-header .popover.bottom>.arrow:after{ + border-bottom-color: #006690; +} +.cloud-block { + float: left; + width: 8.2em; + height: 8.2em; + background-color: #fff; + margin: 0.5em 0em 0.5em 0.5em; + text-align: center; + vertical-align: middle; +} +.cloud-name { + font-size:14px; + margin-top: .5em; + font-weight: 400; +} +.cloud-menu-popover { + position: relative; + float: right; + padding: 0px 8px; + background-color: transparent; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; + color: #fff; + cursor: pointer; +} +#cloud-menu-popover-xs { + color: #fff; + line-height:24px; + border: none; + margin-right: 15px!important; +} +.navbar-toggle{ + border:none; + border-radius: 0px; +} +.navbar-header .popover { + border-radius: 0px; + width: 21em; + max-width:32em; + background-color: #006690; +} +.navbar-header .popover .popover-content{ + padding:0px; +} +.cloud-menu .popover-content { + padding: 0px; +} +.cloud-actions { + background-color: #005578; + float: left; + position: absolute; + width: 100%; + left: 0px; + overflow:hidden; +} +.cloud-actions h3 { + font-size: 16px; + font-weight: 400; + padding-left: 14px; + margin-top: 10px; +} +.cloud-block-invert { + color: #fff; + float: left; + width: 8.2em; + height: 8.2em; + background-color: #1f1f1f; + margin: 0.5em 0em 0.5em 0.5em; + text-align: center; + cursor: pointer; +} + +.cloud-block-default { + color: #006690; + background-color: #fff; + cursor: pointer; +} +.cloud-actions a:hover { + color: #d7d5d5; + background-color: #3d3d3d; + text-decoration: none +} +.cloud-apps a { + text-decoration: none; + color: #006690 !important; + cursor: pointer +} +.cloud-apps a:hover { + text-decoration: none; + color: #006690; + background-color: #c5c5c5; +} +.cloud-apps .cloud-actions a { + color: #fff +} + +.add-padding-top-3x { + padding-top: 15px !important; +} + +.nav li a{ + color: #fff; +} + +.cloud-menu-content li a{ + color:inherit; +} + +html{ + height: 100%; +} + +body{ + height: calc(100% - 50px); +} \ No newline at end of file diff --git a/modules/distribution/src/core/cloud/portal/global-navigation.jag b/modules/distribution/src/core/cloud/portal/global-navigation.jag new file mode 100644 index 00000000..e4f22cc2 --- /dev/null +++ b/modules/distribution/src/core/cloud/portal/global-navigation.jag @@ -0,0 +1,289 @@ +<% +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +%> +<% +var query = request.getQueryString(); +var dest = encodeURIComponent(originalURI + (query ? '?' + query : '')); +%> +
+ + + +
+
Navigate to Cloud
+ +
+ + + + +
diff --git a/modules/distribution/src/core/cloud/portal/portal.js b/modules/distribution/src/core/cloud/portal/portal.js new file mode 100644 index 00000000..0a7386a1 --- /dev/null +++ b/modules/distribution/src/core/cloud/portal/portal.js @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +$(function () { + + var dashboardsApi = ues.utils.tenantPrefix() + 'apis/dashboards'; + var dashboards = []; + var isStillLoading = false; + var nextStart = 0; + var hasMore = true; + + /** + * Page count. + * @const + */ + var PAGE_COUNT = 10; + + // Pre-compiling handlebar templates + var dashboardsListHbs = Handlebars.compile($("#ues-dashboards-list-hbs").html()); + var dashboardThumbnailHbs = Handlebars.compile($("#ues-dashboard-thumbnail-hbs").html()); + var dashboardConfirmHbs = Handlebars.compile($("#ues-dashboard-confirm-hbs").html()); + var dashboardsEmptyHbs = Handlebars.compile($("#ues-dashboards-empty-hbs").html()); + Handlebars.registerPartial('ues-dashboard-thumbnail-hbs', dashboardThumbnailHbs); + + /** + * Find the dashboard using dashboard id. + * @param id + * @return {object} + * @private + * */ + var findDashboard = function (id) { + var i; + var dashboard; + var length = dashboards.length; + for (i = 0; i < length; i++) { + dashboard = dashboards[i]; + if (dashboard.id === id) { + return dashboard; + } + } + }; + + /** + * Delete the selected dashboard + * @param el:-selected dashboard element + * @private + * */ + var deleteDashboard = function (el) { + var button = Ladda.create(el[0]); + button.start(); + var id = el.closest('.ues-dashboard').data('id'); + $.ajax({ + url: dashboardsApi + '/' + id, + method: 'DELETE', + async : false, + success: function () { + button.stop(); + location.reload(); + }, + error: function () { + button.stop(); + } + }); + }; + + /** + * Load the list of dashboards available. + * @private + * */ + var loadDashboards = function () { + isStillLoading = true; + + if (!hasMore) { + isStillLoading = false; + $('.ues-dashboard').each(function (i, obj) { + if ($(this).find('.ues-dashboard-share').length) { + $(this).addClass("shared"); + } + }); + return; + } + ues.store.assets('dashboard', { + start: nextStart, + count: PAGE_COUNT + }, function (err, data) { + var dashboardsEl = $('#ues-portal').find('.ues-dashboards'); + hasMore = data.length; + if (!hasMore && nextStart === 0) { + dashboardsEl.append(dashboardsEmptyHbs()); + return; + } + + nextStart += PAGE_COUNT; + dashboards = dashboards.concat(data); + dashboardsEl.append(dashboardsListHbs(data)); + + var win = $(window); + var doc = $(document); + isStillLoading = false; + if (doc.height() > win.height()) { + return; + } + + loadDashboards(); + + $(".disable").on('click', function (event) { + event.preventDefault(); + }); + }); + }; + + /** + * Initialize the UI functionality such as binding events. + * @private + * */ + var initUI = function () { + var portal = $('#ues-portal'); + portal.on('click', '.ues-dashboards .ues-dashboard-trash-handle', function (e) { + e.preventDefault(); + var thiz = $(this); + var dashboardEl = thiz.closest('.ues-dashboard'); + var id = dashboardEl.data('id'); + var dashboard = findDashboard(id); + dashboardEl.html(dashboardConfirmHbs(dashboard)); + }); + + portal.on('click', '.ues-dashboards .ues-dashboard-trash-confirm', function (e) { + e.preventDefault(); + deleteDashboard($(this)); + }); + + portal.on('click', '.ues-dashboards .ues-dashboard-trash-cancel', function (e) { + e.preventDefault(); + var thiz = $(this); + var dashboardEl = thiz.closest('.ues-dashboard'); + var id = dashboardEl.data('id'); + var dashboard = findDashboard(id); + dashboardEl.html(dashboardThumbnailHbs(dashboard)); + }); + + portal.on('click', '.ues-view:not(.disable)', function(e) { + e.preventDefault(); + window.open($(this).attr('href'), '_blank'); + }); + + $('#filter-dashboards a').on('click', function () { + $('#filter').html($(this).text()); + var filter = $(this).data('filter'); + + $('.ues-dashboard-container').each(function (i, obj) { + if (filter === "All") { + $(this).show(); + } else { + if ($(this).find('.ues-dashboard-share').length) { + filter === "Shared" ? $(this).show() : $(this).hide(); + } else { + filter === "Shared" ? $(this).hide() : $(this).show(); + } + } + }); + }); + + $(window).scroll(function () { + var win = $(window); + var doc = $(document); + if (win.scrollTop() + win.height() < doc.height() - 100) { + return; + } + + if (!isStillLoading) { + loadDashboards(); + } + }); + }; + + + $(document).ready(function () { + $('#cloud-menu-popover i.fw-tiles').popover({ + html: true, + trigger:'click', + title: function() { + return $("#popover-head").html(); + }, + content: function() { + return $("#popover-content").html(); + } + }); + }); + + initUI(); + loadDashboards(); +}); \ No newline at end of file diff --git a/modules/distribution/src/core/conf/analytics/analytics-data-config.xml b/modules/distribution/src/core/conf/analytics/analytics-data-config.xml new file mode 100644 index 00000000..85f9d642 --- /dev/null +++ b/modules/distribution/src/core/conf/analytics/analytics-data-config.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + AUTO + + + + + + http://localhost:9765 + + + + admin + + + + + admin + + + + 200 + + + + 200 + + + + 60000 + + + + 60000 + + + + + + + + + + diff --git a/modules/distribution/src/core/conf/api-manager.xml b/modules/distribution/src/core/conf/api-manager.xml new file mode 100755 index 00000000..1341e29f --- /dev/null +++ b/modules/distribution/src/core/conf/api-manager.xml @@ -0,0 +1,543 @@ + + + jdbc/WSO2AM_DB + + + Synapse + + + false + + + + + https://localhost:${mgt.transport.https.port}${carbon.context}services/ + + ${admin.username} + + ${admin.password} + + false + + + + + true + + + X-JWT-Assertion + + + + + + http://wso2.org/claims + + + SHA256withRSA + + + + + + + + + + + + + + + + + + + + + + Production and Sandbox + This is a hybrid gateway that handles both production and sandbox token traffic. + + https://localhost:${mgt.transport.https.port}${carbon.context}services/ + + ${admin.username} + + ${admin.password} + + http://${carbon.local.ip}:${http.nio.port},https://${carbon.local.ip}:${https.nio.port} + + + + + + + true + + true + + false + + false + + + + + + + + + + + + false + + + {tcp://localhost:7612} + + + ${admin.username} + + ${admin.password} + + + org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRdbmsClientImpl + + + https://localhost:9444 + ${admin.username} + ${admin.password} + + + false + + + org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + false + + + + org.wso2.apimgt.statistics.request + 1.1.0 + + + org.wso2.apimgt.statistics.response + 1.1.0 + + + org.wso2.apimgt.statistics.fault + 1.0.0 + + + org.wso2.apimgt.statistics.throttle + 1.0.0 + + + org.wso2.apimgt.statistics.workflow + 1.0.0 + + + org.wso2.apimgt.statistics.execution.time + 1.0.0 + + + org.wso2.analytics.apim.alertStakeholderInfo + 1.0.0 + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port}${carbon.context}services/ + + + ${admin.username} + + ${admin.password} + + + WSClient + 10000 + + + false + localhost + + + + + org.wso2.carbon.apimgt.keymgt.handlers.DefaultKeyValidationHandler + + + + + + + + + + am_application_scope + + + ^device_.* + + + + /oauth2/token + + https://localhost:${https.nio.port}/revoke + + false + + + + + + true + + + + + + + true + false + https://localhost:${mgt.transport.https.port}/store + + + https://localhost:${mgt.transport.https.port}${carbon.context}services/ + + ${admin.username} + + + ${admin.password} + + false + + false + + + + + true + + + true + + + + + + + false + https://localhost:${mgt.transport.https.port}/publisher + + + + + + + + + + + + + false + + + + + /resource + admin + 1.0.0 + none + none + Any + + + + + + + + + + + true + + + * + + + GET,PUT,POST,DELETE,PATCH,OPTIONS + + + authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction + + + + false + + + + + + + + + + /api/am/publisher/{version}/swagger.json + GET,HEAD + + + /api/am/store/{version}/swagger.json + GET,HEAD + + + /api/am/admin/{version}/swagger.json + GET,HEAD + + + /api/am/store/{version}/apis + GET,HEAD + + + /api/am/store/{version}/apis/{apiId} + GET,HEAD + + + /api/am/store/{version}/apis/{apiId}/swagger + GET,HEAD + + + /api/am/store/{version}/apis/{apiId}/documents + GET,HEAD + + + /api/am/store/{version}/apis/{apiId}/documents/{documentId} + GET,HEAD + + + /api/am/store/{version}/apis/{apiId}/documents/{documentId}/content + GET,HEAD + + + /api/am/store/{version}/apis/{apiId}/thumbnail + GET,HEAD + + + /api/am/store/{version}/tags + GET,HEAD + + + /api/am/store/{version}/tiers/{tierLevel} + GET,HEAD + + + /api/am/store/{version}/tiers/{tierLevel}/{tierName} + GET,HEAD + + + + + false + + false + Binary + tcp://${carbon.local.ip}:${receiver.url.port} + ssl://${carbon.local.ip}:${auth.url.port} + ${admin.username} + ${admin.password} + + 1000 + 200 + + + 200 + 1000 + 200 + + + + https://localhost:${mgt.transport.https.port}${carbon.context}services/ + ${admin.username} + ${admin.password} + + + false + + + + false + tcp://${carbon.local.ip}:${jms.port} + ${admin.username} + ${admin.password} + throttleData + + + TopicConnectionFactory + topic + org.wso2.andes.jndi.PropertiesFileInitialContextFactory + amqp://${jms.username}:${jms.password}@clientid/carbon?brokerlist='${jms.url}' + + + 20 + 100 + 1000 + 10 + + + + org.wso2.andes.jndi.PropertiesFileInitialContextFactory + repository/conf/jndi.properties + topic + throttleData + allow + TopicConnectionFactory + + + true + false + false + false + + + diff --git a/modules/distribution/src/core/conf/app-manager.xml b/modules/distribution/src/core/conf/app-manager.xml new file mode 100644 index 00000000..246b410d --- /dev/null +++ b/modules/distribution/src/core/conf/app-manager.xml @@ -0,0 +1,494 @@ + + + + + + jdbc/WSO2APPM_DB + + jdbc/ES_Storage + + + + + true + + + + + false + false + + + + + + + https://localhost:${mgt.transport.https.port}/services/ + + + admin + + + admin + + + + + + + + + + + + + + + + + + + 1800 + + + true + + + org.wso2.carbon.appmgt.impl.token.JWTGenerator + + + X-JWT-Assertion + + + org.wso2.carbon.appmgt.impl.token.DefaultClaimsRetriever + + + http://wso2.org/claims + + + SHA256withRSA + + + false + + + false + + + + + + + + + + + + Gateway Endpoint + + + https://${carbon.local.ip}:${mgt.transport.https.port}/services/ + + + admin + + + admin + + + http://${carbon.local.ip}:${http.nio.port},https://${carbon.local.ip}:${https.nio.port} + + + + + + + + + + + + + jdbc/WSO2APPM_DB + + + false + + + false + + + org.wso2.carbon.appmgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher + + + org.wso2.carbon.appmgt.usage.client.impl.AppUsageStatisticsRdbmsClient + + + 7612 + + + tcp://localhost:7612 + + + admin + + + admin + + + + org.wso2.appmgt.statistics.request + 1.0.0 + + org.wso2.appmgt.statistics.response + 1.0.0 + + org.wso2.appmgt.statistics.fault + 1.0.0 + + org.wso2.appmgt.statistics.cache + 1.0.0 + + + org.wso2.appmgt.bam.uiactivitypublish + 1.1.0 + + + + + + + + + + + + false + + + UA-XXXXXXXX-X + + + + + + + + + + true + + + + + + + + true + + + https://localhost:9443,http://localhost:9763 + + + authorization,Access-Control-Allow-Origin,Content-Type + + + GET,POST,PUT,DELETE,OPTIONS + + + + + + + + false + + + https://localhost:${mgt.transport.https.port}/samlsso + + + appm/acs + + + true + + + true + + + true + + + 300 + + + wso2carbon + + + + wso2is + 5.0.0 + org.wso2.carbon.appmgt.impl.idp.sso.configurator.IS500SAMLSSOConfigurator + + https://${carbon.local.ip}:${mgt.transport.https.port} + admin + admin + + + + + + + + + + + https://${carbon.local.ip}:${mgt.transport.https.port} + admin + admin + + + + + + + + + + false + + + false + + + true + + + WSO2MDM_INTERNAL + + + false + + + true + + + false + + + %http% + + + publisher/api/mobileapp/getplist + + + true + + + Internal/store-admin + + + + + + + + /store/extensions/assets/mobileapp/resources/models/%s.png + https://localhost:9443 + https://localhost:9443/oauth2 + admin + admin + 100 + + + + + https://localhost:9443 + https://localhost:9443/emm/assets/wso2mobile/img/models/%s.png + admin + admin + + + + + /store/extensions/assets/mobileapp/resources/models/%s.png + + + + + + + + repository/resources/mobileapps/ + /api/mobileapp/getfile/ + + + + + + ${carbon.home}/repository/resources/mobileapps/ + + + + + admin + + + + + mobileapp + + + + + /api/appm/publisher/v1.1 + /api/appm/store/v1.1 + + + + + /api/appm/store/{version}/apps/mobile/binaries/one-time/{uuid} + GET,HEAD + + + /api/appm/store/{version}/apps/static-contents/{fileName} + GET,HEAD + + + /api/appm/store/{version}/apps/mobile/plist/{appId}/{uuid} + GET,HEAD + + + + + diff --git a/modules/distribution/src/core/conf/application-authenticators.xml b/modules/distribution/src/core/conf/application-authenticators.xml new file mode 100755 index 00000000..c13c0401 --- /dev/null +++ b/modules/distribution/src/core/conf/application-authenticators.xml @@ -0,0 +1,23 @@ + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/axis2/axis2.xml b/modules/distribution/src/core/conf/axis2/axis2.xml new file mode 100644 index 00000000..64bd8ab5 --- /dev/null +++ b/modules/distribution/src/core/conf/axis2/axis2.xml @@ -0,0 +1,959 @@ + + + + + + + + + + + true + + true + + + false + + false + + + false + + work/mtom + + 4000 + + + false + + + inmemory + + + + + services + + + axis2services + + + axis2modules + + + WSO2 IoT 1.0.0 + WSO2 IoT 1.O.0 + + + + false + + + + + + + false + + + true + + + 30000 + + + repository/deployment/server/synapse-configs + + . + + . + + localhost + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8280 + true + + + org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor + + + + + + + + + + + + 8243 + true + + + org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + AllowAll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + true + + + repository/resources/security/wso2carbon.jks + JKS + wso2carbon + wso2carbon + + + + + repository/resources/security/client-truststore.jks + JKS + wso2carbon + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + multicast + + + + + wso2.carbon.domain + + + + + + 45564 + + 100 + + 60 + + + + + + 127.0.0.1 + + + + + + 4000 + + + + + + + + + + + + + + + 127.0.0.1 + 4000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/axis2/axis2_client.xml b/modules/distribution/src/core/conf/axis2/axis2_client.xml new file mode 100644 index 00000000..5c407556 --- /dev/null +++ b/modules/distribution/src/core/conf/axis2/axis2_client.xml @@ -0,0 +1,317 @@ + + + + + + + true + false + false + + + 500 + + 15000 + + + false + + + + true + + + + + + false + + + admin + axis2 + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 6071 + + + + + + + + + + + + + + + + + + + + + + HTTP/1.1 + chunked + 60000 + 60000 + + + HTTP/1.1 + chunked + 60000 + 60000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/conf/carbon.xml b/modules/distribution/src/core/conf/carbon.xml new file mode 100644 index 00000000..40345945 --- /dev/null +++ b/modules/distribution/src/core/conf/carbon.xml @@ -0,0 +1,688 @@ + + + + + + + + + ${product.name} + + + ${product.key} + + + ${product.version} + + + + localhost + + + localhost + + + local:/${carbon.context}/services/ + + + + + + + ${default.server.role} + ${cdmf.analytics.role} + CDMFPlatform + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + true + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + http://dist.wso2.org/p2/carbon/releases/4.4.1-SNAPSHOT + + + + + + + + true + + + + + + true + + diff --git a/modules/distribution/src/core/conf/datasources/cdm-datasources.xml b/modules/distribution/src/core/conf/datasources/cdm-datasources.xml new file mode 100755 index 00000000..e647e148 --- /dev/null +++ b/modules/distribution/src/core/conf/datasources/cdm-datasources.xml @@ -0,0 +1,45 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + DM_DS + The datasource used for CDM + + jdbc/DM_DS + + + + jdbc:h2:repository/database/WSO2DM_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + diff --git a/modules/distribution/src/core/conf/datasources/master-datasources.xml b/modules/distribution/src/core/conf/datasources/master-datasources.xml new file mode 100755 index 00000000..ec22c8a6 --- /dev/null +++ b/modules/distribution/src/core/conf/datasources/master-datasources.xml @@ -0,0 +1,147 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + WSO2_CARBON_DB + The datasource used for registry and user manager + + jdbc/WSO2CarbonDB + + + + jdbc:h2:repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=9095 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + WSO2APPM_DB + The datasource used for App Manager database + + jdbc/WSO2APPM_DB + + + + jdbc:h2:repository/database/WSO2APPM_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + WSO2AM_DB + The datasource used for API Manager database + + jdbc/WSO2AM_DB + + + + jdbc:h2:repository/database/WSO2AM_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + WSO2_MB_STORE_DB + The datasource used for message broker database + + WSO2MBStoreDB + + + + jdbc:h2:repository/database/WSO2MB_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + false + + + + + JAGH2 + The datasource used for by the Jaggery Storage Manager + + jdbc/ES_Storage + + + + jdbc:h2:repository/database/ES_STORAGE;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + + + + + WSO2_SOCIAL_DB + The datasource used for Store social database + + jdbc/WSO2_SOCIAL_DB + + + + jdbc:h2:repository/database/WSO2_SOCIAL_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + diff --git a/modules/distribution/src/core/conf/etc/device-analytics-config.xml b/modules/distribution/src/core/conf/etc/device-analytics-config.xml new file mode 100644 index 00000000..9f2ca7f4 --- /dev/null +++ b/modules/distribution/src/core/conf/etc/device-analytics-config.xml @@ -0,0 +1,36 @@ + + + + + + true + tcp://localhost:7613 + admin + admin + diff --git a/modules/distribution/src/core/conf/etc/launch.ini b/modules/distribution/src/core/conf/etc/launch.ini new file mode 100644 index 00000000..9e7e19cd --- /dev/null +++ b/modules/distribution/src/core/conf/etc/launch.ini @@ -0,0 +1,258 @@ +# Eclipse Runtime Configuration Overrides +# These properties are loaded prior to starting the framework and can also be used to override System Properties +# @null is a special value used to override and clear the framework's copy of a System Property prior to starting the framework +# "*" can be used together with @null to clear System Properties that match a prefix name. + +osgi.*=@null +org.osgi.*=@null +eclipse.*=@null + +osgi.parentClassloader=app +osgi.contextClassLoaderParent=app + +# When osgi.clean is set to "true", any cached data used by the OSGi framework +# will be wiped clean. This will clean the caches used to store bundle +# dependency resolution and eclipse extension registry data. Using this +# option will force OSGi framework to reinitialize these caches. +# The following setting is put in place to get rid of the problems +# faced when re-starting the system. Please note that, when this setting is +# true, if you manually start a bundle, it would not be available when +# you re-start the system. To avid this, copy the bundle jar to the plugins +# folder, before you re-start the system. +osgi.clean=true + +# Uncomment the following line to turn on Eclipse Equinox debugging. +# You may also edit the osgi-debug.options file and fine tune the debugging +# options to suite your needs. +#osgi.debug=./repository/conf/osgi-debug.options + +# Following system property allows us to control the public JDK packages exported through the system bundle. +org.osgi.framework.system.packages=javax.accessibility,\ +javax.activity,\ +javax.crypto,\ +javax.crypto.interfaces,\ +javax.crypto.spec,\ +javax.imageio,\ +javax.imageio.event,\ +javax.imageio.metadata,\ +javax.imageio.plugins.bmp,\ +javax.imageio.plugins.jpeg,\ +javax.imageio.spi,\ +javax.imageio.stream,\ +javax.jms,\ +javax.management,\ +javax.management.loading,\ +javax.management.modelmbean,\ +javax.management.monitor,\ +javax.management.openmbean,\ +javax.management.relation,\ +javax.management.remote,\ +javax.management.remote.rmi,\ +javax.management.timer,\ +javax.naming,\ +javax.naming.directory,\ +javax.naming.event,\ +javax.naming.ldap,\ +javax.naming.spi,\ +javax.net,\ +javax.net.ssl,\ +javax.print,\ +javax.print.attribute,\ +javax.print.attribute.standard,\ +javax.print.event,\ +javax.rmi,\ +javax.rmi.CORBA,\ +javax.rmi.ssl,\ +javax.script,\ +javax.security.auth,\ +javax.security.auth.callback,\ +javax.security.auth.kerberos,\ +javax.security.auth.login,\ +javax.security.auth.spi,\ +javax.security.auth.x500,\ +javax.security.cert,\ +javax.security.sasl,\ +javax.sound.midi,\ +javax.sound.midi.spi,\ +javax.sound.sampled,\ +javax.sound.sampled.spi,\ +javax.sql,\ +javax.sql.rowset,\ +javax.sql.rowset.serial,\ +javax.sql.rowset.spi,\ +javax.swing,\ +javax.swing.border,\ +javax.swing.colorchooser,\ +javax.swing.event,\ +javax.swing.filechooser,\ +javax.swing.plaf,\ +javax.swing.plaf.basic,\ +javax.swing.plaf.metal,\ +javax.swing.plaf.multi,\ +javax.swing.plaf.synth,\ +javax.swing.table,\ +javax.swing.text,\ +javax.swing.text.html,\ +javax.swing.text.html.parser,\ +javax.swing.text.rtf,\ +javax.swing.tree,\ +javax.swing.undo,\ +javax.transaction,\ +javax.transaction.xa,\ +javax.xml.namespace,\ +javax.xml.parsers,\ +javax.xml.stream,\ +javax.xml.stream.events,\ +javax.xml.stream.util,\ +javax.xml.transform,\ +javax.xml.transform.stream,\ +javax.xml.transform.dom,\ +javax.xml.transform.sax,\ +javax.xml,\ +javax.xml.validation,\ +javax.xml.datatype,\ +javax.xml.xpath,\ +javax.activation,\ +com.sun.activation.registries,\ +com.sun.activation.viewers,\ +org.ietf.jgss,\ +org.omg.CORBA,\ +org.omg.CORBA_2_3,\ +org.omg.CORBA_2_3.portable,\ +org.omg.CORBA.DynAnyPackage,\ +org.omg.CORBA.ORBPackage,\ +org.omg.CORBA.portable,\ +org.omg.CORBA.TypeCodePackage,\ +org.omg.CosNaming,\ +org.omg.CosNaming.NamingContextExtPackage,\ +org.omg.CosNaming.NamingContextPackage,\ +org.omg.Dynamic,\ +org.omg.DynamicAny,\ +org.omg.DynamicAny.DynAnyFactoryPackage,\ +org.omg.DynamicAny.DynAnyPackage,\ +org.omg.IOP,\ +org.omg.IOP.CodecFactoryPackage,\ +org.omg.IOP.CodecPackage,\ +org.omg.Messaging,\ +org.omg.PortableInterceptor,\ +org.omg.PortableInterceptor.ORBInitInfoPackage,\ +org.omg.PortableServer,\ +org.omg.PortableServer.CurrentPackage,\ +org.omg.PortableServer.POAManagerPackage,\ +org.omg.PortableServer.POAPackage,\ +org.omg.PortableServer.portable,\ +org.omg.PortableServer.ServantLocatorPackage,\ +org.omg.SendingContext,\ +org.omg.stub.java.rmi,\ +org.w3c.dom,\ +org.w3c.dom.bootstrap,\ +org.w3c.dom.css,\ +org.w3c.dom.events,\ +org.w3c.dom.html,\ +org.w3c.dom.ls,\ +org.w3c.dom.ranges,\ +org.w3c.dom.stylesheets,\ +org.w3c.dom.traversal,\ +org.w3c.dom.views ,\ +org.xml.sax,\ +org.xml.sax.ext,\ +org.xml.sax.helpers,\ +org.apache.xerces.xpointer,\ +org.apache.xerces.xni.grammars,\ +org.apache.xerces.impl.xs.util,\ +org.apache.xerces.jaxp.validation,\ +org.apache.xerces.impl.dtd.models,\ +org.apache.xerces.impl.xpath,\ +org.apache.xerces.dom3.as,\ +org.apache.xerces.impl.dv.xs,\ +org.apache.xerces.util,\ +org.apache.xerces.impl.xs.identity,\ +org.apache.xerces.impl.xs.opti,\ +org.apache.xerces.jaxp,\ +org.apache.xerces.impl.dv,\ +org.apache.xerces.xs.datatypes,\ +org.apache.xerces.dom.events,\ +org.apache.xerces.impl.msg,\ +org.apache.xerces.xni,\ +org.apache.xerces.impl.xs,\ +org.apache.xerces.impl,\ +org.apache.xerces.impl.io,\ +org.apache.xerces.xinclude,\ +org.apache.xerces.jaxp.datatype,\ +org.apache.xerces.parsers,\ +org.apache.xerces.impl.dv.util,\ +org.apache.xerces.xni.parser,\ +org.apache.xerces.impl.xs.traversers,\ +org.apache.xerces.impl.dv.dtd,\ +org.apache.xerces.xs,\ +org.apache.xerces.impl.dtd,\ +org.apache.xerces.impl.validation,\ +org.apache.xerces.impl.xs.models,\ +org.apache.xerces.impl.xpath.regex,\ +org.apache.xml.serialize,\ +org.apache.xerces.dom,\ +org.apache.xalan,\ +org.apache.xalan.xslt,\ +org.apache.xalan.templates,\ +org.apache.xalan.xsltc,\ +org.apache.xalan.xsltc.cmdline,\ +org.apache.xalan.xsltc.cmdline.getopt,\ +org.apache.xalan.xsltc.trax,\ +org.apache.xalan.xsltc.dom,\ +org.apache.xalan.xsltc.runtime,\ +org.apache.xalan.xsltc.runtime.output,\ +org.apache.xalan.xsltc.util,\ +org.apache.xalan.xsltc.compiler,\ +org.apache.xalan.xsltc.compiler.util,\ +org.apache.xalan.serialize,\ +org.apache.xalan.client,\ +org.apache.xalan.res,\ +org.apache.xalan.transformer,\ +org.apache.xalan.extensions,\ +org.apache.xalan.lib,\ +org.apache.xalan.lib.sql,\ +org.apache.xalan.processor,\ +org.apache.xalan.trace,\ +org.apache.xml.dtm,\ +org.apache.xml.dtm.ref,\ +org.apache.xml.dtm.ref.sax2dtm,\ +org.apache.xml.dtm.ref.dom2dtm,\ +org.apache.xml.utils,\ +org.apache.xml.utils.res,\ +org.apache.xml.res,\ +org.apache.xml.serializer,\ +org.apache.xml.serializer.utils,\ +org.apache.xpath,\ +org.apache.xpath.domapi,\ +org.apache.xpath.objects,\ +org.apache.xpath.patterns,\ +org.apache.xpath.jaxp,\ +org.apache.xpath.res,\ +org.apache.xpath.operations,\ +org.apache.xpath.functions,\ +org.apache.xpath.axes,\ +org.apache.xpath.compiler,\ +org.apache.xml.resolver,\ +org.apache.xml.resolver.tools,\ +org.apache.xml.resolver.helpers,\ +org.apache.xml.resolver.readers,\ +org.apache.xml.resolver.etc,\ +org.apache.xml.resolver.apps,\ +javax.xml.ws,\ +javax.xml.ws.handler,\ +javax.xml.ws.handler.soap,\ +javax.xml.ws.http,\ +javax.xml.ws.soap,\ +javax.xml.ws.spi,\ +javax.xml.ws.spi.http,\ +javax.xml.ws.wsaddressing,\ +javax.xml.bind,\ +javax.xml.bind.annotation,\ +javax.annotation,\ +javax.xml.bind.annotation.adapters,\ +javax.jws,\ +javax.jws.soap,\ +com.sun.xml.internal.messaging.saaj.soap.ver1_1,\ +com.sun.xml.internal.messaging.saaj.soap,\ +com.sun.tools.internal.ws.spi,\ +org.wso2.carbon.bootstrap diff --git a/modules/distribution/src/core/conf/etc/webapp-publisher-config.xml b/modules/distribution/src/core/conf/etc/webapp-publisher-config.xml new file mode 100644 index 00000000..59a239ac --- /dev/null +++ b/modules/distribution/src/core/conf/etc/webapp-publisher-config.xml @@ -0,0 +1,40 @@ + + + + + + + + https://${iot.core.host}:${iot.core.https.port} + + + true + + + false + + + + default + device-manager + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity/application-authentication.xml b/modules/distribution/src/core/conf/identity/application-authentication.xml new file mode 100644 index 00000000..873810cf --- /dev/null +++ b/modules/distribution/src/core/conf/identity/application-authentication.xml @@ -0,0 +1,162 @@ + + + + + + + smart + + + /devicemgt/login + /authenticationendpoint/retry.do + + + + org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultRequestCoordinator + org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler + org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultLogoutRequestHandler + org.wso2.carbon.identity.application.authentication.framework.handler.sequence.impl.DefaultStepBasedSequenceHandler + org.wso2.carbon.identity.application.authentication.framework.handler.sequence.impl.DefaultRequestPathBasedSequenceHandler + org.wso2.carbon.identity.application.authentication.framework.handler.step.impl.DefaultStepHandler + org.wso2.carbon.identity.application.authentication.framework.handler.hrd.impl.DefaultHomeRealmDiscoverer + org.wso2.carbon.identity.application.authentication.framework.handler.claims.impl.DefaultClaimHandler + org.wso2.carbon.identity.application.authentication.framework.handler.provisioning.impl.DefaultProvisioningHandler + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /authenticationendpoint/login.do + /repository/resources/security/client-truststore.jks + wso2carbon + + + + https://accounts.google.com/o/oauth2/token + https://accounts.google.com/o/oauth2/auth + https://www.googleapis.com/oauth2/v3/userinfo + + + https://login.live.com/oauth20_token.srf + https://login.live.com/oauth20_authorize.srf + https://apis.live.net/v5.0/me?access_token= + + + https://graph.facebook.com/oauth/access_token + http://www.facebook.com/dialog/oauth + https://graph.facebook.com/me + + + /authenticationendpoint/fido-auth.jsp + + + https://api.login.yahoo.com/oauth2/get_token + https://api.login.yahoo.com/oauth2/request_auth + https://social.yahooapis.com/v1/user/ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity/identity-providers/default.xml b/modules/distribution/src/core/conf/identity/identity-providers/default.xml new file mode 100644 index 00000000..090bd787 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/identity-providers/default.xml @@ -0,0 +1,42 @@ + + + + default + default + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity/identity-providers/iot_default.xml b/modules/distribution/src/core/conf/identity/identity-providers/iot_default.xml new file mode 100644 index 00000000..9ef53ce1 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/identity-providers/iot_default.xml @@ -0,0 +1,44 @@ + + + + wso2.org/products/iot + wso2.org/products/iot + + devicemgt + true + + + + + + + + + + + + +MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoMBFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAyMTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzOM4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXnRS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTmxbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogRKv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo= + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity/service-providers/API_STORE.xml b/modules/distribution/src/core/conf/identity/service-providers/API_STORE.xml new file mode 100644 index 00000000..d77e49a3 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/API_STORE.xml @@ -0,0 +1,60 @@ + + + + 8 + API_STORE + App Manager - Publisher + + + + API_STORE + samlsso + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + true + true + + + true + true + + + + + + + + + true + + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/default.xml b/modules/distribution/src/core/conf/identity/service-providers/default.xml new file mode 100644 index 00000000..a619f365 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/default.xml @@ -0,0 +1,67 @@ + + + + 1 + default + Default Service Provider + + + + default + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + + true + true + + + + + + + + true + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/devicemgt.xml b/modules/distribution/src/core/conf/identity/service-providers/devicemgt.xml new file mode 100644 index 00000000..2c7c52d9 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/devicemgt.xml @@ -0,0 +1,60 @@ + + + + 8 + devicemgt + Device Manager + + + + devicemgt + samlsso + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + true + true + + + true + true + + + + + + + + + true + + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/portal.xml b/modules/distribution/src/core/conf/identity/service-providers/portal.xml new file mode 100644 index 00000000..3cd65666 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/portal.xml @@ -0,0 +1,60 @@ + + + + 9 + portal + Carbon Dashboards Portal + + + + portal + samlsso + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + true + true + + + true + true + + + + + + + + + true + + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/publisher.xml b/modules/distribution/src/core/conf/identity/service-providers/publisher.xml new file mode 100644 index 00000000..33a4736d --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/publisher.xml @@ -0,0 +1,60 @@ + + + + 2 + publisher + App Manager - Publisher + + + + publisher + samlsso + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + true + true + + + true + true + + + + + + + + + true + + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/sp_cdm.xml b/modules/distribution/src/core/conf/identity/service-providers/sp_cdm.xml new file mode 100644 index 00000000..40d61237 --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/sp_cdm.xml @@ -0,0 +1,67 @@ + + + + 2 + wso2_cdm + CDM + + + + cdm + samlsso + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + + true + true + + + + + + + + true + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/sp_mdm.xml b/modules/distribution/src/core/conf/identity/service-providers/sp_mdm.xml new file mode 100644 index 00000000..e85c3f4d --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/sp_mdm.xml @@ -0,0 +1,67 @@ + + + + 2 + wso2_mdm + MDM + + + + mdm + samlsso + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + + true + true + + + + + + + + true + + + diff --git a/modules/distribution/src/core/conf/identity/service-providers/store.xml b/modules/distribution/src/core/conf/identity/service-providers/store.xml new file mode 100644 index 00000000..9503a87d --- /dev/null +++ b/modules/distribution/src/core/conf/identity/service-providers/store.xml @@ -0,0 +1,60 @@ + + + + 3 + store + App Manager - Store + + + + store + samlsso + + + + + + + + + 1 + + + BasicAuthenticator + basicauth + true + + + true + true + + + true + true + + + + + + + + + true + + + + diff --git a/modules/distribution/src/core/conf/identity/sso-idp-config.xml b/modules/distribution/src/core/conf/identity/sso-idp-config.xml new file mode 100755 index 00000000..fb00571f --- /dev/null +++ b/modules/distribution/src/core/conf/identity/sso-idp-config.xml @@ -0,0 +1,120 @@ + + + https://stratos-local.wso2.com/carbon/tenant-register/select_domain.jsp + + + devicemgt + + https://localhost:9443/devicemgt/uuf/sso/acs + + https://localhost:9443/devicemgt/uuf/sso/acs + true + true + false + false + + http://wso2.org/claims/role + http://wso2.org/claims/emailaddress + + true + true + + https://localhost:9443/oauth2/token + + + https://localhost:9443/oauth2/token + + + + store + + https://localhost:9443/store/acs + + https://localhost:9443/store/acs + true + /store/login.jag + + + social + + https://localhost:9443/social/acs + + https://localhost:9443/social/acs + true + /social/login + + + publisher + + https://localhost:9443/publisher/acs + + https://localhost:9443/publisher/acs + true + /publisher/controllers/login.jag + true + + carbonServer + + + + API_STORE + + https://localhost:9443/api-store/jagg/jaggery_acs.jag + + https://localhost:9443/api-store/jagg/jaggery_acs.jag + true + true + + carbonServer + + + + portal + + https://localhost:9443/portal/acs + + https://localhost:9443/portal/acs + true + true + true + + https://localhost:9443/oauth2/token + + + https://localhost:9443/oauth2/token + + + + analyticsportal + + https://localhost:9445/portal/acs + + https://localhost:9445/portal/acs + true + true + true + + https://localhost:9443/oauth2/token + + + https://localhost:9443/oauth2/token + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/identity_config_change.xml b/modules/distribution/src/core/conf/identity_config_change.xml new file mode 100644 index 00000000..ddcc0cef --- /dev/null +++ b/modules/distribution/src/core/conf/identity_config_change.xml @@ -0,0 +1,32 @@ + + + + //s:Server/s:OAuth/s:OAuthScopeValidator + + + + //s:Server/s:OAuth/s:OAuthCallbackHandlers + ]]> + + + + //s:Server/s:OAuth/s:SupportedGrantTypes/s:SupportedGrantType[s:GrantTypeName='iwa:ntlm']/s:GrantTypeName + + org.wso2.carbon.identity.oauth.common.NTLMAuthenticationValidator]]> + + + //s:Server/s:OAuth/s:SupportedGrantTypes/s:SupportedGrantType[s:GrantTypeName='iwa:ntlm']/s:GrantTypeName + + org.wso2.carbon.identity.oauth.common.NTLMAuthenticationValidator]]> + + + //s:Server/s:OAuth/s:SupportedGrantTypes/s:SupportedGrantType[s:GrantTypeName='iwa:ntlm'] + + + urn:ietf:params:oauth:grant-type:jwt-bearer + org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant.ExtendedJWTGrantHandler + org.wso2.carbon.identity.oauth2.grant.jwt.JWTGrantValidator + ]]> + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/input-adapter-change.xml b/modules/distribution/src/core/conf/input-adapter-change.xml new file mode 100644 index 00000000..f716cd3e --- /dev/null +++ b/modules/distribution/src/core/conf/input-adapter-change.xml @@ -0,0 +1,33 @@ + + + + inputEventAdaptersConfig/adapterConfig[@type="jms"] + + 8 + 100 + 20000 + 10000 + 2 + 100 + https://${iot.keymanager.host}:${iot.keymanager.https.port} + admin + admin + https://${iot.gateway.host}:${iot.gateway.https.port}/token + https://${iot.gateway.host}:${iot.gateway.https.port} + 100 + + + + + 8 + 100 + 20000 + 10000 + 60 + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register + tcp://${mqtt.broker.host}:${mqtt.broker.port} + admin + admin +]]> + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/license-config.xml b/modules/distribution/src/core/conf/license-config.xml new file mode 100644 index 00000000..0310f314 --- /dev/null +++ b/modules/distribution/src/core/conf/license-config.xml @@ -0,0 +1,52 @@ + + + + + + + wso2 + android + 1.0.0 + en-us + 01-01-2014 + 31-12-2035 + + + + wso2 + ios + 1.0.0 + 1.0.0 + 01-01-2014 + 31-12-2035 + + + + wso2 + windows + 1.0.0 + 1.0.0 + 01-01-2014 + 31-12-2035 + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/log4j.properties b/modules/distribution/src/core/conf/log4j.properties new file mode 100644 index 00000000..a8a589ac --- /dev/null +++ b/modules/distribution/src/core/conf/log4j.properties @@ -0,0 +1,245 @@ +# +# Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +## +# This is the log4j configuration file used by WSO2 ESB +# ===================================================== +# +# IMPORTANT : Please do not remove or change the names of any of the Appenders defined here. +# The layout pattern & log file can be changed using the WSO2 ESB Management Console, and those +# settings will override the settings in this file. +## + +## +# WSO2 ESB is now able to create per-service trace logs at runtime. Thus while a message +# is being processed through a Proxy service or the Synapse service (i.e. message mediation through +# the 'main' sequence), tracing may be turned 'on' at any Proxy, Sequence or Mediator level. This +# trace state 'flows' with the message - i.e from a trace enabled sequence to another sequence etc. +# and applies to all mediators within a trace enabled sequence etc. unless another sequence or +# mediator does not override and specify a different trace setting. +## + +# the root category is ERROR (applies for all 3rd party JARs etc) and will be logged to the +# LOG_APPENDER and the CONSOLE_APPENDER + +log4j.rootLogger=ERROR, CARBON_CONSOLE, CARBON_LOGFILE, CARBON_MEMORY, CARBON_SYS_LOG, ERROR_LOGFILE +log4j.logger.AUDIT_LOG=INFO, AUDIT_LOGFILE + +log4j.category.org.apache.synapse=WARN +log4j.category.org.apache.synapse.transport=WARN +log4j.category.org.apache.axis2=WARN +log4j.category.org.apache.axis2.transport=WARN +log4j.logger.com.atomikos=INFO,ATOMIKOS +log4j.logger.org.quartz=WARN +log4j.logger.org.wso2=INFO +log4j.logger.org.wso2.carbon=INFO +#log4j.category.org.apache.synapse.transport.nhttp.util=DEBUG +#log4j.category.org.apache.http.impl.nio.reactor=DEBUG +#log4j.logger.org.wso2.carbon.utils.deployment.ComponentBuilder=DEBUG +#log4j.logger.org.wso2.carbon.utils.deployment.OSGiBundleDeployer=DEBUG +log4j.logger.org.apache.catalina=WARN +log4j.logger.org.apache.coyote=WARN +log4j.logger.org.apache.axis2.enterprise=FATAL +log4j.logger.de.hunsicker.jalopy.io=FATAL + +# uncomment the following logs to see HTTP headers and messages +#log4j.logger.org.apache.synapse.transport.http.headers=DEBUG +#log4j.logger.org.apache.synapse.transport.http.wire=DEBUG + +#only WARN allowed for access loggers in http transport by default +log4j.logger.org.apache.synapse.transport.http.access=WARN + +# uncomment the flowing entries to see HTTP headers and messages of Callout mediator/MessageProcessor +#log4j.logger.httpclient.wire.header=DEBUG +#log4j.logger.httpclient.wire.content=DEBUG + +# qpid related logs for the message broker +log4j.logger.qpid=WARN +log4j.logger.org.apache.qpid=WARN +log4j.logger.org.apache.qpid.server.Main=INFO +log4j.logger.qpid.message=WARN +log4j.logger.qpid.message.broker.listening=INFO + +#spark log components +log4j.logger.org.apache.spark=WARN +log4j.logger.org.spark-project=WARN +log4j.logger.akka=WARN +log4j.logger.org.apache.spark.util.ClosureCleaner=ERROR + +# The console appender is used to display general information at console +log4j.appender.CARBON_CONSOLE=org.wso2.carbon.utils.logging.appenders.CarbonConsoleAppender +log4j.appender.CARBON_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d{ISO8601}] [${logger.server.name}] %5p - %c{1} %m%n + +# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT +log4j.appender.LOGEVENT=org.wso2.carbon.logging.service.appender.LogEventAppender +log4j.appender.LOGEVENT.url=tcp://localhost:7611 +log4j.appender.LOGEVENT.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout +log4j.appender.LOGEVENT.columnList=%T,%S,%A,%d,%c,%p,%m,%I,%Stacktrace +log4j.appender.LOGEVENT.userName=admin +log4j.appender.LOGEVENT.password=admin +log4j.appender.LOGEVENT.processingLimit=1000 +log4j.appender.LOGEVENT.maxTolerableConsecutiveFailure=20 + +# Configure the service logger at INFO level. Writes only run-time/mediation-time audit messages +log4j.category.SERVICE_LOGGER=INFO, SERVICE_APPENDER +log4j.additivity.SERVICE_LOGGER=false +log4j.appender.SERVICE_APPENDER=org.apache.log4j.RollingFileAppender +log4j.appender.SERVICE_APPENDER.File=${carbon.home}/repository/logs/${instance.log}/wso2-esb-service${instance.log}.log +log4j.appender.SERVICE_APPENDER.MaxFileSize=1000KB +log4j.appender.SERVICE_APPENDER.MaxBackupIndex=10 +log4j.appender.SERVICE_APPENDER.layout=org.apache.log4j.PatternLayout +log4j.appender.SERVICE_APPENDER.layout.ConversionPattern=%d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n + +# The trace logger dumps enough information @INFO level, but maybe pushed upto TRACE. +# Writes only run-time/mediation time tracing/debug messages for messages passing through trace +# enabled sequences, mediators and services. Enabling tracing on these has a performance impact +log4j.category.TRACE_LOGGER=INFO, TRACE_APPENDER, TRACE_MEMORYAPPENDER +log4j.additivity.TRACE_LOGGER=false +log4j.appender.TRACE_APPENDER=org.apache.log4j.DailyRollingFileAppender +log4j.appender.TRACE_APPENDER.File=${carbon.home}/repository/logs/${instance.log}/wso2-esb-trace${instance.log}.log +log4j.appender.TRACE_APPENDER.Append=true +log4j.appender.TRACE_APPENDER.layout=org.apache.log4j.PatternLayout +log4j.appender.TRACE_APPENDER.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n + +# The memory appender for trace logger +log4j.appender.TRACE_MEMORYAPPENDER=org.wso2.carbon.utils.logging.appenders.MemoryAppender +log4j.appender.TRACE_MEMORYAPPENDER.bufferSize=2000 +log4j.appender.TRACE_MEMORYAPPENDER.layout=org.apache.log4j.PatternLayout +log4j.appender.TRACE_MEMORYAPPENDER.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %m%n + +# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout. +log4j.appender.CARBON_LOGFILE=org.wso2.carbon.utils.logging.appenders.CarbonDailyRollingFileAppender +# Log file will be overridden by the configuration setting in the DB +# This path should be relative to WSO2 Carbon Home +log4j.appender.CARBON_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon${instance.log}.log +log4j.appender.CARBON_LOGFILE.Append=true +log4j.appender.CARBON_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout +# ConversionPattern will be overridden by the configuration setting in the DB +log4j.appender.CARBON_LOGFILE.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m {%c}%n +log4j.appender.CARBON_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S] +log4j.appender.CARBON_LOGFILE.threshold=DEBUG + +# The standard error log where all the warnings, errors and fatal errors will be logged +log4j.appender.ERROR_LOGFILE=org.apache.log4j.FileAppender +log4j.appender.ERROR_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2-esb-errors.log +log4j.appender.ERROR_LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.ERROR_LOGFILE.layout.ConversionPattern=%d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n +log4j.appender.ERROR_LOGFILE.threshold=WARN + +# The memory appender for logging +log4j.appender.CARBON_MEMORY=org.wso2.carbon.logging.service.appender.CarbonMemoryAppender +log4j.appender.CARBON_MEMORY.bufferSize=2000 +log4j.appender.CARBON_MEMORY.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout +# ConversionPattern will be overridden by the configuration setting in the DB +log4j.appender.CARBON_MEMORY.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m {%c}%n +log4j.appender.CARBON_MEMORY.layout.TenantPattern=%U%@%D [%T] [%S] +log4j.appender.CARBON_MEMORY.columnList=%T,%S,%A,%d,%c,%p,%m,%H,%I,%Stacktrace +log4j.appender.CARBON_MEMORY.threshold=DEBUG + +log4j.appender.CARBON_SYS_LOG = org.apache.log4j.net.SyslogAppender +log4j.appender.CARBON_SYS_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.CARBON_SYS_LOG.layout.ConversionPattern=[%d] %5p - %x %m {%c}%n +log4j.appender.CARBON_SYS_LOG.SyslogHost=localhost +log4j.appender.CARBON_SYS_LOG.Facility=USER +log4j.appender.CARBON_SYS_LOG.threshold=DEBUG + +log4j.logger.org.apache.directory.shared.ldap=WARN, CARBON_CONSOLE +log4j.logger.org.apache.directory.server.ldap.handlers=WARN, CARBON_CONSOLE +log4j.logger.org.apache.directory.shared.ldap.entry.DefaultServerAttribute=FATAL, CARBON_CONSOLE +log4j.logger.org.apache.directory.shared.ldap.ldif.LdifReader=ERROR, CARBON_CONSOLE +log4j.logger.org.apache.directory.server.ldap.LdapProtocolHandler=ERROR, CARBON_CONSOLE + +## Trace Logger configuration which will append to a XMPP chatroom or JID ## +#log4j.appender.XMPP_APPENDER=org.wso2.carbon.utils.logging.IMAppender +#log4j.appender.XMPP_APPENDER.host=jabber.org +#log4j.appender.XMPP_APPENDER.username=wso2esb +#log4j.appender.XMPP_APPENDER.password=wso2esb +#log4j.appender.XMPP_APPENDER.recipient=ruwan@jabber.org +#log4j.appender.XMPP_APPENDER.layout=org.apache.log4j.PatternLayout +#log4j.appender.XMPP_APPENDER.layout.ConversionPattern=[%X{host}] [%t] %-5p [%d{HH:mm:ss,SSS}] %C{1} - %m%n + + +# Appender config to AUDIT_LOGFILE +log4j.appender.AUDIT_LOGFILE=org.apache.log4j.DailyRollingFileAppender +log4j.appender.AUDIT_LOGFILE.File=${carbon.home}/repository/logs/audit.log +log4j.appender.AUDIT_LOGFILE.Append=true +log4j.appender.AUDIT_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout +log4j.appender.AUDIT_LOGFILE.layout.ConversionPattern=[%d] %P%5p - %x %m %n +log4j.appender.AUDIT_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S] +log4j.appender.AUDIT_LOGFILE.threshold=INFO +log4j.additivity.AUDIT_LOG=false + + +# Appender config to send Atomikos transaction logs to new log file tm.out. +log4j.appender.ATOMIKOS = org.apache.log4j.RollingFileAppender +log4j.appender.ATOMIKOS.File = repository/logs/tm.out +log4j.appender.ATOMIKOS.Append = true +log4j.appender.ATOMIKOS.layout = org.apache.log4j.PatternLayout +log4j.appender.ATOMIKOS.layout.ConversionPattern=%p %t %c - %m%n +log4j.additivity.com.atomikos=false + + +#andes specific +log4j.logger.org.wso2.andes.server.handler.ConnectionStartOkMethodHandler=WARN +log4j.logger.org.wso2.andes.server.handler.ChannelOpenHandler=WARN +log4j.logger.org.wso2.andes.server.handler.ChannelCloseHandler=WARN +log4j.logger.org.wso2.andes.server.AMQChannel=WARN +log4j.logger.org.wso2.andes.server.handler.ConnectionCloseMethodHandler=WARN +log4j.logger.org.wso2.andes.server.handler.QueueDeclareHandler=WARN +log4j.logger.org.wso2.andes.server.handler.QueueBindHandler=WARN +log4j.logger.org.wso2.andes.server.virtualhost.VirtualHostConfigRecoveryHandler=WARN +log4j.logger.org.wso2.andes.amqp.QpidAndesBridge=WARN + +# moquette-log properties +log4j.logger.org.dna.mqtt=INFO +log4j.logger.org.dna.mqtt.moquette.messaging.spi.impl.ProtocolProcessor=INFO +log4j.logger.org.dna.mqtt.moquette.messaging.spi.impl.SimpleMessaging=WARN + +#Protocol parsing +log4j.logger.org.dna.mqtt.moquette.server.netty.NettyMQTTHandler=WARN +#log4j.logger.org.dna.mqtt.moquette.server.netty.NettyMQTTHandler=DEBUG +log4j.logger.org.dna.mqtt.moquette.parser.netty=WARN + +# The event trace logger dumps enough information @INFO level, but maybe pushed upto TRACE. +# Writes only run-time/event processing time tracing/debug messages for event passing through trace +# enabled transport adapters event formatters, builders and processors. Enabling event tracing on these has a performance impact +log4j.category.EVENT_TRACE_LOGGER=INFO, EVENT_TRACE_APPENDER, EVENT_TRACE_MEMORYAPPENDER +log4j.additivity.EVENT_TRACE_LOGGER=false +log4j.appender.EVENT_TRACE_APPENDER=org.apache.log4j.DailyRollingFileAppender +log4j.appender.EVENT_TRACE_APPENDER.File=${carbon.home}/repository/logs/${instance.log}/wso2-das-trace${instance.log}.log +log4j.appender.EVENT_TRACE_APPENDER.Append=true +log4j.appender.EVENT_TRACE_APPENDER.layout=org.apache.log4j.PatternLayout +log4j.appender.EVENT_TRACE_APPENDER.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n + +# The memory appender for trace logger +log4j.appender.EVENT_TRACE_MEMORYAPPENDER=org.wso2.carbon.utils.logging.appenders.MemoryAppender +log4j.appender.EVENT_TRACE_MEMORYAPPENDER.bufferSize=2000 +log4j.appender.EVENT_TRACE_MEMORYAPPENDER.layout=org.apache.log4j.PatternLayout +log4j.appender.EVENT_TRACE_MEMORYAPPENDER.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %m%n + +# Changing events specific info logs to warn +log4j.logger.org.wso2.carbon.application.deployer.internal.ApplicationManager=WARN +log4j.logger.org.wso2.carbon.event.stream.core.EventStreamDeployer=WARN +log4j.logger.org.wso2.carbon.event.input.adapter.core.internal.InputAdapterRuntime=WARN +log4j.logger.org.wso2.carbon.event.stream.core.internal.EventJunction=WARN +log4j.logger.org.wso2.carbon.event.receiver.core.EventReceiverDeployer=WARN +log4j.logger.org.wso2.carbon.analytics.spark.core.SparkScriptCAppDeployer=WARN +log4j.logger.org.wso2.carbon.analytics.eventsink.AnalyticsEventStoreDeployer=WARN +log4j.logger.org.wso2.carbon.event.processor.core.EventProcessorDeployer=WARN +log4j.logger.org.wso2.carbon.core.services.util.CarbonAuthenticationUtil=WARN +log4j.logger.net.sf.ehcache=ERROR +log4j.logger.org.wso2.carbon.apimgt.gateway.handlers.throttling=ERROR \ No newline at end of file diff --git a/modules/distribution/src/core/conf/nhttp.properties b/modules/distribution/src/core/conf/nhttp.properties new file mode 100644 index 00000000..56abe765 --- /dev/null +++ b/modules/distribution/src/core/conf/nhttp.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This file contains the configuration parameters used by the Non-blocking HTTP transport + +#http.socket.timeout=60000 +#http.socket.buffer-size=8192 +#http.tcp.nodelay=1 +#http.connection.stalecheck=0 + +# Uncomment the following property for an AIX based deployment +#http.nio.interest-ops-queueing=true + +# HTTP Sender thread pool parameters +#snd_t_core=20 +#snd_t_max=100 +#snd_alive_sec=5 +#snd_qlen=-1 +#snd_io_threads=2 + +# HTTP Listener thread pool parameters +#lst_t_core=20 +#lst_t_max=100 +#lst_alive_sec=5 +#lst_qlen=-1 +#lst_io_threads=2 +nhttp.rest.dispatcher.service=__MultitenantDispatcherService + +rest_uri_api_regex=\\w+://.+:\\d+/t/.*|\\w+://.+\\w+/t/.*|^(/t/).* +rest_uri_proxy_regex=\\w+://.+:\\d+/services/t/.*|\\w+://.+\\w+/services/t/.*|^(/services/t/) + +# This property is crucial for automated tests +http.socket.reuseaddr=true \ No newline at end of file diff --git a/modules/distribution/src/core/conf/output-adapter-change.xml b/modules/distribution/src/core/conf/output-adapter-change.xml new file mode 100644 index 00000000..6db841ef --- /dev/null +++ b/modules/distribution/src/core/conf/output-adapter-change.xml @@ -0,0 +1,41 @@ + + + + /outputEventAdaptersConfig/adapterConfig[@type="websocket"] + + + 8 + 100 + 20000 + 10000 + 60 + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register + https://${iot.gateway.host}:${iot.gateway.https.port}/token + tcp://${mqtt.broker.host}:${mqtt.broker.port} + admin + admin + + + + + 8 + 100 + 20000 + 10000 + + org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.OAuthAuthenticator + https://${iot.keymanager.host}:${iot.keymanager.https.port} + 2 + 100 + org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.DeviceAuthorizer + https://${iot.gateway.host}:${iot.gateway.https.port}/token + https://${iot.gateway.host}:${iot.gateway.https.port} + admin + admin + + /permission/admin/device-mgt/realtime_analytics + + 100 + ]]> + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/passthru-http.properties b/modules/distribution/src/core/conf/passthru-http.properties new file mode 100644 index 00000000..6645b8d1 --- /dev/null +++ b/modules/distribution/src/core/conf/passthru-http.properties @@ -0,0 +1,51 @@ +# +# Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +## This file contains the configuration parameters used by the Pass-through HTTP transport + +## Nhttp tuning parameters +#http.socket.timeout=60000 +#http.connection.timeout=0 +#http.socket.buffer-size=8192 +#http.socket.linger=-1 +#http.nio.select-interval=1000 +#http.tcp.nodelay=true +#http.connection.stalecheck=false +#http.socket.reuseaddr=false + +## Uncomment the following for AIX based deployments +#http.nio.interest-ops-queueing=true + +## Pass-through HTTP transport specific tuning parameters +worker_pool_size_core=400 +worker_pool_size_max=500 +#worker_thread_keepalive_sec=60 +#worker_pool_queue_length=-1 +#io_threads_per_reactor=2 +io_buffer_size=16384 +#http.max.connection.per.host.port=32767 + +## Other parameters +#http.user.agent.preserve=false +#http.server.preserve=true +#http.connection.disable.keepalive=false + +# URI configurations that determine if it requires custom rest dispatcher +rest_uri_api_regex=\\w+://.+:\\d+/t/.*|\\w+://.+\\w+/t/.*|^(/t/).* +rest_uri_proxy_regex=\\w+://.+:\\d+/services/t/.*|\\w+://.+\\w+/services/t/.*|^(/services/t/) + +# This property is crucial for automated tests +http.socket.reuseaddr=true \ No newline at end of file diff --git a/modules/distribution/src/core/conf/registry.xml b/modules/distribution/src/core/conf/registry.xml new file mode 100644 index 00000000..f49dbfc2 --- /dev/null +++ b/modules/distribution/src/core/conf/registry.xml @@ -0,0 +1,304 @@ + + + + + + + + + + wso2registry + false + true + / + + + + + jdbc/WSO2CarbonDB + + + + + + + + + + .* + + + + + + + + + + + application/vnd.wso2-service+xml + + + + + + + + + /_system/governance/event/topics/registry/notifications/.* + + + + + + + + + + + /trunk/policies/ + + + application/policy+xml + + + + + + + + true + + /trunk/schemas/ + + + application/x-xsd+xml + + + + + + + + + + + + + .* + + + + + + + .* + + + + + + + workflow-config + + + + + + + + + + + + + + + + + + + + 60 + 2 + + 50 + + 10 + + /_system/local/repository/components/org.wso2.carbon.registry/indexing/lastaccesstime + + + + + + + + + + + + + + + + + + + + + + + + + true + true + true + true + + /trunk/services/ + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.Carbon.properties b/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.Carbon.properties new file mode 100644 index 00000000..345a112a --- /dev/null +++ b/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.Carbon.properties @@ -0,0 +1,488 @@ +# The OWASP CSRFGuard Project, BSD License +# Eric Sheridan (eric@infraredsecurity.com), Copyright (c) 2011 +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of OWASP nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# From: https://github.com/esheri3/OWASP-CSRFGuard/blob/master/csrfguard-test/src/main/webapp/WEB-INF/csrfguard.properties + +# Common substitutions +# %servletContext% is the servlet context (e.g. the configured app prefix or war file name, or blank. +# e.g. if you deploy a default warfile as someApp.war, then %servletContext% will be /someApp +# if there isnt a context it will be the empty string. So to use this in the configuration, use e.g. %servletContext%/something.html +# which will translate to e.g. /someApp/something.html + +# Logger +# +# The logger property (org.owasp.csrfguard.Logger) defines the qualified class name of +# the object responsible for processing all log messages produced by CSRFGuard. The default +# CSRFGuard logger is org.owasp.csrfguard.log.ConsoleLogger. This class logs all messages +# to System.out which JavaEE application servers redirect to a vendor specific log file. +# Developers can customize the logging behavior of CSRFGuard by implementing the +# org.owasp.csrfguard.log.ILogger interface and setting the logger property to the new +# logger's qualified class name. The following configuration snippet instructs OWASP CSRFGuard +# to capture all log messages to the console: +# +# org.owasp.csrfguard.Logger=org.owasp.csrfguard.log.ConsoleLogger +org.owasp.csrfguard.Logger=org.owasp.csrfguard.log.JavaLogger + +# Which configuration provider factory you want to use. The default is org.owasp.csrfguard.config.PropertiesConfigurationProviderFactory +# Another configuration provider has more features including config overlays: org.owasp.csrfguard.config.overlay.ConfigurationOverlayProviderFactory +# The default configuration provider is: org.owasp.csrfguard.config.overlay.ConfigurationAutodetectProviderFactory +# which will look for an overlay file, it is there, and the factory inside that file is set it will use it, otherwise will be PropertiesConfigurationProviderFactory +# it needs to implement org.owasp.csrfguard.config.ConfigurationProviderFactory +org.owasp.csrfguard.configuration.provider.factory = org.owasp.csrfguard.config.overlay.ConfigurationAutodetectProviderFactory + + +# If csrfguard filter is enabled +org.owasp.csrfguard.Enabled = true + +# If csrf guard filter should check even if there is no session for the user +# Note: this changed around 2014/04, the default behavior used to be to +# not check if there is no session. If you want the legacy behavior (if your app +# is not susceptible to CSRF if the user has no session), set this to false +org.owasp.csrfguard.ValidateWhenNoSessionExists = false + +# New Token Landing Page +# +# The new token landing page property (org.owasp.csrfguard.NewTokenLandingPage) defines where +# to send a user if the token is being generated for the first time, and the use new token landing +# page boolean property (org.owasp.csrfguard.UseNewTokenLandingPage) determines if any redirect happens. +# UseNewTokenLandingPage defaults to false if NewTokenLandingPage is not specified, and to true +# if it is specified.. If UseNewTokenLandingPage is set true then this request is generated +# using auto-posting forms and will only contain the CSRF prevention token parameter, if +# applicable. All query-string or form parameters sent with the original request will be +# discarded. If this property is not defined, CSRFGuard will instead auto-post the user to the +# original context and servlet path. The following configuration snippet instructs OWASP CSRFGuard to +# redirect the user to %servletContext%/index.html when the user visits a protected resource +# without having a corresponding CSRF token present in the HttpSession object: +# +# org.owasp.csrfguard.NewTokenLandingPage=%servletContext%/index.html + + +# Protected Methods +# +# The protected methods property (org.owasp.csrfguard.ProtectedMethods) defines a comma +# separated list of HTTP request methods that should be protected by CSRFGuard. The default +# list is an empty list which will cause all HTTP methods to be protected, thus preserving +# legacy behavior. This setting allows the user to inform CSRFGuard that only requests of the +# given types should be considered for protection. All HTTP methods not in the list will be +# considered safe (i.e. view only / unable to modify data). This should be used only when the +# user has concrete knowledge that all requests made via methods not in the list +# are safe (i.e. do not apply an action to any data) since it can actually introduce new +# security vulnerabilities. For example: the user thinks that all actionable requests are +# only available by POST requests when in fact some are available via GET requests. If the +# user has excluded GET requests from the list then they have introduced a vulnerability. +# The following configuration snippet instructs OWASP CSRFGuard to protect only the POST, +# PUT, and DELETE HTTP methods. +# +# org.owasp.csrfguard.ProtectedMethods=POST,PUT,DELETE + +# or you can configure all to be protected, and specify which is unprotected. This is the preferred approach + +# WSO2 : Since state-changing operations are not performed via HTTP GET, +# disabling CSRF validation for GET method. +org.owasp.csrfguard.UnprotectedMethods=GET + +# Unique Per-Page Tokens +# +# The unique token per-page property (org.owasp.csrfguard.TokenPerPage) is a boolean value that +# determines if CSRFGuard should make use of unique per-page (i.e. URI) prevention tokens as +# opposed to unique per-session prevention tokens. When a user requests a protected resource, +# CSRFGuard will determine if a page specific token has been previously generated. If a page +# specific token has not yet been previously generated, CSRFGuard will verify the request was +# submitted with the per-session token intact. After verifying the presence of the per-session token, +# CSRFGuard will create a page specific token that is required for all subsequent requests to the +# associated resource. The per-session CSRF token can only be used when requesting a resource for +# the first time. All subsequent requests must have the per-page token intact or the request will +# be treated as a CSRF attack. This behavior can be changed with the org.owasp.csrfguard.TokenPerPagePrecreate +# property. Enabling this property will make CSRFGuard calculate the per page token prior to a first +# visit. This option only works with JSTL token injection and is useful for preserving the validity of +# links if the user pushes the back button. There may be a performance impact when enabling this option +# if the .jsp has a large number of proctected links that need tokens to be calculated. +# Use of the unique token per page property is currently experimental +# but provides a significant amount of improved security. Consider the exposure of a CSRF token using +# the legacy unique per-session model. Exposure of this token facilitates the attacker's ability to +# carry out a CSRF attack against the victim's active session for any resource exposed by the web +# application. Now consider the exposure of a CSRF token using the experimental unique token per-page +# model. Exposure of this token would only allow the attacker to carry out a CSRF attack against the +# victim's active session for a small subset of resources exposed by the web application. Use of the +# unique token per-page property is a strong defense in depth strategy significantly reducing the +# impact of exposed CSRF prevention tokens. The following configuration snippet instructs OWASP +# CSRFGuard to utilize the unique token per-page model: +# +# org.owasp.csrfguard.TokenPerPage=true +# org.owasp.csrfguard.TokenPerPagePrecreate=false + +# WSO2 : Considering overhead, necessity, as well as current unintended behaviour +# of library after blocking a CSRF attack, disabling per-page tokens. +org.owasp.csrfguard.TokenPerPage=false +org.owasp.csrfguard.TokenPerPagePrecreate=false + +# Token Rotation +# +# The rotate token property (org.owasp.csrfguard.Rotate) is a boolean value that determines if +# CSRFGuard should generate and utilize a new token after verifying the previous token. Rotation +# helps minimize the window of opportunity an attacker has to leverage the victim's stolen token +# in a targeted CSRF attack. However, this functionality generally causes navigation problems in +# most applications. Specifically, the 'Back' button in the browser will often cease to function +# properly. When a user hits the 'Back' button and interacts with the HTML, the browser may submit +# an old token causing CSRFGuard to incorrectly believe this request is a CSRF attack in progress +# (i.e. a 'false positive'). Users can prevent this scenario by preventing the caching of HTML pages +# containing FORM submissions using the cache-control header. However, this may also introduce +# performance problems as the browser will have to request HTML on a more frequent basis. The following +# configuration snippet enables token rotation: +# +# org.owasp.csrfguard.Rotate=true + +# Ajax and XMLHttpRequest Support +# +# The Ajax property (org.owasp.csrfguard.Ajax) is a boolean value that indicates whether or not OWASP +# CSRFGuard should support the injection and verification of unique per-session prevention tokens for +# XMLHttpRequests. To leverage Ajax support, the user must not only set this property to true but must +# also reference the JavaScript DOM Manipulation code using a script element. This dynamic script will +# override the send method of the XMLHttpRequest object to ensure the submission of an X-Requested-With +# header name value pair coupled with the submission of a custom header name value pair for each request. +# The name of the custom header is the value of the token name property and the value of the header is +# always the unique per-session token value. This custom header is analogous to the HTTP parameter name +# value pairs submitted via traditional GET and POST requests. If the X-Requested-With header was sent +# in the HTTP request, then CSRFGuard will look for the presence and ensure the validity of the unique +# per-session token in the custom header name value pair. Note that verification of these headers takes +# precedence over verification of the CSRF token supplied as an HTTP parameter. More specifically, +# CSRFGuard does not verify the presence of the CSRF token if the Ajax support property is enabled and +# the corresponding X-Requested-With and custom headers are embedded within the request. The following +# configuration snippet instructs OWASP CSRFGuard to support Ajax requests by verifying the presence and +# correctness of the X-Requested-With and custom headers: +# +# org.owasp.csrfguard.Ajax=true +org.owasp.csrfguard.Ajax=true + +# The default behavior of CSRFGuard is to protect all pages. Pages marked as unprotected will not be protected. +# If the Protect property is enabled, this behavior is reversed. Pages must be marked as protected to be protected. +# All other pages will not be protected. This is useful when the CsrfGuardFilter is aggressively mapped (ex: /*), +# but you only want to protect a few pages. +# +# org.owasp.csrfguard.Protect=true + +# Unprotected Pages: +# +# The unprotected pages property (org.owasp.csrfguard.unprotected.*) defines a series of pages that +# should not be protected by CSRFGuard. Such configurations are useful when the CsrfGuardFilter is +# aggressively mapped (ex: /*). The syntax of the property name is org.owasp.csrfguard.unprotected.[PageName], +# where PageName is some arbitrary identifier that can be used to reference a resource. The syntax of +# defining the uri of unprotected pages is the same as the syntax used by the JavaEE container for uri mapping. +# Specifically, CSRFGuard will identify the first match (if any) between the requested uri and an unprotected +# page in order of declaration. Match criteria is as follows: +# +# Case 1: exact match between request uri and unprotected page +# Case 2: longest path prefix match, beginning / and ending /* +# Case 3: extension match, beginning *. +# Case 4: if the value starts with ^ and ends with $, it will be evaulated as a regex. Note that before the +# regex is compiled, any common variables will be substituted (e.g. %servletContext%) +# Default: requested resource must be validated by CSRFGuard +# +# The following code snippet illustrates the four use cases over four examples. The first two examples +# (Tag and JavaScriptServlet) look for direct URI matches. The third example (Html) looks for all resources +# ending in a .html extension. The next example (Public) looks for all resources prefixed with the URI path /MySite/Public/*. +# The last example looks for resources that end in Public.do +# +# org.owasp.csrfguard.unprotected.Tag=%servletContext%/tag.jsp +# org.owasp.csrfguard.unprotected.JavaScriptServlet=%servletContext%/JavaScriptServlet +# org.owasp.csrfguard.unprotected.Html=*.html +# org.owasp.csrfguard.unprotected.Public=%servletContext%/Public/* +# regex example starts with ^ and ends with $, and the %servletContext% is evaluated before the regex +# org.owasp.csrfguard.unprotected.PublicServlet=^%servletContext%/.*Public\.do$ + +#org.owasp.csrfguard.unprotected.Default=%servletContext%/ +#org.owasp.csrfguard.unprotected.Upload=%servletContext%/upload.html +#org.owasp.csrfguard.unprotected.JavaScriptServlet=%servletContext%/JavaScriptServlet +#org.owasp.csrfguard.unprotected.Ajax=%servletContext%/ajax.html +#org.owasp.csrfguard.unprotected.Error=%servletContext%/error.html +#org.owasp.csrfguard.unprotected.Index=%servletContext%/index.html +#org.owasp.csrfguard.unprotected.JavaScript=%servletContext%/javascript.html +#org.owasp.csrfguard.unprotected.Tag=%servletContext%/tag.jsp +#org.owasp.csrfguard.unprotected.Redirect=%servletContext%/redirect.jsp +#org.owasp.csrfguard.unprotected.Forward=%servletContext%/forward.jsp +#org.owasp.csrfguard.unprotected.Session=%servletContext%/session.jsp + +# Actions: Responding to Attacks +# +# The actions directive (org.owasp.csrfguard.action.*) gives the user the ability to specify one or more +# actions that should be invoked when a CSRF attack is detected. Every action must implement the +# org.owasp.csrfguard.action.IAction interface either directly or indirectly through the +# org.owasp.csrfguard.action.AbstractAction helper class. Many actions accept parameters that can be specified +# along with the action class declaration. These parameters are consumed at runtime and impact the behavior of +# the associated action. +# +# The syntax for defining and configuring CSRFGuard actions is relatively straight forward. Let us assume we wish +# to redirect the user to a default page when a CSRF attack is detected. A redirect action already exists within +# the CSRFGuard bundle and is available via the class name org.owasp.csrfguard.actions.Redirect. In order to enable +# this action, we capture the following declaration in the Owasp.CsrfGuard.properties file: +# +# syntax: org.owasp.csrfguard.action.[actionName]=[className] +# example: org.owasp.csrfguard.action.class.Redirect=org.owasp.csrfguard.actions.Redirect +# +# The aforementioned directive declares an action called "Redirect" (i.e. [actionName]) referencing the Java class +# "org.owasp.csrfguard.actions.Redirect" (i.e. [className]). Anytime a CSRF attack is detected, the Redirect action +# will be executed. You may be asking yourself, "but how do I specify where the user is redirected?"; this is where +# action parameters come into play. In order to specify the redirect location, we capture the following declaration +# in the Owasp.CsrfGuard.properties file: +# +# syntax: org.owasp.csrfguard.action.[actionName].[parameterName]=[parameterValue] +# example: org.owasp.csrfguard.action.Redirect.ErrorPage=%servletContext%/error.html +# +# The aforementioned directive declares an action parameter called "ErrorPage" (i.e. [parameterName]) with the value +# of "%servletContext%/error.html" (i.e. [parameterValue]) for the action "Redirect" (i.e. [actionName]). The +# Redirect action expects the "ErrorPage" parameter to be defined and will redirect the user to this location when +# an attack is detected. +# +#org.owasp.csrfguard.action.Empty=org.owasp.csrfguard.action.Empty +org.owasp.csrfguard.action.Log=org.owasp.csrfguard.action.Log +org.owasp.csrfguard.action.Log.Message=potential cross-site request forgery (CSRF) attack thwarted (user:%user%, ip:%remote_ip%, method:%request_method%, uri:%request_uri%, error:%exception_message%) +#org.owasp.csrfguard.action.Invalidate=org.owasp.csrfguard.action.Invalidate + +# WSO2 : Disable redirecting user to an error page after blocking a CSRF attack +#org.owasp.csrfguard.action.Redirect=org.owasp.csrfguard.action.Redirect +#org.owasp.csrfguard.action.Redirect.Page=%servletContext%/error.html + +#org.owasp.csrfguard.action.RequestAttribute=org.owasp.csrfguard.action.RequestAttribute +#org.owasp.csrfguard.action.RequestAttribute.AttributeName=Owasp_CsrfGuard_Exception_Key + +# WSO2 : Disabling token rotation after blocking a CSRF attack, since this behaviour +# will break back navigation after blocking an attack. +#org.owasp.csrfguard.action.Rotate=org.owasp.csrfguard.action.Rotate + +#org.owasp.csrfguard.action.SessionAttribute=org.owasp.csrfguard.action.SessionAttribute +#org.owasp.csrfguard.action.SessionAttribute.AttributeName=Owasp_CsrfGuard_Exception_Key + +# WSO2 : Enable sending a 403 error after blocking a CSRF attack. Product teams +# can add error page that handles 403 or “org.owasp.csrfguard.action.Error” to +# display custom error pages. +org.owasp.csrfguard.action.Error=org.owasp.csrfguard.action.Error +org.owasp.csrfguard.action.Error.Code=403 +org.owasp.csrfguard.action.Error.Message=Security violation. + +# Token Name +# +# The token name property (org.owasp.csrfguard.TokenName) defines the name of the HTTP parameter +# to contain the value of the OWASP CSRFGuard token for each request. The following configuration +# snippet sets the CSRFGuard token parameter name to the value OWASP_CSRFTOKEN: +# +# org.owasp.csrfguard.TokenName=OWASP_CSRFTOKEN + +# WSO2 : Since, CSRFGuard will send relevant token name as HTTP header +# “X-” prefix was added to express that this is a non-standard header. +org.owasp.csrfguard.TokenName=X-CSRF-Token + +# Session Key +# +# The session key property (org.owasp.csrfguard.SessionKey) defines the string literal used to save +# and lookup the CSRFGuard token from the session. This value is used by the filter and the tag +# libraries to retrieve and set the token value in the session. Developers can use this key to +# programmatically lookup the token within their own code. The following configuration snippet sets +# the session key to the value OWASP_CSRFTOKEN: +# +# org.owasp.csrfguard.SessionKey=OWASP_CSRFTOKEN +org.owasp.csrfguard.SessionKey=OWASP_CSRFTOKEN + +# Token Length +# +# The token length property (org.owasp.csrfguard.TokenLength) defines the number of characters that +# should be found within the CSRFGuard token. Note that characters are delimited by dashes (-) in groups +# of four. For cosmetic reasons, users are encourage to ensure the token length is divisible by four. +# The following configuration snippet sets the token length property to 32 characters: +# +# org.owasp.csrfguard.TokenLength=32 +org.owasp.csrfguard.TokenLength=32 + +# Pseudo-random Number Generator +# +# The pseudo-random number generator property (org.owasp.csrfguard.PRNG) defines what PRNG should be used +# to generate the OWASP CSRFGuard token. Always ensure this value references a cryptographically strong +# pseudo-random number generator algorithm. The following configuration snippet sets the pseudo-random number +# generator to SHA1PRNG: +# +# org.owasp.csrfguard.PRNG=SHA1PRNG +org.owasp.csrfguard.PRNG=SHA1PRNG + +# Pseudo-random Number Generator Provider + +# The pseudo-random number generator provider property (org.owasp.csrfguard.PRNG.Provider) defines which +# provider's implementation of org.owasp.csrfguard.PRNG we should utilize. The following configuration +# snippet instructs the JVM to leverage SUN's implementation of the algorithm denoted by the +# org.owasp.csrfguard.PRNG property: + +# org.owasp.csrfguard.PRNG.Provider=SUN +# WSO2 - Pseudo-random number generator provider should be configured based on +# environment (SUN/IBMJCE) +org.owasp.csrfguard.PRNG.Provider=SUN + +# If not specifying the print config option in the web.xml, you can specify it here, to print the config +# on startup + +# WSO2 : Disable printing configuration during start-up +org.owasp.csrfguard.Config.Print = false + +########################### +## Javascript servlet settings if not set in web.xml +## https://www.owasp.org/index.php/CSRFGuard_3_Token_Injection +########################### + +# leave this blank and blank in web.xml and it will read from META-INF/csrfguard.js from the jarfile +# Denotes the location of the JavaScript template file that should be consumed and dynamically +# augmented by the JavaScriptServlet class. The default value is WEB-INF/Owasp.CsrfGuard.js. +# Use of this property and the existence of the specified template file is required. +org.owasp.csrfguard.JavascriptServlet.sourceFile = + +# Boolean value that determines whether or not the dynamic JavaScript code should be strict +# with regards to what links it should inject the CSRF prevention token. With a value of true, +# the JavaScript code will only place the token in links that point to the same exact domain +# from which the HTML originated. With a value of false, the JavaScript code will place the +# token in links that not only point to the same exact domain from which the HTML originated, +# but sub-domains as well. +org.owasp.csrfguard.JavascriptServlet.domainStrict = true + +# Allows the developer to specify the value of the Cache-Control header in the HTTP response +# when serving the dynamic JavaScript file. The default value is private, maxage=28800. +# Caching of the dynamic JavaScript file is intended to minimize traffic and improve performance. +# Note that the Cache-Control header is always set to "no-store" when either the "Rotate" +# "TokenPerPage" options is set to true in Owasp.CsrfGuard.properties. +org.owasp.csrfguard.JavascriptServlet.cacheControl = private, maxage=28800 + +# Allows the developer to specify a regular expression describing the required value of the +# Referer header. Any attempts to access the servlet with a Referer header that does not +# match the captured expression is discarded. Inclusion of referer header checking is to +# help minimize the risk of JavaScript Hijacking attacks that attempt to steal tokens from +# the dynamically generated JavaScript. While the primary defenses against JavaScript +# Hijacking attacks are implemented within the dynamic JavaScript itself, referer header +# checking is implemented to achieve defense in depth. +org.owasp.csrfguard.JavascriptServlet.refererPattern = .* + +# Similar to javascript servlet referer pattern, but this will make sure the referer of the +# javascript servlet matches the domain of the request. If there is no referer (proxy strips it?) +# then it will not fail. Generally this is a good idea to be true. +org.owasp.csrfguard.JavascriptServlet.refererMatchDomain = true + +# Boolean value that determines whether or not the dynamic JavaScript code should +# inject the CSRF prevention token as a hidden field into HTML forms. The default +# value is true. Developers are strongly discouraged from disabling this property +# as most server-side state changing actions are triggered via a POST request. +org.owasp.csrfguard.JavascriptServlet.injectIntoForms = true + +# if the token should be injected in GET forms (which will be on the URL) +# if the HTTP method GET is unprotected, then this should likely be false + +# WSO2 : Disable JavaScript from injecting token value to HTTP GET based forms. +# This prevents token leakage that could occur when sending token in URL. +# State-changing actions should not be performed over HTTP GET +org.owasp.csrfguard.JavascriptServlet.injectGetForms = false + +# if the token should be injected in the action in forms +# note, if injectIntoForms is true, then this might not need to be true + +# WSO2 : Disable JavaScript from injecting token value to form action. +# This prevents token leakage that could occur when sending token in URL. +org.owasp.csrfguard.JavascriptServlet.injectFormAttributes = false + + +# Boolean value that determines whether or not the dynamic JavaScript code should +# inject the CSRF prevention token in the query string of src and href attributes. +# Injecting the CSRF prevention token in a URL resource increases its general risk +# of exposure to unauthorized parties. However, most JavaEE web applications respond +# in the exact same manner to HTTP requests and their associated parameters regardless +# of the HTTP method. The risk associated with not protecting GET requests in this +# situation is perceived greater than the risk of exposing the token in protected GET +# requests. As a result, the default value of this attribute is set to true. Developers +# that are confident their server-side state changing controllers will only respond to +# POST requests (i.e. discarding GET requests) are strongly encouraged to disable this property. + +# WSO2 : Disable JavaScript from injecting token value to “src” and “href”. +# This prevents token leakage that could occur when sending token in URL. +org.owasp.csrfguard.JavascriptServlet.injectIntoAttributes = false + + +# WSO2 : Changing X-Request-With header text to avoid unnecessary information disclosure. +org.owasp.csrfguard.JavascriptServlet.xRequestedWith = WSO2 CSRF Protection + +########################### +## Config overlay settings if you have the provider above set to ConfigurationOverlayProvider +## This CSRF config provider uses Internet2 Configuration Overlays (documented on Internet2 wiki) +## By default the configuration is read from the Owasp.CsrfGuard.properties +## (which should not be edited), and the Owasp.CsrfGuard.overlay.properties overlays +## the base settings. See the Owasp.CsrfGuard.properties for the possible +## settings that can be applied to the Owasp.CsrfGuard.overlay.properties +########################### + +# comma separated config files that override each other (files on the right override the left) +# each should start with file: or classpath: +# e.g. classpath:Owasp.CsrfGuard.properties, file:c:/temp/myFile.properties +org.owasp.csrfguard.configOverlay.hierarchy = classpath:Owasp.CsrfGuard.properties, classpath:Owasp.CsrfGuard.overlay.properties + +# seconds between checking to see if the config files are updated +org.owasp.csrfguard.configOverlay.secondsBetweenUpdateChecks = 60 + + +########################### + + +# please remove the below entry to enable protection for services. +org.owasp.csrfguard.unprotected.oauth=%servletContext%/commonauth/* +org.owasp.csrfguard.unprotected.samlsso=%servletContext%/samlsso/* +org.owasp.csrfguard.unprotected.authenticationEndpoint=%servletContext%/authenticationendpoint/* +org.owasp.csrfguard.unprotected.wso2=%servletContext%/wso2/* +org.owasp.csrfguard.unprotected.oauth2=%servletContext%/oauth2/* +org.owasp.csrfguard.unprotected.openId=%servletContext%/openid/* +org.owasp.csrfguard.unprotected.openIdServer=%servletContext%/openidserver/* +org.owasp.csrfguard.unprotected.passivests=%servletContext%/passivests/* +org.owasp.csrfguard.unprotected.thrift=%servletContext%/thriftAuthenticator/* +org.owasp.csrfguard.unprotected.publisherRestApi=%servletContext%/api/appm/publisher/* +org.owasp.csrfguard.unprotected.storeRestApi=%servletContext%/api/appm/store/* +org.owasp.csrfguard.unprotected.certificateMgtRestApi=%servletContext%/api/certificate-mgt/* +org.owasp.csrfguard.unprotected.deviceMgtRestApi=%servletContext%/api/device-mgt/* +org.owasp.csrfguard.unprotected.dcrRestApi=%servletContext%/dynamic-client-web/* +org.owasp.csrfguard.unprotected.deviceMgtSSOAcs=%servletContext%/devicemgt/uuf/sso/acs +org.owasp.csrfguard.unprotected.deviceMgtAcs=%servletContext%/uuf/sso/acs +org.owasp.csrfguard.unprotected.deviceMgtApi=%servletContext%/devicemgt/api/* +org.owasp.csrfguard.unprotected.storeEventPublisher=%servletContext%/store/apis/eventpublish/* +org.owasp.csrfguard.unprotected.publisherAcs=%servletContext%/publisher/acs +org.owasp.csrfguard.unprotected.publisherApi=%servletContext%/publisher/api +org.owasp.csrfguard.unprotected.storeAcs=%servletContext%/store/acs +org.owasp.csrfguard.unprotected.apiStoreAcs=%servletContext%/api-store/acs +org.owasp.csrfguard.unprotected.apiStoreApis=%servletContext%/api-store/apis +org.owasp.csrfguard.unprotected.portalAcs=%servletContext%/portal/acs +org.owasp.csrfguard.unprotected.portalApis=%servletContext%/portal/apis/* +org.owasp.csrfguard.unprotected.socialAcs=%servletContext%/social/acs +org.owasp.csrfguard.unprotected.socialApis=%servletContext%/social/apis +org.owasp.csrfguard.unprotected.appStoreDevices=%servletContext%/store/apps/devices/* +org.owasp.csrfguard.unprotected.appStoreApis=%servletContext%/store/apis/* +org.owasp.csrfguard.unprotected.appPortalClient=%servletContext%/portal/apis/* + + +#carbon +org.owasp.csrfguard.unprotected.Services=%servletContext%/services/* + +#identity +org.owasp.csrfguard.unprotected.acs=%servletContext%/acs/* +org.owasp.csrfguard.unprotected.iwa=%servletContext%/iwa/* +org.owasp.csrfguard.unprotected.oauthiwa=%servletContext%/commonauth/iwa/* diff --git a/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.dashboard.properties b/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.dashboard.properties new file mode 100644 index 00000000..88257953 --- /dev/null +++ b/modules/distribution/src/core/conf/security/Owasp.CsrfGuard.dashboard.properties @@ -0,0 +1,446 @@ +# The OWASP CSRFGuard Project, BSD License +# Eric Sheridan (eric@infraredsecurity.com), Copyright (c) 2011 +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of OWASP nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# From: https://github.com/esheri3/OWASP-CSRFGuard/blob/master/csrfguard-test/src/main/webapp/WEB-INF/csrfguard.properties + +# Common substitutions +# %servletContext% is the servlet context (e.g. the configured app prefix or war file name, or blank. +# e.g. if you deploy a default warfile as someApp.war, then %servletContext% will be /someApp +# if there isnt a context it will be the empty string. So to use this in the configuration, use e.g. %servletContext%/something.html +# which will translate to e.g. /someApp/something.html + +# Logger +# +# The logger property (org.owasp.csrfguard.Logger) defines the qualified class name of +# the object responsible for processing all log messages produced by CSRFGuard. The default +# CSRFGuard logger is org.owasp.csrfguard.log.ConsoleLogger. This class logs all messages +# to System.out which JavaEE application servers redirect to a vendor specific log file. +# Developers can customize the logging behavior of CSRFGuard by implementing the +# org.owasp.csrfguard.log.ILogger interface and setting the logger property to the new +# logger's qualified class name. The following configuration snippet instructs OWASP CSRFGuard +# to capture all log messages to the console: +# +# org.owasp.csrfguard.Logger=org.owasp.csrfguard.log.ConsoleLogger +org.owasp.csrfguard.Logger=org.owasp.csrfguard.log.JavaLogger + +# Which configuration provider factory you want to use. The default is org.owasp.csrfguard.config.PropertiesConfigurationProviderFactory +# Another configuration provider has more features including config overlays: org.owasp.csrfguard.config.overlay.ConfigurationOverlayProviderFactory +# The default configuration provider is: org.owasp.csrfguard.config.overlay.ConfigurationAutodetectProviderFactory +# which will look for an overlay file, it is there, and the factory inside that file is set it will use it, otherwise will be PropertiesConfigurationProviderFactory +# it needs to implement org.owasp.csrfguard.config.ConfigurationProviderFactory +org.owasp.csrfguard.configuration.provider.factory = org.owasp.csrfguard.config.overlay.ConfigurationAutodetectProviderFactory + + +# If csrfguard filter is enabled +org.owasp.csrfguard.Enabled = true + +# If csrf guard filter should check even if there is no session for the user +# Note: this changed around 2014/04, the default behavior used to be to +# not check if there is no session. If you want the legacy behavior (if your app +# is not susceptible to CSRF if the user has no session), set this to false +org.owasp.csrfguard.ValidateWhenNoSessionExists = false + +# New Token Landing Page +# +# The new token landing page property (org.owasp.csrfguard.NewTokenLandingPage) defines where +# to send a user if the token is being generated for the first time, and the use new token landing +# page boolean property (org.owasp.csrfguard.UseNewTokenLandingPage) determines if any redirect happens. +# UseNewTokenLandingPage defaults to false if NewTokenLandingPage is not specified, and to true +# if it is specified.. If UseNewTokenLandingPage is set true then this request is generated +# using auto-posting forms and will only contain the CSRF prevention token parameter, if +# applicable. All query-string or form parameters sent with the original request will be +# discarded. If this property is not defined, CSRFGuard will instead auto-post the user to the +# original context and servlet path. The following configuration snippet instructs OWASP CSRFGuard to +# redirect the user to %servletContext%/index.html when the user visits a protected resource +# without having a corresponding CSRF token present in the HttpSession object: +# +# org.owasp.csrfguard.NewTokenLandingPage=%servletContext%/index.html + + +# Protected Methods +# +# The protected methods property (org.owasp.csrfguard.ProtectedMethods) defines a comma +# separated list of HTTP request methods that should be protected by CSRFGuard. The default +# list is an empty list which will cause all HTTP methods to be protected, thus preserving +# legacy behavior. This setting allows the user to inform CSRFGuard that only requests of the +# given types should be considered for protection. All HTTP methods not in the list will be +# considered safe (i.e. view only / unable to modify data). This should be used only when the +# user has concrete knowledge that all requests made via methods not in the list +# are safe (i.e. do not apply an action to any data) since it can actually introduce new +# security vulnerabilities. For example: the user thinks that all actionable requests are +# only available by POST requests when in fact some are available via GET requests. If the +# user has excluded GET requests from the list then they have introduced a vulnerability. +# The following configuration snippet instructs OWASP CSRFGuard to protect only the POST, +# PUT, and DELETE HTTP methods. +# +# org.owasp.csrfguard.ProtectedMethods=POST,PUT,DELETE + +# or you can configure all to be protected, and specify which is unprotected. This is the preferred approach + +# WSO2 : Since state-changing operations are not performed via HTTP GET, +# disabling CSRF validation for GET method. +org.owasp.csrfguard.UnprotectedMethods=GET + +# Unique Per-Page Tokens +# +# The unique token per-page property (org.owasp.csrfguard.TokenPerPage) is a boolean value that +# determines if CSRFGuard should make use of unique per-page (i.e. URI) prevention tokens as +# opposed to unique per-session prevention tokens. When a user requests a protected resource, +# CSRFGuard will determine if a page specific token has been previously generated. If a page +# specific token has not yet been previously generated, CSRFGuard will verify the request was +# submitted with the per-session token intact. After verifying the presence of the per-session token, +# CSRFGuard will create a page specific token that is required for all subsequent requests to the +# associated resource. The per-session CSRF token can only be used when requesting a resource for +# the first time. All subsequent requests must have the per-page token intact or the request will +# be treated as a CSRF attack. This behavior can be changed with the org.owasp.csrfguard.TokenPerPagePrecreate +# property. Enabling this property will make CSRFGuard calculate the per page token prior to a first +# visit. This option only works with JSTL token injection and is useful for preserving the validity of +# links if the user pushes the back button. There may be a performance impact when enabling this option +# if the .jsp has a large number of proctected links that need tokens to be calculated. +# Use of the unique token per page property is currently experimental +# but provides a significant amount of improved security. Consider the exposure of a CSRF token using +# the legacy unique per-session model. Exposure of this token facilitates the attacker's ability to +# carry out a CSRF attack against the victim's active session for any resource exposed by the web +# application. Now consider the exposure of a CSRF token using the experimental unique token per-page +# model. Exposure of this token would only allow the attacker to carry out a CSRF attack against the +# victim's active session for a small subset of resources exposed by the web application. Use of the +# unique token per-page property is a strong defense in depth strategy significantly reducing the +# impact of exposed CSRF prevention tokens. The following configuration snippet instructs OWASP +# CSRFGuard to utilize the unique token per-page model: +# +# org.owasp.csrfguard.TokenPerPage=true +# org.owasp.csrfguard.TokenPerPagePrecreate=false + +# WSO2 : Considering overhead, necessity, as well as current unintended behaviour +# of library after blocking a CSRF attack, disabling per-page tokens. +org.owasp.csrfguard.TokenPerPage=false +org.owasp.csrfguard.TokenPerPagePrecreate=false + +# Token Rotation +# +# The rotate token property (org.owasp.csrfguard.Rotate) is a boolean value that determines if +# CSRFGuard should generate and utilize a new token after verifying the previous token. Rotation +# helps minimize the window of opportunity an attacker has to leverage the victim's stolen token +# in a targeted CSRF attack. However, this functionality generally causes navigation problems in +# most applications. Specifically, the 'Back' button in the browser will often cease to function +# properly. When a user hits the 'Back' button and interacts with the HTML, the browser may submit +# an old token causing CSRFGuard to incorrectly believe this request is a CSRF attack in progress +# (i.e. a 'false positive'). Users can prevent this scenario by preventing the caching of HTML pages +# containing FORM submissions using the cache-control header. However, this may also introduce +# performance problems as the browser will have to request HTML on a more frequent basis. The following +# configuration snippet enables token rotation: +# +# org.owasp.csrfguard.Rotate=true + +# Ajax and XMLHttpRequest Support +# +# The Ajax property (org.owasp.csrfguard.Ajax) is a boolean value that indicates whether or not OWASP +# CSRFGuard should support the injection and verification of unique per-session prevention tokens for +# XMLHttpRequests. To leverage Ajax support, the user must not only set this property to true but must +# also reference the JavaScript DOM Manipulation code using a script element. This dynamic script will +# override the send method of the XMLHttpRequest object to ensure the submission of an X-Requested-With +# header name value pair coupled with the submission of a custom header name value pair for each request. +# The name of the custom header is the value of the token name property and the value of the header is +# always the unique per-session token value. This custom header is analogous to the HTTP parameter name +# value pairs submitted via traditional GET and POST requests. If the X-Requested-With header was sent +# in the HTTP request, then CSRFGuard will look for the presence and ensure the validity of the unique +# per-session token in the custom header name value pair. Note that verification of these headers takes +# precedence over verification of the CSRF token supplied as an HTTP parameter. More specifically, +# CSRFGuard does not verify the presence of the CSRF token if the Ajax support property is enabled and +# the corresponding X-Requested-With and custom headers are embedded within the request. The following +# configuration snippet instructs OWASP CSRFGuard to support Ajax requests by verifying the presence and +# correctness of the X-Requested-With and custom headers: +# +# org.owasp.csrfguard.Ajax=true +org.owasp.csrfguard.Ajax=true + +# The default behavior of CSRFGuard is to protect all pages. Pages marked as unprotected will not be protected. +# If the Protect property is enabled, this behavior is reversed. Pages must be marked as protected to be protected. +# All other pages will not be protected. This is useful when the CsrfGuardFilter is aggressively mapped (ex: /*), +# but you only want to protect a few pages. +# +# org.owasp.csrfguard.Protect=true + +# Unprotected Pages: +# +# The unprotected pages property (org.owasp.csrfguard.unprotected.*) defines a series of pages that +# should not be protected by CSRFGuard. Such configurations are useful when the CsrfGuardFilter is +# aggressively mapped (ex: /*). The syntax of the property name is org.owasp.csrfguard.unprotected.[PageName], +# where PageName is some arbitrary identifier that can be used to reference a resource. The syntax of +# defining the uri of unprotected pages is the same as the syntax used by the JavaEE container for uri mapping. +# Specifically, CSRFGuard will identify the first match (if any) between the requested uri and an unprotected +# page in order of declaration. Match criteria is as follows: +# +# Case 1: exact match between request uri and unprotected page +# Case 2: longest path prefix match, beginning / and ending /* +# Case 3: extension match, beginning *. +# Case 4: if the value starts with ^ and ends with $, it will be evaulated as a regex. Note that before the +# regex is compiled, any common variables will be substituted (e.g. %servletContext%) +# Default: requested resource must be validated by CSRFGuard +# +# The following code snippet illustrates the four use cases over four examples. The first two examples +# (Tag and JavaScriptServlet) look for direct URI matches. The third example (Html) looks for all resources +# ending in a .html extension. The next example (Public) looks for all resources prefixed with the URI path /MySite/Public/*. +# The last example looks for resources that end in Public.do +# +# org.owasp.csrfguard.unprotected.Tag=%servletContext%/tag.jsp +# org.owasp.csrfguard.unprotected.JavaScriptServlet=%servletContext%/JavaScriptServlet +# org.owasp.csrfguard.unprotected.Html=*.html +# org.owasp.csrfguard.unprotected.Public=%servletContext%/Public/* +# regex example starts with ^ and ends with $, and the %servletContext% is evaluated before the regex +# org.owasp.csrfguard.unprotected.PublicServlet=^%servletContext%/.*Public\.do$ + +#org.owasp.csrfguard.unprotected.Default=%servletContext%/ +#org.owasp.csrfguard.unprotected.Upload=%servletContext%/upload.html +#org.owasp.csrfguard.unprotected.JavaScriptServlet=%servletContext%/JavaScriptServlet +#org.owasp.csrfguard.unprotected.Ajax=%servletContext%/ajax.html +#org.owasp.csrfguard.unprotected.Error=%servletContext%/error.html +#org.owasp.csrfguard.unprotected.Index=%servletContext%/index.html +#org.owasp.csrfguard.unprotected.JavaScript=%servletContext%/javascript.html +#org.owasp.csrfguard.unprotected.Tag=%servletContext%/tag.jsp +#org.owasp.csrfguard.unprotected.Redirect=%servletContext%/redirect.jsp +#org.owasp.csrfguard.unprotected.Forward=%servletContext%/forward.jsp +#org.owasp.csrfguard.unprotected.Session=%servletContext%/session.jsp + +# Actions: Responding to Attacks +# +# The actions directive (org.owasp.csrfguard.action.*) gives the user the ability to specify one or more +# actions that should be invoked when a CSRF attack is detected. Every action must implement the +# org.owasp.csrfguard.action.IAction interface either directly or indirectly through the +# org.owasp.csrfguard.action.AbstractAction helper class. Many actions accept parameters that can be specified +# along with the action class declaration. These parameters are consumed at runtime and impact the behavior of +# the associated action. +# +# The syntax for defining and configuring CSRFGuard actions is relatively straight forward. Let us assume we wish +# to redirect the user to a default page when a CSRF attack is detected. A redirect action already exists within +# the CSRFGuard bundle and is available via the class name org.owasp.csrfguard.actions.Redirect. In order to enable +# this action, we capture the following declaration in the Owasp.CsrfGuard.properties file: +# +# syntax: org.owasp.csrfguard.action.[actionName]=[className] +# example: org.owasp.csrfguard.action.class.Redirect=org.owasp.csrfguard.actions.Redirect +# +# The aforementioned directive declares an action called "Redirect" (i.e. [actionName]) referencing the Java class +# "org.owasp.csrfguard.actions.Redirect" (i.e. [className]). Anytime a CSRF attack is detected, the Redirect action +# will be executed. You may be asking yourself, "but how do I specify where the user is redirected?"; this is where +# action parameters come into play. In order to specify the redirect location, we capture the following declaration +# in the Owasp.CsrfGuard.properties file: +# +# syntax: org.owasp.csrfguard.action.[actionName].[parameterName]=[parameterValue] +# example: org.owasp.csrfguard.action.Redirect.ErrorPage=%servletContext%/error.html +# +# The aforementioned directive declares an action parameter called "ErrorPage" (i.e. [parameterName]) with the value +# of "%servletContext%/error.html" (i.e. [parameterValue]) for the action "Redirect" (i.e. [actionName]). The +# Redirect action expects the "ErrorPage" parameter to be defined and will redirect the user to this location when +# an attack is detected. +# +#org.owasp.csrfguard.action.Empty=org.owasp.csrfguard.action.Empty +org.owasp.csrfguard.action.Log=org.owasp.csrfguard.action.Log +org.owasp.csrfguard.action.Log.Message=potential cross-site request forgery (CSRF) attack thwarted (user:%user%, ip:%remote_ip%, method:%request_method%, uri:%request_uri%, error:%exception_message%) +#org.owasp.csrfguard.action.Invalidate=org.owasp.csrfguard.action.Invalidate + +# WSO2 : Disable redirecting user to an error page after blocking a CSRF attack +#org.owasp.csrfguard.action.Redirect=org.owasp.csrfguard.action.Redirect +#org.owasp.csrfguard.action.Redirect.Page=%servletContext%/error.html + +#org.owasp.csrfguard.action.RequestAttribute=org.owasp.csrfguard.action.RequestAttribute +#org.owasp.csrfguard.action.RequestAttribute.AttributeName=Owasp_CsrfGuard_Exception_Key + +# WSO2 : Disabling token rotation after blocking a CSRF attack, since this behaviour +# will break back navigation after blocking an attack. +#org.owasp.csrfguard.action.Rotate=org.owasp.csrfguard.action.Rotate + +#org.owasp.csrfguard.action.SessionAttribute=org.owasp.csrfguard.action.SessionAttribute +#org.owasp.csrfguard.action.SessionAttribute.AttributeName=Owasp_CsrfGuard_Exception_Key + +# WSO2 : Enable sending a 403 error after blocking a CSRF attack. Product teams +# can add error page that handles 403 or “org.owasp.csrfguard.action.Error” to +# display custom error pages. +org.owasp.csrfguard.action.Error=org.owasp.csrfguard.action.Error +org.owasp.csrfguard.action.Error.Code=403 +org.owasp.csrfguard.action.Error.Message=Security violation. + +# Token Name +# +# The token name property (org.owasp.csrfguard.TokenName) defines the name of the HTTP parameter +# to contain the value of the OWASP CSRFGuard token for each request. The following configuration +# snippet sets the CSRFGuard token parameter name to the value OWASP_CSRFTOKEN: +# +# org.owasp.csrfguard.TokenName=OWASP_CSRFTOKEN + +# WSO2 : Since, CSRFGuard will send relevant token name as HTTP header +# “X-” prefix was added to express that this is a non-standard header. +org.owasp.csrfguard.TokenName=X-CSRF-Token + +# Session Key +# +# The session key property (org.owasp.csrfguard.SessionKey) defines the string literal used to save +# and lookup the CSRFGuard token from the session. This value is used by the filter and the tag +# libraries to retrieve and set the token value in the session. Developers can use this key to +# programmatically lookup the token within their own code. The following configuration snippet sets +# the session key to the value OWASP_CSRFTOKEN: +# +# org.owasp.csrfguard.SessionKey=OWASP_CSRFTOKEN +org.owasp.csrfguard.SessionKey=OWASP_CSRFTOKEN + +# Token Length +# +# The token length property (org.owasp.csrfguard.TokenLength) defines the number of characters that +# should be found within the CSRFGuard token. Note that characters are delimited by dashes (-) in groups +# of four. For cosmetic reasons, users are encourage to ensure the token length is divisible by four. +# The following configuration snippet sets the token length property to 32 characters: +# +# org.owasp.csrfguard.TokenLength=32 +org.owasp.csrfguard.TokenLength=32 + +# Pseudo-random Number Generator +# +# The pseudo-random number generator property (org.owasp.csrfguard.PRNG) defines what PRNG should be used +# to generate the OWASP CSRFGuard token. Always ensure this value references a cryptographically strong +# pseudo-random number generator algorithm. The following configuration snippet sets the pseudo-random number +# generator to SHA1PRNG: +# +# org.owasp.csrfguard.PRNG=SHA1PRNG +org.owasp.csrfguard.PRNG=SHA1PRNG + +# Pseudo-random Number Generator Provider + +# The pseudo-random number generator provider property (org.owasp.csrfguard.PRNG.Provider) defines which +# provider's implementation of org.owasp.csrfguard.PRNG we should utilize. The following configuration +# snippet instructs the JVM to leverage SUN's implementation of the algorithm denoted by the +# org.owasp.csrfguard.PRNG property: + +# org.owasp.csrfguard.PRNG.Provider=SUN +# WSO2 - Pseudo-random number generator provider should be configured based on +# environment (SUN/IBMJCE) +org.owasp.csrfguard.PRNG.Provider=SUN + +# If not specifying the print config option in the web.xml, you can specify it here, to print the config +# on startup + +# WSO2 : Disable printing configuration during start-up +org.owasp.csrfguard.Config.Print = false + +########################### +## Javascript servlet settings if not set in web.xml +## https://www.owasp.org/index.php/CSRFGuard_3_Token_Injection +########################### + +# leave this blank and blank in web.xml and it will read from META-INF/csrfguard.js from the jarfile +# Denotes the location of the JavaScript template file that should be consumed and dynamically +# augmented by the JavaScriptServlet class. The default value is WEB-INF/Owasp.CsrfGuard.js. +# Use of this property and the existence of the specified template file is required. +org.owasp.csrfguard.JavascriptServlet.sourceFile = + +# Boolean value that determines whether or not the dynamic JavaScript code should be strict +# with regards to what links it should inject the CSRF prevention token. With a value of true, +# the JavaScript code will only place the token in links that point to the same exact domain +# from which the HTML originated. With a value of false, the JavaScript code will place the +# token in links that not only point to the same exact domain from which the HTML originated, +# but sub-domains as well. +org.owasp.csrfguard.JavascriptServlet.domainStrict = true + +# Allows the developer to specify the value of the Cache-Control header in the HTTP response +# when serving the dynamic JavaScript file. The default value is private, maxage=28800. +# Caching of the dynamic JavaScript file is intended to minimize traffic and improve performance. +# Note that the Cache-Control header is always set to "no-store" when either the "Rotate" +# "TokenPerPage" options is set to true in Owasp.CsrfGuard.properties. +org.owasp.csrfguard.JavascriptServlet.cacheControl = private, maxage=28800 + +# Allows the developer to specify a regular expression describing the required value of the +# Referer header. Any attempts to access the servlet with a Referer header that does not +# match the captured expression is discarded. Inclusion of referer header checking is to +# help minimize the risk of JavaScript Hijacking attacks that attempt to steal tokens from +# the dynamically generated JavaScript. While the primary defenses against JavaScript +# Hijacking attacks are implemented within the dynamic JavaScript itself, referer header +# checking is implemented to achieve defense in depth. +org.owasp.csrfguard.JavascriptServlet.refererPattern = .* + +# Similar to javascript servlet referer pattern, but this will make sure the referer of the +# javascript servlet matches the domain of the request. If there is no referer (proxy strips it?) +# then it will not fail. Generally this is a good idea to be true. +org.owasp.csrfguard.JavascriptServlet.refererMatchDomain = true + +# Boolean value that determines whether or not the dynamic JavaScript code should +# inject the CSRF prevention token as a hidden field into HTML forms. The default +# value is true. Developers are strongly discouraged from disabling this property +# as most server-side state changing actions are triggered via a POST request. +org.owasp.csrfguard.JavascriptServlet.injectIntoForms = true + +# if the token should be injected in GET forms (which will be on the URL) +# if the HTTP method GET is unprotected, then this should likely be false + +# WSO2 : Disable JavaScript from injecting token value to HTTP GET based forms. +# This prevents token leakage that could occur when sending token in URL. +# State-changing actions should not be performed over HTTP GET +org.owasp.csrfguard.JavascriptServlet.injectGetForms = false + +# if the token should be injected in the action in forms +# note, if injectIntoForms is true, then this might not need to be true + +# WSO2 : Disable JavaScript from injecting token value to form action. +# This prevents token leakage that could occur when sending token in URL. +org.owasp.csrfguard.JavascriptServlet.injectFormAttributes = false + + +# Boolean value that determines whether or not the dynamic JavaScript code should +# inject the CSRF prevention token in the query string of src and href attributes. +# Injecting the CSRF prevention token in a URL resource increases its general risk +# of exposure to unauthorized parties. However, most JavaEE web applications respond +# in the exact same manner to HTTP requests and their associated parameters regardless +# of the HTTP method. The risk associated with not protecting GET requests in this +# situation is perceived greater than the risk of exposing the token in protected GET +# requests. As a result, the default value of this attribute is set to true. Developers +# that are confident their server-side state changing controllers will only respond to +# POST requests (i.e. discarding GET requests) are strongly encouraged to disable this property. + +# WSO2 : Disable JavaScript from injecting token value to “src” and “href”. +# This prevents token leakage that could occur when sending token in URL. +org.owasp.csrfguard.JavascriptServlet.injectIntoAttributes = false + + +# WSO2 : Changing X-Request-With header text to avoid unnecessary information disclosure. +org.owasp.csrfguard.JavascriptServlet.xRequestedWith = WSO2 CSRF Protection + +########################### +## Config overlay settings if you have the provider above set to ConfigurationOverlayProvider +## This CSRF config provider uses Internet2 Configuration Overlays (documented on Internet2 wiki) +## By default the configuration is read from the Owasp.CsrfGuard.properties +## (which should not be edited), and the Owasp.CsrfGuard.overlay.properties overlays +## the base settings. See the Owasp.CsrfGuard.properties for the possible +## settings that can be applied to the Owasp.CsrfGuard.overlay.properties +########################### + +# comma separated config files that override each other (files on the right override the left) +# each should start with file: or classpath: +# e.g. classpath:Owasp.CsrfGuard.properties, file:c:/temp/myFile.properties +org.owasp.csrfguard.configOverlay.hierarchy = classpath:Owasp.CsrfGuard.properties, classpath:Owasp.CsrfGuard.overlay.properties + +# seconds between checking to see if the config files are updated +org.owasp.csrfguard.configOverlay.secondsBetweenUpdateChecks = 60 + + +########################## \ No newline at end of file diff --git a/modules/distribution/src/core/conf/security/authenticators.xml b/modules/distribution/src/core/conf/security/authenticators.xml new file mode 100644 index 00000000..4b8e8fb8 --- /dev/null +++ b/modules/distribution/src/core/conf/security/authenticators.xml @@ -0,0 +1,77 @@ + + + + + + + + + + 5 + + + 10 + + false + https://localhost:9443 + admin + admin + + + + + + 5 + + + + + + + + 10 + + /carbon/admin/login.jsp + carbonServer + https://localhost:9443/samlsso + urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/synapse-handlers.xml b/modules/distribution/src/core/conf/synapse-handlers.xml new file mode 100644 index 00000000..b1291943 --- /dev/null +++ b/modules/distribution/src/core/conf/synapse-handlers.xml @@ -0,0 +1,20 @@ + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/conf/synapse.properties b/modules/distribution/src/core/conf/synapse.properties new file mode 100755 index 00000000..dc3fd2d1 --- /dev/null +++ b/modules/distribution/src/core/conf/synapse.properties @@ -0,0 +1,54 @@ +# +# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +# +# WSO2 Inc. licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +#synapse.threads.core = 20 +#synapse.threads.max = 100 +#synapse.threads.keepalive = 5 +#synapse.threads.qlen = 10 +#synapse.threads.group = synapse-thread-group +#synapse.threads.idprefix = SynapseWorker + +#inbound.threads.core = 20 +#inbound.threads.max = 100 + +synapse.sal.endpoints.sesssion.timeout.default=600000 +synapse.global_timeout_interval=120000 +#In memory statistics cleaning state +statistics.clean.enable=true +statistics.clean.interval=1000 + +# Dependency tracking Synapse observer +# Comment out to disable dependency management +synapse.observers=org.wso2.carbon.mediation.dependency.mgt.DependencyTracker + +#preserve namespace when converting XML to JSON +synapse.commons.json.preserve.namespace=false + +# User defined wsdlLocator/Schema Resolver Implementations. +# synapse.wsdl.resolver=org.wso2.carbon.mediation.initializer.RegistryWSDLLocator +# synapse.schema.resolver=org.wso2.carbon.mediation.initializer.RegistryXmlSchemaURIResolver + +# Uncomment following to support fallback XPATH 2.0 support with DOM and Saxon +#synapse.xpath.dom.failover.enabled=true +synapse.temp_data.chunk.size=3072 + +# A configurator to add tenant information to the out thread local carbon context +synapse.carbon.ext.tenant.info=org.wso2.carbon.mediation.initializer.handler.CarbonTenantInfoConfigurator + +#external componenent registration for secure vault xpath funtion lookup +synapse.xpath.func.extensions=org.wso2.carbon.mediation.security.vault.xpath.SecureVaultLookupXPathFunctionProvider diff --git a/modules/distribution/src/core/conf/tomcat/carbon/WEB-INF/web.xml b/modules/distribution/src/core/conf/tomcat/carbon/WEB-INF/web.xml new file mode 100755 index 00000000..fffa6b5c --- /dev/null +++ b/modules/distribution/src/core/conf/tomcat/carbon/WEB-INF/web.xml @@ -0,0 +1,185 @@ + + + + + + + + Owasp.CsrfGuard.Config + repository/conf/security/Owasp.CsrfGuard.Carbon.properties + + + bridgeservlet + Carbon Bridge Servlet + Carbon Bridge Servlet + org.wso2.carbon.tomcat.ext.servlet.DelegationServlet + 1 + + + + JavaScriptServlet + org.owasp.csrfguard.servlet.JavaScriptServlet + + + bridgeservlet + /* + + + + bridgeservlet + *.jsp + + + JavaScriptServlet + /carbon/admin/js/csrfPrevention.js + + + + CharsetFilter + org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter + + requestEncoding + UTF-8 + + + + + CSRFGuard + org.owasp.csrfguard.CsrfGuardFilter + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + HttpHeaderSecurityFilter + * + + + HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL + org.apache.catalina.filters.HttpHeaderSecurityFilter + + + hstsEnabled + false + + + blockContentTypeSniffingEnabled + false + + + xssProtectionEnabled + false + + + antiClickJackingOption + SAMEORIGIN + + + + URLBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.URLBasedCachePreventionFilter + + + HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL + /samlsso + + + CharsetFilter + /* + + + CSRFGuard + /* + + + URLBasedCachePreventionFilter + *.jsp + + + + org.owasp.csrfguard.CsrfGuardServletContextListener + + + + org.owasp.csrfguard.CsrfGuardHttpSessionListener + + + 15 + + true + + + + + 400 + /carbon/errors/error_400.html + + + 401 + /carbon/errors/error_401.html + + + 403 + /carbon/errors/error_403.html + + + 404 + /carbon/errors/error_404.html + + + 405 + /carbon/errors/error_405.html + + + 408 + /carbon/errors/error_408.html + + + 410 + /carbon/errors/error_410.html + + + 500 + /carbon/errors/error_500.html + + + 502 + /carbon/errors/error_502.html + + + 503 + /carbon/errors/error_503.html + + + 504 + /carbon/errors/error_504.html + + + /carbon/errors/error.html + + diff --git a/modules/distribution/src/core/conf/tomcat/catalina-server.xml b/modules/distribution/src/core/conf/tomcat/catalina-server.xml new file mode 100644 index 00000000..c68a93ef --- /dev/null +++ b/modules/distribution/src/core/conf/tomcat/catalina-server.xml @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/conf/tomcat/context.xml b/modules/distribution/src/core/conf/tomcat/context.xml new file mode 100644 index 00000000..512337cd --- /dev/null +++ b/modules/distribution/src/core/conf/tomcat/context.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/conf/user-mgt.xml b/modules/distribution/src/core/conf/user-mgt.xml new file mode 100644 index 00000000..8a9afc53 --- /dev/null +++ b/modules/distribution/src/core/conf/user-mgt.xml @@ -0,0 +1,260 @@ + + + + + + true + admin + + admin + admin + + everyone + true + true + jdbc/WSO2CarbonDB + + + + + org.wso2.carbon.user.core.tenant.JDBCTenantManager + false + true + true + ^[\S]{3,30}$ + ^[\S]{3,30}$ + Username pattern policy violated + ^[\S]{5,30}$ + ^[\S]{5,30}$ + Password length should be within 5 to 30 characters + ^[\S]{3,30}$ + ^[\S]{3,30}$ + true + false + true + SHA-256 + true + , + 100 + 100 + true + false + + + + + + + + + + + + + /permission + true + false + + + + + diff --git a/modules/distribution/src/core/conf/user_mgt_config_change.xml b/modules/distribution/src/core/conf/user_mgt_config_change.xml new file mode 100644 index 00000000..ededb309 --- /dev/null +++ b/modules/distribution/src/core/conf/user_mgt_config_change.xml @@ -0,0 +1,9 @@ + + + //UserManager/Realm/Configuration/Property[@name='initializeNewClaimManager'] + + + //UserManager/Realm/Configuration/Property[@name='isCascadeDeleteEnabled'] + true
]]> + + \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/android-web-agent/jaggery.conf b/modules/distribution/src/core/jaggeryapps/android-web-agent/jaggery.conf new file mode 100644 index 00000000..7c33479a --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/android-web-agent/jaggery.conf @@ -0,0 +1,58 @@ +{ + "displayName": "UUF Template App", + "logLevel": "warn", + "urlMappings": [ + { + "url": "/uuf/login", + "path": "/lib/modules/auth/login.jag" + }, + { + "url": "/uuf/logout", + "path": "/lib/modules/auth/logout.jag" + }, + { + "url": "/uuf/sso/acs", + "path": "/lib/modules/auth/acs.jag" + }, + { + "url": "/public/*", + "path": "/lib/static-files.jag" + }, + { + "url": "/unit/*", + "path": "/lib/units.jag" + }, + { + "url": "/*", + "path": "/lib/pages.jag" + } + ], + "filters": [ + { + "name": "ContentTypeBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", + "params" : [ + {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, + {"name" : "filterAction", "value" : "enforce"}, + {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} + ] + }, + { + "name":"HttpHeaderSecurityFilter", + "class":"org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params" : [{"name" : "hstsEnabled", "value" : "false"}] + } + + ], + "filterMappings": [ + { + "name":"HttpHeaderSecurityFilter", + "url":"*" + }, + { + "name":"ContentTypeBasedCachePreventionFilter", + "url":"*" + } + + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/api-store/jaggery.conf b/modules/distribution/src/core/jaggeryapps/api-store/jaggery.conf new file mode 100644 index 00000000..520acab5 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/api-store/jaggery.conf @@ -0,0 +1,86 @@ +{ + "welcomeFiles":["site/pages/list-apis.jag", "index.html"], + + "logLevel" : "info", + + "errorPages": + { + "401":"/site/pages/error-pages/401.html", + "403":"/site/pages/error-pages/403.html", + "404":"/site/pages/error-pages/404.html", + "500":"/site/pages/error-pages/500.html" + } + , + + "securityConstraints":[ + { + "securityConstraint":{ + "webResourceCollection":{ + "name":"site", + "urlPatterns":["/site/conf/site.json"], + "methods":["GET", "POST", "PUT", "DELETE", "PATCH"] + }, + "authRoles":["admin"] + } + } + ], + + "urlMappings":[ + { + "url":"/apis/info", + "path":"/site/pages/item-info.jag" + }, + { + "url":"/apis/widget", + "path":"/site/pages/widget.jag" + }, + { + "url":"/apis/list", + "path":"/site/pages/list-apis.jag" + }, + { + "url":"/forum/api/topic/*", + "path":"/site/blocks/forum/controller/topics.jag" + }, + { + "url":"/forum/api/reply/*", + "path":"/site/blocks/forum/controller/reply.jag" + }, + { + "url":"/forum/*", + "path":"/site/pages/forum.jag" + }, + { + "url":"/api-docs/*", + "path":"/site/blocks/api-doc/ajax/get.jag" + } + ], + + "filters":[ + { + "name":"HttpHeaderSecurityFilter", + "class":"org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params" : [{"name" : "hstsEnabled", "value" : "false"}] + }, + { + "name": "ContentTypeBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", + "params" : [ + {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, + {"name" : "filterAction", "value" : "enforce"}, + {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} + ] + } + ], + + "filterMappings":[ + { + "name":"HttpHeaderSecurityFilter", + "url":"*" + }, + { + "name":"ContentTypeBasedCachePreventionFilter", + "url":"*" + } + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/api-store/site/conf/site.json b/modules/distribution/src/core/jaggeryapps/api-store/site/conf/site.json new file mode 100644 index 00000000..13f9190b --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/api-store/site/conf/site.json @@ -0,0 +1,56 @@ +{ + "theme" : { + "base" : "wso2" + }, + "context" : "/api-store", + "showPublicStoreURL":true, + "showThemesMenu":false, + "tagWiseMode" :"false", + "tagGroupKey" :"-group", + "ssoConfiguration" : { + "enabled" : "true", + "issuer" : "API_STORE", + "identityProviderURL" : "https://localhost:9443/samlsso", + "keyStorePassword" : "", + "identityAlias" : "", + "responseSigningEnabled":"true", + "assertionSigningEnabled":"true", + "keyStoreName" :"", + "passive" : "true", + "signRequests" : "true", + "assertionEncryptionEnabled" : "false" + }, + "oidcConfiguration" : { + "enabled" : "false", + "issuer" : "API_STORE", + "identityProviderURI" : "http://localhost:8080/openid-connect-server-webapp/", + "authorizationEndpointURI" : "http://localhost:8080/openid-connect-server-webapp/authorize", + "tokenEndpointURI" : "http://localhost:8080/openid-connect-server-webapp/token", + "userInfoURI" : "http://localhost:8080/openid-connect-server-webapp/userinfo", + "jwksURI" : "http://localhost:8080/openid-connect-server-webapp/jwk", + "clientConfiguration" : { + "clientId" : "client_am_store", + "clientSecret" : "secret", + "responseType" : "code", + "authorizationType" : "authorization_code", + "scope" : "phone email address openid profile", + "redirectURI" : "https://localhost:9443/api-store/jagg/jaggery_oidc_acs.jag", + "clientAlgorithm" : "RS256" + } + }, + "mutualAuthConfiguration" : { + "enabled" : "false" + }, + "forum" : { + "topicsPerPage" : "5", + "repliesPerPage" : "5", + "resourceIdentifier" : "common" + }, + "reverseProxy" : { + "enabled" : false, + "host" : "sample.proxydomain.com", + "context":"" + }, + "mapExistingAuthApps" : false + +} diff --git a/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json b/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json new file mode 100644 index 00000000..2f049839 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/configs/designer.json @@ -0,0 +1,95 @@ +{ + "store": { + "types": ["fs"] + }, + "gadgetGeneration" :{ + "isCreateGadgetEnable": false, + "ignoreProviders": ["rt"] + }, + "authentication": { + "activeMethod": "sso", + "methods": { + "sso": { + "attributes": { + "issuer": "portal", + "identityProviderURL": "%https.host%/samlsso", + "responseSigningEnabled": true, + "validateAssertionValidityPeriod": true, + "validateAudienceRestriction": true, + "assertionSigningEnabled": true, + "acs": "%https.host%/portal/acs", + "identityAlias": "wso2carbon", + "defaultNameIDPolicy": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", + "useTenantKey": true, + "isPassive": false + } + }, + "basic": { + "attributes": {} + } + } + }, + "authorization": { + "activeMethod": "oauth", + "methods": { + "oauth": { + "attributes": { + "apimgt-gateway": true, + "oauthProvider": { + "appRegistration": { + "appType": "webapp", + "clientName": "portal", + "owner": "admin", + "password":"admin", + "dynamicClientAppRegistrationServiceURL": "https://localhost:9443/dynamic-client-web/register", + "apiManagerClientAppRegistrationServiceURL": "%https.host%/api-application-registration/register/tenants", + "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer urn:ietf:params:oauth:grant-type:jwt-bearer", + "tokenScope": "admin", + "callbackUrl": "%https.host%/portal", + "saasApp":true, + "samlGrantTypeName":"urn:ietf:params:oauth:grant-type:saml2-bearer" + }, + "tokenServiceURL": "https://localhost:9443/oauth2/token" + }, + "adminUser":"admin@carbon.super", + "adminUserTenantId":"-1234", + "adminRole":"admin", + "scopes" : [ + "device:view" + ] + } + } + } + }, + "designers": [ + "Internal/everyone" + ], + "tenantPrefix": "/t", + "shareStore": false, + "theme": "basic", + "cacheTimeoutSeconds": "5", + "cacheSizeBytes": "1073741824", + "defaultDashboardRedirect": false, + "isCreateGadgetEnable": true, + "isSecureVaultEnabled" : false, + "assets": { + "gadget": { + "fileSizeLimit": 5 + }, + "layout": { + "fileSizeLimit": 1 + } + }, + "oauth": { + "username": "admin", + "password": "admin" + }, + "host": { + "hostname": "localhost", + "port": "", + "protocol": "" + }, + "queryParameters" : { + "passBetweenPages" : ["shared"] + } +} diff --git a/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf b/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf new file mode 100644 index 00000000..30af6585 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/jaggery.conf @@ -0,0 +1,195 @@ +{ + "initScripts": [ + "js/dashboard-deployer.js" + ], + "welcomeFiles": [ + "routers/tenant.jag" + ], + "errorPages": { + "500": "/controllers/error-pages/error500.html", + "404": "/controllers/error-pages/error404.html", + "401": "/controllers/error-pages/error401.html", + "405": "/controllers/error-pages/error405.html", + "403": "/controllers/error-pages/error403.html", + "400": "/controllers/error-pages/error400.html" + }, + "urlMappings": [ + { + "url": "/login-controller", + "path": "/routers/tenant.jag" + }, + { + "url": "/login", + "path": "/routers/tenant.jag" + }, + { + "url": "/logout", + "path": "/routers/tenant.jag" + }, + { + "url": "/t/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/apis/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/dashboards/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/gadget/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/layout/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/assets/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/create-dashboard", + "path": "/routers/tenant.jag" + }, + { + "url": "/dashboard-settings/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/select-layout", + "path": "/routers/tenant.jag" + }, + { + "url": "/create-gadget", + "path": "/routers/tenant.jag" + }, + { + "url": "/upload-gadget", + "path": "/routers/tenant.jag" + }, + { + "url": "/upload-layout", + "path": "/routers/tenant.jag" + }, + { + "url": "/geojson/world/*", + "path": "/templates/geojson/world.json" + }, + { + "url": "/geojson/europe/*", + "path": "/templates/geojson/europe.json" + }, + { + "url": "/geojson/usa/*", + "path": "/templates/geojson/usa.json" + }, + { + "url": "/geojson/countryInfo/*", + "path": "/templates/geojson/countryInfo.json" + }, + { + "url": "/geojson/usaInfo/*", + "path": "/templates/geojson/usaInfo.json" + }, + { + "url": "/acs", + "path": "/controllers/acs.jag" + }, + { + "url": "/banners/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/gadgets/*", + "path": "/routers/tenant.jag" + }, + { + "url": "/configs/designer.json", + "path": "/controllers/error-pages/error404.html" + } + ], + "listeners": [ + { + "class": "org.owasp.csrfguard.CsrfGuardServletContextListener" + }, + { + "class": "org.owasp.csrfguard.CsrfGuardHttpSessionListener" + } + ], + "servlets": [ + { + "name": "JavaScriptServlet", + "class": "org.owasp.csrfguard.servlet.JavaScriptServlet" + } + ], + "servletMappings": [ + { + "name": "JavaScriptServlet", + "url": "/csrf.js" + } + ], + "contextParams": [ + { + "name": "Owasp.CsrfGuard.Config", + "value": "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" + } + ], + "filters": [ + { + "name": "ContentTypeBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", + "params" : [ + {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, + {"name" : "filterAction", "value" : "enforce"}, + {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} + ] + }, + { + "name": "HttpHeaderSecurityFilter", + "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params": [ + { + "name": "hstsEnabled", + "value": "false" + }, + { + "name": "antiClickJackingOption", + "value": "SAMEORIGIN" + } + ] + }, + { + "name": "TenantStoresFilter", + "class": "org.wso2.carbon.dashboard.store.filter.TenantStoreFilter" + }, + { + "name" : "CSRFGuard", + "class" : "org.owasp.csrfguard.CsrfGuardFilter" + } + ], + "filterMappings": [ + { + "name": "HttpHeaderSecurityFilter", + "url": "*" + }, + { + "name": "TenantStoresFilter", + "url": "/store/*" + }, + { + "name": "TenantStoresFilter", + "url": "/temp/*" + }, + { + "name" : "CSRFGuard", + "url" : "/*" + }, + { + "name":"ContentTypeBasedCachePreventionFilter", + "url":"*" + } + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js b/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js new file mode 100644 index 00000000..c6a8aab5 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/modules/oauth/token-handler-utils.js @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var utils = function () { + var log = new Log("/modules/oauth/token-handler-utils.js"); + + var configs = require('/configs/portal.js').config(); + var constants = require("/modules/constants.js"); + var carbon = require("carbon"); + + //noinspection JSUnresolvedVariable + var Base64 = Packages.org.apache.commons.codec.binary.Base64; + //noinspection JSUnresolvedVariable + var String = Packages.java.lang.String; + + var publicMethods = {}; + var privateMethods = {}; + + publicMethods["encode"] = function (payload) { + return String(Base64.encodeBase64(String(payload).getBytes())); + }; + + publicMethods["decode"] = function (payload) { + return String(Base64.decodeBase64(String(payload).getBytes())); + }; + + /** + * Check whether this application is oauth enable or not + * @returns boolean if oauth enable + */ + publicMethods["checkOAuthEnabled"] = function () { + if (constants.AUTHORIZATION_TYPE_OAUTH === configs["authorization"]["activeMethod"]) { + return true; + } + return false; + }; + + /** + * Set access token into xml http request header + * @param xhr xml http request + * @returns {*} xhr which has access token it's header + */ + publicMethods["setAccessToken"] = function (xhr, callback) { + var accessToken; + if (publicMethods.checkOAuthEnabled()) { + try { + accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; + xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken); + } catch (exception) { + log.error("Access token hasn't been set yet, " + exception); + } finally { + callback(xhr); + } + } + callback(xhr); + }; + + /** + * Get access token of current logged user + * @param callBack response with access token + */ + publicMethods["getAccessToken"] = function (callBack) { + var accessToken = null; + if (publicMethods.checkOAuthEnabled()) { + try { + accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"]; + } catch (exception) { + log.error("Access token hasn't been set yet, " + exception); + } finally { + callBack(accessToken); + } + } + callBack(accessToken); + }; + + /** + * Create error message which adhere to xml http response object + * @param statusCode response status code + * @param status response status + * @param responseText response message + * @returns {{statusCode: *, status: *, responseText: *}} + */ + publicMethods["createXHRObject"] = function (statusCode, status, responseText) { + return {"statusCode": statusCode, "status": status, "responseText": responseText}; + }; + + /** + * check whether user already logged to system before invoking any apis + * @param callBack + */ + publicMethods["isUserAuthorized"] = function (callBack) { + if (session.get("Loged") !== constants.LOGIN_MESSAGE) { + callBack(false); + } else { + callBack(true); + } + }; + + /** + * Get identity provider uir + * @returns {*} + */ + publicMethods["getIdPServerURL"] = function () { + return configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["tokenServiceURL"]; + }; + + /** + * Get an Access token pair based on client secret + * @param encodedClientKeys {{clientId:"", clientSecret:""}} + * @param scope eg: PRODUCTION + * @param idPServer identity provider url + * @returns {{accessToken: *, refreshToken: *}} + */ + publicMethods["getTokenWithClientSecretType"] = function (encodedClientKeys, scope, idPServer) { + var xhr = new XMLHttpRequest(); + var tokenEndpoint = idPServer; + xhr.open(constants.HTTP_POST, tokenEndpoint, false); + xhr.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_X_WWW_FOR_URLENCODED); + xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BASIC_PREFIX + encodedClientKeys); + xhr.send("grant_type=client_credentials&scope=" + scope); + var tokenPair = {}; + if (xhr.status == constants.HTTP_ACCEPTED) { + var data = parse(xhr.responseText); + tokenPair.refreshToken = data.refresh_token; + tokenPair.accessToken = data.access_token; + } else if (xhr.status == constants.HTTP_USER_NOT_AUTHENTICATED) { + log.error("Error in obtaining token with client secret grant type, You are not authenticated yet"); + return null; + } else { + log.error("Error in obtaining token with client secret grant type, This might be a problem with client meta " + + "data which required for client secret grant type"); + return null; + } + return tokenPair; + }; + + + /** + * This will create client id and client secret for a given application + * @param properties "callbackUrl": "", + * "clientName": "", + * "owner": "", + * "applicationType": "", + * "grantType": "", + * "saasApp" :"", + * "dynamicClientRegistrationEndPoint" : "" + * + * @returns {{clientId:*, clientSecret:*}} + */ + publicMethods["getDynamicClientAppCredentials"] = function (username) { + // setting up dynamic client application properties + var dcAppProperties = { + "applicationType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["appType"], + "clientName": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["clientName"], + "owner": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"], + "tokenScope": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["tokenScope"], + "grantType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["grantType"], + "callbackUrl": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["callbackUrl"], + "saasApp" : configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["saasApp"] + }; + + var tenantDomain = carbon.server.tenantDomain({username: username}); + if (!tenantDomain) { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials. Unable to obtain a valid tenant domain for provided username "+ + username +"- getDynamicClientAppCredentials(x)"); + return null; + } else { + var cachedTenantBasedClientAppCredentials = privateMethods. + getCachedTenantBasedClientAppCredentials(tenantDomain); + if (cachedTenantBasedClientAppCredentials) { + return cachedTenantBasedClientAppCredentials; + } else { + // calling dynamic client app registration service endpoint + var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"] + ["dynamicClientAppRegistrationServiceURL"]; + var requestPayload = dcAppProperties; + var token = publicMethods.encode(configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] + ["appRegistration"]["owner"] + ":" + configs["authorization"]["methods"]["oauth"]["attributes"] + ["oauthProvider"]["appRegistration"]["password"]); + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("Authorization", "Basic "+ token); + xhr.send(stringify(requestPayload)); + var dynamicClientAppCredentials = {}; + if (xhr["status"] == 201 || xhr["status"] == 200 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var clientId = responsePayload["client_id"]; + var clientSecret = responsePayload["client_secret"]; + if(typeof clientId == "undefined"){ + clientId = responsePayload["clientId"]; + } + if(typeof clientSecret == "undefined"){ + clientSecret = responsePayload["clientSecret"]; + } + dynamicClientAppCredentials["clientId"] = clientId; + dynamicClientAppCredentials["clientSecret"] = clientSecret; + privateMethods. + setCachedTenantBasedClientAppCredentials(tenantDomain, dynamicClientAppCredentials); + } else if (xhr["status"] == 400) { + log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + + "Bad request. Invalid data provided as dynamic client application properties."); + dynamicClientAppCredentials = null; + } else { + log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + + "Error in retrieving dynamic client credentials."); + dynamicClientAppCredentials = null; + } + // returning dynamic client credentials + return dynamicClientAppCredentials; + } + } + }; + + /** + * If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create oauth application + * @param username username of current logged user + * @returns {{clientId:*, clientSecret:*}} + */ + publicMethods["getTenantBasedClientAppCredentials"] = function (username) { + if (!username) { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client app credentials. No username " + + "as input - getTenantBasedClientAppCredentials(x)"); + return null; + } else { + //noinspection JSUnresolvedFunction, JSUnresolvedVariable + var tenantDomain = carbon.server.tenantDomain({username: username}); + + if (!tenantDomain) { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials. Unable to obtain a valid tenant domain for provided " + + "username - getTenantBasedClientAppCredentials(x, y)"); + return null; + } else { + var cachedTenantBasedClientAppCredentials = privateMethods. + getCachedTenantBasedClientAppCredentials(tenantDomain); + if (cachedTenantBasedClientAppCredentials) { + return cachedTenantBasedClientAppCredentials; + } else { + var adminUsername = configs["authorization"]["methods"]["oauth"]["attributes"]["adminUser"]; + var adminUserTenantId = configs["authorization"]["methods"]["oauth"]["attributes"] + ["adminUserTenantId"]; + //claims required for jwtAuthenticator. + var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId, + "http://wso2.org/claims/enduser": adminUsername}; + var jwtToken = publicMethods.getJwtToken(adminUsername, claims); + // register a tenant based client app at API Manager + var applicationName = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] + ["appRegistration"]["clientName"] + "_" + tenantDomain; + var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] + ["appRegistration"]["apiManagerClientAppRegistrationServiceURL"] + + "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken); + xhr.send(); + if ((xhr["status"] == 201 || xhr["status"] == 200) && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var tenantBasedClientAppCredentials = {}; + var clientId = responsePayload["client_id"]; + var clientSecret = responsePayload["client_secret"]; + if(typeof clientId == "undefined"){ + clientId = responsePayload["clientId"]; + } + if(typeof clientSecret == "undefined"){ + clientSecret = responsePayload["clientSecret"]; + } + tenantBasedClientAppCredentials["clientId"] = clientId; + tenantBasedClientAppCredentials["clientSecret"] = clientSecret; + privateMethods. + setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); + return tenantBasedClientAppCredentials; + } else { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials from API " + + "Manager - getTenantBasedClientAppCredentials(x, y)"); + return null; + } + } + } + } + }; + + /** + * Caching oauth application credentials + * @param tenantDomain tenant domain where application is been created + * @param clientAppCredentials {{clientId:*, clientSecret:*}} + */ + privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); + if (!cachedTenantBasedClientAppCredentialsMap) { + cachedTenantBasedClientAppCredentialsMap = {}; + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + application.put(constants["CACHED_CREDENTIALS_PORTAL_APP"], cachedTenantBasedClientAppCredentialsMap); + } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + } + }; + + /** + * Get oauth application credentials from cache + * @param tenantDomain tenant domain where application is been created + * @returns {{clientId:*, clientSecret:*}} + */ + privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]); + if (!cachedTenantBasedClientAppCredentialsMap || + !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + return null; + } else { + return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; + } + }; + + /** + * Get access token and refresh token using password grant type + * @param username username of the logged user + * @param password password of the logged user + * @param encodedClientAppCredentials {{clientId:*, clientSecret:*}} + * @param scopes scopes list + * @returns {{accessToken: *, refreshToken: *}} + */ + publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password + , encodedClientAppCredentials, scopes) { + if (!username || !password || !encodedClientAppCredentials || !scopes) { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + + "grant type. No username, password, encoded client app credentials or scopes are " + + "found - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); + return null; + } else { + // calling oauth provider token service endpoint + var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"] + ["tokenServiceURL"]; + var requestPayload = "grant_type=password&username=" + + username + "&password=" + password + "&scope=" + scopes; + + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); + xhr.send(requestPayload); + + if (xhr["status"] == 200 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var tokenData = {}; + tokenData["accessToken"] = responsePayload["access_token"]; + tokenData["refreshToken"] = responsePayload["refresh_token"]; + tokenData["scopes"] = responsePayload["scope"]; + return tokenData; + } else { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " + + "by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)"); + return null; + } + } + }; + + /** + * Get access token and refresh token using SAML grant type + * @param assertion + * @param encodedClientAppCredentials + * @param scopes + * @returns {{accessToken: *, refreshToken: *}} + */ + publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (username, encodedClientAppCredentials, scopes) { + if (!username || !encodedClientAppCredentials || !scopes) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " + + "grant type. No assertion, encoded client app credentials or scopes are " + + "found - getTokenPairAndScopesByJWTGrantType(x, y, z)"); + return null; + } else { + var JWTClientManagerServicePackagePath = + "org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"; + //noinspection JSUnresolvedFunction, JSUnresolvedVariable + var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath); + //noinspection JSUnresolvedFunction + var jwtClient = JWTClientManagerService.getJWTClient(); + // returning access token by JWT grant type + var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials, + username, scopes); + var tokenData = {}; + tokenData["accessToken"] = tokenInfo.getAccessToken(); + tokenData["refreshToken"] = tokenInfo.getRefreshToken(); + tokenData["scopes"] = tokenInfo.getScopes(); + return tokenData; + } + }; + + /** + * Get access token and refresh token using SAML grant type + * @param assertion + * @param encodedClientAppCredentials + * @param scopes + * @returns {{accessToken: *, refreshToken: *}} + */ + publicMethods["getTokenPairAndScopesBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) { + if (!assertion || !encodedClientAppCredentials || !scopes) { + log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + + "grant type. No assertion, encoded client app credentials or scopes are " + + "found - getTokenPairAndScopesBySAMLGrantType(x, y, z)"); + return null; + } else { + + var assertionXML = publicMethods.decode(assertion); + /* + TODO: make assertion extraction with proper parsing. + Since Jaggery XML parser seem to add formatting which causes signature verification to fail. + */ + var assertionStartMarker = " h1 { + padding: 15px 15px 0 15px; + font-weight: 100; + text-transform: uppercase; + font-size: 18px; +} + +.dashboard .page-header .page-title > h1 > .icon { + font-size: 24px; + margin-top: -5px; + margin-right: 5px; +} + +.dashboard .page-header .navbar-header { + margin-right: 15px; + margin-left: 15px; + float: none; +} + +@media (min-width: 768px) { + .dashboard .page-header .navbar-collapse.collapse { + display: none !important; + } + .page-header .container-fluid { + padding: 0 15px; + } + .navbar-nav > li > a { + padding: 10px 0; + } +} + +.nav > li > a > .icon { + margin-right: 8px; +} + +.nav > li > a > .badge { + position: absolute; + top: 5px; + right: 5px; + background: #ff124a; +} + +.dashboard .page-header .auth { + margin-bottom: 0; + padding: 6px 0; +} + +.dashboard .page-content { + overflow: inherit; +} + +.dashboard .footer { + background: #0d1219; +} + +.dashboard .gadget-wrapper { + border: 1px dashed #e4e4e4; +} + +.dashboard .gadget .gadget-heading { + background: transparent; + border-bottom: none; + color: #29313e; +} + +.gadget .gadget-heading > .gadget-title { + font-size: 20px; +} + +.gadget .gadget-heading > .gadget-actions button { + border: none; +} + +.sidebar-wrapper hr { + border-top-color: #ebeced; +} + +.sidebar-toggle-button { + float: left; + height: 50px; + line-height: 50px; + font-size: 18px; + background: #438cad; + color: #ffffff; + margin-left: -15px; +} + +.sidebar-toggle-button > .icon { + line-height: 48px; +} + +.sidebar-nav { + background: #29313e; + color: #e3e5e6; +} + +.nav.pages { + text-transform: uppercase; +} + +.nav.pages > li { + line-height: 20px; +} + +.nav > li { + text-indent: 0; + line-height: 10px; +} + +.nav > li > a { + border-radius: 0; + color: #e3e5e6; + background: transparent; +} + +.collapse-nav-sub > li > a { + padding: 4px 10px; + font-size: 21px; +} + +.collapse-nav-sub > li > a > .icon { + margin: 0; +} + +.page-header .fw-inverse { + color: #29313e; +} + +.nav li:hover > a, +.nav li.open > a, +.nav li.open > a:focus, +.nav li.open > a:hover { + background: #1a2332; +} + +.nav > li > a:focus { + background: transparent; +} + +.nav.pages > li.active a { + background: #121822; + border-left: 5px solid #438cad; +} + +.navbar-collapse { + padding: 15px; + background: #1A2331; +} + +.navbar-collapse li:hover > a { + background: #29313E; +} + +.sidebar-nav .user { + text-align: center; + margin: 20px auto; +} + +.sidebar-nav .user > .user-image { + margin-bottom: 10px; +} + +.sidebar-nav .user > .user-image > .default .icon { + font-size: 25px; +} + +.sidebar-nav .user > .user-image > .default .icon .fw-inverse, +.sidebar-nav .user > .user-image > .default .icon .fa-inverse { + color: #29313e; +} + +.widget .gadget-wrapper { + border: none; +} + +.widget .ues-component-heading { + display: none !important; + height: 0; +} + +.widget .ues-component { + height: auto; +} + +.widget.form-control-widget { + height: 35px !important; +} + +.dropdown-menu.arrow.arrow-top-right:before { + right: 20px; +} + +.dropdown-menu.arrow:before, +.dropdown-menu.arrow.arrow-top-left:before { + top: -10px; + border-right: 10px solid transparent; + border-bottom: 10px solid #e4e4e4; + border-left: 10px solid transparent; +} + +.dropdown-menu.alerts { + min-width: 400px; + max-width: 100%; + line-height: 1.2; +} + +ul.sidebar-messages > li:first-child { + margin-top: 0; +} + +ul.sidebar-messages > li:last-child { + margin-bottom: 0; +} \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js new file mode 100644 index 00000000..e1b44c83 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/VizGrammarSettings.js @@ -0,0 +1,12 @@ +var vizgSettings = { + colorScale: colorbrewer.RdYlBu[4].reverse(), + colors: { + green:"#5FCE9B", + blue:"#438CAD", + red:"#E87352", + yellow:"#EECA5A", + purple:"#B6688F", + grey:"434343", + brown:"#C59787" + } +} \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js new file mode 100644 index 00000000..5266d212 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/js/colorbrewer.js @@ -0,0 +1,303 @@ +// This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/). +// JavaScript specs as packaged in the D3 library (d3js.org). Please see license at http://colorbrewer.org/export/LICENSE.txt +var colorbrewer = {YlGn: { +3: ["#f7fcb9","#addd8e","#31a354"], +4: ["#ffffcc","#c2e699","#78c679","#238443"], +5: ["#ffffcc","#c2e699","#78c679","#31a354","#006837"], +6: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#31a354","#006837"], +7: ["#ffffcc","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"], +8: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#005a32"], +9: ["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"] +},YlGnBu: { +3: ["#edf8b1","#7fcdbb","#2c7fb8"], +4: ["#ffffcc","#a1dab4","#41b6c4","#225ea8"], +5: ["#ffffcc","#a1dab4","#41b6c4","#2c7fb8","#253494"], +6: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"], +7: ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"], +8: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#0c2c84"], +9: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"] +},GnBu: { +3: ["#e0f3db","#a8ddb5","#43a2ca"], +4: ["#f0f9e8","#bae4bc","#7bccc4","#2b8cbe"], +5: ["#f0f9e8","#bae4bc","#7bccc4","#43a2ca","#0868ac"], +6: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#43a2ca","#0868ac"], +7: ["#f0f9e8","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"], +8: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"], +9: ["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"] +},BuGn: { +3: ["#e5f5f9","#99d8c9","#2ca25f"], +4: ["#edf8fb","#b2e2e2","#66c2a4","#238b45"], +5: ["#edf8fb","#b2e2e2","#66c2a4","#2ca25f","#006d2c"], +6: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#2ca25f","#006d2c"], +7: ["#edf8fb","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"], +8: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#005824"], +9: ["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"] +},PuBuGn: { +3: ["#ece2f0","#a6bddb","#1c9099"], +4: ["#f6eff7","#bdc9e1","#67a9cf","#02818a"], +5: ["#f6eff7","#bdc9e1","#67a9cf","#1c9099","#016c59"], +6: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#1c9099","#016c59"], +7: ["#f6eff7","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"], +8: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016450"], +9: ["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"] +},PuBu: { +3: ["#ece7f2","#a6bddb","#2b8cbe"], +4: ["#f1eef6","#bdc9e1","#74a9cf","#0570b0"], +5: ["#f1eef6","#bdc9e1","#74a9cf","#2b8cbe","#045a8d"], +6: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#2b8cbe","#045a8d"], +7: ["#f1eef6","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"], +8: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#034e7b"], +9: ["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"] +},BuPu: { +3: ["#e0ecf4","#9ebcda","#8856a7"], +4: ["#edf8fb","#b3cde3","#8c96c6","#88419d"], +5: ["#edf8fb","#b3cde3","#8c96c6","#8856a7","#810f7c"], +6: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8856a7","#810f7c"], +7: ["#edf8fb","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"], +8: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#6e016b"], +9: ["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"] +},RdPu: { +3: ["#fde0dd","#fa9fb5","#c51b8a"], +4: ["#feebe2","#fbb4b9","#f768a1","#ae017e"], +5: ["#feebe2","#fbb4b9","#f768a1","#c51b8a","#7a0177"], +6: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#c51b8a","#7a0177"], +7: ["#feebe2","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"], +8: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177"], +9: ["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"] +},PuRd: { +3: ["#e7e1ef","#c994c7","#dd1c77"], +4: ["#f1eef6","#d7b5d8","#df65b0","#ce1256"], +5: ["#f1eef6","#d7b5d8","#df65b0","#dd1c77","#980043"], +6: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#dd1c77","#980043"], +7: ["#f1eef6","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"], +8: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#91003f"], +9: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"] +},OrRd: { +3: ["#fee8c8","#fdbb84","#e34a33"], +4: ["#fef0d9","#fdcc8a","#fc8d59","#d7301f"], +5: ["#fef0d9","#fdcc8a","#fc8d59","#e34a33","#b30000"], +6: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#e34a33","#b30000"], +7: ["#fef0d9","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"], +8: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#990000"], +9: ["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"] +},YlOrRd: { +3: ["#ffeda0","#feb24c","#f03b20"], +4: ["#ffffb2","#fecc5c","#fd8d3c","#e31a1c"], +5: ["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"], +6: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#f03b20","#bd0026"], +7: ["#ffffb2","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"], +8: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#b10026"], +9: ["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"] +},YlOrBr: { +3: ["#fff7bc","#fec44f","#d95f0e"], +4: ["#ffffd4","#fed98e","#fe9929","#cc4c02"], +5: ["#ffffd4","#fed98e","#fe9929","#d95f0e","#993404"], +6: ["#ffffd4","#fee391","#fec44f","#fe9929","#d95f0e","#993404"], +7: ["#ffffd4","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"], +8: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#8c2d04"], +9: ["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"] +},Purples: { +3: ["#efedf5","#bcbddc","#756bb1"], +4: ["#f2f0f7","#cbc9e2","#9e9ac8","#6a51a3"], +5: ["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"], +6: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#756bb1","#54278f"], +7: ["#f2f0f7","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"], +8: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#4a1486"], +9: ["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"] +},Blues: { +3: ["#deebf7","#9ecae1","#3182bd"], +4: ["#eff3ff","#bdd7e7","#6baed6","#2171b5"], +5: ["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"], +6: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#3182bd","#08519c"], +7: ["#eff3ff","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"], +8: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#084594"], +9: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"] +},Greens: { +3: ["#e5f5e0","#a1d99b","#31a354"], +4: ["#edf8e9","#bae4b3","#74c476","#238b45"], +5: ["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"], +6: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#31a354","#006d2c"], +7: ["#edf8e9","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"], +8: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32"], +9: ["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"] +},Oranges: { +3: ["#fee6ce","#fdae6b","#e6550d"], +4: ["#feedde","#fdbe85","#fd8d3c","#d94701"], +5: ["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"], +6: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#e6550d","#a63603"], +7: ["#feedde","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"], +8: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#8c2d04"], +9: ["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"] +},Reds: { +3: ["#fee0d2","#fc9272","#de2d26"], +4: ["#fee5d9","#fcae91","#fb6a4a","#cb181d"], +5: ["#fee5d9","#fcae91","#fb6a4a","#de2d26","#a50f15"], +6: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#de2d26","#a50f15"], +7: ["#fee5d9","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"], +8: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#99000d"], +9: ["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"] +},Greys: { +3: ["#f0f0f0","#bdbdbd","#636363"], +4: ["#f7f7f7","#cccccc","#969696","#525252"], +5: ["#f7f7f7","#cccccc","#969696","#636363","#252525"], +6: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#636363","#252525"], +7: ["#f7f7f7","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"], +8: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525"], +9: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"] +},PuOr: { +3: ["#f1a340","#f7f7f7","#998ec3"], +4: ["#e66101","#fdb863","#b2abd2","#5e3c99"], +5: ["#e66101","#fdb863","#f7f7f7","#b2abd2","#5e3c99"], +6: ["#b35806","#f1a340","#fee0b6","#d8daeb","#998ec3","#542788"], +7: ["#b35806","#f1a340","#fee0b6","#f7f7f7","#d8daeb","#998ec3","#542788"], +8: ["#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788"], +9: ["#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788"], +10: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"], +11: ["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"] +},BrBG: { +3: ["#d8b365","#f5f5f5","#5ab4ac"], +4: ["#a6611a","#dfc27d","#80cdc1","#018571"], +5: ["#a6611a","#dfc27d","#f5f5f5","#80cdc1","#018571"], +6: ["#8c510a","#d8b365","#f6e8c3","#c7eae5","#5ab4ac","#01665e"], +7: ["#8c510a","#d8b365","#f6e8c3","#f5f5f5","#c7eae5","#5ab4ac","#01665e"], +8: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e"], +9: ["#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e"], +10: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"], +11: ["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"] +},PRGn: { +3: ["#af8dc3","#f7f7f7","#7fbf7b"], +4: ["#7b3294","#c2a5cf","#a6dba0","#008837"], +5: ["#7b3294","#c2a5cf","#f7f7f7","#a6dba0","#008837"], +6: ["#762a83","#af8dc3","#e7d4e8","#d9f0d3","#7fbf7b","#1b7837"], +7: ["#762a83","#af8dc3","#e7d4e8","#f7f7f7","#d9f0d3","#7fbf7b","#1b7837"], +8: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837"], +9: ["#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837"], +10: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"], +11: ["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"] +},PiYG: { +3: ["#e9a3c9","#f7f7f7","#a1d76a"], +4: ["#d01c8b","#f1b6da","#b8e186","#4dac26"], +5: ["#d01c8b","#f1b6da","#f7f7f7","#b8e186","#4dac26"], +6: ["#c51b7d","#e9a3c9","#fde0ef","#e6f5d0","#a1d76a","#4d9221"], +7: ["#c51b7d","#e9a3c9","#fde0ef","#f7f7f7","#e6f5d0","#a1d76a","#4d9221"], +8: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221"], +9: ["#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221"], +10: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"], +11: ["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"] +},RdBu: { +3: ["#ef8a62","#f7f7f7","#67a9cf"], +4: ["#ca0020","#f4a582","#92c5de","#0571b0"], +5: ["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"], +6: ["#b2182b","#ef8a62","#fddbc7","#d1e5f0","#67a9cf","#2166ac"], +7: ["#b2182b","#ef8a62","#fddbc7","#f7f7f7","#d1e5f0","#67a9cf","#2166ac"], +8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac"], +9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac"], +10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"], +11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"] +},RdGy: { +3: ["#ef8a62","#ffffff","#999999"], +4: ["#ca0020","#f4a582","#bababa","#404040"], +5: ["#ca0020","#f4a582","#ffffff","#bababa","#404040"], +6: ["#b2182b","#ef8a62","#fddbc7","#e0e0e0","#999999","#4d4d4d"], +7: ["#b2182b","#ef8a62","#fddbc7","#ffffff","#e0e0e0","#999999","#4d4d4d"], +8: ["#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d"], +9: ["#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d"], +10: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"], +11: ["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"] +},RdYlBu: { +3: ["#fc8d59","#ffffbf","#91bfdb"], +4: ["#d7191c","#fdae61","#abd9e9","#2c7bb6"], +5: ["#d7191c","#fdae61","#ffffbf","#abd9e9","#2c7bb6"], +6: ["#d73027","#fc8d59","#fee090","#e0f3f8","#91bfdb","#4575b4"], +7: ["#d73027","#fc8d59","#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"], +8: ["#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4"], +9: ["#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4"], +10: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"], +11: ["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"] +},Spectral: { +3: ["#fc8d59","#ffffbf","#99d594"], +4: ["#d7191c","#fdae61","#abdda4","#2b83ba"], +5: ["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"], +6: ["#d53e4f","#fc8d59","#fee08b","#e6f598","#99d594","#3288bd"], +7: ["#d53e4f","#fc8d59","#fee08b","#ffffbf","#e6f598","#99d594","#3288bd"], +8: ["#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd"], +9: ["#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd"], +10: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"], +11: ["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"] +},RdYlGn: { +3: ["#fc8d59","#ffffbf","#91cf60"], +4: ["#d7191c","#fdae61","#a6d96a","#1a9641"], +5: ["#d7191c","#fdae61","#ffffbf","#a6d96a","#1a9641"], +6: ["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"], +7: ["#d73027","#fc8d59","#fee08b","#ffffbf","#d9ef8b","#91cf60","#1a9850"], +8: ["#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850"], +9: ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"], +10: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"], +11: ["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"] +},Accent: { +3: ["#7fc97f","#beaed4","#fdc086"], +4: ["#7fc97f","#beaed4","#fdc086","#ffff99"], +5: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0"], +6: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f"], +7: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17"], +8: ["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"] +},Dark2: { +3: ["#1b9e77","#d95f02","#7570b3"], +4: ["#1b9e77","#d95f02","#7570b3","#e7298a"], +5: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e"], +6: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02"], +7: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d"], +8: ["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"] +},Paired: { +3: ["#a6cee3","#1f78b4","#b2df8a"], +4: ["#a6cee3","#1f78b4","#b2df8a","#33a02c"], +5: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99"], +6: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c"], +7: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f"], +8: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00"], +9: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"], +10: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a"], +11: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99"], +12: ["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"] +},Pastel1: { +3: ["#fbb4ae","#b3cde3","#ccebc5"], +4: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4"], +5: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6"], +6: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc"], +7: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd"], +8: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"], +9: ["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"] +},Pastel2: { +3: ["#b3e2cd","#fdcdac","#cbd5e8"], +4: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4"], +5: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9"], +6: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae"], +7: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc"], +8: ["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"] +},Set1: { +3: ["#e41a1c","#377eb8","#4daf4a"], +4: ["#e41a1c","#377eb8","#4daf4a","#984ea3"], +5: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"], +6: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33"], +7: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628"], +8: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"], +9: ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"] +},Set2: { +3: ["#66c2a5","#fc8d62","#8da0cb"], +4: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3"], +5: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854"], +6: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"], +7: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494"], +8: ["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"] +},Set3: { +3: ["#8dd3c7","#ffffb3","#bebada"], +4: ["#8dd3c7","#ffffb3","#bebada","#fb8072"], +5: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3"], +6: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462"], +7: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69"], +8: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5"], +9: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9"], +10: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd"], +11: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5"], +12: ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"] +}}; \ No newline at end of file diff --git a/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag new file mode 100644 index 00000000..be15e2cb --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/themes/analytics/templates/dashboard.jag @@ -0,0 +1,447 @@ + +<% + // i18n + var i18n = require("i18n"); + i18n.init(request, utils.getLocaleResourcePath()); + + // If the pageId is null, render the landing page + pageId = pageId || dashboard.landing; + + var usr = require('/modules/user.js'), + user = usr.current(), + isAnonView = request.getParameter('isAnonView'); + + // Get the anon view + if (!user) { + if (isAnonView) { + response.sendRedirect(request.getRequestURL()); + } + isAnonView = true; + } else { + isAnonView = JSON.parse(isAnonView); + + if((user.domain != urlDomain && urlDomain) || + (dashboard.isanon && !utils.allowed(user.roles, dashboard.permissions.editors) && !utils.allowed(user.roles, dashboard.permissions.viewers))) { + isAnonView = true; + } + } + + // Get the current page + var pages = dashboard.pages, + page; + pages.forEach(function(p) { + if (p.id == pageId) { + page = p; + } + }); +%> + + + + + + + <%= i18n.localize("dashboard.server.label")%> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + + + +
+ +
+ +
+ <%=renderEngine.getDashboardContent(pageId || dashboard.landing, isAnonView)%> +
+
+
+ +
+
+
+ + +
+
+

WSO2 Dashboard Server 2.0.0 | © Inc.

+
+
+ + + + + + + + + + + + + + + + + + + + + <% include('/controllers/includes/common-scripts.jag'); %> + <% include('/controllers/includes/dashboard-scripts.jag'); %> + + + + + + + + + + + <% include('/controllers/includes/theme-dashboard-scripts.jag'); %> + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag b/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag new file mode 100644 index 00000000..3f8fa1d4 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/portal/uipublisher/websocketSubscriptionEndpoint.jag @@ -0,0 +1,52 @@ +<% +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +var user = session.get('user'); +var streamName; +var streamVersion; +var log = new Log(); +var JaggeryWebSocketHelper = Packages.org.wso2.carbon.event.output.adapter.ui.JaggeryWebSocketHelper; + +webSocket.onopen = function () { + if (user == null) { + this.close(); + } +}; + +webSocket.ontext = function (data) { + log.info(data); + var dataObj = parse(data); + streamName = dataObj.streamName; + streamVersion = dataObj.streamVersion; + JaggeryWebSocketHelper.subscribeWebSocket(streamName, streamVersion, stringify(dataObj.filterProps), + user.username, session.getId(), user.tenantId, this); +}; + +webSocket.onclose = function () { + if (user != null && streamName != null && streamVersion != null) { //onclose may get invoked when an invalid user (user==null case) closes the connection. Hence this check is required. + JaggeryWebSocketHelper.unsubscribeWebsocket(streamName, streamVersion, session.getId(), user.tenantId); + } +}; + +webSocket.onerror = function () { + if (user != null) { + JaggeryWebSocketHelper.unsubscribeWebsocket(streamId.split(":")[0], streamId.split(":")[1], session.getId(), user.tenantId); + } +}; + +%> diff --git a/modules/distribution/src/core/jaggeryapps/publisher/jaggery.conf b/modules/distribution/src/core/jaggeryapps/publisher/jaggery.conf new file mode 100644 index 00000000..1eae2b9e --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/publisher/jaggery.conf @@ -0,0 +1,195 @@ +{ + "initScripts": ["config/app.js"], + "welcomeFiles": ["/controllers/index_router.jag"], + "sessionDestroyedListeners": ["config/clearindex.js"], + "logLevel": "info", + "urlMappings": [ + { + "url": "/api/authenticate", + "path": "/apis/v1/authenticate.jag" + }, + { + "url": "/asset/*", + "path": "/controllers/asset_router.jag" + }, + { + "url": "/assets/*", + "path": "/controllers/assets_router.jag" + }, + { + "url": "/assets/discover/*", + "path": "/controllers/app_discover_router.jag" + }, + { + "url": "/api/asset/*", + "path": "/apis/v1/asset_api_router.jag" + }, + { + "url": "/api/assets/*", + "path": "/apis/v1/assets_api_router.jag" + }, + { + "url": "/api/discover/*", + "path": "/apis/v1/app_discover_api_router.jag" + }, + { + "url": "/api/lifecycle/*", + "path": "/apis/v1/lifecycle_api_router.jag" + }, + { + "url": "/api/entitlement/*", + "path": "/apis/v1/entitlement_api_router.jag" + }, + { + "url": "/api/mobile/*", + "path": "/extensions/mobileapp/api/mobile_api_router.jag" + }, + { + "url": "/api/validations/assets/*", + "path": "/apis/v1/validations_api_router.jag" + }, + { + "url": "/api/validate/*", + "path": "/apis/v1/validations_api_router.jag" + }, + { + "url": "/api/version/*", + "path": "/apis/v1/version_api_router.jag" + }, + { + "url": "/api/tag/*", + "path": "/apis/v1/tags_api_router.jag" + }, + { + "url": "/api/cache/*", + "path": "/apis/v1/cache_api_router.jag" + }, + { + "url": "/storage/*", + "path": "/controllers/storage_router.jag" + }, + { + "url": "/test", + "path": "/test.jag" + }, + { + "url": "/login", + "path": "/controllers/login.jag" + }, + { + "url": "/acs", + "path": "/controllers/acs.jag" + }, + { + "url": "/logout", + "path": "/controllers/logout.jag" + }, + { + "url": "/api/doc", + "path": "/apis/v1/docs.jag" + }, + { + "url": "/webapp/doc/inline", + "path": "/controllers/inline-editor.jag" + }, + { + "url": "/api/sso/*", + "path": "/apis/v1/ssoconfig_api_router.jag" + }, + { + "url": "/api/mobileapp/getfile/*", + "path": "/extensions/mobileapp/getfile.jag" + }, + { + "url": "/api/mobileapp/getplist/*", + "path": "/extensions/mobileapp/plist.jag" + }, + { + "url": "/api/xacmlpolicy", + "path": "/extensions/webapp/modules/manager/xacmlpolicies.jag" + }, + { + "url": "/api/mobileapp/upload", + "path": "/extensions/mobileapp/mobileupload.jag" + } + ], + "errorPages": { + "401": "/controllers/error401.html", + "500": "/controllers/error500.html", + "404": "/controllers/error404.html", + "403": "/controllers/error403.html", + "400": "/controllers/error400.html" + }, + "filters": [ + { + "name": "HttpHeaderSecurityFilter", + "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params": [ + { + "name": "hstsEnabled", + "value": "false" + } + ] + }, + { + "name": "URLBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.URLBasedCachePreventionFilter" + }, + { + "name" : "CSRFGuard", + "class" : "org.owasp.csrfguard.CsrfGuardFilter" + } + ], + "filterMappings": [ + { + "name": "HttpHeaderSecurityFilter", + "url": "*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/api/*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/asset/*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/assets/*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/storage/*" + }, + { + "name" : "CSRFGuard", + "url" : "/*" + } + ], + "listeners": [ + { + "class": "org.owasp.csrfguard.CsrfGuardServletContextListener" + }, + { + "class": "org.owasp.csrfguard.CsrfGuardHttpSessionListener" + } + ], + "servlets": [ + { + "name": "JavaScriptServlet", + "class": "org.owasp.csrfguard.servlet.JavaScriptServlet" + } + ], + "servletMappings": [ + { + "name": "JavaScriptServlet", + "url": "/csrf.js" + } + ], + "contextParams": [ + { + "name": "Owasp.CsrfGuard.Config", + "value": "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" + } + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/social/jaggery.conf b/modules/distribution/src/core/jaggeryapps/social/jaggery.conf new file mode 100644 index 00000000..2da098c3 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/social/jaggery.conf @@ -0,0 +1,115 @@ +{ + "welcomeFiles": ["index.jag"], + "sessionDestroyedListeners":["modules/clearindex.js"], + "initScripts": ["inits/app.js"], + "urlMappings": [ + { + "url": "/apis/v1/comments/*", + "path": "/apis/v1/comments.jag" + }, + { + "url": "/apis/v1/rating/*", + "path": "/apis/v1/rating.jag" + }, + { + "url": "/", + "path": "/controllers/index.jag" + }, + { + "url": "/t/*", + "path": "/controllers/index.jag" + }, + { + "url": "/login", + "path": "/controllers/login.jag" + }, + { + "url": "/logout", + "path": "/controllers/logout.jag" + }, + { + "url": "/acs", + "path": "/controllers/acs.jag" + }, + { + "url": "/configs/*", + "path": "/" + } + ], + "errorPages": { + "500": "/controllers/error500.html", + "404": "/controllers/error404.html", + "401": "/controllers/error401.html", + "403": "/controllers/error403.html" + }, + "filters":[ + { + "name": "ContentTypeBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", + "params" : [ + {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, + {"name" : "filterAction", "value" : "enforce"}, + {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} + ] + }, + { + "name":"HttpHeaderSecurityFilter", + "class":"org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params" : [{"name" : "hstsEnabled", "value" : "false"}] + }, + { + "name":"HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL", + "class":"org.apache.catalina.filters.HttpHeaderSecurityFilter" + "params" : [ + {"name" : "hstsEnabled", "value" : "false"}, + {"name" : "blockContentTypeSniffingEnabled", "value" : "false"}, + {"name" : "xssProtectionEnabled", "value" : "false"}, + {"name" : "antiClickJackingOption", "value" : "SAMEORIGIN"} + ] + }, + { + "name" : "CSRFGuard", + "class" : "org.owasp.csrfguard.CsrfGuardFilter" + } + ], + "filterMappings":[ + { + "name":"HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL", + "url":"/social/*" + }, + { + "name":"ContentTypeBasedCachePreventionFilter", + "url":"*" + }, + { + "name" : "CSRFGuard", + "url" : "/*" + } + ], + "listeners" : [ + { + "class" : "org.owasp.csrfguard.CsrfGuardServletContextListener" + }, + { + "class" : "org.owasp.csrfguard.CsrfGuardHttpSessionListener" + } + ], + "servlets" : [ + { + "name" : "JavaScriptServlet", + "class" : "org.owasp.csrfguard.servlet.JavaScriptServlet" + } + ], + "servletMappings" : [ + { + "name" : "JavaScriptServlet", + "url" : "/csrf.js" + } + ], + "contextParams" : [ + { + "name" : "Owasp.CsrfGuard.Config", + "value" : "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" + } + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/store/jaggery.conf b/modules/distribution/src/core/jaggeryapps/store/jaggery.conf new file mode 100644 index 00000000..2df48819 --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/store/jaggery.conf @@ -0,0 +1,242 @@ +{ + "welcomeFiles":[ + "/controllers/public-stores.jag" + ], + "initScripts":[ + "/config/app.js" + ], + "sessionDestroyedListeners":[ + "/config/clearindex.js" + ], + "logLevel":"info", + "urlMappings":[ + { + "url":"/modules/*", + "path":"/" + }, + { + "url":"/apis/v1/assets/*", + "path":"/apis/v1/assets.jag" + }, + { + "url":"/apis/asset/*", + "path":"/apis/asset.jag" + }, + { + "url":"/apis/assets/*", + "path":"/apis/assets.jag" + }, + { + "url":"/apis/remove/*", + "path":"/apis/asset.jag" + }, + { + "url":"/apis/tag/*", + "path":"/apis/tag.jag" + }, + { + "url":"/apis/myAsset/*", + "path":"/apis/asset.jag" + }, + { + "url":"/t/*", + "path":"/controllers/ref_tenant_router.jag" + }, + { + "url":"/apis/user/*", + "path":"/apis/user.jag" + }, + { + "url":"/apis/comment/*", + "path":"/apis/comment.jag" + }, + { + "url":"/apis/enterprise/*", + "path":"/apis/enterprise.jag" + }, + { + "url":"/apis/comments/*", + "path":"/apis/comment.jag" + }, + { + "url":"/apis/eventpublish/*", + "path":"/apis/eventpublish.jag" + }, + { + "url":"/apis/rate/*", + "path":"/apis/rating.jag" + }, + { + "url":"/apis/favourite/*", + "path":"/apis/favourite.jag" + }, + { + "url":"/apis/*", + "path":"/controllers/routers/apis.jag" + }, + { + "url":"/assets/*", + "path":"/controllers/routers/assets.jag" + }, + { + "url":"/resources/*", + "path":"/controllers/routers/restfulapis.jag" + }, + { + "url":"/storage/*", + "path":"/controllers/routers/storage_router.jag" + }, + { + "url":"/extensions/*", + "path":"/controllers/routers/extensions.jag" + }, + { + "url":"/subscriptions/*", + "path":"/controllers/routers/subscriptions.jag" + }, + { + "url":"/assets/", + "path":"/controllers/home.jag" + }, + { + "url":"/assets/favourite", + "path":"/controllers/favouriteapps.jag" + }, + { + "url":"/asset/*", + "path":"/routers/asset.jag" + }, + { + "url":"/config", + "path":"/" + }, + { + "url":"/acs", + "path":"/controllers/acs.jag" + }, + { + "url":"/dashboard", + "path":"/controllers/dashboard.jag" + }, + { + "url":"/login", + "path":"/controllers/login.jag" + }, + { + "url":"/logout", + "path":"/controllers/logout.jag" + }, + { + "url":"/mobileapp/device_image", + "path":"/extensions/assets/mobileapp/pages/device_image.jag" + }, + { + "url":"/apps/*", + "path":"/extensions/assets/mobileapp/apis.jag" + }, + { + "url":"/mobileapp/myapps", + "path":"/extensions/assets/mobileapp/pages/myapps.jag" + }, + { + "url":"/api/mobileapp/getfile/*", + "path":"/extensions/assets/mobileapp/pages/getfile.jag" + } + ], + "errorPages":{ + "500":"/controllers/error500.html", + "404":"/controllers/error404.html", + "401":"/controllers/error401.html", + "403":"/controllers/error403.jag" + }, + "filters": [ + { + "name": "HttpHeaderSecurityFilter", + "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params": [ + { + "name": "hstsEnabled", + "value": "false" + } + ] + }, + { + "name": "HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL", + "class": "org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params": [ + { + "name": "hstsEnabled", + "value": "false" + }, + { + "name": "blockContentTypeSniffingEnabled", + "value": "false" + }, + { + "name": "xssProtectionEnabled", + "value": "false" + }, + { + "name": "antiClickJackingOption", + "value": "SAMEORIGIN" + } + ] + }, + { + "name": "URLBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.URLBasedCachePreventionFilter" + }, + { + "name" : "CSRFGuard", + "class" : "org.owasp.csrfguard.CsrfGuardFilter" + } + ], + "filterMappings": [ + { + "name": "HttpHeaderSecurityFilter", + "url": "*" + }, + { + "name": "HttpHeaderSecurityFilter_AntiClickJacking_SpecialURL", + "url": "/samlsso/*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/apis/*" + }, + { + "name":"URLBasedCachePreventionFilter", + "url":"/assets/*" + }, + { + "name" : "CSRFGuard", + "url" : "/*" + } + ], + "listeners": [ + { + "class": "org.owasp.csrfguard.CsrfGuardServletContextListener" + }, + { + "class": "org.owasp.csrfguard.CsrfGuardHttpSessionListener" + } + ], + "servlets": [ + { + "name": "JavaScriptServlet", + "class": "org.owasp.csrfguard.servlet.JavaScriptServlet" + } + ], + "servletMappings": [ + { + "name": "JavaScriptServlet", + "url": "/csrf.js" + } + ], + "contextParams": [ + { + "name": "Owasp.CsrfGuard.Config", + "value": "repository/conf/security/Owasp.CsrfGuard.dashboard.properties" + } + ] +} diff --git a/modules/distribution/src/core/jaggeryapps/windows-web-agent/jaggery.conf b/modules/distribution/src/core/jaggeryapps/windows-web-agent/jaggery.conf new file mode 100644 index 00000000..00514b3a --- /dev/null +++ b/modules/distribution/src/core/jaggeryapps/windows-web-agent/jaggery.conf @@ -0,0 +1,125 @@ +{ + "displayName": "EMM Web Agent", + "logLevel": "error", + "initScripts": ["/app/modules/init.js"], + "urlMappings": [ + { + "url": "/enrollment", + "path": "/lib/pages.jag" + }, + { + "url": "/enrollment/windows/login", + "path": "/app/modules/enrollments/windows/agent-controller.jag" + }, + { + "url": "/enrollment/windows/enroll", + "path": "/app/modules/enrollments/windows/agent-enroll.jag" + }, + { + "url": "/enrollment/ios/download-certificate", + "path": "/app/modules/enrollments/ios/certificate.jag" + }, + { + "url": "/enrollment/ios/download-agent", + "path": "/app/modules/enrollments/ios/agent.jag" + }, + { + "url": "/enrollment/ios/login", + "path": "/app/modules/enrollments/ios/agent-controller.jag" + }, + { + "url": "/enrollment/ios/enroll", + "path": "/app/modules/enrollments/ios/agent-enroll.jag" + }, + { + "url": "/enrollment/ios/check", + "path": "/app/modules/enrollments/ios/agent-check.jag" + }, + { + "url": "/api/invoker/*", + "path": "/api/invoker-api.jag" + }, + { + "url": "/uuf/login", + "path": "/lib/modules/auth/login.jag" + }, + { + "url": "/uuf/logout", + "path": "/lib/modules/auth/logout.jag" + }, + { + "url": "/uuf/sso/acs", + "path": "/lib/modules/auth/acs.jag" + }, + { + "url": "/public/*", + "path": "/lib/static-files.jag" + }, + { + "url": "/unit/*", + "path": "/lib/units.jag" + }, + { + "url": "/*", + "path": "/lib/pages.jag" + } + ], + "securityConstraints": [ + { + "securityConstraint": { + "webResourceCollection": { + "name": "WINDOWS-WEB-AGENT", + "urlPatterns": [ + "/*" + ] + }, + "userDataConstraint": { + "transportGuarantee": "CONFIDENTIAL" + } + } + }, + { + "securityConstraint": { + "webResourceCollection": { + "name": "WINDOWS-WEB-AGENT-http", + "urlPatterns": [ + "/public/*", + "/enrollments/windows/*", + "/enrollment/windows/*" + ] + }, + "userDataConstraint": { + "transportGuarantee": "NONE" + } + } + } + ], + "filters": [ + { + "name": "ContentTypeBasedCachePreventionFilter", + "class": "org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter", + "params" : [ + {"name" : "patterns", "value" : "text/html\" ,application/json\" ,text/plain"}, + {"name" : "filterAction", "value" : "enforce"}, + {"name" : "httpHeaders", "value" : "Cache-Control: no-store, no-cache, must-revalidate, private"} + ] + }, + { + "name":"HttpHeaderSecurityFilter", + "class":"org.apache.catalina.filters.HttpHeaderSecurityFilter", + "params" : [{"name" : "hstsEnabled", "value" : "false"}] + } + + ], + "filterMappings": [ + { + "name":"HttpHeaderSecurityFilter", + "url":"*" + }, + { + "name":"ContentTypeBasedCachePreventionFilter", + "url":"*" + } + + ] +} diff --git a/modules/distribution/src/core/modules/apimstore/module.xml b/modules/distribution/src/core/modules/apimstore/module.xml new file mode 100644 index 00000000..a6483f90 --- /dev/null +++ b/modules/distribution/src/core/modules/apimstore/module.xml @@ -0,0 +1,10 @@ + + + org.wso2.carbon.apimgt.hostobjects.APIStoreHostObject + APIStore + + + org.wso2.carbon.apimgt.hostobjects.MutualAuthHostObject + MutualAuthHostObject + + diff --git a/modules/distribution/src/core/modules/encode/module.xml b/modules/distribution/src/core/modules/encode/module.xml new file mode 100755 index 00000000..15a97625 --- /dev/null +++ b/modules/distribution/src/core/modules/encode/module.xml @@ -0,0 +1,7 @@ + + + org.wso2.carbon.apimgt.hostobjects.EncodeHostObject + Encode + + + diff --git a/modules/distribution/src/core/modules/lifecycle/module.xml b/modules/distribution/src/core/modules/lifecycle/module.xml new file mode 100755 index 00000000..e063a048 --- /dev/null +++ b/modules/distribution/src/core/modules/lifecycle/module.xml @@ -0,0 +1,10 @@ + + + + diff --git a/modules/distribution/src/core/modules/lifecycle/scripts/api/api.js b/modules/distribution/src/core/modules/lifecycle/scripts/api/api.js new file mode 100755 index 00000000..4cd81d5e --- /dev/null +++ b/modules/distribution/src/core/modules/lifecycle/scripts/api/api.js @@ -0,0 +1,89 @@ +/* + * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The api namespace exposes methods to retrieve information individual states of the lifecycles + * deployed to the Governance Registry + * @namespace + * @example + * var api = require('lifecycle').api; + * var superTenantId=-1234; + * + * api.getLifecycleList(superTenantId); + * @requires store + * @requires event + * @requires utils + * @requires Packages.org.wso2.carbon.governance.lcm.util.CommonUtil + */ +var api = {}; +(function (api, core) { + var log = new Log('lifecycle'); + + /** + * Represents a class which models a lifecycle + * @constructor + * @param {Object} definiton The JSON definition of a lifecycle + * @memberOf api + */ + function Lifecycle(definiton) { + this.definition = definiton; + } + + /** + * Returns the JSON definition for the lifecycle managed by the instance + * @return {Object} Lifecycle definition + */ + Lifecycle.prototype.getDefinition = function () { + return this.definition; + }; + + /** + * Returns the name of the lifecycle + * @return {String} The name of the lifecycle + */ + Lifecycle.prototype.getName = function () { + if (!this.definition.name) { + throw 'Unable to locate name attribute in the lifecycle definition '; + } + return this.definition.name; + }; + + + /** + * Returns an instance of the Lifecycle class + * @example + * var lc = api.getLifecycle('SimpleLifeCycle',-1234); + * lc.nextStates('initial'); + * @param {String} lifecycleName The name of the lifecycle + * @param {Number} tenantDomain The tenant ID + * @return {Object} An instance of the Lifecycle class + * @throws Unable to locate lifecycle without a tenant ID + */ + api.getLifecycle = function (tenantDomain, APIProvider) { + if (!tenantDomain) { + throw 'Unable to locate lifecycle without a tenantDomain'; + } + var lcJSON = core.getJSONDef(tenantDomain,APIProvider); + + if (!lcJSON) { + log.warn('Unable to locate lifecycle for the tenant: ' + tenantDomain); + return null; //TODO: This should throw an exception + } + return new Lifecycle(lcJSON); + }; + + +}(api, core)); diff --git a/modules/distribution/src/core/modules/lifecycle/scripts/core/core.js b/modules/distribution/src/core/modules/lifecycle/scripts/core/core.js new file mode 100755 index 00000000..bf224cba --- /dev/null +++ b/modules/distribution/src/core/modules/lifecycle/scripts/core/core.js @@ -0,0 +1,158 @@ + +/* + * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The core namespace contains methods that load the lifecycle definitions from the registry + * @namespace + * @example + * var core = require('lifecycle').core; + * core.init(); //Should only be called once in the lifecycle of an app.Ideally in an init script + * @requires store + * @requires event + * @requires utils + * @requires Packages.org.wso2.carbon.governance.lcm.util.CommonUtil + */ +var core = {}; +(function(core) { + var CommonUtil = Packages.org.wso2.carbon.governance.lcm.util.CommonUtil; + var LC_MAP = 'lc.map'; + var EMPTY = ''; + var log = new Log('lifecycle'); + var addRawLifecycle = function(lifecycleName, content, tenantId) { + var lcMap = core.configs(tenantId); + if (!lcMap.raw) { + lcMap.raw = {}; + } + lcMap.raw[lifecycleName] = new String(content); + }; + var addJsonLifecycle = function(lifecycleName, definition, tenantId) { + var lcMap = core.configs(tenantId); + if (!lcMap.json) { + lcMap.json = {}; + } + lcMap.json[lifecycleName] = definition; + }; + + /** + * Converts array references to properties.The JSON conversion produces some properties which need to be accessed + * using array indexes. + * @param {Object} obj Unaltered JSON object + * @return {Object} JSON object with resolved array references + */ + var transformJSONLifecycle = function(obj) { + obj.configuration = obj.configuration[0]; + obj.configuration.lifecycle = obj.configuration.lifecycle[0]; + obj.configuration.lifecycle.scxml = obj.configuration.lifecycle.scxml[0]; + var states = obj.configuration.lifecycle.scxml.state; + var stateObj = {}; + var state; + for (var index = 0; index < states.length; index++) { + state = states[index]; + stateObj[state.id.toLowerCase()] = state; + if (stateObj[state.id.toLowerCase()].datamodel) { + stateObj[state.id.toLowerCase()].datamodel = stateObj[state.id.toLowerCase()].datamodel[0]; + } + } + obj.configuration.lifecycle.scxml.state = stateObj; + return obj; + }; + /* + Creates an xml file from the contents of an Rxt file + @rxtFile: An rxt file + @return: An xml file + */ + var createXml = function(content) { + var fixedContent = content.replace('', EMPTY).replace('', EMPTY); + return new XML(fixedContent); + }; + var parseLifeycle = function(content) { + var ref = require('utils').xml; + var obj = ref.convertE4XtoJSON(createXml(content)); + return obj; + }; + var loadLifecycles = function(tenantDomain,APIProvider) { + + //Obtain the definition + content = APIProvider.getLifecycleConfiguration(tenantDomain); + //Store the raw lifecycle + addRawLifecycle("APILifeCycle", content, tenantDomain); + //Parse the raw lifecycle definition into a json + var jsonLifecycle = parseLifeycle(new String(content)); + //Correct any array references + jsonLifecycle = transformJSONLifecycle(jsonLifecycle); + //Store the json lifecycle definition + addJsonLifecycle("APILifeCycle", jsonLifecycle, tenantDomain); + if(log.isDebugEnabled()){ + log.debug('Found lifecycle: ' + jsonLifecycle.name + ' tenant: ' + tenantDomain); + } + + }; + var init = function(tenantDomain,APIProvider) { + loadLifecycles(tenantDomain,APIProvider); + }; + core.force = function(tenantDomain,APIProvider) { + init(tenantDomain,APIProvider); + }; + + /** + * Returns the lifecycle map which is stored in the application context + * The map is maintained on a per user basis + * @param {Number} tenantId The tenant ID + * @return {Object} The lifecycle map + */ + core.configs = function(tenantDomain) { + var lcMap = application.get(LC_MAP); + if (!lcMap) { + log.debug('Creating lcMap in the application context'); + lcMap = {}; + application.put(LC_MAP, lcMap); + } + if (!lcMap[tenantDomain]) { + log.debug('Creating lcMap for the tenant: ' + tenantDomain + ' in application context'); + lcMap[tenantDomain] = {}; + } + return lcMap[tenantDomain]; + }; + + /** + * Returns the JSON definition of the provided lifecycle for the given tenant + * @param {Number} tenantDomain The tenant Domain + * @return {Object} The JSON definitin of the lifecycle + * @throws There is no lifcycle information for the tenant + * @throws There is no json lifecycle information for the lifecycle of the tenant + */ + core.getJSONDef = function(tenantDomain,APIProvider) { + var lifecycleName='APILifeCycle'; + var lcMap = core.configs(tenantDomain); + if (!lcMap) { + throw 'There is no lifecycle information for the tenant: ' + tenantDomain; + } + //if (!lcMap.json) { + // throw 'There is no json lifecycle information for the lifecycle of tenant: ' + tenantDomain; + //} + if (!lcMap.json) { + core.force(tenantDomain,APIProvider); + lcMap = core.configs(tenantDomain); + if (!lcMap.json[lifecycleName]){ + throw 'There is no lifecycle information for '; + } + } + return lcMap.json[lifecycleName]; + }; + + +}(core)); diff --git a/modules/distribution/src/core/modules/sso/module.xml b/modules/distribution/src/core/modules/sso/module.xml new file mode 100755 index 00000000..23cde8c2 --- /dev/null +++ b/modules/distribution/src/core/modules/sso/module.xml @@ -0,0 +1,10 @@ + + + + org.wso2.carbon.hostobjects.sso.SAMLSSORelyingPartyObject + SSORelyingParty + + \ No newline at end of file diff --git a/modules/distribution/src/core/modules/sso/scripts/sso.client.js b/modules/distribution/src/core/modules/sso/scripts/sso.client.js new file mode 100644 index 00000000..73b551d7 --- /dev/null +++ b/modules/distribution/src/core/modules/sso/scripts/sso.client.js @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/** + * Following module act as a client to create a saml request and also to + * unwrap and return attributes of a returning saml response + * @type {{}} + */ + +var client = {}; + +(function (client) { + + var Util = Packages.org.wso2.store.sso.common.util.Util, + carbon = require('carbon'), + log = new Log(); + + /** + * obtains an encoded saml response and return a decoded/unmarshalled saml obj + * @param samlResp + * @return {*} + */ + client.getSamlObject = function (samlResp) { + var marshalledResponse; + try { + var decodedResp = Util.decode(samlResp); + marshalledResponse = Util.unmarshall(decodedResp); + } catch (e) { + log.error('Unable to unmarshall SAML response'); + log.error(e); + } + return marshalledResponse; + + }; + + /** + * validating the signature of the response saml object + */ + client.validateSignature = function (samlObj, config) { + var tDomain = Util.getDomainName(samlObj); + var tId = carbon.server.tenantId({domain: tDomain}); + if (tId != carbon.server.superTenant.tenantId) { + var identityTenantUtil = Packages.org.wso2.carbon.identity.core.util.IdentityTenantUtil; + identityTenantUtil.initializeRegistry(tId,tDomain); + } + return Util.validateSignature(samlObj, + config.KEY_STORE_NAME, config.KEY_STORE_PASSWORD, config.IDP_ALIAS, tId, tDomain); + }; + + /** + * Checking if the request is a logout call + */ + client.isLogoutRequest = function (samlObj) { + return samlObj instanceof Packages.org.opensaml.saml2.core.LogoutRequest; + }; + + /** + * Checking if the request is a logout call + */ + client.isLogoutResponse = function (samlObj) { + return samlObj instanceof Packages.org.opensaml.saml2.core.LogoutResponse; + }; + + /** + * getting url encoded saml authentication request + * @param issuerId + */ + client.getEncodedSAMLAuthRequest = function (issuerId) { + return Util.encode( + Util.marshall( + new Packages.org.wso2.store.sso.common.builders.AuthReqBuilder().buildAuthenticationRequest(issuerId) + )); + }; + + /** + * get url encoded saml logout request + */ + client.getEncodedSAMLLogoutRequest = function (user, sessionIndex, issuerId) { + return Util.encode( + Util.marshall( + new Packages.org.wso2.store.sso.common.builders.LogoutRequestBuilder().buildLogoutRequest(user, sessionIndex, + Packages.org.wso2.store.sso.common.constants.SSOConstants.LOGOUT_USER, + issuerId))); + }; + + /** + * Reads the returning SAML login response and populates a session info object + */ + client.decodeSAMLLoginResponse = function (samlObj, samlResp, sessionId) { + var samlSessionObj = { + // sessionId, loggedInUser, sessionIndex, samlToken + }; + + if (samlObj instanceof Packages.org.opensaml.saml2.core.Response) { + + var assertions = samlObj.getAssertions(); + + // extract the session index + if (assertions != null && assertions.size() > 0) { + var authenticationStatements = assertions.get(0).getAuthnStatements(); + var authnStatement = authenticationStatements.get(0); + if (authnStatement != null) { + if (authnStatement.getSessionIndex() != null) { + samlSessionObj.sessionIndex = authnStatement.getSessionIndex(); + } + } + } + + // extract the username + if (assertions != null && assertions.size() > 0) { + var subject = assertions.get(0).getSubject(); + if (subject != null) { + if (subject.getNameID() != null) { + samlSessionObj.loggedInUser = subject.getNameID().getValue(); + } + } + } + samlSessionObj.sessionId = sessionId; + samlSessionObj.samlToken = samlResp; + } + + return samlSessionObj; + }; + + /** + * This method is to get the session index when a single logout happens + * The IDP sends a logout request to the ACS with the session index, so that + * the app can invalidate the associated HTTP Session + */ + client.decodeSAMLLogoutRequest = function (samlObj) { + var sessionIndex = null; + + if (samlObj instanceof org.opensaml.saml2.core.LogoutRequest) { + var sessionIndexes = samlObj.getSessionIndexes(); + if (sessionIndexes != null && sessionIndexes.size() > 0) { + sessionIndex = sessionIndexes.get(0).getSessionIndex(); + } + } + + return sessionIndex; + + }; + + /** + * The method is used to encapsulate all of the validations that + * should be performed on a SAML Response + */ + client.validateSamlResponse = function(samlObj, props, keyStoreProps) { + props = props || {}; + var Util = Packages.org.wso2.store.sso.common.util.Util; + var propList = createProperties(props); + var DEFAULT_TO_TRUE = true; + var DEFAULT_TO_FALSE = false; + var isValid = true; //Assume all validations will be succeed + var isAssertionValidityPeriodChecked = props.validateAssertionValidityPeriod ? props.validateAssertionValidityPeriod : DEFAULT_TO_FALSE; + var isAudienceRestrictionChecked = props.validateAudienceRestriction ? props.validateAudienceRestriction : DEFAULT_TO_FALSE; + var isAssertionSigningEnabled = props.assertionSigningEnabled ? props.assertionSigningEnabled : DEFAULT_TO_FALSE; + var isResponseSigningEnabled = props.responseSigningEnabled ? props.responseSigningEnabled : DEFAULT_TO_FALSE; + + //Step #1: Validate the token validity period + if (isAssertionValidityPeriodChecked) { + isValid = Util.validateAssertionValidityPeriod(samlObj, propList); + } + + //Break processing if the assertion validity period has expired + if (!isValid) { + return isValid; + } + //Step #2: Validate the assertion audience + if (isAudienceRestrictionChecked) { + isValid = Util.validateAudienceRestriction(samlObj, propList); + } + //Break processing if the audience restriction check fails + if (!isValid) { + return isValid; + } + + //Step #3: Validate the response signature + if (isResponseSigningEnabled) { + isValid = client.validateSignature(samlObj, keyStoreProps); + } + + //Break processing if the signature validation fails + if (!isValid) { + return isValid; + } + + //Step #4: Perform assertion signature verification + if (isAssertionSigningEnabled) { + isValid = callValidateAssertionSignature(samlObj, keyStoreProps); + } + return isValid; + }; + + /** + * getting url encoded signed saml authentication request + */ + client.getEncodedSignedSAMLAuthRequest = function (issuerId, destination, acsUrl, isPassive, tenantId, tenantDomain, nameIdPolicy) { + return Util.encode( + Util.marshall( + new Packages.org.jaggeryjs.modules.sso.common.builders.AuthReqBuilder().buildAuthenticationRequest(issuerId, destination, acsUrl, + isPassive, tenantId, tenantDomain, nameIdPolicy) + )); + }; + + /** + * get url encoded signed saml logout request + */ + client.getEncodedSignedSAMLLogoutRequest = function (user, sessionIndex, issuerId, tenantId, tenantDomain, destination, nameIdFormat) { + return Util.encode( + Util.marshall( + new Packages.org.jaggeryjs.modules.sso.common.builders.LogoutRequestBuilder().buildLogoutRequest(user, sessionIndex, + Packages.org.wso2.store.sso.common.constants.SSOConstants.LOGOUT_USER, + issuerId))); + + }; + + /** + * A utility method used to convert a JSON object to + * a properties object + */ + function createProperties(props) { + var javaPropertyList = new java.util.Properties(); + Object.keys(props).forEach(function(key) { + if (props.hasOwnProperty(key)) { + javaPropertyList.setProperty(key, props[key]); + } + }); + return javaPropertyList; + } + /** + * Invokes the validateAssertionSignature method by first + * resolving tenant details + */ + function callValidateAssertionSignature(samlObj, config) { + var Util = Packages.org.wso2.store.sso.common.util.Util; + var tDomain, tId; + var carbon = require('carbon'); + if (config.USE_ST_KEY) { + tDomain = carbon.server.superTenant.domain; + tId = carbon.server.superTenant.tenantId; + } else { + tDomain = Util.getDomainName(samlObj); + tId = carbon.server.tenantId({ + domain: tDomain + }); + } + return Util.validateAssertionSignature(samlObj, config.KEY_STORE_NAME, config.KEY_STORE_PASSWORD, config.IDP_ALIAS, tId, tDomain); + } + +}(client)); \ No newline at end of file diff --git a/modules/distribution/src/core/modules/tenantmanager/module.xml b/modules/distribution/src/core/modules/tenantmanager/module.xml new file mode 100755 index 00000000..1afbf025 --- /dev/null +++ b/modules/distribution/src/core/modules/tenantmanager/module.xml @@ -0,0 +1,7 @@ + + + org.wso2.carbon.apimgt.hostobjects.TenantManagerHostObject + TenantManager + + + diff --git a/modules/distribution/src/core/modules/utils/module.xml b/modules/distribution/src/core/modules/utils/module.xml new file mode 100755 index 00000000..98050dee --- /dev/null +++ b/modules/distribution/src/core/modules/utils/module.xml @@ -0,0 +1,6 @@ + + + diff --git a/modules/distribution/src/core/modules/utils/scripts/xml/xml.js b/modules/distribution/src/core/modules/utils/scripts/xml/xml.js new file mode 100755 index 00000000..7caefe9d --- /dev/null +++ b/modules/distribution/src/core/modules/utils/scripts/xml/xml.js @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +var xml = {}; + +(function () { + + var log=new Log('util.xml') + + /* + The method is used to create a JSON object using + an xml object. + @xmlElement: An xml element object to be processed + @return: A pseudo object containing the properties of the + xml element. + */ + var createJSONObject = function (xmlElement) { + + var pseudo = {}; + + //Extract all attributes + var attributes = xmlElement.@*; + + //Fill the pseudo object with the attributes of the element + for (var attributeKey in attributes) { + var attribute = attributes[attributeKey]; + pseudo[attribute.localName()] = attribute.toString(); + } + + return pseudo; + }; + + /* + The function converts an E4X Xml object to a JSON object + This function has been adapted from the work of Oleg Podsechin available at + https://gist.github.com/olegp/642667 + It uses a slightly modified version of his algorithm , therefore + all credit should be attributed to Oleg Podsechin. + IMPORTANT: + 1. It does not create a 1..1 mapping due to the differences + between Xml and JSON.It is IMPORTANT that you verify the structure + of the object generated before using it. + 2. The input xml object must not contain the xml header information + This is a known bug 336551 (Mozilla Developer Network) + Source: https://developer.mozilla.org/en/docs/E4X + Please remove the header prior to sending the xml object for processing. + @root: A starting element in an E4X Xml object + @return: A JSON object mirroring the provided Xml object + */ + var recursiveConvertE4XtoJSON = function (root) { + + log.debug('Root: ' + root.localName()); + + //Obtain child nodes + var children = root.*; + + //The number of children + var numChildren = children.length(); + + //No children + if (numChildren == 0) { + + //Extract contents + return createJSONObject(root); + } + else { + + //Create an empty object + var rootObject = createJSONObject(root); + + //Could be multiple children + for (var childElementKey in children) { + + var child = children[childElementKey]; + + log.debug('Examining child: ' + child.localName()); + + //If the child just contains a single value then stop + if (child.localName() == undefined) { + + log.debug('Child is undefined: ' + child.toString()); + + //Change the object to just a key value pair + rootObject[root.localName()] = child.toString(); + return rootObject; + } + + //Make a recursive call to construct the child element + var createdObject = recursiveConvertE4XtoJSON(child); + + log.debug('Converted object: ' + stringify(createdObject)); + + //Check if the root object has the property + if (rootObject.hasOwnProperty(child.localName())) { + + log.debug('key: ' + child.localName() + ' already present.'); + rootObject[child.localName()].push(createdObject); + } + else { + + log.debug('key: ' + child.localName() + ' not present.'); + rootObject[child.localName()] = []; + rootObject[child.localName()].push(createdObject); + + } + } + + log.debug('root: ' + root.localName()); + + return rootObject; + } + }; + + /** + * The function is used to convert an E4X xml to JSON + * @param root + */ + xml.convertE4XtoJSON = function (root) { + return recursiveConvertE4XtoJSON(root); + }; + + +}()); diff --git a/modules/distribution/src/core/release-notes.html b/modules/distribution/src/core/release-notes.html new file mode 100644 index 00000000..f4b4e774 --- /dev/null +++ b/modules/distribution/src/core/release-notes.html @@ -0,0 +1,244 @@ +Release Notes - WSO2 IOT Server - Version 3.0.0 + +

Bug +

+
    +
  • [IOTS-181] - The Graphs are rendered incorrectly +
  • +
  • [IOTS-182] - The units are missing from Y axis +
  • +
  • [IOTS-222] - INSTALL.txt needs to be updated +
  • +
  • [IOTS-262] - APIThrottleHandler Unable to find throttling info continuously printed. +
  • +
  • [IOTS-4] - Fresh Pack - Table Not Found: X1234_DeviceGRAVITYSummaryData +
  • +
  • [IOTS-115] - Edit Role: The domain name can be typed +
  • +
  • [IOTS-116] - Edit Role: The user is unable to change name +
  • +
  • [IOTS-119] - When existing role name is used to create a role no validation message is shown +
  • +
  • [IOTS-128] - Previously selected permission tree is shown for another admin user +
  • +
  • [IOTS-138] - Remove the admin-device-access role permission +
  • +
  • [IOTS-144] - Operations Log: the data doesn't load +
  • +
  • [IOTS-170] - Proper validation is not fired when an invalid domain is used to login +
  • +
  • [IOTS-179] - Users who register from APIM Store can login to IOTS and enroll devices +
  • +
  • [IOTS-190] - Multi Tenancy: error 500 loads on logging for the first time. +
  • +
  • [IOTS-198] - wso2.anonymous.user in API-Store does not have permission to access custom device types API +
  • +
  • [IOTS-202] - OAuth2BasedMQTTAuthenticator errors thrown if server is bounced while MQTT clients are publishing +
  • +
  • [IOTS-226] - MqttException thrown when a device is pushing erroneous events +
  • +
  • [IOTS-227] - When a device is publishing erroneous events at a high rate over MQTT other device events are dropped +
  • +
  • [IOTS-244] - MQTT clients can authenticate/authorize using tokens generated with credentials not belonging to them +
  • +
  • [IOTS-255] - [External APIM] https-ep in deviceConfig.properties is not populated with APIM details +
  • +
  • [IOTS-256] - Errors thrown at HTTP Gateway profile startup +
  • +
  • [IOTS-257] - transports not bound for HTTP Gateway profile node +
  • +
  • [IOTS-259] - ERROR - js {} thrown from devicemgt +
  • +
  • [IOTS-260] - Error loading properties from a file printed due to missing properties files +
  • +
  • [IOTS-269] - [Intermittent] Force shutdown fails with errors +
  • +
  • [IOTS-270] - Arduino device type control events are lost if the server is restarted +
  • +
  • [IOTS-274] - [IOT] /oauth2/token cannot be called directly +
  • +
  • [IOTS-277] - Accessing swagger definition failed with CNF +
  • +
  • [IOTS-315] - Missing the start-all.bat and stop-all.bat files +
  • +
  • [IOTS-339] - Error occurred while registering device management plugin 'android' +
  • +
  • [IOTS-369] - Add missing grant types in identity.xml +
  • +
  • [IOTS-378] - Windows Device location is not showing in Device view page +
  • +
  • [IOTS-391] - Notification Pane position issue +
  • +
  • [IOTS-18] - Need to add refresh token generation in Android Sense agent. +
  • +
  • [IOTS-103] - Grouping: need a mechanisam to add devices to a group from the grouping page +
  • +
  • [IOTS-108] - When user shares device policies fails with 401 +
  • +
  • [IOTS-118] - Change Role permissions: Selecting the rights need to be synced correctly +
  • +
  • [IOTS-120] - Last name should allow space in-between when creating / editing the name +
  • +
  • [IOTS-151] - Server startup fails when configured to use Oracle +
  • +
  • [IOTS-168] - A role with permission assigned to a user is not functioning +
  • +
  • [IOTS-173] - Same device can be added multiple times to the same group +
  • +
  • [IOTS-178] - User cannot login to APIM store with IOT credentials +
  • +
  • [IOTS-183] - Some buttons are not visible +
  • +
  • [IOTS-193] - Policies: User is unable to add a policy +
  • +
  • [IOTS-200] - IllegalTransactionStateException when trying to add a new policy +
  • +
  • [IOTS-204] - Duplicate log4j.properties file in CARBON_HOME/repository +
  • +
  • [IOTS-212] - [External APIM] NPE thrown when downloading virtual fire alarm, rasp pi and arduino agents +
  • +
  • [IOTS-218] - Group: when a device is removed from the group the device is completely removed from the devices list +
  • +
  • [IOTS-232] - Multi Tenancy: error 500 loads when user access the system +
  • +
  • [IOTS-236] - Sharing a group fails silently if there is group with the same name and no roles are selected +
  • +
  • [IOTS-239] - SSO failing due to getting the access token from APIM +
  • +
  • [IOTS-254] - samples-deployer build fails with missing dependency +
  • +
  • [IOTS-263] - [UI] Same device can be added to a group multiple times +
  • +
  • [IOTS-344] - Need to remove Android IOT gadget from IoT Core Dashboard +
  • +
  • [IOTS-346] - Cannot view devices when registered as a new user +
  • +
  • [IOTS-356] - When UI is configured to use Gateway, Cannot Login +
  • +
  • [IOTS-365] - Make Policy Management to be part of device management +
  • +
  • [IOTS-366] - Dynamic values for push notification needs to have default values +
  • +
  • [IOTS-137] - -Detup fails, logging exceptions +
  • +
  • [IOTS-151] - Server startup fails when configured to use Oracle +
  • +
  • [IOTS-160] - Although two roles are shown in roles section several roles are shown when assigning to users +
  • +
  • [IOTS-172] - The db scripts are not executed with -Dsetup +
  • +
  • [IOTS-176] - Creating a New Device Type - device-deployer build failed +
  • +
  • [IOTS-177] - Device types fail to register to IOTS when configured with Oracle db +
  • +
  • [IOTS-184] - Windows startup error on hadoop +
  • +
  • [IOTS-195] - Single sign-on(SSO) cannot enable Between devicemgt and DS +
  • +
  • [IOTS-201] - DashboardDeployer Gadget directory copying to Wrong path +
  • +
  • [IOTS-316] - Publisher and store apps are not working +
  • +
  • [IOTS-319] - Implement enrolment functionality for AndroidSens +
  • +
  • [IOTS-325] - Unable to delete policies associated with a group +
  • +
  • [IOTS-330] - Policy not added for Virtual firealarm +
  • +
  • [IOTS-332] - Devices listing page doesn't honor analyticsEnabled and groupingEnabled configs +
  • +
  • [IOTS-333] - Devices listing page doesn't honor analyticsEnabled and groupingEnabled configs +
  • +
  • [IOTS-335] - View Dashboard Permissions missing in the role permission tree +
  • +
  • [IOTS-337] - Permissions (except device-mgt permissions) added through carbon console gets removed when adding permissions through deviceMgt UI +
  • +
  • [IOTS-340] - NPE for username thrown on Broker +
  • +
+ +

Task +

+
    +
  • [IOTS-292] - Migrating to synapse gateway +
  • +
  • [IOTS-381] - device type listing fails when only windows and android features are installed +
  • +
  • [IOTS-363] - Windows and IOS enrollment related UI page Logos (Wso2 EMM) should be changed into wso2 IOT +
  • +
  • [IOTS-307] - Stabilize Android Sense + Integrating with new dashboard +
  • +
+ +

Improvement +

+
    +
  • [IOTS-145] - Remove the second confirmation message to remove a user or role +
  • +
  • [IOTS-282] - Distributed setup - device-key-manager node gives 405 when try to access /devicemgt +
  • +
  • [IOTS-370] - Move adapter configs as global configs +
  • +
  • [IOTS-374] - Updating font wso2 to newest version +
  • +
  • [IOTS-379] - Modal markup fixes +
  • +
  • [IOTS-382] - Windows 10 Reboot operation support +
  • +
  • [IOTS-383] - Modal opening for multiple times +
  • +
  • [IOTS-390] - Missing action buttons on details views +
  • +
  • [IOTS-392] - Inconsistent notification pane messege +
  • +
  • [IOTS-394] - Data table selection issue +
  • +
  • [IOTS-397] - Advance Search for devices view +
  • +
  • [IOTS-171] - Register User Form: username message +
  • +
  • [IOTS-187] - The UI for Role creation should have an option for the user to tick if he wants to have the group name prefix added +
  • +
  • [IOTS-271] - Viewing Group Details +
  • +
  • [IOTS-273] - about.html is for UES +
  • +
  • [IOTS-283] - Distributed Setup - mqtt profile - Class not found error +
  • +
  • [IOTS-306] - Refactoring permission to scope mapping +
  • +
  • [IOTS-348] - OOTB H2 needs to be shared with DAS and Core +
  • +
  • [IOTS-351] - Windows 10 Device Location support +
  • +
  • [IOTS-352] - CDMF Android agent must use the new gateway DCR endpoints +
  • +
  • [IOTS-362] - UI configurations need to refactor +
  • +
  • [IOTS-368] - Federated login page should be compatible with Windows 10 Laptop +
  • +
  • [IOTS-334] - Add three buttons to improve device enrollment screens +
  • +
  • [IOTS-336] - The UI to download the Android Agent uses the old EMM UI +
  • +
  • [IOTS-338] - Windows 10 MDM support +
  • +
  • [IOTS-341] - Re-word message when selecting roles for group sharing +
  • +
  • [IOTS-342] - Re-word the message for adding users to the role when sharing a group with users +
  • +
+ + +

Sub-task +

+
    +
  • [IOTS-354] - Test Android with Gateway +
  • +
  • [IOTS-355] - Test Windows with Gateway +
  • +
  • [IOTS-359] - Re-Enable Integration tests for the new IOT pack. +
  • +
  • [IOTS-360] - Modify the existing tests and make them working for the current IOT pack. +
  • +
\ No newline at end of file diff --git a/modules/distribution/src/core/resources/appm-tenant-conf.xml b/modules/distribution/src/core/resources/appm-tenant-conf.xml new file mode 100644 index 00000000..377b7d54 --- /dev/null +++ b/modules/distribution/src/core/resources/appm-tenant-conf.xml @@ -0,0 +1,25 @@ + + + + + + + false + false + + + + + mobileapp + + + diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/db2.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/db2.sql new file mode 100644 index 00000000..bb56b48c --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/db2.sql @@ -0,0 +1,1304 @@ +-- Start of IDENTITY Tables-- +CREATE TABLE IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR (20) NOT NULL, + PRIMARY KEY (PRODUCT_NAME)) +/ +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server') +/ +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL, + CONSUMER_KEY VARCHAR (255) NOT NULL, + CONSUMER_SECRET VARCHAR (512), + USERNAME VARCHAR (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR (255), + OAUTH_VERSION VARCHAR (128), + CALLBACK_URL VARCHAR (1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE + / +CREATE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIGGER NO CASCADE BEFORE INSERT ON IDN_OAUTH_CONSUMER_APPS +REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) + = (NEXTVAL FOR IDN_OAUTH_CONSUMER_APPS_SEQUENCE); + END +/ +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR (512) NOT NULL, + REQUEST_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR (1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR (128), + OAUTH_VERIFIER VARCHAR (512), + AUTHZ_USER VARCHAR (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR (512) NOT NULL, + ACCESS_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255) NOT NULL, + ACCESS_TOKEN VARCHAR (255) NOT NULL, + REFRESH_TOKEN VARCHAR (255), + CONSUMER_KEY_ID INTEGER NOT NULL, + AUTHZ_USER VARCHAR (100) NOT NULL, + TENANT_ID INTEGER NOT NULL, + USER_DOMAIN VARCHAR (50) NOT NULL, + USER_TYPE VARCHAR (25) NOT NULL, + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR (32) NOT NULL, + TOKEN_STATE VARCHAR (25) DEFAULT 'ACTIVE' NOT NULL, + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE' NOT NULL, + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID)) +/ + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE) +/ + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED) +/ + +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255) NOT NULL, + AUTHORIZATION_CODE VARCHAR (512) NOT NULL, + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR (1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100) NOT NULL, + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR (50) NOT NULL, + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR(255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ + +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255) NOT NULL, + TOKEN_SCOPE VARCHAR (60) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER NOT NULL, + SCOPE_KEY VARCHAR (100) NOT NULL, + NAME VARCHAR (255) NULL, + DESCRIPTION VARCHAR (512) NULL, + TENANT_ID INTEGER DEFAULT 0 NOT NULL, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID)) +/ +CREATE SEQUENCE IDN_OAUTH2_SCOPE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDN_OAUTH2_SCOPE_TRIGGER NO CASCADE BEFORE INSERT ON IDN_OAUTH2_SCOPE +REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL + +BEGIN ATOMIC + + SET (NEW.SCOPE_ID) + = (NEXTVAL FOR IDN_OAUTH2_SCOPE_SEQUENCE); + +END +/ +CREATE TABLE IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR (255) NOT NULL, + SCOPE_ID INTEGER NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE +)/ + +CREATE TABLE IDN_SCIM_GROUP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_SCIM_GROUP_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDN_SCIM_GROUP_TRIGGER NO CASCADE BEFORE INSERT ON IDN_SCIM_GROUP +REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL + +BEGIN ATOMIC + + SET (NEW.ID) + = (NEXTVAL FOR IDN_SCIM_GROUP_SEQUENCE); + +END +/ +CREATE TABLE IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0 NOT NULL, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID)) +/ +CREATE TABLE IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0 NOT NULL, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL)) +/ +CREATE TABLE IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE)) +/ +CREATE TABLE IDN_STS_STORE ( + ID INTEGER NOT NULL, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_STS_STORE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDN_STS_STORE_TRIGGER NO CASCADE BEFORE INSERT ON IDN_STS_STORE +REFERENCING NEW AS NEW FOR EACH ROW MODE DB2SQL + +BEGIN ATOMIC + + SET (NEW.ID) + = (NEXTVAL FOR IDN_STS_STORE_SEQUENCE); + +END +/ +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234 NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY)) +/ +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234 NOT NULL, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA)) +/ +CREATE TABLE IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +) +/ + +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED BIGINT NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +) +/ +CREATE TABLE SP_APP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_APP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_APP_TRIG NO CASCADE + BEFORE INSERT + ON SP_APP + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_APP_SEQ); + END +/ +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID) +/ + + +CREATE TABLE SP_METADATA ( + ID INTEGER NOT NULL, + SP_ID INTEGER NOT NULL, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE SP_METADATA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_METADATA_TRIG NO CASCADE + BEFORE INSERT + ON SP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_METADATA_SEQ); + END +/ + +CREATE TABLE SP_INBOUND_AUTH ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_INBOUND_AUTH_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_INBOUND_AUTH_TRIG NO CASCADE + BEFORE INSERT + ON SP_INBOUND_AUTH + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_INBOUND_AUTH_SEQ); + END +/ +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_AUTH_STEP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL , + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_AUTH_STEP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_AUTH_STEP_TRIG NO CASCADE + BEFORE INSERT + ON SP_AUTH_STEP + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_AUTH_STEP_SEQ); + END +/ +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID)) +/ +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_CLAIM_MAPPING_TRIG NO CASCADE + BEFORE INSERT + ON SP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_CLAIM_MAPPING_SEQ); + END +/ +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_ROLE_MAPPING ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_ROLE_MAPPING_TRIG NO CASCADE + BEFORE INSERT + ON SP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_ROLE_MAPPING_SEQ); + END +/ +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_REQ_PATH_AUTH_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_REQ_PATH_AUTH_TRIG NO CASCADE + BEFORE INSERT + ON SP_REQ_PATH_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_REQ_PATH_AUTH_SEQ); + END +/ +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_PROV_CONNECTOR_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER SP_PROV_CONNECTOR_TRIG NO CASCADE + BEFORE INSERT + ON SP_PROVISIONING_CONNECTOR + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR SP_PROV_CONNECTOR_SEQ); + END +/ +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE BLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)) +/ +CREATE SEQUENCE IDP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_TRIG NO CASCADE + BEFORE INSERT + ON IDP + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_SEQ); + END +/ + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost')/ + +CREATE TABLE IDP_ROLE ( + ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + ROLE VARCHAR(254) NOT NULL, + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_ROLE_TRIG NO CASCADE + BEFORE INSERT + ON IDP_ROLE + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_ROLE_SEQ); + END +/ +CREATE TABLE IDP_ROLE_MAPPING ( + ID INTEGER NOT NULL, + IDP_ROLE_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + USER_STORE_ID VARCHAR (253) NOT NULL, + LOCAL_ROLE VARCHAR(253) NOT NULL, + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_ROLE_MAPPING_TRIG NO CASCADE + BEFORE INSERT + ON IDP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_ROLE_MAPPING_SEQ); + END +/ +CREATE TABLE IDP_CLAIM ( + ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + CLAIM VARCHAR(254) NOT NULL, + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_CLAIM_TRIG NO CASCADE + BEFORE INSERT + ON IDP_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_CLAIM_SEQ); + END +/ +CREATE TABLE IDP_CLAIM_MAPPING ( + ID INTEGER NOT NULL, + IDP_CLAIM_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + LOCAL_CLAIM VARCHAR(253) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_CLAIM_MAPPING_TRIG NO CASCADE + BEFORE INSERT + ON IDP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_CLAIM_MAPPING_SEQ); + END +/ +CREATE TABLE IDP_AUTHENTICATOR ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_AUTHENTICATOR_TRIG NO CASCADE + BEFORE INSERT + ON IDP_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_AUTHENTICATOR_SEQ); + END +/ + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso')/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties')/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests')/ + +CREATE TABLE IDP_METADATA ( + ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255), + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ + +CREATE SEQUENCE IDP_METADATA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_METADATA_TRIG NO CASCADE + BEFORE INSERT + ON IDP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_METADATA_SEQ); + END +/ + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout')/ +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout')/ + +CREATE TABLE IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_PROP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_AUTHENTICATOR_PROP_TRIG NO CASCADE + BEFORE INSERT + ON IDP_AUTHENTICATOR_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_AUTHENTICATOR_PROP_SEQ); + END +/ + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0')/ +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0')/ + +CREATE TABLE IDP_PROVISIONING_CONFIG ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_CONFIG_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_PROV_CONFIG_TRIG NO CASCADE + BEFORE INSERT + ON IDP_PROVISIONING_CONFIG + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_PROV_CONFIG_SEQ); + END +/ +CREATE TABLE IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PROVISIONING_CONFIG_ID INTEGER NOT NULL, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_CONFIG_PROP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_PROV_CONFIG_PROP_TRIG NO CASCADE + BEFORE INSERT + ON IDP_PROV_CONFIG_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_PROV_CONFIG_PROP_SEQ); + END +/ +CREATE TABLE IDP_PROVISIONING_ENTITY ( + ID INTEGER NOT NULL, + PROVISIONING_CONFIG_ID INTEGER NOT NULL, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_ENTITY_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_PROV_ENTITY_TRIG NO CASCADE + BEFORE INSERT + ON IDP_PROVISIONING_ENTITY + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_PROV_ENTITY_SEQ); + END +/ +CREATE TABLE IDP_LOCAL_CLAIM ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + IDP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_LOCAL_CLAIM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDP_LOCAL_CLAIM_TRIG NO CASCADE + BEFORE INSERT + ON IDP_LOCAL_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDP_LOCAL_CLAIM_SEQ); + END +/ +CREATE TABLE IDN_ASSOCIATED_ID ( + ID INTEGER NOT NULL, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ + +CREATE SEQUENCE IDN_ASSOCIATED_ID_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE TRIGGER IDN_ASSOCIATED_ID_TRIG NO CASCADE + BEFORE INSERT + ON IDN_ASSOCIATED_ID + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR IDN_ASSOCIATED_ID_SEQ); + END +/ +CREATE TABLE IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)) +/ +CREATE TABLE FIDO_DEVICE_STORE ( + TENANT_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)) +/ + +CREATE TABLE WF_REQUEST ( + UUID VARCHAR (45) NOT NULL, + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER NOT NULL DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID)) +/ + +CREATE TABLE WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45) NOT NULL, + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + TENANT_ID INTEGER NOT NULL DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID)) +/ + +CREATE TABLE WF_WORKFLOW( + ID VARCHAR (45) NOT NULL, + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER NOT NULL DEFAULT -1, + PRIMARY KEY (ID)) +/ + +CREATE TABLE WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL, + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE SEQUENCE WF_WORKFLOW_ASSOCIATION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE TRIGGER WF_WORKFLOW_ASSOCIATION_TRIG NO CASCADE + BEFORE INSERT + ON WF_WORKFLOW_ASSOCIATION + REFERENCING NEW AS NEW + FOR EACH ROW MODE DB2SQL + BEGIN ATOMIC + SET (NEW.ID) = (NEXTVAL FOR WF_WORKFLOW_ASSOCIATION_SEQ); + END +/ + +CREATE TABLE WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45) NOT NULL, + PARAM_NAME VARCHAR (45) NOT NULL, + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45) NOT NULL, + PARAM_HOLDER VARCHAR (45) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45) NOT NULL, + ENTITY_NAME VARCHAR (255) NOT NULL, + ENTITY_TYPE VARCHAR (50) NOT NULL, + TENANT_ID INTEGER NOT NULL DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45) NOT NULL, + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) + / + + +-- End of IDENTITY Tables-- + + +-- Start of API-MGT Tables -- +CREATE TABLE AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UNIQUE (TENANT_ID,USER_ID) +)/ + +CREATE TABLE AM_APPLICATION ( + APPLICATION_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(100) NOT NULL, + SUBSCRIBER_ID INTEGER NOT NULL, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +)/ + +CREATE TABLE AM_API ( + API_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_PROVIDER VARCHAR(200) NOT NULL, + API_NAME VARCHAR(200) NOT NULL, + API_VERSION VARCHAR(30) NOT NULL, + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +)/ + +CREATE TABLE AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY (URL_MAPPING_ID) +)/ + +CREATE TABLE AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(256) NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +)/ + +CREATE TABLE AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER NOT NULL, + ACCESS_TOKEN VARCHAR(255) NOT NULL, + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +)/ + +CREATE TABLE AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER NOT NULL, + CONSUMER_KEY VARCHAR(255), + KEY_TYPE VARCHAR(512) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +)/ + +CREATE TABLE AM_API_LC_EVENT ( + EVENT_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +)/ + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255) NOT NULL, + AUTHZ_DOMAIN VARCHAR(255) NOT NULL DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +)/ + +CREATE TABLE AM_API_COMMENTS ( + COMMENT_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED TIMESTAMP NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +)/ + +CREATE TABLE AM_API_RATINGS ( + RATING_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE RESTRICT, + PRIMARY KEY (RATING_ID) +)/ + +CREATE TABLE AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +)/ + +CREATE TABLE AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE RESTRICT, + PRIMARY KEY (APISTORE_ID) +) +/ + +CREATE TABLE AM_WORKFLOWS( + WF_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP NOT NULL GENERATED ALWAYS FOR EACH ROW ON UPDATE AS ROW CHANGE TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +)/ + +CREATE TABLE AM_APPLICATION_REGISTRATION ( + REG_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + SUBSCRIBER_ID INT NOT NULL, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT NOT NULL, + TOKEN_TYPE VARCHAR(30) NOT NULL, + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +)/ + +CREATE TABLE AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE , + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE +)/ + +CREATE TABLE AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +)/ + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID)/ + +CREATE TABLE AM_ALERT_TYPES ( + ALERT_TYPE_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + ALERT_TYPE_NAME VARCHAR(256) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +)/ + +CREATE TABLE AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER NOT NULL, + USER_NAME VARCHAR(256) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONSTRAINT UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +)/ + +CREATE TABLE AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + USER_NAME VARCHAR(256) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (EMAIL_LIST_ID), + CONSTRAINT AM_ALERT_EMAILLIST_CONSTRAINT UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER) +)/ + +CREATE TABLE AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER NOT NULL, + EMAIL VARCHAR(255) NOT NULL, + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONSTRAINT UNIQUE (EMAIL_LIST_ID,EMAIL) +)/ + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher')/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher')/ + + + +-- AM Throttling tables -- + +CREATE TABLE AM_POLICY_SUBSCRIPTION ( + POLICY_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INT NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INT NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED SMALLINT NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH SMALLINT NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(256) NOT NULL, + PRIMARY KEY (POLICY_ID), + CONSTRAINT AM_POLICY_SUBSCRIPTION_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +)/ + +CREATE TABLE AM_POLICY_APPLICATION ( + POLICY_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED SMALLINT NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR(256) NOT NULL, + PRIMARY KEY (POLICY_ID), + CONSTRAINT APP_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +)/ + +CREATE TABLE AM_POLICY_HARD_THROTTLING ( + POLICY_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(512) NOT NULL, + TENANT_ID INT NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED SMALLINT NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + CONSTRAINT POLICY_HARD_NAME_TENANT UNIQUE (NAME, TENANT_ID) +)/ + + +CREATE TABLE AM_API_THROTTLE_POLICY ( + POLICY_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED SMALLINT NOT NULL DEFAULT 0, + UUID VARCHAR(256) NOT NULL, + PRIMARY KEY (POLICY_ID), + CONSTRAINT API_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +)/ + +CREATE TABLE AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE +)/ + +CREATE TABLE AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING SMALLINT DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +)/ + +CREATE TABLE AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING SMALLINT DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +)/ + +CREATE TABLE AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING SMALLINT DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +)/ + +CREATE TABLE AM_IP_CONDITION ( + AM_IP_CONDITION_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE SMALLINT DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE) +/ + +CREATE INDEX fk_AM_IP_CONDITION_1_idx ON AM_IP_CONDITION (CONDITION_GROUP_ID) +/ + +CREATE TABLE AM_POLICY_GLOBAL ( + POLICY_ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(512) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INT NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED SMALLINT NOT NULL DEFAULT 0, + UUID VARCHAR(256) NOT NULL, + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +)/ + +CREATE TABLE AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INT NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +/ + +CREATE TABLE AM_BLOCK_CONDITIONS ( + CONDITION_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1), + TYPE varchar(45) DEFAULT NULL, + VALUE varchar(45) DEFAULT NULL, + ENABLED varchar(45) DEFAULT NULL, + DOMAIN varchar(45) DEFAULT NULL, + UUID VARCHAR(256) NOT NULL, + PRIMARY KEY (CONDITION_ID), + UNIQUE (UUID) +) / + +-- End of API-MGT Tables -- + +-- Performance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME)/ +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN)/ +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE)/ +create index IDX_AAI_CTX on AM_API (CONTEXT)/ +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY)/ +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID)/ +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER)/ +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE)/ +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE)/ +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE)/ +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID)/ +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE)/ +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY)/ + +-- Performance indexes end-- diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/h2-sample-data.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/h2-sample-data.sql new file mode 100644 index 00000000..2b96659e --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/h2-sample-data.sql @@ -0,0 +1,67 @@ +DELETE FROM AM_SUBSCRIPTION_KEY_MAPPING; +DELETE FROM AM_APPLICATION_KEY_MAPPING; +DELETE FROM AM_SUBSCRIPTION ; +DELETE FROM AM_APPLICATION ; +DELETE FROM AM_SUBSCRIBER; +DELETE FROM AM_API; +DELETE FROM IDN_OAUTH2_ACCESS_TOKEN ; +DELETE FROM IDN_OAUTH_CONSUMER_APPS; + +ALTER TABLE AM_SUBSCRIBER ALTER COLUMN SUBSCRIBER_ID RESTART WITH 1; +ALTER TABLE AM_APPLICATION ALTER COLUMN APPLICATION_ID RESTART WITH 100; +ALTER TABLE AM_API ALTER COLUMN API_ID RESTART WITH 500; +ALTER TABLE AM_SUBSCRIPTION ALTER COLUMN SUBSCRIPTION_ID RESTART WITH 1000; + +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('SUMEDHA',-1234,'SUMEDHA@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('PRABATH',-1234,'PRABATH@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('THILINA',-1234,'THILINA@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('UDAYANGA',-1234,'UDAYANGA@WSO2.COM','2012-03-05 12:10:11'); + + +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('APPLICATION1',1,'97e5871a-cee9-4c1e-a138-9c3a9038125a'); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('APPLICATION2',1,'98841b88-75d9-4ed1-bf2d-bdf7edb837c5'); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('APPLICATION3',2,'4d43fe13-366e-455b-8f4e-88ee22015719'); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('APPLICATION4',2,'0a43614b-12f5-494d-bb79-edb22fe3360a'); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('APPLICATION5',3,'ea069058-6388-40e2-bfec-39365f5333d2'); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID,UUID ) VALUES ('DeliciousApp',4,'3f3e4aac-4692-4eea-a31e-7c80ee0454a8'); + +INSERT INTO AM_API (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('SUMEDHA', 'API1', 'V1.0.0','/context1'); +INSERT INTO AM_API (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('PRABATH', 'API2', 'V1.0.0','/deli2'); +INSERT INTO AM_API (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('ADMIN', 'API3', 'V1.0.0','/test'); +INSERT INTO AM_API (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('DEL', 'Delicious', '1.0.0','/deli'); + +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',500,100,'2012-03-05 12:10:11','7af95c9d-6177-4101-ab3e-d3f6c1cdc4c2'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',501,101,'2012-03-05 12:10:11','696430b1-c564-4d82-8ea9-ea1a61db0a60'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',500,102,'2012-03-05 12:10:11','2cb4a9c0-7f9d-41fe-bea2-2dc7b9073188'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',502,103,'2012-03-05 12:10:11','95556f88-b5ed-41fc-ac83-dc8d4cd6ccae'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',501,104,'2012-03-05 12:10:11','f36e661b-6eef-4af2-9927-7d220993aff2'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',503,105,'2012-03-05 12:10:11','443afa79-848a-4be6-8fbe-c6d73ed06ced'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED , UUID) VALUES ('T1',501,102,'2012-03-05 12:10:11','821b9664-eeca-4173-9f56-3dc6d46bd6eb'); + +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1000, 'SSDCHEJJ-AWUIS-232', 'PRODUCTION'); +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1001, 'a1b2c3d4', 'SANDBOX'); +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1002, 'p1q2r3s4', 'PRODUCTION'); + +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (100, 'CON1', 'PRODUCTION'); +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (100, 'CON2', 'SANDBOX'); +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (101, 'CON3', 'PRODUCTION'); + +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON1','MY PEN','2.0',0,'PRABATH'); +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON2','MY PEN','2.0',0,'PRABATH'); +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON3','MY PEN','2.0',0,'admin'); + +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( TOKEN_ID, ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE_HASH , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('TI1','a1b2c3d4','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','SANDBOXHASH','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( TOKEN_ID, ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE_HASH , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('TI2','p1q2r3s4','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','PRODUCTIONHASH','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( TOKEN_ID, ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE_HASH , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('TI3','test1','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','PRODUCTIONHASH','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( TOKEN_ID, ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE_HASH , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('TI4','test2','UDAYANGA','DEVELOPER','CON2',NULL,'2012-01-01','SANDBOXHASH','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( TOKEN_ID, ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE_HASH , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('TI5','test3','UDAYANGA','DEVELOPER','CON3',NULL,'2012-01-01','PRODUCTIONHASH','ACTIVE',3600); + +INSERT INTO IDN_OAUTH2_SCOPE_ASSOCIATION (TOKEN_ID, TOKEN_SCOPE ) VALUES ('TI1','SANDBOX') +INSERT INTO IDN_OAUTH2_SCOPE_ASSOCIATION (TOKEN_ID, TOKEN_SCOPE ) VALUES ('TI2','PRODUCTION') +INSERT INTO IDN_OAUTH2_SCOPE_ASSOCIATION (TOKEN_ID, TOKEN_SCOPE ) VALUES ('TI3','PRODUCTION') +INSERT INTO IDN_OAUTH2_SCOPE_ASSOCIATION (TOKEN_ID, TOKEN_SCOPE ) VALUES ('TI4','SANDBOX') +INSERT INTO IDN_OAUTH2_SCOPE_ASSOCIATION (TOKEN_ID, TOKEN_SCOPE ) VALUES ('TI5','PRODUCTION') + +SELECT * FROM AM_SUBSCRIBER; +SELECT * FROM AM_APPLICATION; +SELECT * FROM AM_SUBSCRIPTION; \ No newline at end of file diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/h2.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/h2.sql new file mode 100644 index 00000000..d4ba2707 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/h2.sql @@ -0,0 +1,989 @@ +-- Start of IDN Tables -- +CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR (20), + PRIMARY KEY (PRODUCT_NAME) +); + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR (255), + CONSUMER_SECRET VARCHAR (512), + USERNAME VARCHAR (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR (255), + OAUTH_VERSION VARCHAR (128), + CALLBACK_URL VARCHAR (1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR (512), + REQUEST_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR (1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR (128), + OAUTH_VERIFIER VARCHAR (512), + AUTHZ_USER VARCHAR (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR (512), + ACCESS_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR (255), + REFRESH_TOKEN VARCHAR (255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP DEFAULT 0, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP DEFAULT 0, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR (32), + TOKEN_STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +); + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR (1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR (255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER NOT NULL AUTO_INCREMENT, + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INTEGER NOT NULL DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER (11) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +); + +CREATE TABLE IF NOT EXISTS IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +); + +CREATE TABLE IDN_STS_STORE ( + ID INTEGER AUTO_INCREMENT, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +); + +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +); + +CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +); + +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +); +CREATE TABLE IF NOT EXISTS SP_APP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +CREATE TABLE IF NOT EXISTS SP_METADATA ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS SP_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_AUTH_STEP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL , + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID)); + +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID)); + +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_ROLE_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS IDP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE MEDIUMBLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)); + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +CREATE TABLE IF NOT EXISTS IDP_ROLE ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_ROLE_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_CLAIM ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_CLAIM_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + +CREATE TABLE IF NOT EXISTS IDP_METADATA ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_CONFIG ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_ENTITY ( + ID INTEGER AUTO_INCREMENT, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +CREATE TABLE IF NOT EXISTS IDN_ASSOCIATED_ID ( + ID INTEGER AUTO_INCREMENT, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)); + +CREATE TABLE IF NOT EXISTS FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA LONGVARCHAR NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)); + +CREATE TABLE IF NOT EXISTS WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID) +); + +CREATE TABLE IF NOT EXISTS WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL AUTO_INCREMENT, + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); +-- Start of API-MGT Tables -- + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UNIQUE (TENANT_ID,USER_ID) +); + +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_API ( + API_ID INTEGER AUTO_INCREMENT, + API_PROVIDER VARCHAR(256), + API_NAME VARCHAR(256), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + PRIMARY KEY(API_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +); + +CREATE TABLE IF NOT EXISTS AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB DEFAULT NULL, + PRIMARY KEY(URL_MAPPING_ID) +); + + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +); + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +); + +CREATE TABLE IF NOT EXISTS AM_API_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +); + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +); + +CREATE TABLE IF NOT EXISTS AM_API_COMMENTS ( + COMMENT_ID INTEGER AUTO_INCREMENT, + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED TIMESTAMP NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +); + +CREATE TABLE IF NOT EXISTS AM_API_RATINGS( + RATING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (RATING_ID) +); + +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +); + +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES( + APISTORE_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (APISTORE_ID) +); + +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP , + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +); + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_REGISTRATION ( + REG_ID INT AUTO_INCREMENT, + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +); + +CREATE TABLE IF NOT EXISTS AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INT AUTO_INCREMENT, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +); + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); + + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER AUTO_INCREMENT, + ALERT_TYPE_NAME VARCHAR(256) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +); + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(256) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONSTRAINT UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +); + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER AUTO_INCREMENT, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (EMAIL_LIST_ID), + CONSTRAINT AM_ALERT_EMAILLIST_CONSTRAINT UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER) +); + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONSTRAINT UNIQUE (EMAIL_LIST_ID,EMAIL) +); + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + +-- AM Throttling tables -- + +CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INT(11) NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX AM_POLICY_SUBSCRIPTION_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX APP_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX POLICY_HARD_NAME_TENANT (NAME, TENANT_ID) +); + + +CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX API_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS AM_IP_CONDITION ( + AM_IP_CONDITION_ID INT NOT NULL AUTO_INCREMENT, + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BOOLEAN DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE); + + +CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +); + +CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL AUTO_INCREMENT, + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INT(11) NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)); + +CREATE TABLE `AM_BLOCK_CONDITIONS` ( + `CONDITION_ID` int(11) NOT NULL AUTO_INCREMENT, + `TYPE` varchar(45) DEFAULT NULL, + `VALUE` varchar(45) DEFAULT NULL, + `ENABLED` varchar(45) DEFAULT NULL, + `DOMAIN` varchar(45) DEFAULT NULL, + `UUID` VARCHAR(256), + PRIMARY KEY (`CONDITION_ID`), + UNIQUE (UUID) +); + +-- End of API-MGT Tables -- diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/mssql.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/mssql.sql new file mode 100644 index 00000000..058d18ff --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/mssql.sql @@ -0,0 +1,1103 @@ +-- Start of IDN Tables -- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_BASE_TABLE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR(20), + PRIMARY KEY (PRODUCT_NAME) +); + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH_CONSUMER_APPS]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER IDENTITY, + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR(1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH1A_REQUEST_TOKEN]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(512), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR(128), + OAUTH_VERIFIER VARCHAR(512), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH1A_ACCESS_TOKEN]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(512), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH2_ACCESS_TOKEN]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED DATETIME, + REFRESH_TOKEN_TIME_CREATED DATETIME, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR(32), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +); + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +IF EXISTS (SELECT NAME FROM SYSINDEXES WHERE NAME = 'IDX_AT_CK_AU') +DROP INDEX IDN_OAUTH2_ACCESS_TOKEN.IDX_AT_CK_AU + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH2_AUTHORIZATION_CODE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED DATETIME, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR (255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH2_ACCESS_TOKEN_SCOPE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH2_SCOPE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER IDENTITY, + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INTEGER NOT NULL DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH2_RESOURCE_SCOPE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_SCIM_GROUP]') AND TYPE IN (N'U')) +CREATE TABLE IDN_SCIM_GROUP ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OPENID_REMEMBER_ME]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME DATETIME, + PRIMARY KEY (USER_NAME, TENANT_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OPENID_USER_RPS]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OPENID_ASSOCIATIONS]') AND TYPE IN (N'U')) +CREATE TABLE IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN DATETIME NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_STS_STORE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_STS_STORE ( + ID INTEGER IDENTITY, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT VARBINARY(MAX) NOT NULL, + CREATE_DATE DATETIME NOT NULL, + EXPIRE_DATE DATETIME NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_IDENTITY_USER_DATA]') AND TYPE IN (N'U')) +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_IDENTITY_META_DATA]') AND TYPE IN (N'U')) +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_THRIFT_SESSION]') AND TYPE IN (N'U')) +CREATE TABLE IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_AUTH_SESSION_STORE]') AND TYPE IN (N'U')) +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT VARBINARY(MAX), + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_APP]') AND TYPE IN (N'U')) +CREATE TABLE SP_APP ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID), + CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID)); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_METADATA]') AND TYPE IN (N'U')) +CREATE TABLE SP_METADATA ( + ID INTEGER IDENTITY, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_INBOUND_AUTH]') AND TYPE IN (N'U')) +CREATE TABLE SP_INBOUND_AUTH ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_AUTH_STEP]') AND TYPE IN (N'U')) +CREATE TABLE SP_AUTH_STEP ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL, + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID), + CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_FEDERATED_IDP]') AND TYPE IN (N'U')) +CREATE TABLE SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID), + CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_CLAIM_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID), + CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_ROLE_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE SP_ROLE_MAPPING ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_REQ_PATH_AUTHENTICATOR]') AND TYPE IN (N'U')) +CREATE TABLE SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SP_PROVISIONING_CONNECTOR]') AND TYPE IN (N'U')) +CREATE TABLE SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL IDENTITY, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID), + CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP]') AND TYPE IN (N'U')) +CREATE TABLE IDP ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE VARBINARY(MAX), + CERTIFICATE VARBINARY(MAX), + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID), + DISPLAY_NAME VARCHAR(255), + UNIQUE (TENANT_ID, NAME)); + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_ROLE]') AND TYPE IN (N'U')) +CREATE TABLE IDP_ROLE ( + ID INTEGER IDENTITY, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_ROLE_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE IDP_ROLE_MAPPING ( + ID INTEGER IDENTITY, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_CLAIM]') AND TYPE IN (N'U')) +CREATE TABLE IDP_CLAIM ( + ID INTEGER IDENTITY, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_CLAIM_MAPPING]') AND TYPE IN (N'U')) +CREATE TABLE IDP_CLAIM_MAPPING ( + ID INTEGER IDENTITY, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_AUTHENTICATOR]') AND TYPE IN (N'U')) +CREATE TABLE IDP_AUTHENTICATOR ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_METADATA]') AND TYPE IN (N'U')) +CREATE TABLE IDP_METADATA ( + ID INTEGER IDENTITY, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_AUTHENTICATOR_PROPERTY]') AND TYPE IN (N'U')) +CREATE TABLE IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_PROVISIONING_CONFIG]') AND TYPE IN (N'U')) +CREATE TABLE IDP_PROVISIONING_CONFIG ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_PROV_CONFIG_PROPERTY]') AND TYPE IN (N'U')) +CREATE TABLE IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE VARBINARY(MAX), + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_PROVISIONING_ENTITY]') AND TYPE IN (N'U')) +CREATE TABLE IDP_PROVISIONING_ENTITY ( + ID INTEGER IDENTITY, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDP_LOCAL_CLAIM]') AND TYPE IN (N'U')) +CREATE TABLE IDP_LOCAL_CLAIM ( + ID INTEGER IDENTITY, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_ASSOCIATED_ID]') AND TYPE IN (N'U')) +CREATE TABLE IDN_ASSOCIATED_ID ( + ID INTEGER IDENTITY, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_USER_ACCOUNT_ASSOCIATION]') AND TYPE IN (N'U')) +CREATE TABLE IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[FIDO_DEVICE_STORE]') AND TYPE IN (N'U')) +CREATE TABLE FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED DATETIME, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_REQUEST]') AND TYPE IN (N'U')) +CREATE TABLE WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT DATETIME, + UPDATED_AT DATETIME, + STATUS VARCHAR (30), + REQUEST VARBINARY(MAX), + PRIMARY KEY (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_BPS_PROFILE]') AND TYPE IN (N'U')) +CREATE TABLE WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_WORKFLOW]') AND TYPE IN (N'U')) +CREATE TABLE WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_WORKFLOW_ASSOCIATION]') AND TYPE IN (N'U')) +CREATE TABLE WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL IDENTITY , + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_WORKFLOW_CONFIG_PARAM]') AND TYPE IN (N'U')) +CREATE TABLE WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_REQUEST_ENTITY_RELATIONSHIP]') AND TYPE IN (N'U')) +CREATE TABLE WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[WF_WORKFLOW_REQUEST_RELATION]') AND TYPE IN (N'U')) +CREATE TABLE WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT DATETIME, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); + + +-- Start of API-Mgt Tables -- + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_SUBSCRIBER]') AND TYPE IN (N'U')) + +CREATE TABLE AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER IDENTITY(1,1), + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED DATETIME NOT NULL, + CREATED_BY VARCHAR(100), + CREATED_TIME DATETIME, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATETIME, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_APPLICATION]') AND TYPE IN (N'U')) + +CREATE TABLE AM_APPLICATION ( + APPLICATION_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(100) COLLATE Latin1_General_CS_AS, + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME DATETIME, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATETIME, + UUID VARCHAR(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API ( + API_ID INTEGER IDENTITY(1,1), + API_PROVIDER VARCHAR(200), + API_NAME VARCHAR(200), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME DATETIME, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATETIME, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_URL_MAPPING]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER IDENTITY(1,1), + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT VARBINARY(MAX), + PRIMARY KEY (URL_MAPPING_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_SUBSCRIPTION]') AND TYPE IN (N'U')) + +CREATE TABLE AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER IDENTITY(1,1), + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED DATETIME NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME DATETIME, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATETIME, + UUID VARCHAR(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_SUBSCRIPTION_KEY_MAPPING]') AND TYPE IN (N'U')) + +CREATE TABLE AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(255), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_APPLICATION_KEY_MAPPING]') AND TYPE IN (N'U')) + +CREATE TABLE AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_APPLICATION_REGISTRATION]') AND TYPE IN (N'U')) + +CREATE TABLE AM_APPLICATION_REGISTRATION ( + REG_ID INTEGER IDENTITY(1,1), + SUBSCRIBER_ID INTEGER, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INTEGER, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE NO ACTION, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE NO ACTION, + PRIMARY KEY (REG_ID) +); + + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_LC_EVENT]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_LC_EVENT ( + EVENT_ID INTEGER IDENTITY(1,1), + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATETIME NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE, + PRIMARY KEY (EVENT_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_APP_KEY_DOMAIN_MAPPING]') AND TYPE IN (N'U')) + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(512), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) + +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_COMMENTS]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_COMMENTS ( + COMMENT_ID INTEGER IDENTITY(1,1), + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED DATETIME NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE, + PRIMARY KEY (COMMENT_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_RATINGS]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_RATINGS ( + RATING_ID INTEGER IDENTITY(1,1), + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE, + PRIMARY KEY (RATING_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_TIER_PERMISSIONS]') AND TYPE IN (N'U')) + +CREATE TABLE AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER IDENTITY(1,1), + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_EXTERNAL_STORES]') AND TYPE IN (N'U')) + +CREATE TABLE AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER IDENTITY(1,1), + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE, + PRIMARY KEY (APISTORE_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_WORKFLOWS]') AND TYPE IN (N'U')) + +CREATE TABLE AM_WORKFLOWS( + WF_ID INTEGER IDENTITY(1,1), + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME DATETIME DEFAULT GETDATE(), + WF_UPDATED_TIME DATETIME DEFAULT GETDATE(), + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL UNIQUE, + PRIMARY KEY (WF_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_SCOPES]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_DEFAULT_VERSION]') AND TYPE IN (N'U')) + +CREATE TABLE AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INTEGER NOT NULL IDENTITY, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +); + + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); + + + +CREATE TABLE AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER NOT NULL IDENTITY, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(10) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +); + +CREATE TABLE AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONST UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +); + +CREATE TABLE AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER NOT NULL IDENTITY, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_EMAILLIST_CONST UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER), + PRIMARY KEY (EMAIL_LIST_ID) +); + +CREATE TABLE AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONST UNIQUE (EMAIL_LIST_ID,EMAIL) +); + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + + +-- AM Throttling tables -- +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_POLICY_SUBSCRIPTION]') AND TYPE IN (N'U')) +CREATE TABLE AM_POLICY_SUBSCRIPTION ( + POLICY_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INTEGER NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED BIT NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES VARBINARY(MAX) DEFAULT NULL, + STOP_ON_QUOTA_REACH BIT NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_POLICY_APPLICATION]') AND TYPE IN (N'U')) +CREATE TABLE AM_POLICY_APPLICATION ( + POLICY_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED BIT NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES VARBINARY(MAX) DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_POLICY_HARD_THROTTLING]') AND TYPE IN (N'U')) +CREATE TABLE AM_POLICY_HARD_THROTTLING ( + POLICY_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED BIT NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_API_THROTTLE_POLICY]') AND TYPE IN (N'U')) +CREATE TABLE AM_API_THROTTLE_POLICY ( + POLICY_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED BIT NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_CONDITION_GROUP]') AND TYPE IN (N'U')) +CREATE TABLE AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER IDENTITY(1,1), + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_QUERY_PARAMETER_CONDITION]') AND TYPE IN (N'U')) +CREATE TABLE AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER IDENTITY(1,1), + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BIT DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_HEADER_FIELD_CONDITION]') AND TYPE IN (N'U')) +CREATE TABLE AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER IDENTITY(1,1), + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BIT DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_JWT_CLAIM_CONDITION]') AND TYPE IN (N'U')) +CREATE TABLE AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER IDENTITY(1,1), + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BIT DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_IP_CONDITION]') AND TYPE IN (N'U')) +CREATE TABLE AM_IP_CONDITION ( + AM_IP_CONDITION_ID INTEGER IDENTITY(1,1), + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BIT DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_POLICY_GLOBAL]') AND TYPE IN (N'U')) +CREATE TABLE AM_POLICY_GLOBAL ( + POLICY_ID INTEGER IDENTITY(1,1), + NAME VARCHAR(512) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY VARBINARY(MAX) DEFAULT NULL, + IS_DEPLOYED BIT NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_THROTTLE_TIER_PERMISSIONS]') AND TYPE IN (N'U')) +CREATE TABLE AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INTEGER IDENTITY(1,1), + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_BLOCK_CONDITIONS]') AND TYPE IN (N'U')) +CREATE TABLE AM_BLOCK_CONDITIONS ( + CONDITION_ID INTEGER IDENTITY(1,1), + TYPE varchar(45) DEFAULT NULL, + VALUE varchar(45) DEFAULT NULL, + ENABLED varchar(45) DEFAULT NULL, + DOMAIN varchar(45) DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (CONDITION_ID), + UNIQUE (UUID) +); + +-- End of API-MGT Tables -- + + +--Permance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN); +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE); +create index IDX_AAI_CTX on AM_API (CONTEXT); +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY); +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID); +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER); +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE); +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE); +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE); +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID); +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE); +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY); + +-- Performance indexes end-- + diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/mysql.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql.sql new file mode 100644 index 00000000..35e38d7e --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql.sql @@ -0,0 +1,1039 @@ +-- Start of IDENTITY Tables-- + +CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR(20), + PRIMARY KEY (PRODUCT_NAME) +)ENGINE INNODB; + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(255), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR(128), + OAUTH_VERIFIER VARCHAR(512), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP DEFAULT 0, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP DEFAULT 0, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR(32), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +)ENGINE INNODB; + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR(255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( + SCOPE_ID INT(11) NOT NULL AUTO_INCREMENT, + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INT(11) NOT NULL DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER (11) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_STS_STORE ( + ID INTEGER AUTO_INCREMENT, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB(1024) NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS SP_APP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +CREATE TABLE IF NOT EXISTS SP_METADATA ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS SP_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_AUTH_STEP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL , + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID) +)ENGINE INNODB; + +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_ROLE_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS IDP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE MEDIUMBLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME) +)ENGINE INNODB; + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +CREATE TABLE IF NOT EXISTS IDP_ROLE ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_ROLE_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + +CREATE TABLE IF NOT EXISTS IDP_METADATA ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_CONFIG ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_ENTITY ( + ID INTEGER AUTO_INCREMENT, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_ASSOCIATED_ID ( + ID INTEGER AUTO_INCREMENT, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE) + )ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + CALLBACK_USERNAME VARCHAR (45), + CALLBACK_PASSWORD VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL AUTO_INCREMENT, + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE INNODB; + +-- End of IDENTITY Tables-- + +-- Start of API-MGT Tables -- +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UNIQUE (TENANT_ID,USER_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(254), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API ( + API_ID INTEGER AUTO_INCREMENT, + API_PROVIDER VARCHAR(200), + API_NAME VARCHAR(200), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY (URL_MAPPING_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(254), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(255), + KEY_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(255), + KEY_TYPE VARCHAR(255) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +)ENGINE INNODB; + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_COMMENTS ( + COMMENT_ID INTEGER AUTO_INCREMENT, + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED TIMESTAMP NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_RATINGS ( + RATING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (RATING_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, +FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (APISTORE_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT 0, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP , + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_REGISTRATION ( + REG_ID INT AUTO_INCREMENT, + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INT AUTO_INCREMENT, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +)ENGINE = INNODB; + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); + + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER AUTO_INCREMENT, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONSTRAINT UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER AUTO_INCREMENT, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (EMAIL_LIST_ID), + CONSTRAINT AM_ALERT_EMAILLIST_CONSTRAINT UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONSTRAINT UNIQUE (EMAIL_LIST_ID,EMAIL) +)ENGINE = INNODB; + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + + +-- AM Throttling tables -- + +CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INT(11) NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX AM_POLICY_SUBSCRIPTION_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX APP_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX POLICY_HARD_NAME_TENANT (NAME, TENANT_ID) +)ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX API_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_IP_CONDITION ( + AM_IP_CONDITION_ID INT NOT NULL AUTO_INCREMENT, + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BOOLEAN DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + INDEX fk_AM_IP_CONDITION_1_idx (CONDITION_GROUP_ID ASC), CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE) +ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL AUTO_INCREMENT, + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INT(11) NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +ENGINE = InnoDB; + +CREATE TABLE `AM_BLOCK_CONDITIONS` ( + `CONDITION_ID` int(11) NOT NULL AUTO_INCREMENT, + `TYPE` varchar(45) DEFAULT NULL, + `VALUE` varchar(45) DEFAULT NULL, + `ENABLED` varchar(45) DEFAULT NULL, + `DOMAIN` varchar(45) DEFAULT NULL, + `UUID` VARCHAR(254), + PRIMARY KEY (`CONDITION_ID`), + UNIQUE (`UUID`) +) ENGINE=InnoDB; + +-- End of API-MGT Tables -- + +-- Performance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN); +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE); +create index IDX_AAI_CTX on AM_API (CONTEXT); +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY); +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID); +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER); +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE); +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE); +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE); +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID); +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE); +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY); + +-- Performance indexes end-- diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/mysql5.7.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql5.7.sql new file mode 100644 index 00000000..c644470c --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql5.7.sql @@ -0,0 +1,1038 @@ +-- Start of IDENTITY Tables-- + +CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR(20), + PRIMARY KEY (PRODUCT_NAME) +)ENGINE INNODB; + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(255), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR(128), + OAUTH_VERIFIER VARCHAR(512), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR(32), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +)ENGINE INNODB; + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR(255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( + SCOPE_ID INT(11) NOT NULL AUTO_INCREMENT, + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INT(11) NOT NULL DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER (11) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_STS_STORE ( + ID INTEGER AUTO_INCREMENT, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB(1024) NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS SP_APP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +CREATE TABLE IF NOT EXISTS SP_METADATA ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS SP_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_AUTH_STEP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL , + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID) +)ENGINE INNODB; + +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_ROLE_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE INNODB; + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS IDP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE MEDIUMBLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME) +)ENGINE INNODB; + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +CREATE TABLE IF NOT EXISTS IDP_ROLE ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_ROLE_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + +CREATE TABLE IF NOT EXISTS IDP_METADATA ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE +)ENGINE INNODB; + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_CONFIG ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_ENTITY ( + ID INTEGER AUTO_INCREMENT, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_ASSOCIATED_ID ( + ID INTEGER AUTO_INCREMENT, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE) + )ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + CALLBACK_USERNAME VARCHAR (45), + CALLBACK_PASSWORD VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL AUTO_INCREMENT, + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE INNODB; + +-- End of IDENTITY Tables-- + +-- Start of API-MGT Tables -- +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE (TENANT_ID,USER_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UUID VARCHAR(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API ( + API_ID INTEGER AUTO_INCREMENT, + API_PROVIDER VARCHAR(200), + API_NAME VARCHAR(200), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY (URL_MAPPING_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UUID VARCHAR(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(255), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(255), + KEY_TYPE VARCHAR(512) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +)ENGINE INNODB; + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_COMMENTS ( + COMMENT_ID INTEGER AUTO_INCREMENT, + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED TIMESTAMP NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_RATINGS ( + RATING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (RATING_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, +FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (APISTORE_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP , + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_REGISTRATION ( + REG_ID INT AUTO_INCREMENT, + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INT AUTO_INCREMENT, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +)ENGINE = INNODB; + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); + + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER AUTO_INCREMENT, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER AUTO_INCREMENT, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER) +)ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + PRIMARY KEY (EMAIL_LIST_ID,EMAIL) +)ENGINE = INNODB; + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + + +-- AM Throttling tables -- + +CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INT(11) NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX AM_POLICY_SUBSCRIPTION_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX APP_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX POLICY_HARD_NAME_TENANT (NAME, TENANT_ID) +)ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX API_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_IP_CONDITION ( + AM_IP_CONDITION_ID INT NOT NULL AUTO_INCREMENT, + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BOOLEAN DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + INDEX fk_AM_IP_CONDITION_1_idx (CONDITION_GROUP_ID ASC), CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE) +ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(512) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL AUTO_INCREMENT, + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INT(11) NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +ENGINE = InnoDB; + +CREATE TABLE `AM_BLOCK_CONDITIONS` ( + `CONDITION_ID` int(11) NOT NULL AUTO_INCREMENT, + `TYPE` varchar(45) DEFAULT NULL, + `VALUE` varchar(45) DEFAULT NULL, + `ENABLED` varchar(45) DEFAULT NULL, + `DOMAIN` varchar(45) DEFAULT NULL, + `UUID` VARCHAR(256), + PRIMARY KEY (`CONDITION_ID`), + UNIQUE (`UUID`) +) ENGINE=InnoDB; + +-- End of API-MGT Tables -- + +-- Performance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN); +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE); +create index IDX_AAI_CTX on AM_API (CONTEXT); +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY); +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID); +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER); +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE); +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE); +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE); +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID); +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE); +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY); + +-- Performance indexes end-- diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/mysql_cluster.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql_cluster.sql new file mode 100644 index 00000000..2c6721ff --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/mysql_cluster.sql @@ -0,0 +1,1039 @@ +-- Start of IDN Tables -- +CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR(20), + PRIMARY KEY (PRODUCT_NAME) +)ENGINE NDB; + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(255), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR(128), + OAUTH_VERIFIER VARCHAR(512), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(255), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP DEFAULT 0, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP DEFAULT 0, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR(32), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +)ENGINE NDB; + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR(255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( + SCOPE_ID INT(11) NOT NULL AUTO_INCREMENT, + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INT(11) NOT NULL DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER (11) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_STS_STORE ( + ID INTEGER AUTO_INCREMENT, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB(1024) NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS SP_APP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +CREATE TABLE IF NOT EXISTS SP_METADATA ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS SP_INBOUND_AUTH ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_AUTH_STEP ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL , + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID) +)ENGINE NDB; + +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_CLAIM_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_ROLE_MAPPING ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS SP_PROVISIONING_CONNECTOR ( + ID INTEGER NOT NULL AUTO_INCREMENT, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID) +)ENGINE NDB; + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS IDP ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE MEDIUMBLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME) +)ENGINE NDB; + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +CREATE TABLE IF NOT EXISTS IDP_ROLE ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_ROLE_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_CLAIM_MAPPING ( + ID INTEGER AUTO_INCREMENT, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + +CREATE TABLE IF NOT EXISTS IDP_METADATA ( + ID INTEGER AUTO_INCREMENT, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE +)ENGINE NDB; + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_CONFIG ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_ENTITY ( + ID INTEGER AUTO_INCREMENT, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM ( + ID INTEGER AUTO_INCREMENT, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_ASSOCIATED_ID ( + ID INTEGER AUTO_INCREMENT, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE) + )ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + CALLBACK_USERNAME VARCHAR (45), + CALLBACK_PASSWORD VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_ASSOCIATION( + ID INTEGER NOT NULL AUTO_INCREMENT, + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +)ENGINE NDB; + +-- End of IDN Tables-- + +-- Start of API-MGT Tables -- +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UNIQUE (TENANT_ID,USER_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(254), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API ( + API_ID INTEGER AUTO_INCREMENT, + API_PROVIDER VARCHAR(200), + API_NAME VARCHAR(200), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY (URL_MAPPING_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME TIMESTAMP, + UPDATED_BY VARCHAR(100), + UPDATED_TIME TIMESTAMP, + UUID VARCHAR(254), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(255), + KEY_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(255), + KEY_TYPE VARCHAR(255) NOT NULL, + STATE VARCHAR(30) NOT NULL, + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +)ENGINE NDB; + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API_COMMENTS ( + COMMENT_ID INTEGER AUTO_INCREMENT, + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED TIMESTAMP NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API_RATINGS ( + RATING_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (RATING_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER AUTO_INCREMENT, + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, +FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, +PRIMARY KEY (APISTORE_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT 0, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP , + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_REGISTRATION ( + REG_ID INT AUTO_INCREMENT, + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INT AUTO_INCREMENT, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +); + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); + + + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER AUTO_INCREMENT, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONSTRAINT UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +)ENGINE NDB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER AUTO_INCREMENT, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + PRIMARY KEY (EMAIL_LIST_ID), + CONSTRAINT AM_ALERT_EMAILLIST_CONSTRAINT UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER) +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONSTRAINT UNIQUE (EMAIL_LIST_ID,EMAIL) +)ENGINE = NDB; + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + + +-- AM Throttling tables -- + +CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INT(11) NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT 0, + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX AM_POLICY_SUBSCRIPTION_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX APP_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INT(11) NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INT(11) NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX POLICY_HARD_NAME_TENANT (NAME, TENANT_ID) +)ENGINE = NDB; + + +CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE INDEX API_NAME_TENANT (NAME, TENANT_ID), + UNIQUE (UUID) +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL AUTO_INCREMENT, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BOOLEAN DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_IP_CONDITION ( + AM_IP_CONDITION_ID INT NOT NULL AUTO_INCREMENT, + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BOOLEAN DEFAULT 1, + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + INDEX fk_AM_IP_CONDITION_1_idx (CONDITION_GROUP_ID ASC), CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE) +ENGINE = NDB; + + +CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL ( + POLICY_ID INT(11) NOT NULL AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INT(11) NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0, + UUID VARCHAR(254), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +)ENGINE = NDB; + +CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL AUTO_INCREMENT, + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INT(11) NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +ENGINE = NDB; + +CREATE TABLE `AM_BLOCK_CONDITIONS` ( + `CONDITION_ID` int(11) NOT NULL AUTO_INCREMENT, + `TYPE` varchar(45) DEFAULT NULL, + `VALUE` varchar(45) DEFAULT NULL, + `ENABLED` varchar(45) DEFAULT NULL, + `DOMAIN` varchar(45) DEFAULT NULL, + `UUID` VARCHAR(254), + PRIMARY KEY (`CONDITION_ID`), + UNIQUE (`UUID`) +) ENGINE = NDB; + +-- End of API-MGT Tables -- + +-- Performance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN); +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE); +create index IDX_AAI_CTX on AM_API (CONTEXT); +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY); +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID); +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER); +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE); +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE); +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE); +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID); +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE); +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY); + +-- Performance indexes end-- diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/oracle.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/oracle.sql new file mode 100644 index 00000000..40b8f1fe --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/oracle.sql @@ -0,0 +1,1647 @@ +-- Create Oracle New User and Connect +-------------------------------------- +-- CREATE USER apimuser IDENTIFIED BY wso2; +-- GRANT CONNECT,RESOURCE to apimuser WITH ADMIN OPTION; +-- CONNECT apimuser/wso2 +-- + +-- Start of IDN Tables -- + +CREATE TABLE IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR2 (20), + PRIMARY KEY (PRODUCT_NAME)) +/ +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server') +/ +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER, + CONSUMER_KEY VARCHAR2 (255), + CONSUMER_SECRET VARCHAR2 (512), + USERNAME VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR2 (255), + OAUTH_VERSION VARCHAR2 (128), + CALLBACK_URL VARCHAR2 (1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIG + BEFORE INSERT + ON IDN_OAUTH_CONSUMER_APPS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_OAUTH_CONSUMER_APPS_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR2 (512), + REQUEST_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHORIZED VARCHAR2 (128), + OAUTH_VERIFIER VARCHAR2 (512), + AUTHZ_USER VARCHAR2 (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR2 (512), + ACCESS_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR2 (255), + REFRESH_TOKEN VARCHAR2 (255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR2 (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR2 (50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + REFRESH_TOKEN_VALIDITY_PERIOD NUMBER(19), + TOKEN_SCOPE_HASH VARCHAR2 (32), + TOKEN_STATE VARCHAR2 (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TOKEN_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID)) +/ +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED) +/ +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE) +/ +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR2 (50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR (255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR2 (255), + TOKEN_SCOPE VARCHAR2 (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER, + SCOPE_KEY VARCHAR2 (100) NOT NULL, + NAME VARCHAR2 (255) NULL, + DESCRIPTION VARCHAR2 (512) NULL, + TENANT_ID INTEGER DEFAULT 0, + ROLES VARCHAR2 (500) NULL, + PRIMARY KEY (SCOPE_ID)) +/ +CREATE SEQUENCE IDN_OAUTH2_SCOPE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDN_OAUTH2_SCOPE_TRIGGER + BEFORE INSERT + ON IDN_OAUTH2_SCOPE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_OAUTH2_SCOPE_SEQUENCE.nextval INTO :NEW.SCOPE_ID FROM dual; + END; +/ +CREATE TABLE IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR2 (255) NOT NULL, + SCOPE_ID INTEGER NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_SCIM_GROUP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR2(255) NOT NULL, + ATTR_NAME VARCHAR2(1024) NOT NULL, + ATTR_VALUE VARCHAR2(1024), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_SCIM_GROUP_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER IDN_SCIM_GROUP_TRIGGER + BEFORE INSERT + ON IDN_SCIM_GROUP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_SCIM_GROUP_SEQUENCE.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID)) +/ +CREATE TABLE IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL)) +/ +CREATE TABLE IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE)) +/ +CREATE TABLE IDN_STS_STORE ( + ID INTEGER, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_STS_STORE_SEQUENCE START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER IDN_STS_STORE_TRIGGER + BEFORE INSERT + ON IDN_STS_STORE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_STS_STORE_SEQUENCE.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY)) +/ +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA)) +/ +CREATE TABLE IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR2(255) NOT NULL, + USER_NAME VARCHAR2(255) NOT NULL, + CREATED_TIME VARCHAR2(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR2(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +) +/ +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED NUMBER(19), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +) +/ +CREATE TABLE SP_APP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_APP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_APP_TRIG + BEFORE INSERT + ON SP_APP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_APP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID) +/ + + +CREATE TABLE SP_METADATA ( + ID INTEGER, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE SP_METADATA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_METADATA_TRIG + BEFORE INSERT + ON SP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_METADATA_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +CREATE TABLE SP_INBOUND_AUTH ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_INBOUND_AUTH_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_INBOUND_AUTH_TRIG + BEFORE INSERT + ON SP_INBOUND_AUTH + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_INBOUND_AUTH_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_AUTH_STEP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL, + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_AUTH_STEP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_AUTH_STEP_TRIG + BEFORE INSERT + ON SP_AUTH_STEP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_AUTH_STEP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONST_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID)) +/ +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_CLAIM_MAPPING ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_CLAIM_MAPPING_TRIG + BEFORE INSERT + ON SP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_CLAIM_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_ROLE_MAPPING ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_ROLE_MAPPING_TRIG + BEFORE INSERT + ON SP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_ROLE_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_REQ_PATH_AUTH_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_REQ_PATH_AUTH_TRIG + BEFORE INSERT + ON SP_REQ_PATH_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_REQ_PATH_AUTH_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_PROVISIONING_CONNECTOR ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) DEFAULT '0', + BLOCKING CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_PROV_CONNECTOR_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER SP_PROV_CONNECTOR_TRIG + BEFORE INSERT + ON SP_PROVISIONING_CONNECTOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_PROV_CONNECTOR_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONST FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE IDP ( + ID INTEGER, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) DEFAULT '1', + IS_PRIMARY CHAR(1) DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE BLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)) +/ +CREATE SEQUENCE IDP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_TRIG + BEFORE INSERT + ON IDP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_ROLE ( + ID INTEGER, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost') +/ +CREATE OR REPLACE TRIGGER IDP_ROLE_TRIG + BEFORE INSERT + ON IDP_ROLE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_ROLE_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_ROLE_MAPPING ( + ID INTEGER, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_ROLE_MAPPING_TRIG + BEFORE INSERT + ON IDP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_ROLE_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_CLAIM ( + ID INTEGER, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_CLAIM_TRIG + BEFORE INSERT + ON IDP_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_CLAIM_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_CLAIM_MAPPING ( + ID INTEGER, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_CLAIM_MAPPING_TRIG + BEFORE INSERT + ON IDP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_CLAIM_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_AUTHENTICATOR ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_AUTHENTICATOR_TRIG + BEFORE INSERT + ON IDP_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_AUTHENTICATOR_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso') +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties') +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests') +/ +CREATE TABLE IDP_METADATA ( + ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_METADATA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_METADATA_TRIG + BEFORE INSERT + ON IDP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_METADATA_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout') +/ +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout') +/ +CREATE TABLE IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_PROP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_AUTHENTICATOR_PROP_TRIG + BEFORE INSERT + ON IDP_AUTHENTICATOR_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_AUTHENTICATOR_PROP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0') +/ +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0') +/ +CREATE TABLE IDP_PROVISIONING_CONFIG ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROVISIONING_CONFIG_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_PROVISIONING_CONFIG_TRIG + BEFORE INSERT + ON IDP_PROVISIONING_CONFIG + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROVISIONING_CONFIG_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_CONFIG_PROP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_PROV_CONFIG_PROP_TRIG + BEFORE INSERT + ON IDP_PROV_CONFIG_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROV_CONFIG_PROP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_PROVISIONING_ENTITY ( + ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_ENTITY_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_PROV_ENTITY_TRIG + BEFORE INSERT + ON IDP_PROVISIONING_ENTITY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROV_ENTITY_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_LOCAL_CLAIM ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_LOCAL_CLAIM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDP_LOCAL_CLAIM_TRIG + BEFORE INSERT + ON IDP_LOCAL_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_LOCAL_CLAIM_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_ASSOCIATED_ID ( + ID INTEGER, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +) +/ +CREATE SEQUENCE IDN_ASSOCIATED_ID_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDN_ASSOCIATED_ID_TRIG +BEFORE INSERT +ON IDN_ASSOCIATED_ID +REFERENCING NEW AS NEW +FOR EACH ROW + BEGIN + SELECT IDN_ASSOCIATED_ID_SEQ.nextval + INTO :NEW.ID + FROM dual; + END; +/ +CREATE TABLE IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)) +/ +CREATE TABLE FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)) +/ + +CREATE TABLE WF_REQUEST ( + UUID VARCHAR2 (45), + CREATED_BY VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR2 (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR2 (30), + REQUEST BLOB, + PRIMARY KEY (UUID)) +/ + +CREATE TABLE WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR2(45), + HOST_URL_MANAGER VARCHAR2(255), + HOST_URL_WORKER VARCHAR2(255), + USERNAME VARCHAR2(45), + PASSWORD VARCHAR2(255), + CALLBACK_HOST VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID)) +/ + +CREATE TABLE WF_WORKFLOW( + ID VARCHAR2 (45), + WF_NAME VARCHAR2 (45), + DESCRIPTION VARCHAR2 (255), + TEMPLATE_ID VARCHAR2 (45), + IMPL_ID VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID)) +/ + +CREATE TABLE WF_WORKFLOW_ASSOCIATION( + ID INTEGER, + ASSOC_NAME VARCHAR2 (45), + EVENT_ID VARCHAR2(45), + ASSOC_CONDITION VARCHAR2 (2000), + WORKFLOW_ID VARCHAR2 (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE SEQUENCE WF_WORKFLOW_ASSOCIATION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER WF_WORKFLOW_ASSOCIATION_TRIG +BEFORE INSERT +ON WF_WORKFLOW_ASSOCIATION +REFERENCING NEW AS NEW +FOR EACH ROW + BEGIN + SELECT WF_WORKFLOW_ASSOCIATION_SEQ.nextval + INTO :NEW.ID + FROM dual; + END; +/ + +CREATE TABLE WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR2 (45), + PARAM_NAME VARCHAR2 (45), + PARAM_VALUE VARCHAR2 (1000), + PARAM_QNAME VARCHAR2 (45), + PARAM_HOLDER VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR2 (45), + ENTITY_NAME VARCHAR2 (255), + ENTITY_TYPE VARCHAR2 (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR2 (45), + WORKFLOW_ID VARCHAR2 (45), + REQUEST_ID VARCHAR2 (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) +/ +-- End of IDENTITY Tables-- + +-- Start of API-MGT Tables-- +CREATE TABLE AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR2(256) NULL, + DATE_SUBSCRIBED DATE NOT NULL, + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +) +/ + +CREATE SEQUENCE AM_SUBSCRIBER_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_SUBSCRIBER_TRIGGER + BEFORE INSERT + ON AM_SUBSCRIBER + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_SUBSCRIBER_SEQUENCE.nextval INTO :NEW.SUBSCRIBER_ID FROM dual; + END; +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(SUBSCRIBER_ID) relation +CREATE TABLE AM_APPLICATION ( + APPLICATION_ID INTEGER, + NAME VARCHAR2(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR2(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR2(512), + DESCRIPTION VARCHAR2(512), + APPLICATION_STATUS VARCHAR2(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR2(100), + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + UUID VARCHAR2(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE CASCADE, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +) +/ + +CREATE SEQUENCE AM_APPLICATION_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_APPLICATION_TRIGGER + BEFORE INSERT + ON AM_APPLICATION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_APPLICATION_SEQUENCE.nextval INTO :NEW.APPLICATION_ID FROM dual; + END; +/ + +CREATE TABLE AM_API ( + API_ID INTEGER, + API_PROVIDER VARCHAR2(256), + API_NAME VARCHAR2(256), + API_VERSION VARCHAR2(30), + CONTEXT VARCHAR2(256), + CONTEXT_TEMPLATE VARCHAR2(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +) +/ + +CREATE SEQUENCE AM_API_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_API_TRIGGER + BEFORE INSERT + ON AM_API + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_SEQUENCE.nextval INTO :NEW.API_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY(URL_MAPPING_ID) +) +/ + +CREATE SEQUENCE AM_API_URL_MAPPING_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_API_URL_MAPPING_TRIGGER + BEFORE INSERT + ON AM_API_URL_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_URL_MAPPING_SEQUENCE.nextval INTO :NEW.URL_MAPPING_ID FROM dual; + END; +/ + +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(SUBSCRIPTION_ID) relation +CREATE TABLE AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER, + TIER_ID VARCHAR2(50), + API_ID INTEGER, + LAST_ACCESSED DATE NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + UUID VARCHAR2(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE CASCADE, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +) +/ + +CREATE SEQUENCE AM_SUBSCRIPTION_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_SUBSCRIPTION_TRIGGER + BEFORE INSERT + ON AM_SUBSCRIPTION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_SUBSCRIPTION_SEQUENCE.nextval INTO :NEW.SUBSCRIPTION_ID FROM dual; + END; +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(APPLICATION_ID) and FOREIGN KEY(API_ID) relations +CREATE TABLE AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR2(512), + KEY_TYPE VARCHAR2(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON DELETE CASCADE, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +) +/ +--TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(APPLICATION_ID) relation +CREATE TABLE AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR2(512), + KEY_TYPE VARCHAR2(512) NOT NULL, + CREATE_MODE VARCHAR2(30) DEFAULT 'CREATED', + STATE VARCHAR2(30) NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE CASCADE, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +) +/ + +CREATE TABLE AM_APPLICATION_REGISTRATION ( + REG_ID INTEGER , + SUBSCRIBER_ID INTEGER, + WF_REF VARCHAR2(255) NOT NULL, + APP_ID INTEGER, + TOKEN_TYPE VARCHAR2(30), + TOKEN_SCOPE VARCHAR2(256) DEFAULT 'default', + INPUTS VARCHAR2(1024), + ALLOWED_DOMAINS VARCHAR2(256), + VALIDITY_PERIOD NUMBER(19), + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID), + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID), + PRIMARY KEY (REG_ID) +) +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(API_ID) relation +CREATE TABLE AM_API_LC_EVENT ( + EVENT_ID INTEGER, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR2(50), + NEW_STATE VARCHAR2(50) NOT NULL, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATE NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (EVENT_ID) +) +/ + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +) +/ + +CREATE TABLE AM_API_COMMENTS ( + COMMENT_ID INTEGER, + COMMENT_TEXT VARCHAR2(512), + COMMENTED_USER VARCHAR2(255), + DATE_COMMENTED DATE NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (COMMENT_ID) +) +/ + +CREATE SEQUENCE AM_API_COMMENTS_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_API_COMMENTS_TRIGGER + BEFORE INSERT + ON AM_API_COMMENTS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_COMMENTS_SEQUENCE.nextval INTO :NEW.COMMENT_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_RATINGS ( + RATING_ID INTEGER, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE CASCADE, + PRIMARY KEY (RATING_ID) +) +/ + +CREATE SEQUENCE AM_API_RATINGS_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_API_RATINGS_TRIGGER + BEFORE INSERT + ON AM_API_RATINGS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_RATINGS_SEQUENCE.nextval INTO :NEW.RATING_ID FROM dual; + END; +/ + +CREATE TABLE AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER, + TIER VARCHAR2(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR2(50) NOT NULL, + ROLES VARCHAR2(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +) +/ + +CREATE SEQUENCE AM_TIER_PERMISSIONS_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_TIER_PERMISSIONS_TRIGGER + BEFORE INSERT + ON AM_TIER_PERMISSIONS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_TIER_PERMISSIONS_SEQUENCE.nextval INTO :NEW.TIER_PERMISSIONS_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_API_LC_EVENT_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_API_LC_EVENT_TRIGGER + BEFORE INSERT + ON AM_API_LC_EVENT + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_LC_EVENT_SEQUENCE.nextval INTO :NEW.EVENT_ID FROM dual; + END; +/ +-- Start of IDP-APPLICATION-MGT Tables -- + +-- End of IDP-APPLICATION-MGT Tables -- + + +CREATE TABLE AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER, + API_ID INTEGER, + STORE_ID VARCHAR2(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR2(255) NOT NULL, + STORE_ENDPOINT VARCHAR2(255) NOT NULL, + STORE_TYPE VARCHAR2(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (APISTORE_ID) +) +/ + +CREATE TABLE AM_WORKFLOWS( + WF_ID INTEGER, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL UNIQUE, + PRIMARY KEY (WF_ID) +) +/ + +CREATE TABLE AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE +) +/ +CREATE SEQUENCE AM_APP_REGISTRATION_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_APP_REGISTRATION_TRIGGER + BEFORE INSERT + ON AM_APPLICATION_REGISTRATION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_APP_REGISTRATION_SEQUENCE.nextval INTO :NEW.REG_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_WORKFLOWS_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_WORKFLOWS_TRIGGER + BEFORE INSERT + ON AM_WORKFLOWS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_WORKFLOWS_SEQUENCE.nextval INTO :NEW.WF_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_EXTERNAL_STORES_SEQUENCE START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER AM_EXTERNAL_STORES_TRIGGER + BEFORE INSERT + ON AM_EXTERNAL_STORES + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_EXTERNAL_STORES_SEQUENCE.nextval INTO :NEW.APISTORE_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID NUMBER, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +) +/ +CREATE SEQUENCE AM_API_DEFAULT_VERSION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER AM_API_DEFAULT_VERSION_TRG + BEFORE INSERT + ON AM_API_DEFAULT_VERSION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_DEFAULT_VERSION_SEQ.nextval INTO :NEW.DEFAULT_VERSION_ID FROM dual; + END; +/ +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID) +/ + + +CREATE TABLE AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID)) +/ + +CREATE SEQUENCE AM_ALERT_TYPES_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER AM_ALERT_TYPES_TRIG + BEFORE INSERT + ON AM_ALERT_TYPES + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_ALERT_TYPES_SEQ.nextval INTO :NEW.ALERT_TYPE_ID FROM dual; + END; +/ + + +CREATE TABLE AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONST UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER)) +/ + +CREATE TABLE AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_EMAILLIST_CONST UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER), + PRIMARY KEY (EMAIL_LIST_ID)) +/ + +CREATE SEQUENCE AM_ALERT_EMAILLIST_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER AM_ALERT_EMAILLIST_TRIG + BEFORE INSERT + ON AM_ALERT_EMAILLIST + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_ALERT_EMAILLIST_SEQ.nextval INTO :NEW.EMAIL_LIST_ID FROM dual; + END; +/ + +CREATE TABLE AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAIL_LIST_DET_CONST UNIQUE (EMAIL_LIST_ID,EMAIL)) +/ + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher') +/ + +-- AM Throttling tables -- + +CREATE TABLE AM_POLICY_SUBSCRIPTION ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + QUOTA_TYPE VARCHAR2(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + RATE_LIMIT_COUNT INTEGER DEFAULT NULL NULL, + RATE_LIMIT_TIME_UNIT VARCHAR2(25) DEFAULT NULL NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH INTEGER DEFAULT 0 NOT NULL, + BILLING_PLAN VARCHAR2(20), + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT SUBSCRIPTION_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_SUBSCRIPTION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_POLICY_SUBSCRIPTION_seq_tr + BEFORE INSERT ON AM_POLICY_SUBSCRIPTION FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_SUBSCRIPTION_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_POLICY_APPLICATION ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + QUOTA_TYPE VARCHAR2(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) DEFAULT NULL NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT AM_POLICY_APP_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_APPLICATION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_POLICY_APPLICATION_seq_tr + BEFORE INSERT ON AM_POLICY_APPLICATION FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_APPLICATION_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_API_THROTTLE_POLICY ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2 (1024), + DEFAULT_QUOTA_TYPE VARCHAR2(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR2(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR2(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR2(25) NOT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT API_POLICY_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_API_THROTTLE_POLICY_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_API_THROTTLE_POLICY_seq_tr + BEFORE INSERT ON AM_API_THROTTLE_POLICY FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_API_THROTTLE_POLICY_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR2(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) DEFAULT NULL NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_CONDITION_GROUP_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_CONDITION_GROUP_seq_tr + BEFORE INSERT ON AM_CONDITION_GROUP FOR EACH ROW + WHEN (NEW.CONDITION_GROUP_ID IS NULL) +BEGIN + SELECT AM_CONDITION_GROUP_seq.NEXTVAL INTO :NEW.CONDITION_GROUP_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR2(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR2(255) DEFAULT NULL, + IS_PARAM_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE QUERY_PARAMETER_CONDITION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER QUERY_PARAMETER_CONDITION_tr + BEFORE INSERT ON AM_QUERY_PARAMETER_CONDITION FOR EACH ROW + WHEN (NEW.QUERY_PARAMETER_ID IS NULL) +BEGIN + SELECT QUERY_PARAMETER_CONDITION_seq.NEXTVAL INTO :NEW.QUERY_PARAMETER_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR2(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR2(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_HEADER_FIELD_CONDITION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_HEADER_FIELD_CONDITION_tr + BEFORE INSERT ON AM_HEADER_FIELD_CONDITION FOR EACH ROW + WHEN (NEW.HEADER_FIELD_ID IS NULL) +BEGIN + SELECT AM_HEADER_FIELD_CONDITION_seq.NEXTVAL INTO :NEW.HEADER_FIELD_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR2(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR2(1024) DEFAULT NULL, + IS_CLAIM_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_JWT_CLAIM_CONDITION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_JWT_CLAIM_CONDITION_seq_tr + BEFORE INSERT ON AM_JWT_CLAIM_CONDITION FOR EACH ROW + WHEN (NEW.JWT_CLAIM_ID IS NULL) +BEGIN + SELECT AM_JWT_CLAIM_CONDITION_seq.NEXTVAL INTO :NEW.JWT_CLAIM_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_IP_CONDITION ( + AM_IP_CONDITION_ID INTEGER NOT NULL, + STARTING_IP VARCHAR2(45) NULL, + ENDING_IP VARCHAR2(45) NULL, + SPECIFIC_IP VARCHAR2(45) NULL, + WITHIN_IP_RANGE CHAR(1) DEFAULT 1, + CONDITION_GROUP_ID INTEGER NULL, + PRIMARY KEY (AM_IP_CONDITION_ID) + , CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ) + +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_IP_CONDITION_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_IP_CONDITION_seq_tr + BEFORE INSERT ON AM_IP_CONDITION FOR EACH ROW + WHEN (NEW.AM_IP_CONDITION_ID IS NULL) +BEGIN + SELECT AM_IP_CONDITION_seq.NEXTVAL INTO :NEW.AM_IP_CONDITION_ID FROM DUAL; +END; +/ + +CREATE INDEX fk_AM_IP_CONDITION_1_idx ON AM_IP_CONDITION (CONDITION_GROUP_ID ASC) +/ + +CREATE TABLE AM_POLICY_GLOBAL ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + KEY_TEMPLATE VARCHAR2(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_GLOBAL_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_POLICY_GLOBAL_seq_tr + BEFORE INSERT ON AM_POLICY_GLOBAL FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_GLOBAL_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INTEGER NOT NULL, + TIER VARCHAR2(50) NULL, + PERMISSIONS_TYPE VARCHAR2(50) NULL, + ROLES VARCHAR2(512) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +/ + +-- Generate ID using sequence and trigger +CREATE SEQUENCE THROTTLE_TIER_PERMISSIONS_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER THROTTLE_TIER_PERMISSIONS_tr + BEFORE INSERT ON AM_THROTTLE_TIER_PERMISSIONS FOR EACH ROW + WHEN (NEW.THROTTLE_TIER_PERMISSIONS_ID IS NULL) +BEGIN + SELECT THROTTLE_TIER_PERMISSIONS_seq.NEXTVAL INTO :NEW.THROTTLE_TIER_PERMISSIONS_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_BLOCK_CONDITIONS ( + CONDITION_ID INTEGER NOT NULL, + TYPE varchar2(45) DEFAULT NULL, + VALUE varchar2(45) DEFAULT NULL, + ENABLED varchar2(45) DEFAULT NULL, + DOMAIN varchar2(45) DEFAULT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (CONDITION_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_BLOCK_CONDITIONS_seq START WITH 1 INCREMENT BY 1 +/ +CREATE OR REPLACE TRIGGER AM_BLOCK_CONDITIONS_seq_tr + BEFORE INSERT ON AM_BLOCK_CONDITIONS FOR EACH ROW + WHEN (NEW.CONDITION_ID IS NULL) +BEGIN + SELECT AM_BLOCK_CONDITIONS_seq.NEXTVAL INTO :NEW.CONDITION_ID FROM DUAL; +END; +/ + +-- End of API-MGT Tables -- + +--permance indexes start-- +/ +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME) +/ +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN) +/ +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE) +/ +create index IDX_AAI_CTX on AM_API (CONTEXT) +/ +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY) +/ +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID) +/ +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER) +/ +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE) +/ +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE) +/ +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE) +/ +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID) +/ +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE) +/ +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY) +/ +-- Performance indexes end-- + diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/oracle_rac.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/oracle_rac.sql new file mode 100644 index 00000000..3f0d9d64 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/oracle_rac.sql @@ -0,0 +1,1647 @@ +-- Create Oracle New User and Connect +-------------------------------------- +-- CREATE USER apimuser IDENTIFIED BY wso2; +-- GRANT CONNECT,RESOURCE to apimuser WITH ADMIN OPTION; +-- CONNECT apimuser/wso2 +-- + +-- Start of IDN Tables -- +CREATE TABLE IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR2 (20), + PRIMARY KEY (PRODUCT_NAME)) +/ +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server') +/ +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER, + CONSUMER_KEY VARCHAR2 (255), + CONSUMER_SECRET VARCHAR2 (512), + USERNAME VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR2 (255), + OAUTH_VERSION VARCHAR2 (128), + CALLBACK_URL VARCHAR2 (1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIG + BEFORE INSERT + ON IDN_OAUTH_CONSUMER_APPS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_OAUTH_CONSUMER_APPS_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR2 (512), + REQUEST_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHORIZED VARCHAR2 (128), + OAUTH_VERIFIER VARCHAR2 (512), + AUTHZ_USER VARCHAR2 (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR2 (512), + ACCESS_TOKEN_SECRET VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR2 (255), + REFRESH_TOKEN VARCHAR2 (255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR2 (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR2 (50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + REFRESH_TOKEN_VALIDITY_PERIOD NUMBER(19), + TOKEN_SCOPE_HASH VARCHAR2 (32), + TOKEN_STATE VARCHAR2 (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TOKEN_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID)) +/ +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE) +/ +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED) +/ +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR2 (512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR2 (1024), + SCOPE VARCHAR2(2048), + AUTHZ_USER VARCHAR2 (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR2(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD NUMBER(19), + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR (255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR2 (255), + TOKEN_SCOPE VARCHAR2 (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER, + SCOPE_KEY VARCHAR2 (100) NOT NULL, + NAME VARCHAR2 (255) NULL, + DESCRIPTION VARCHAR2 (512) NULL, + TENANT_ID INTEGER DEFAULT 0, + ROLES VARCHAR2 (500) NULL, + PRIMARY KEY (SCOPE_ID)) +/ +CREATE SEQUENCE IDN_OAUTH2_SCOPE_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDN_OAUTH2_SCOPE_TRIGGER + BEFORE INSERT + ON IDN_OAUTH2_SCOPE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_OAUTH2_SCOPE_SEQUENCE.nextval INTO :NEW.SCOPE_ID FROM dual; + END; +/ +CREATE TABLE IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR2 (255) NOT NULL, + SCOPE_ID INTEGER NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE) +/ +CREATE TABLE IDN_SCIM_GROUP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR2(255) NOT NULL, + ATTR_NAME VARCHAR2(1024) NOT NULL, + ATTR_VALUE VARCHAR2(1024), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_SCIM_GROUP_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER IDN_SCIM_GROUP_TRIGGER + BEFORE INSERT + ON IDN_SCIM_GROUP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_SCIM_GROUP_SEQUENCE.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID)) +/ +CREATE TABLE IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL)) +/ +CREATE TABLE IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE)) +/ +CREATE TABLE IDN_STS_STORE ( + ID INTEGER, + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BLOB NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE IDN_STS_STORE_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER IDN_STS_STORE_TRIGGER + BEFORE INSERT + ON IDN_STS_STORE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_STS_STORE_SEQUENCE.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY)) +/ +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA)) +/ +CREATE TABLE IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR2(255) NOT NULL, + USER_NAME VARCHAR2(255) NOT NULL, + CREATED_TIME VARCHAR2(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR2(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +) +/ +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR (100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BLOB, + TIME_CREATED NUMBER(19), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) +) +/ +CREATE TABLE SP_APP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_APP_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_APP_TRIG + BEFORE INSERT + ON SP_APP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_APP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID) +/ + +CREATE TABLE SP_METADATA ( + ID INTEGER, + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE SP_METADATA_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_METADATA_TRIG + BEFORE INSERT + ON SP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_METADATA_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +CREATE TABLE SP_INBOUND_AUTH ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_INBOUND_AUTH_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_INBOUND_AUTH_TRIG + BEFORE INSERT + ON SP_INBOUND_AUTH + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_INBOUND_AUTH_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_AUTH_STEP ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL, + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_AUTH_STEP_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_AUTH_STEP_TRIG + BEFORE INSERT + ON SP_AUTH_STEP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_AUTH_STEP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID)) +/ +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_CLAIM_MAPPING ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_CLAIM_MAPPING_TRIG + BEFORE INSERT + ON SP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_CLAIM_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_ROLE_MAPPING ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_ROLE_MAPPING_TRIG + BEFORE INSERT + ON SP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_ROLE_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_REQ_PATH_AUTH_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_REQ_PATH_AUTH_TRIG + BEFORE INSERT + ON SP_REQ_PATH_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_REQ_PATH_AUTH_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE SP_PROVISIONING_CONNECTOR ( + ID INTEGER, + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) DEFAULT '0', + BLOCKING CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)) +/ +CREATE SEQUENCE SP_PROV_CONNECTOR_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER SP_PROV_CONNECTOR_TRIG + BEFORE INSERT + ON SP_PROVISIONING_CONNECTOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT SP_PROV_CONNECTOR_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE +/ +CREATE TABLE IDP ( + ID INTEGER, + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) DEFAULT '1', + IS_PRIMARY CHAR(1) DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE BLOB, + CERTIFICATE BLOB, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '0', + DISPLAY_NAME VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)) +/ +CREATE SEQUENCE IDP_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_TRIG + BEFORE INSERT + ON IDP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost') +/ +CREATE TABLE IDP_ROLE ( + ID INTEGER, + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_ROLE_TRIG + BEFORE INSERT + ON IDP_ROLE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_ROLE_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_ROLE_MAPPING ( + ID INTEGER, + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_ROLE_MAPPING_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_ROLE_MAPPING_TRIG + BEFORE INSERT + ON IDP_ROLE_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_ROLE_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_CLAIM ( + ID INTEGER, + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_CLAIM_TRIG + BEFORE INSERT + ON IDP_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_CLAIM_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_CLAIM_MAPPING ( + ID INTEGER, + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_CLAIM_MAPPING_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_CLAIM_MAPPING_TRIG + BEFORE INSERT + ON IDP_CLAIM_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_CLAIM_MAPPING_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_AUTHENTICATOR ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_AUTHENTICATOR_TRIG + BEFORE INSERT + ON IDP_AUTHENTICATOR + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_AUTHENTICATOR_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso') +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties') +/ +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests') +/ +CREATE TABLE IDP_METADATA ( + ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_METADATA_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_METADATA_TRIG + BEFORE INSERT + ON IDP_METADATA + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_METADATA_SEQ.nextval INTO :NEW.ID FROM dual; + END; + +/ +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout') +/ +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout') +/ +CREATE TABLE IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER, + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_AUTHENTICATOR_PROP_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_AUTHENTICATOR_PROP_TRIG + BEFORE INSERT + ON IDP_AUTHENTICATOR_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_AUTHENTICATOR_PROP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0') +/ +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0') +/ +CREATE TABLE IDP_PROVISIONING_CONFIG ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROVISIONING_CONFIG_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_PROVISIONING_CONFIG_TRIG + BEFORE INSERT + ON IDP_PROVISIONING_CONFIG + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROVISIONING_CONFIG_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER, + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BLOB, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_CONFIG_PROP_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_PROV_CONFIG_PROP_TRIG + BEFORE INSERT + ON IDP_PROV_CONFIG_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROV_CONFIG_PROP_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_PROVISIONING_ENTITY ( + ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_PROV_ENTITY_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_PROV_ENTITY_TRIG + BEFORE INSERT + ON IDP_PROVISIONING_ENTITY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_PROV_ENTITY_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDP_LOCAL_CLAIM ( + ID INTEGER, + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE) +/ +CREATE SEQUENCE IDP_LOCAL_CLAIM_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER IDP_LOCAL_CLAIM_TRIG + BEFORE INSERT + ON IDP_LOCAL_CLAIM + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDP_LOCAL_CLAIM_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_ASSOCIATED_ID ( + ID INTEGER, + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +) +/ +CREATE SEQUENCE IDN_ASSOCIATED_ID_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ +CREATE OR REPLACE TRIGGER IDN_ASSOCIATED_ID_TRIG + BEFORE INSERT + ON IDN_ASSOCIATED_ID + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_ASSOCIATED_ID_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ +CREATE TABLE IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)) +/ +CREATE TABLE FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)) +/ + +CREATE TABLE WF_REQUEST ( + UUID VARCHAR2 (45), + CREATED_BY VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR2 (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR2 (30), + REQUEST BLOB, + PRIMARY KEY (UUID)) +/ + +CREATE TABLE WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR2(45), + HOST_URL_MANAGER VARCHAR2(255), + HOST_URL_WORKER VARCHAR2(255), + USERNAME VARCHAR2(45), + PASSWORD VARCHAR2(255), + CALLBACK_HOST VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID)) +/ + +CREATE TABLE WF_WORKFLOW( + ID VARCHAR2 (45), + WF_NAME VARCHAR2 (45), + DESCRIPTION VARCHAR2 (255), + TEMPLATE_ID VARCHAR2 (45), + IMPL_ID VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID)) +/ + +CREATE TABLE WF_WORKFLOW_ASSOCIATION( + ID INTEGER, + ASSOC_NAME VARCHAR2 (45), + EVENT_ID VARCHAR2(45), + ASSOC_CONDITION VARCHAR2 (2000), + WORKFLOW_ID VARCHAR2 (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE SEQUENCE WF_WORKFLOW_ASSOCIATION_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER WF_WORKFLOW_ASSOCIATION_TRIG +BEFORE INSERT +ON WF_WORKFLOW_ASSOCIATION +REFERENCING NEW AS NEW +FOR EACH ROW + BEGIN + SELECT WF_WORKFLOW_ASSOCIATION_SEQ.nextval + INTO :NEW.ID + FROM dual; + END; +/ + +CREATE TABLE WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR2 (45), + PARAM_NAME VARCHAR2 (45), + PARAM_VALUE VARCHAR2 (1000), + PARAM_QNAME VARCHAR2 (45), + PARAM_HOLDER VARCHAR2 (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR2 (45), + ENTITY_NAME VARCHAR2 (255), + ENTITY_TYPE VARCHAR2 (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) +/ + +CREATE TABLE WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR2 (45), + WORKFLOW_ID VARCHAR2 (45), + REQUEST_ID VARCHAR2 (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE) +/ +-- End of IDENTITY Tables-- + +-- Start of API-MGT Tables-- +CREATE TABLE AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR2(256) NULL, + DATE_SUBSCRIBED DATE NOT NULL, + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +) +/ + +CREATE SEQUENCE AM_SUBSCRIBER_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_SUBSCRIBER_TRIGGER + BEFORE INSERT + ON AM_SUBSCRIBER + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_SUBSCRIBER_SEQUENCE.nextval INTO :NEW.SUBSCRIBER_ID FROM dual; + END; +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(SUBSCRIBER_ID) relation +CREATE TABLE AM_APPLICATION ( + APPLICATION_ID INTEGER, + NAME VARCHAR2(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR2(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR2(512), + DESCRIPTION VARCHAR2(512), + APPLICATION_STATUS VARCHAR2(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR2(100), + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + UUID VARCHAR2(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE CASCADE, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +) +/ + +CREATE SEQUENCE AM_APPLICATION_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_APPLICATION_TRIGGER + BEFORE INSERT + ON AM_APPLICATION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_APPLICATION_SEQUENCE.nextval INTO :NEW.APPLICATION_ID FROM dual; + END; +/ + +CREATE TABLE AM_API ( + API_ID INTEGER, + API_PROVIDER VARCHAR2(256), + API_NAME VARCHAR2(256), + API_VERSION VARCHAR2(30), + CONTEXT VARCHAR2(256), + CONTEXT_TEMPLATE VARCHAR2(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +) +/ + +CREATE SEQUENCE AM_API_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_API_TRIGGER + BEFORE INSERT + ON AM_API + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_SEQUENCE.nextval INTO :NEW.API_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER, + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BLOB, + PRIMARY KEY(URL_MAPPING_ID) +) +/ + +CREATE SEQUENCE AM_API_URL_MAPPING_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_API_URL_MAPPING_TRIGGER + BEFORE INSERT + ON AM_API_URL_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_URL_MAPPING_SEQUENCE.nextval INTO :NEW.URL_MAPPING_ID FROM dual; + END; +/ + +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(SUBSCRIPTION_ID) relation +CREATE TABLE AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER, + TIER_ID VARCHAR2(50), + API_ID INTEGER, + LAST_ACCESSED DATE NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR2(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR2(100), + UPDATED_TIME DATE, + UUID VARCHAR2(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE CASCADE, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +) +/ + +CREATE SEQUENCE AM_SUBSCRIPTION_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_SUBSCRIPTION_TRIGGER + BEFORE INSERT + ON AM_SUBSCRIPTION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_SUBSCRIPTION_SEQUENCE.nextval INTO :NEW.SUBSCRIPTION_ID FROM dual; + END; +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(APPLICATION_ID) and FOREIGN KEY(API_ID) relations +CREATE TABLE AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR2(512), + KEY_TYPE VARCHAR2(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON DELETE CASCADE, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +) +/ +--TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(APPLICATION_ID) relation +CREATE TABLE AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR2(512), + KEY_TYPE VARCHAR2(512) NOT NULL, + CREATE_MODE VARCHAR2(30) DEFAULT 'CREATED', + STATE VARCHAR2(30) NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON DELETE CASCADE, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +) +/ + +CREATE TABLE AM_APPLICATION_REGISTRATION ( + REG_ID INTEGER , + SUBSCRIBER_ID INTEGER, + WF_REF VARCHAR2(255) NOT NULL, + APP_ID INTEGER, + TOKEN_TYPE VARCHAR2(30), + TOKEN_SCOPE VARCHAR2(256) DEFAULT 'default', + INPUTS VARCHAR2(1000), + ALLOWED_DOMAINS VARCHAR2(256), + VALIDITY_PERIOD NUMBER(19), + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID), + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID), + PRIMARY KEY (REG_ID) +) +/ +-- TODO: Have to add ON UPDATE CASCADE for the FOREIGN KEY(API_ID) relation +CREATE TABLE AM_API_LC_EVENT ( + EVENT_ID INTEGER, + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR2(50), + NEW_STATE VARCHAR2(50) NOT NULL, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATE NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (EVENT_ID) +) +/ + +CREATE TABLE AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) + +) +/ + +CREATE TABLE AM_API_COMMENTS ( + COMMENT_ID INTEGER, + COMMENT_TEXT VARCHAR2(512), + COMMENTED_USER VARCHAR2(255), + DATE_COMMENTED DATE NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (COMMENT_ID) +) +/ + +CREATE SEQUENCE AM_API_COMMENTS_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_API_COMMENTS_TRIGGER + BEFORE INSERT + ON AM_API_COMMENTS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_COMMENTS_SEQUENCE.nextval INTO :NEW.COMMENT_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_RATINGS ( + RATING_ID INTEGER, + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON DELETE CASCADE, + PRIMARY KEY (RATING_ID) +) +/ + +CREATE SEQUENCE AM_API_RATINGS_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_API_RATINGS_TRIGGER + BEFORE INSERT + ON AM_API_RATINGS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_RATINGS_SEQUENCE.nextval INTO :NEW.RATING_ID FROM dual; + END; +/ + +CREATE TABLE AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER, + TIER VARCHAR2(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR2(50) NOT NULL, + ROLES VARCHAR2(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +) +/ + +CREATE SEQUENCE AM_TIER_PERMISSIONS_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_TIER_PERMISSIONS_TRIGGER + BEFORE INSERT + ON AM_TIER_PERMISSIONS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_TIER_PERMISSIONS_SEQUENCE.nextval INTO :NEW.TIER_PERMISSIONS_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_API_LC_EVENT_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_API_LC_EVENT_TRIGGER + BEFORE INSERT + ON AM_API_LC_EVENT + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_LC_EVENT_SEQUENCE.nextval INTO :NEW.EVENT_ID FROM dual; + END; +/ +-- Start of IDP-APPLICATION-MGT Tables -- + +-- End of IDP-APPLICATION-MGT Tables -- + + +CREATE TABLE AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER, + API_ID INTEGER, + STORE_ID VARCHAR2(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR2(255) NOT NULL, + STORE_ENDPOINT VARCHAR2(255) NOT NULL, + STORE_TYPE VARCHAR2(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE, + PRIMARY KEY (APISTORE_ID) +) +/ + +CREATE TABLE AM_WORKFLOWS( + WF_ID INTEGER, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL UNIQUE, + PRIMARY KEY (WF_ID) +) +/ + +CREATE TABLE AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE +) +/ +CREATE SEQUENCE AM_APP_REGISTRATION_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_APP_REGISTRATION_TRIGGER + BEFORE INSERT + ON AM_APPLICATION_REGISTRATION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_APP_REGISTRATION_SEQUENCE.nextval INTO :NEW.REG_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_WORKFLOWS_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_WORKFLOWS_TRIGGER + BEFORE INSERT + ON AM_WORKFLOWS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_WORKFLOWS_SEQUENCE.nextval INTO :NEW.WF_ID FROM dual; + END; +/ + +CREATE SEQUENCE AM_EXTERNAL_STORES_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ + +CREATE OR REPLACE TRIGGER AM_EXTERNAL_STORES_TRIGGER + BEFORE INSERT + ON AM_EXTERNAL_STORES + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_EXTERNAL_STORES_SEQUENCE.nextval INTO :NEW.APISTORE_ID FROM dual; + END; +/ + +CREATE TABLE AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID NUMBER, + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +) +/ +CREATE SEQUENCE AM_API_DEFAULT_VERSION_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_API_DEFAULT_VERSION_TRG + BEFORE INSERT + ON AM_API_DEFAULT_VERSION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_API_DEFAULT_VERSION_SEQ.nextval INTO :NEW.DEFAULT_VERSION_ID FROM dual; + END; +/ +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID) +/ + + +CREATE TABLE AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER, + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID)) +/ + +CREATE SEQUENCE AM_ALERT_TYPES_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER AM_ALERT_TYPES_TRIG + BEFORE INSERT + ON AM_ALERT_TYPES + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_ALERT_TYPES_SEQ.nextval INTO :NEW.ALERT_TYPE_ID FROM dual; + END; +/ + + +CREATE TABLE AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONST UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER)) +/ + +CREATE TABLE AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_EMAILLIST_CONST UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER), + PRIMARY KEY (EMAIL_LIST_ID)) +/ + +CREATE SEQUENCE AM_ALERT_EMAILLIST_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER AM_ALERT_EMAILLIST_TRIG + BEFORE INSERT + ON AM_ALERT_EMAILLIST + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT AM_ALERT_EMAILLIST_SEQ.nextval INTO :NEW.EMAIL_LIST_ID FROM dual; + END; +/ + +CREATE TABLE AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAIL_LIST_DET_CONST UNIQUE (EMAIL_LIST_ID,EMAIL)) +/ + + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher') +/ +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher') +/ + +-- AM Throttling tables -- + +CREATE TABLE AM_POLICY_SUBSCRIPTION ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + QUOTA_TYPE VARCHAR2(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + RATE_LIMIT_COUNT INTEGER DEFAULT NULL NULL, + RATE_LIMIT_TIME_UNIT VARCHAR2(25) DEFAULT NULL NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + STOP_ON_QUOTA_REACH INTEGER DEFAULT 0 NOT NULL, + BILLING_PLAN VARCHAR2(20), + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT SUBSCRIPTION_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_SUBSCRIPTION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_POLICY_SUBSCRIPTION_seq_tr + BEFORE INSERT ON AM_POLICY_SUBSCRIPTION FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_SUBSCRIPTION_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_POLICY_APPLICATION ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + QUOTA_TYPE VARCHAR2(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) DEFAULT NULL NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + CUSTOM_ATTRIBUTES BLOB DEFAULT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT AM_POLICY_APP_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_APPLICATION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_POLICY_APPLICATION_seq_tr + BEFORE INSERT ON AM_POLICY_APPLICATION FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_APPLICATION_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_API_THROTTLE_POLICY ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + DISPLAY_NAME VARCHAR2(512) DEFAULT NULL NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2 (1024), + DEFAULT_QUOTA_TYPE VARCHAR2(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR2(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR2(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR2(25) NOT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + CONSTRAINT API_POLICY_NAME_TENANT UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_API_THROTTLE_POLICY_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_API_THROTTLE_POLICY_seq_tr + BEFORE INSERT ON AM_API_THROTTLE_POLICY FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_API_THROTTLE_POLICY_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR2(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR2(10) DEFAULT NULL NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR2(25) NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_CONDITION_GROUP_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_CONDITION_GROUP_seq_tr + BEFORE INSERT ON AM_CONDITION_GROUP FOR EACH ROW + WHEN (NEW.CONDITION_GROUP_ID IS NULL) +BEGIN + SELECT AM_CONDITION_GROUP_seq.NEXTVAL INTO :NEW.CONDITION_GROUP_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR2(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR2(255) DEFAULT NULL, + IS_PARAM_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE QUERY_PARAMETER_CONDITION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER QUERY_PARAMETER_CONDITION_tr + BEFORE INSERT ON AM_QUERY_PARAMETER_CONDITION FOR EACH ROW + WHEN (NEW.QUERY_PARAMETER_ID IS NULL) +BEGIN + SELECT AM_QUERY_PARAMETER_CONDITION_seq.NEXTVAL INTO :NEW.QUERY_PARAMETER_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR2(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR2(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_HEADER_FIELD_CONDITION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_HEADER_FIELD_CONDITION_tr + BEFORE INSERT ON AM_HEADER_FIELD_CONDITION FOR EACH ROW + WHEN (NEW.HEADER_FIELD_ID IS NULL) +BEGIN + SELECT AM_HEADER_FIELD_CONDITION_seq.NEXTVAL INTO :NEW.HEADER_FIELD_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER NOT NULL, + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR2(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR2(1024) DEFAULT NULL, + IS_CLAIM_MAPPING CHAR(1) DEFAULT 1, + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_JWT_CLAIM_CONDITION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_JWT_CLAIM_CONDITION_seq_tr + BEFORE INSERT ON AM_JWT_CLAIM_CONDITION FOR EACH ROW + WHEN (NEW.JWT_CLAIM_ID IS NULL) +BEGIN + SELECT AM_JWT_CLAIM_CONDITION_seq.NEXTVAL INTO :NEW.JWT_CLAIM_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_IP_CONDITION ( + AM_IP_CONDITION_ID INTEGER NOT NULL, + STARTING_IP VARCHAR2(45) NULL, + ENDING_IP VARCHAR2(45) NULL, + SPECIFIC_IP VARCHAR2(45) NULL, + WITHIN_IP_RANGE CHAR(1) DEFAULT 1, + CONDITION_GROUP_ID INTEGER NULL, + PRIMARY KEY (AM_IP_CONDITION_ID) + , CONSTRAINT fk_AM_IP_CONDITION_1 FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ) + +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_IP_CONDITION_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_IP_CONDITION_seq_tr + BEFORE INSERT ON AM_IP_CONDITION FOR EACH ROW + WHEN (NEW.AM_IP_CONDITION_ID IS NULL) +BEGIN + SELECT AM_IP_CONDITION_seq.NEXTVAL INTO :NEW.AM_IP_CONDITION_ID FROM DUAL; +END; +/ + +CREATE INDEX fk_AM_IP_CONDITION_1_idx ON AM_IP_CONDITION (CONDITION_GROUP_ID ASC) +/ + +CREATE TABLE AM_POLICY_GLOBAL ( + POLICY_ID INTEGER NOT NULL, + NAME VARCHAR2(512) NOT NULL, + KEY_TEMPLATE VARCHAR2(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR2(1024) DEFAULT NULL NULL, + SIDDHI_QUERY BLOB DEFAULT NULL, + IS_DEPLOYED INTEGER DEFAULT 0 NOT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_POLICY_GLOBAL_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_POLICY_GLOBAL_seq_tr + BEFORE INSERT ON AM_POLICY_GLOBAL FOR EACH ROW + WHEN (NEW.POLICY_ID IS NULL) +BEGIN + SELECT AM_POLICY_GLOBAL_seq.NEXTVAL INTO :NEW.POLICY_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INTEGER NOT NULL, + TIER VARCHAR2(50) NULL, + PERMISSIONS_TYPE VARCHAR2(50) NULL, + ROLES VARCHAR2(512) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)) +/ + +-- Generate ID using sequence and trigger +CREATE SEQUENCE THROTTLE_TIER_PERMISSIONS_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER THROTTLE_TIER_PERMISSIONS_tr + BEFORE INSERT ON AM_THROTTLE_TIER_PERMISSIONS FOR EACH ROW + WHEN (NEW.THROTTLE_TIER_PERMISSIONS_ID IS NULL) +BEGIN + SELECT THROTTLE_TIER_PERMISSIONS_seq.NEXTVAL INTO :NEW.THROTTLE_TIER_PERMISSIONS_ID FROM DUAL; +END; +/ + +CREATE TABLE AM_BLOCK_CONDITIONS ( + CONDITION_ID INTEGER NOT NULL, + TYPE varchar2(45) DEFAULT NULL, + VALUE varchar2(45) DEFAULT NULL, + ENABLED varchar2(45) DEFAULT NULL, + DOMAIN varchar2(45) DEFAULT NULL, + UUID VARCHAR2(256), + PRIMARY KEY (CONDITION_ID), + UNIQUE (UUID) +) +/ +-- Generate ID using sequence and trigger +CREATE SEQUENCE AM_BLOCK_CONDITIONS_seq START WITH 1 INCREMENT BY 1 CACHE 20 ORDER +/ +CREATE OR REPLACE TRIGGER AM_BLOCK_CONDITIONS_seq_tr + BEFORE INSERT ON AM_BLOCK_CONDITIONS FOR EACH ROW + WHEN (NEW.CONDITION_ID IS NULL) +BEGIN + SELECT AM_BLOCK_CONDITIONS_seq.NEXTVAL INTO :NEW.CONDITION_ID FROM DUAL; +END; +/ + +-- End of API-MGT Tables -- + +--permance indexes start-- +/ +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME) +/ +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN) +/ +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE) +/ +create index IDX_AAI_CTX on AM_API (CONTEXT) +/ +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY) +/ +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID) +/ +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER) +/ +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE) +/ +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE) +/ +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE) +/ +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID) +/ +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE) +/ +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY) +/ +-- Performance indexes end-- + diff --git a/modules/distribution/src/core/resources/dbscripts/apimgt/postgresql.sql b/modules/distribution/src/core/resources/dbscripts/apimgt/postgresql.sql new file mode 100644 index 00000000..a8f0a407 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/apimgt/postgresql.sql @@ -0,0 +1,1162 @@ +BEGIN TRANSACTION; + +-- Start of IDN Tables -- +DROP TABLE IF EXISTS IDN_BASE_TABLE; +CREATE TABLE IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR(20), + PRIMARY KEY (PRODUCT_NAME) +); + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +DROP TABLE IF EXISTS IDN_OAUTH_CONSUMER_APPS; +DROP SEQUENCE IF EXISTS IDN_OAUTH_CONSUMER_APPS_PK_SEQ; +CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_PK_SEQ; +CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER DEFAULT NEXTVAL('IDN_OAUTH_CONSUMER_APPS_PK_SEQ'), + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR (1024), + PKCE_MANDATORY CHAR(1) DEFAULT '0', + PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +); + +DROP TABLE IF EXISTS IDN_OAUTH1A_REQUEST_TOKEN; +CREATE TABLE IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR(512), + REQUEST_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR(128), + OAUTH_VERIFIER VARCHAR(512), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH1A_ACCESS_TOKEN; +CREATE TABLE IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR(512), + ACCESS_TOKEN_SECRET VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR(512), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH2_ACCESS_TOKEN; +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN ( + TOKEN_ID VARCHAR (255), + ACCESS_TOKEN VARCHAR(255), + REFRESH_TOKEN VARCHAR(255), + CONSUMER_KEY_ID INTEGER, + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + USER_TYPE VARCHAR (25), + GRANT_TYPE VARCHAR (50), + TIME_CREATED TIMESTAMP, + REFRESH_TOKEN_TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE_HASH VARCHAR(32), + TOKEN_STATE VARCHAR(25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', + SUBJECT_IDENTIFIER VARCHAR(255), + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, + CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TOKEN_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, + TOKEN_STATE,TOKEN_STATE_ID) +); + +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TOKEN_STATE, USER_TYPE); + +CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); + +DROP TABLE IF EXISTS IDN_OAUTH2_AUTHORIZATION_CODE; +CREATE TABLE IDN_OAUTH2_AUTHORIZATION_CODE ( + CODE_ID VARCHAR (255), + AUTHORIZATION_CODE VARCHAR(512), + CONSUMER_KEY_ID INTEGER, + CALLBACK_URL VARCHAR(1024), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (100), + TENANT_ID INTEGER, + USER_DOMAIN VARCHAR(50), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_ID VARCHAR(255), + SUBJECT_IDENTIFIER VARCHAR(255), + PKCE_CODE_CHALLENGE VARCHAR (255), + PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), + PRIMARY KEY (CODE_ID), + FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE; +CREATE TABLE IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( + TOKEN_ID VARCHAR (255), + TOKEN_SCOPE VARCHAR (60), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDN_OAUTH2_SCOPE; +DROP SEQUENCE IF EXISTS IDN_OAUTH2_SCOPE_PK_SEQ; +CREATE SEQUENCE IDN_OAUTH2_SCOPE_PK_SEQ; +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( + SCOPE_ID INTEGER DEFAULT NEXTVAL('IDN_OAUTH2_SCOPE_PK_SEQ'), + SCOPE_KEY VARCHAR(100) NOT NULL, + NAME VARCHAR(255) NULL, + DESCRIPTION VARCHAR(512) NULL, + TENANT_ID INTEGER DEFAULT 0, + ROLES VARCHAR (500) NULL, + PRIMARY KEY (SCOPE_ID) +); + +DROP TABLE IF EXISTS IDN_OAUTH2_RESOURCE_SCOPE; +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( + RESOURCE_PATH VARCHAR(255) NOT NULL, + SCOPE_ID INTEGER NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RESOURCE_PATH), + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +DROP TABLE IF EXISTS IDN_SCIM_GROUP; +DROP SEQUENCE IF EXISTS IDN_SCIM_GROUP_PK_SEQ; +CREATE SEQUENCE IDN_SCIM_GROUP_PK_SEQ; +CREATE TABLE IDN_SCIM_GROUP ( + ID INTEGER DEFAULT NEXTVAL('IDN_SCIM_GROUP_PK_SEQ'), + TENANT_ID INTEGER NOT NULL, + ROLE_NAME VARCHAR(255) NOT NULL, + ATTR_NAME VARCHAR(1024) NOT NULL, + ATTR_VALUE VARCHAR(1024), + PRIMARY KEY (ID) +); + +DROP TABLE IF EXISTS IDN_OPENID_REMEMBER_ME; +CREATE TABLE IDN_OPENID_REMEMBER_ME ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + COOKIE_VALUE VARCHAR(1024), + CREATED_TIME TIMESTAMP, + PRIMARY KEY (USER_NAME, TENANT_ID) +); + +DROP TABLE IF EXISTS IDN_OPENID_USER_RPS; +CREATE TABLE IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +); + +DROP TABLE IF EXISTS IDN_OPENID_ASSOCIATIONS; +CREATE TABLE IDN_OPENID_ASSOCIATIONS ( + HANDLE VARCHAR(255) NOT NULL, + ASSOC_TYPE VARCHAR(255) NOT NULL, + EXPIRE_IN TIMESTAMP NOT NULL, + MAC_KEY VARCHAR(255) NOT NULL, + ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (HANDLE) +); + +DROP TABLE IF EXISTS IDN_STS_STORE; +DROP SEQUENCE IF EXISTS IDN_STS_STORE_PK_SEQ; +CREATE SEQUENCE IDN_STS_STORE_PK_SEQ; +CREATE TABLE IDN_STS_STORE ( + ID INTEGER DEFAULT NEXTVAL('IDN_STS_STORE_PK_SEQ'), + TOKEN_ID VARCHAR(255) NOT NULL, + TOKEN_CONTENT BYTEA NOT NULL, + CREATE_DATE TIMESTAMP NOT NULL, + EXPIRE_DATE TIMESTAMP NOT NULL, + STATE INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +DROP TABLE IF EXISTS IDN_IDENTITY_USER_DATA; +CREATE TABLE IDN_IDENTITY_USER_DATA ( + TENANT_ID INTEGER DEFAULT -1234, + USER_NAME VARCHAR(255) NOT NULL, + DATA_KEY VARCHAR(255) NOT NULL, + DATA_VALUE VARCHAR(255), + PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) +); + +DROP TABLE IF EXISTS IDN_IDENTITY_META_DATA; +CREATE TABLE IDN_IDENTITY_META_DATA ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + METADATA_TYPE VARCHAR(255) NOT NULL, + METADATA VARCHAR(255) NOT NULL, + VALID VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) +); + +DROP TABLE IF EXISTS IDN_THRIFT_SESSION; +CREATE TABLE IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID) +); + +DROP TABLE IF EXISTS IDN_AUTH_SESSION_STORE; +CREATE TABLE IDN_AUTH_SESSION_STORE ( + SESSION_ID VARCHAR(100) NOT NULL, + SESSION_TYPE VARCHAR(100) NOT NULL, + OPERATION VARCHAR(10) NOT NULL, + SESSION_OBJECT BYTEA, + TIME_CREATED BIGINT, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) + ); + +DROP TABLE IF EXISTS SP_APP; +DROP SEQUENCE IF EXISTS SP_APP_SEQ; +CREATE SEQUENCE SP_APP_SEQ; +CREATE TABLE SP_APP ( + ID INTEGER DEFAULT NEXTVAL('SP_APP_SEQ'), + TENANT_ID INTEGER NOT NULL, + APP_NAME VARCHAR (255) NOT NULL , + USER_STORE VARCHAR (255) NOT NULL, + USERNAME VARCHAR (255) NOT NULL , + DESCRIPTION VARCHAR (1024), + ROLE_CLAIM VARCHAR (512), + AUTH_TYPE VARCHAR (255) NOT NULL, + PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), + IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', + IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', + IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', + IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', + SUBJECT_CLAIM_URI VARCHAR (512), + IS_SAAS_APP CHAR(1) DEFAULT '0', + IS_DUMB_MODE CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); + +DROP TABLE IF EXISTS SP_METADATA; +DROP SEQUENCE IF EXISTS SP_METADATA_SEQ; +CREATE SEQUENCE SP_METADATA_SEQ; +CREATE TABLE SP_METADATA ( + ID INTEGER DEFAULT NEXTVAL('SP_METADATA_SEQ'), + SP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS SP_INBOUND_AUTH; +DROP SEQUENCE IF EXISTS SP_INBOUND_AUTH_SEQ; +CREATE SEQUENCE SP_INBOUND_AUTH_SEQ; +CREATE TABLE SP_INBOUND_AUTH ( + ID INTEGER DEFAULT NEXTVAL('SP_INBOUND_AUTH_SEQ'), + TENANT_ID INTEGER NOT NULL, + INBOUND_AUTH_KEY VARCHAR (255), + INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, + PROP_NAME VARCHAR (255), + PROP_VALUE VARCHAR (1024) , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_AUTH_STEP; +DROP SEQUENCE IF EXISTS SP_AUTH_STEP_SEQ; +CREATE SEQUENCE SP_AUTH_STEP_SEQ; +CREATE TABLE SP_AUTH_STEP ( + ID INTEGER DEFAULT NEXTVAL('SP_AUTH_STEP_SEQ'), + TENANT_ID INTEGER NOT NULL, + STEP_ORDER INTEGER DEFAULT 1, + APP_ID INTEGER NOT NULL, + IS_SUBJECT_STEP CHAR(1) DEFAULT '0', + IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_FEDERATED_IDP; +CREATE TABLE SP_FEDERATED_IDP ( + ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_ID INTEGER NOT NULL, + PRIMARY KEY (ID, AUTHENTICATOR_ID)); + +ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_CLAIM_MAPPING; +DROP SEQUENCE IF EXISTS SP_CLAIM_MAPPING_SEQ; +CREATE SEQUENCE SP_CLAIM_MAPPING_SEQ; +CREATE TABLE SP_CLAIM_MAPPING ( + ID INTEGER DEFAULT NEXTVAL('SP_CLAIM_MAPPING_SEQ'), + TENANT_ID INTEGER NOT NULL, + IDP_CLAIM VARCHAR (512) NOT NULL , + SP_CLAIM VARCHAR (512) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_REQUESTED VARCHAR(128) DEFAULT '0', + DEFAULT_VALUE VARCHAR(255), + PRIMARY KEY (ID)); + +ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_ROLE_MAPPING; +DROP SEQUENCE IF EXISTS SP_ROLE_MAPPING_SEQ; +CREATE SEQUENCE SP_ROLE_MAPPING_SEQ; +CREATE TABLE SP_ROLE_MAPPING ( + ID INTEGER DEFAULT NEXTVAL('SP_ROLE_MAPPING_SEQ'), + TENANT_ID INTEGER NOT NULL, + IDP_ROLE VARCHAR (255) NOT NULL , + SP_ROLE VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_REQ_PATH_AUTH; +DROP SEQUENCE IF EXISTS SP_REQ_PATH_AUTH_SEQ; +CREATE SEQUENCE SP_REQ_PATH_AUTH_SEQ; +CREATE TABLE SP_REQ_PATH_AUTHENTICATOR ( + ID INTEGER DEFAULT NEXTVAL('SP_REQ_PATH_AUTH_SEQ'), + TENANT_ID INTEGER NOT NULL, + AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + PRIMARY KEY (ID)); + +ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS SP_PROV_CONNECTOR; +DROP SEQUENCE IF EXISTS SP_PROV_CONNECTOR_SEQ; +CREATE SEQUENCE SP_PROV_CONNECTOR_SEQ; +CREATE TABLE SP_PROVISIONING_CONNECTOR ( + ID INTEGER DEFAULT NEXTVAL('SP_PROV_CONNECTOR_SEQ'), + TENANT_ID INTEGER NOT NULL, + IDP_NAME VARCHAR (255) NOT NULL , + CONNECTOR_NAME VARCHAR (255) NOT NULL , + APP_ID INTEGER NOT NULL, + IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', + BLOCKING CHAR(1) NOT NULL DEFAULT '0', + PRIMARY KEY (ID)); + +ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; + +DROP TABLE IF EXISTS IDP; +DROP SEQUENCE IF EXISTS IDP_SEQ; +CREATE SEQUENCE IDP_SEQ; +CREATE TABLE IDP ( + ID INTEGER DEFAULT NEXTVAL('IDP_SEQ'), + TENANT_ID INTEGER, + NAME VARCHAR(254) NOT NULL, + IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', + IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', + HOME_REALM_ID VARCHAR(254), + IMAGE BYTEA, + CERTIFICATE BYTEA, + ALIAS VARCHAR(254), + INBOUND_PROV_ENABLED CHAR (1) NOT NULL DEFAULT '0', + INBOUND_PROV_USER_STORE_ID VARCHAR(254), + USER_CLAIM_URI VARCHAR(254), + ROLE_CLAIM_URI VARCHAR(254), + DESCRIPTION VARCHAR (1024), + DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), + DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), + PROVISIONING_ROLE VARCHAR(128), + IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', + IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, NAME)); + +DROP TABLE IF EXISTS IDP_ROLE; +DROP SEQUENCE IF EXISTS IDP_ROLE_SEQ; + +INSERT INTO IDP (TENANT_ID, NAME, HOME_REALM_ID) VALUES (-1234, 'LOCAL', 'localhost'); + +CREATE SEQUENCE IDP_ROLE_SEQ; +CREATE TABLE IDP_ROLE ( + ID INTEGER DEFAULT NEXTVAL('IDP_ROLE_SEQ'), + IDP_ID INTEGER, + TENANT_ID INTEGER, + ROLE VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, ROLE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_ROLE_MAPPING; +DROP SEQUENCE IF EXISTS IDP_ROLE_MAPPING_SEQ; +CREATE SEQUENCE IDP_ROLE_MAPPING_SEQ; +CREATE TABLE IDP_ROLE_MAPPING ( + ID INTEGER DEFAULT NEXTVAL('IDP_ROLE_MAPPING_SEQ'), + IDP_ROLE_ID INTEGER, + TENANT_ID INTEGER, + USER_STORE_ID VARCHAR (253), + LOCAL_ROLE VARCHAR(253), + PRIMARY KEY (ID), + UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), + FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_CLAIM; +DROP SEQUENCE IF EXISTS IDP_CLAIM_SEQ; +CREATE SEQUENCE IDP_CLAIM_SEQ; +CREATE TABLE IDP_CLAIM ( + ID INTEGER DEFAULT NEXTVAL('IDP_CLAIM_SEQ'), + IDP_ID INTEGER, + TENANT_ID INTEGER, + CLAIM VARCHAR(254), + PRIMARY KEY (ID), + UNIQUE (IDP_ID, CLAIM), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_CLAIM_MAPPING; +DROP SEQUENCE IF EXISTS IDP_CLAIM_MAPPING_SEQ; +CREATE SEQUENCE IDP_CLAIM_MAPPING_SEQ; +CREATE TABLE IDP_CLAIM_MAPPING ( + ID INTEGER DEFAULT NEXTVAL('IDP_CLAIM_MAPPING_SEQ'), + IDP_CLAIM_ID INTEGER, + TENANT_ID INTEGER, + LOCAL_CLAIM VARCHAR(253), + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), + FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_AUTHENTICATOR; +DROP SEQUENCE IF EXISTS IDP_AUTHENTICATOR_SEQ; +CREATE SEQUENCE IDP_AUTHENTICATOR_SEQ; +CREATE TABLE IDP_AUTHENTICATOR ( + ID INTEGER DEFAULT NEXTVAL('IDP_AUTHENTICATOR_SEQ'), + TENANT_ID INTEGER, + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '1', + DISPLAY_NAME VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'samlsso'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'IDPProperties'); +INSERT INTO IDP_AUTHENTICATOR (TENANT_ID, IDP_ID, NAME) VALUES (-1234, 1, 'passivests'); + + +DROP TABLE IF EXISTS IDP_METADATA; +DROP SEQUENCE IF EXISTS IDP_METADATA_SEQ; +CREATE SEQUENCE IDP_METADATA_SEQ; +CREATE TABLE IDP_METADATA ( + ID INTEGER DEFAULT NEXTVAL('IDP_METADATA_SEQ'), + IDP_ID INTEGER, + NAME VARCHAR(255) NOT NULL, + VALUE VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'SessionIdleTimeout', '20160', 'Session Idle Timeout'); +INSERT INTO IDP_METADATA (IDP_ID, NAME, VALUE, DISPLAY_NAME) VALUES (1, 'RememberMeTimeout', '15', 'RememberMe Timeout'); + +DROP TABLE IF EXISTS IDP_AUTHENTICATOR_PROP; +DROP SEQUENCE IF EXISTS IDP_AUTHENTICATOR_PROP_SEQ; +CREATE SEQUENCE IDP_AUTHENTICATOR_PROP_SEQ; +CREATE TABLE IDP_AUTHENTICATOR_PROPERTY ( + ID INTEGER DEFAULT NEXTVAL('IDP_AUTHENTICATOR_PROP_SEQ'), + TENANT_ID INTEGER, + AUTHENTICATOR_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2047), + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), + FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE); + +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 1 , 'IdPEntityId', 'localhost', '0'); +INSERT INTO IDP_AUTHENTICATOR_PROPERTY (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY,PROPERTY_VALUE, IS_SECRET ) VALUES (-1234, 3 , 'IdPEntityId', 'localhost', '0'); + +DROP TABLE IF EXISTS IDP_PROV_CONFIG; +DROP SEQUENCE IF EXISTS IDP_PROV_CONFIG_SEQ; +CREATE SEQUENCE IDP_PROV_CONFIG_SEQ; +CREATE TABLE IDP_PROVISIONING_CONFIG ( + ID INTEGER DEFAULT NEXTVAL('IDP_PROV_CONFIG_SEQ'), + TENANT_ID INTEGER, + IDP_ID INTEGER, + PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, + IS_ENABLED CHAR (1) DEFAULT '0', + IS_BLOCKING CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_PROV_CONFIG_PROP; +DROP SEQUENCE IF EXISTS IDP_PROV_CONFIG_PROP_SEQ; +CREATE SEQUENCE IDP_PROV_CONFIG_PROP_SEQ; +CREATE TABLE IDP_PROV_CONFIG_PROPERTY ( + ID INTEGER DEFAULT NEXTVAL('IDP_PROV_CONFIG_PROP_SEQ'), + TENANT_ID INTEGER, + PROVISIONING_CONFIG_ID INTEGER, + PROPERTY_KEY VARCHAR(255) NOT NULL, + PROPERTY_VALUE VARCHAR(2048), + PROPERTY_BLOB_VALUE BYTEA, + PROPERTY_TYPE CHAR(32) NOT NULL, + IS_SECRET CHAR (1) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_PROV_ENTITY; +DROP SEQUENCE IF EXISTS IDP_PROV_ENTITY_SEQ; +CREATE SEQUENCE IDP_PROV_ENTITY_SEQ; +CREATE TABLE IDP_PROVISIONING_ENTITY ( + ID INTEGER DEFAULT NEXTVAL('IDP_PROV_ENTITY_SEQ'), + PROVISIONING_CONFIG_ID INTEGER, + ENTITY_TYPE VARCHAR(255) NOT NULL, + ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, + ENTITY_NAME VARCHAR(255) NOT NULL, + ENTITY_VALUE VARCHAR(255), + TENANT_ID INTEGER, + ENTITY_LOCAL_ID VARCHAR(255), + PRIMARY KEY (ID), + UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), + UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), + FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDP_LOCAL_CLAIM; +DROP SEQUENCE IF EXISTS IDP_LOCAL_CLAIM_SEQ; +CREATE SEQUENCE IDP_LOCAL_CLAIM_SEQ; +CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM( + ID INTEGER DEFAULT NEXTVAL('IDP_LOCAL_CLAIM_SEQ'), + TENANT_ID INTEGER, + IDP_ID INTEGER, + CLAIM_URI VARCHAR(255) NOT NULL, + DEFAULT_VALUE VARCHAR(255), + IS_REQUESTED VARCHAR(128) DEFAULT '0', + PRIMARY KEY (ID), + UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); + +DROP TABLE IF EXISTS IDN_ASSOCIATED_ID; +DROP SEQUENCE IF EXISTS IDN_ASSOCIATED_ID_SEQ; +CREATE SEQUENCE IDN_ASSOCIATED_ID_SEQ; +CREATE TABLE IDN_ASSOCIATED_ID ( + ID INTEGER DEFAULT NEXTVAL('IDN_ASSOCIATED_ID_SEQ'), + IDP_USER_ID VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT -1234, + IDP_ID INTEGER NOT NULL, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), + FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE +); + +DROP TABLE IF EXISTS IDN_USER_ACCOUNT_ASSOCIATION; +CREATE TABLE IDN_USER_ACCOUNT_ASSOCIATION ( + ASSOCIATION_KEY VARCHAR(255) NOT NULL, + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)); + +DROP TABLE IF EXISTS FIDO_DEVICE_STORE; +CREATE TABLE FIDO_DEVICE_STORE ( + TENANT_ID INTEGER, + DOMAIN_NAME VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(45) NOT NULL, + TIME_REGISTERED TIMESTAMP, + KEY_HANDLE VARCHAR(200) NOT NULL, + DEVICE_DATA VARCHAR(2048) NOT NULL, + PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)); + +DROP TABLE IF EXISTS WF_REQUEST; +CREATE TABLE WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BYTEA, + PRIMARY KEY (UUID) +); + +DROP TABLE IF EXISTS WF_BPS_PROFILE; +CREATE TABLE WF_BPS_PROFILE ( + PROFILE_NAME VARCHAR(45), + HOST_URL_MANAGER VARCHAR(255), + HOST_URL_WORKER VARCHAR(255), + USERNAME VARCHAR(45), + PASSWORD VARCHAR(255), + CALLBACK_HOST VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (PROFILE_NAME, TENANT_ID) +); + +DROP TABLE IF EXISTS WF_WORKFLOW; +CREATE TABLE WF_WORKFLOW( + ID VARCHAR (45), + WF_NAME VARCHAR (45), + DESCRIPTION VARCHAR (255), + TEMPLATE_ID VARCHAR (45), + IMPL_ID VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID) +); + +DROP TABLE IF EXISTS WF_WORKFLOW_ASSOCIATION; +DROP SEQUENCE IF EXISTS WF_WORKFLOW_ASSOCIATION_PK_SEQ; +CREATE SEQUENCE WF_WORKFLOW_ASSOCIATION_PK_SEQ; +CREATE TABLE WF_WORKFLOW_ASSOCIATION( + ID INTEGER DEFAULT NEXTVAL('WF_WORKFLOW_ASSOCIATION_PK_SEQ'), + ASSOC_NAME VARCHAR (45), + EVENT_ID VARCHAR(45), + ASSOC_CONDITION VARCHAR (2000), + WORKFLOW_ID VARCHAR (45), + IS_ENABLED CHAR (1) DEFAULT '1', + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +DROP TABLE IF EXISTS WF_WORKFLOW_CONFIG_PARAM; +CREATE TABLE WF_WORKFLOW_CONFIG_PARAM( + WORKFLOW_ID VARCHAR (45), + PARAM_NAME VARCHAR (45), + PARAM_VALUE VARCHAR (1000), + PARAM_QNAME VARCHAR (45), + PARAM_HOLDER VARCHAR (45), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (WORKFLOW_ID, PARAM_NAME, PARAM_QNAME, PARAM_HOLDER), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE +); + +DROP TABLE IF EXISTS WF_REQUEST_ENTITY_RELATIONSHIP; +CREATE TABLE WF_REQUEST_ENTITY_RELATIONSHIP( + REQUEST_ID VARCHAR (45), + ENTITY_NAME VARCHAR (255), + ENTITY_TYPE VARCHAR (50), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY(REQUEST_ID, ENTITY_NAME, ENTITY_TYPE, TENANT_ID), + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); + +DROP TABLE IF EXISTS WF_WORKFLOW_REQUEST_RELATION; +CREATE TABLE WF_WORKFLOW_REQUEST_RELATION( + RELATIONSHIP_ID VARCHAR (45), + WORKFLOW_ID VARCHAR (45), + REQUEST_ID VARCHAR (45), + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (RELATIONSHIP_ID), + FOREIGN KEY (WORKFLOW_ID) REFERENCES WF_WORKFLOW(ID)ON DELETE CASCADE, + FOREIGN KEY (REQUEST_ID) REFERENCES WF_REQUEST(UUID)ON DELETE CASCADE +); + +-- End of IDENTITY Tables-- + +CREATE SEQUENCE AM_SUBSCRIBER_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER DEFAULT nextval('am_subscriber_sequence'), + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED DATE NOT NULL, + CREATED_BY VARCHAR(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATE, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +) +; + +CREATE SEQUENCE AM_APPLICATION_SEQUENCE START WITH 1 INCREMENT BY 1 ; +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER DEFAULT nextval('am_application_sequence'), + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + GROUP_ID VARCHAR(100), + CREATED_BY VARCHAR(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATE, + UUID VARCHAR(256), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID), + UNIQUE (UUID) +) +; + +CREATE SEQUENCE AM_API_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API ( + API_ID INTEGER DEFAULT nextval('am_api_sequence'), + API_PROVIDER VARCHAR(256), + API_NAME VARCHAR(256), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + CONTEXT_TEMPLATE VARCHAR(256), + API_TIER VARCHAR(256), + CREATED_BY VARCHAR(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATE, + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +); + +CREATE SEQUENCE AM_API_URL_MAPPING_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API_URL_MAPPING ( + URL_MAPPING_ID INTEGER DEFAULT nextval('am_api_url_mapping_sequence'), + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + MEDIATION_SCRIPT BYTEA, + PRIMARY KEY(URL_MAPPING_ID) +) +; + +CREATE SEQUENCE AM_SUBSCRIPTION_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER DEFAULT nextval('am_subscription_sequence'), + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED DATE NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + SUBS_CREATE_STATE VARCHAR(50) DEFAULT 'SUBSCRIBE', + CREATED_BY VARCHAR(100), + CREATED_TIME DATE, + UPDATED_BY VARCHAR(100), + UPDATED_TIME DATE, + UUID VARCHAR(256), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (UUID) +) +; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +) +; + +CREATE TABLE AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + STATE VARCHAR(30), + CREATE_MODE VARCHAR(30) DEFAULT 'CREATED', + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,KEY_TYPE) +) +; + +CREATE SEQUENCE AM_APPLICATION_REGISTRATION_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_APPLICATION_REGISTRATION ( + REG_ID INTEGER DEFAULT nextval('am_application_registration_sequence'), + SUBSCRIBER_ID INT, + WF_REF VARCHAR(255) NOT NULL, + APP_ID INT, + TOKEN_TYPE VARCHAR(30), + TOKEN_SCOPE VARCHAR(256) DEFAULT 'default', + INPUTS VARCHAR(1000), + ALLOWED_DOMAINS VARCHAR(256), + VALIDITY_PERIOD BIGINT, + UNIQUE (SUBSCRIBER_ID,APP_ID,TOKEN_TYPE), + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (REG_ID) +) +; + + + +CREATE SEQUENCE AM_API_LC_EVENT_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API_LC_EVENT ( + EVENT_ID INTEGER DEFAULT nextval('am_api_lc_event_sequence'), + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATE NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +) +; + +CREATE TABLE IF NOT EXISTS AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN) +) +; + +CREATE SEQUENCE AM_API_COMMENTS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API_COMMENTS ( + COMMENT_ID INTEGER DEFAULT nextval('am_api_comments_sequence'), + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED DATE NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +) +; + +CREATE SEQUENCE AM_WORKFLOWS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER DEFAULT nextval('am_workflows_sequence'), + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP , + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +) +; + +CREATE SEQUENCE AM_API_RATINGS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API_RATINGS ( + RATING_ID INTEGER DEFAULT nextval('am_api_ratings_sequence'), + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (RATING_ID) +) +; + +CREATE SEQUENCE AM_TIER_PERMISSIONS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER DEFAULT nextval('am_tier_permissions_sequence'), + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +); + +CREATE SEQUENCE AM_EXTERNAL_STORES_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER DEFAULT nextval('am_external_stores_sequence'), + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES AM_API(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (APISTORE_ID) +) +; + + +CREATE TABLE IF NOT EXISTS AM_API_SCOPES ( + API_ID INTEGER NOT NULL, + SCOPE_ID INTEGER NOT NULL, + FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + + +CREATE SEQUENCE AM_API_DEFAULT_VERSION_PK_SEQ; +CREATE TABLE IF NOT EXISTS AM_API_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INTEGER DEFAULT NEXTVAL('am_api_default_version_pk_seq'), + API_NAME VARCHAR(256) NOT NULL , + API_PROVIDER VARCHAR(256) NOT NULL , + DEFAULT_API_VERSION VARCHAR(30) , + PUBLISHED_DEFAULT_API_VERSION VARCHAR(30) , + PRIMARY KEY (DEFAULT_VERSION_ID) +); + + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID) +; + +CREATE SEQUENCE AM_ALERT_TYPES_SEQ START WITH 1 INCREMENT BY 1; + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES ( + ALERT_TYPE_ID INTEGER DEFAULT NEXTVAL('am_alert_types_seq'), + ALERT_TYPE_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL, + PRIMARY KEY (ALERT_TYPE_ID) +); + +CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES ( + ALERT_TYPE_ID INTEGER, + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_TYPES_VALUES_CONST UNIQUE (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER) +); + +CREATE SEQUENCE AM_ALERT_EMAILLIST_SEQ START WITH 1 INCREMENT BY 1; + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST ( + EMAIL_LIST_ID INTEGER DEFAULT NEXTVAL('am_alert_emaillist_seq'), + USER_NAME VARCHAR(255) NOT NULL , + STAKE_HOLDER VARCHAR(100) NOT NULL , + CONSTRAINT AM_ALERT_EMAILLIST_CONST UNIQUE (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER), + PRIMARY KEY (EMAIL_LIST_ID) +); + +CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST_DETAILS ( + EMAIL_LIST_ID INTEGER, + EMAIL VARCHAR(255), + CONSTRAINT AM_ALERT_EMAILLIST_DETAILS_CONST UNIQUE (EMAIL_LIST_ID,EMAIL) +); + +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher'); +INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher'); + + + +-- AM Throttling tables -- +CREATE SEQUENCE AM_POLICY_SUBSCRIPTION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION ( + POLICY_ID INTEGER DEFAULT NEXTVAL('AM_POLICY_SUBSCRIPTION_SEQ'), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + RATE_LIMIT_COUNT INTEGER NULL DEFAULT NULL, + RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL, + IS_DEPLOYED BOOLEAN NOT NULL DEFAULT '0', + CUSTOM_ATTRIBUTES BYTEA DEFAULT NULL, + STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT '0', + BILLING_PLAN VARCHAR(20) NOT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE SEQUENCE AM_POLICY_APPLICATION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION ( + POLICY_ID INTEGER DEFAULT NEXTVAL('AM_POLICY_APPLICATION_SEQ'), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED BOOLEAN NOT NULL DEFAULT '0', + CUSTOM_ATTRIBUTES BYTEA DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE SEQUENCE AM_POLICY_HARD_THROTTLING_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING ( + POLICY_ID INTEGER DEFAULT NEXTVAL('AM_POLICY_HARD_THROTTLING_SEQ'), + NAME VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + QUOTA_TYPE VARCHAR(25) NOT NULL, + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + IS_DEPLOYED BOOLEAN NOT NULL DEFAULT '0', + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID) +); + +CREATE SEQUENCE AM_API_THROTTLE_POLICY_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY ( + POLICY_ID INTEGER DEFAULT NEXTVAL('AM_API_THROTTLE_POLICY_SEQ'), + NAME VARCHAR(512) NOT NULL, + DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR (1024), + DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL, + DEFAULT_QUOTA INTEGER NOT NULL, + DEFAULT_QUOTA_UNIT VARCHAR(10) NULL, + DEFAULT_UNIT_TIME INTEGER NOT NULL, + DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL, + APPLICABLE_LEVEL VARCHAR(25) NOT NULL, + IS_DEPLOYED BOOLEAN NOT NULL DEFAULT '0', + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (NAME, TENANT_ID), + UNIQUE (UUID) +); + +CREATE SEQUENCE AM_CONDITION_GROUP_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP ( + CONDITION_GROUP_ID INTEGER DEFAULT NEXTVAL('AM_CONDITION_GROUP_SEQ'), + POLICY_ID INTEGER NOT NULL, + QUOTA_TYPE VARCHAR(25), + QUOTA INTEGER NOT NULL, + QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL, + UNIT_TIME INTEGER NOT NULL, + TIME_UNIT VARCHAR(25) NOT NULL, + DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL, + PRIMARY KEY (CONDITION_GROUP_ID), + FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE SEQUENCE AM_QUERY_PARAMETER_CONDITION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION ( + QUERY_PARAMETER_ID INTEGER DEFAULT NEXTVAL('AM_QUERY_PARAMETER_CONDITION_SEQ'), + CONDITION_GROUP_ID INTEGER NOT NULL, + PARAMETER_NAME VARCHAR(255) DEFAULT NULL, + PARAMETER_VALUE VARCHAR(255) DEFAULT NULL, + IS_PARAM_MAPPING BOOLEAN DEFAULT '1', + PRIMARY KEY (QUERY_PARAMETER_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE SEQUENCE AM_HEADER_FIELD_CONDITION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION ( + HEADER_FIELD_ID INTEGER DEFAULT NEXTVAL('AM_HEADER_FIELD_CONDITION_SEQ'), + CONDITION_GROUP_ID INTEGER NOT NULL, + HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL, + HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL, + IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT '1', + PRIMARY KEY (HEADER_FIELD_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE SEQUENCE AM_JWT_CLAIM_CONDITION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION ( + JWT_CLAIM_ID INTEGER DEFAULT NEXTVAL('AM_JWT_CLAIM_CONDITION_SEQ'), + CONDITION_GROUP_ID INTEGER NOT NULL, + CLAIM_URI VARCHAR(512) DEFAULT NULL, + CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL, + IS_CLAIM_MAPPING BOOLEAN DEFAULT '1', + PRIMARY KEY (JWT_CLAIM_ID), + FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE SEQUENCE AM_IP_CONDITION_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_IP_CONDITION ( + AM_IP_CONDITION_ID INTEGER DEFAULT NEXTVAL('AM_IP_CONDITION_SEQ'), + STARTING_IP VARCHAR(45) NULL, + ENDING_IP VARCHAR(45) NULL, + SPECIFIC_IP VARCHAR(45) NULL, + WITHIN_IP_RANGE BOOLEAN DEFAULT '1', + CONDITION_GROUP_ID INT NULL, + PRIMARY KEY (AM_IP_CONDITION_ID), + FOREIGN KEY (CONDITION_GROUP_ID) + REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE); + +CREATE SEQUENCE AM_POLICY_GLOBAL_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL ( + POLICY_ID INTEGER DEFAULT NEXTVAL('AM_POLICY_GLOBAL_SEQ'), + NAME VARCHAR(512) NOT NULL, + KEY_TEMPLATE VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL, + SIDDHI_QUERY BYTEA DEFAULT NULL, + IS_DEPLOYED BOOLEAN NOT NULL DEFAULT '0', + UUID VARCHAR(256), + PRIMARY KEY (POLICY_ID), + UNIQUE (UUID) +); + +CREATE SEQUENCE AM_THROTTLE_TIER_PERMISSIONS_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS ( + THROTTLE_TIER_PERMISSIONS_ID INTEGER DEFAULT NEXTVAL('AM_THROTTLE_TIER_PERMISSIONS_SEQ'), + TIER VARCHAR(50) NULL, + PERMISSIONS_TYPE VARCHAR(50) NULL, + ROLES VARCHAR(512) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID)); + +CREATE SEQUENCE AM_BLOCK_CONDITIONS_SEQ START WITH 1 INCREMENT BY 1; +CREATE TABLE AM_BLOCK_CONDITIONS ( + CONDITION_ID INTEGER DEFAULT NEXTVAL('AM_BLOCK_CONDITIONS_SEQ'), + TYPE varchar(45) DEFAULT NULL, + VALUE varchar(45) DEFAULT NULL, + ENABLED varchar(45) DEFAULT NULL, + DOMAIN varchar(45) DEFAULT NULL, + UUID VARCHAR(256), + PRIMARY KEY (CONDITION_ID), + UNIQUE (UUID) +); + +-- End of API-MGT Tables -- + +-- Performance indexes start-- + +create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); +create index IDX_IOAT_AT on IDN_OAUTH2_ACCESS_TOKEN (ACCESS_TOKEN); +create index IDX_IOAT_UT on IDN_OAUTH2_ACCESS_TOKEN (USER_TYPE); +create index IDX_AAI_CTX on AM_API (CONTEXT); +create index IDX_AAKM_CK on AM_APPLICATION_KEY_MAPPING (CONSUMER_KEY); +create index IDX_AAUM_AI on AM_API_URL_MAPPING (API_ID); +create index IDX_AAUM_TT on AM_API_URL_MAPPING (THROTTLING_TIER); +create index IDX_AATP_DQT on AM_API_THROTTLE_POLICY (DEFAULT_QUOTA_TYPE); +create index IDX_ACG_QT on AM_CONDITION_GROUP (QUOTA_TYPE); +create index IDX_APS_QT on AM_POLICY_SUBSCRIPTION (QUOTA_TYPE); +create index IDX_AS_AITIAI on AM_SUBSCRIPTION (API_ID,TIER_ID,APPLICATION_ID); +create index IDX_APA_QT on AM_POLICY_APPLICATION (QUOTA_TYPE); +create index IDX_AA_AT_CB on AM_APPLICATION (APPLICATION_TIER,CREATED_BY); + +-- Performance indexes end-- + + +commit; + diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/h2-sample-data.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/h2-sample-data.sql new file mode 100644 index 00000000..5ade02bc --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/h2-sample-data.sql @@ -0,0 +1,61 @@ +DELETE FROM AM_SUBSCRIPTION_KEY_MAPPING; +DELETE FROM AM_APPLICATION_KEY_MAPPING; +DELETE FROM AM_SUBSCRIPTION ; +DELETE FROM AM_APPLICATION ; +DELETE FROM AM_SUBSCRIBER; +DELETE FROM APPMGR_APP; +DELETE FROM IDN_OAUTH2_ACCESS_TOKEN ; +DELETE FROM IDN_OAUTH_CONSUMER_APPS; + +ALTER TABLE AM_SUBSCRIBER ALTER COLUMN SUBSCRIBER_ID RESTART WITH 1; +ALTER TABLE AM_APPLICATION ALTER COLUMN APPLICATION_ID RESTART WITH 100; +ALTER TABLE APPMGR_APP ALTER COLUMN API_ID RESTART WITH 500; +ALTER TABLE AM_SUBSCRIPTION ALTER COLUMN SUBSCRIPTION_ID RESTART WITH 1000; + +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('SUMEDHA',-1234,'SUMEDHA@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('PRABATH',-1234,'PRABATH@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('THILINA',-1234,'THILINA@WSO2.COM','2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIBER ( USER_ID , TENANT_ID , EMAIL_ADDRESS , DATE_SUBSCRIBED ) VALUES ('UDAYANGA',-1234,'UDAYANGA@WSO2.COM','2012-03-05 12:10:11'); + + +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('APPLICATION1',1); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('APPLICATION2',1); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('APPLICATION3',2); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('APPLICATION4',2); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('APPLICATION5',3); +INSERT INTO AM_APPLICATION (NAME,SUBSCRIBER_ID ) VALUES ('DeliciousApp',4); + +INSERT INTO APPMGR_APP (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('SUMEDHA', 'API1', 'V1.0.0','/context1'); +INSERT INTO APPMGR_APP (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('PRABATH', 'API2', 'V1.0.0','/deli2'); +INSERT INTO APPMGR_APP (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('ADMIN', 'API3', 'V1.0.0','/test'); +INSERT INTO APPMGR_APP (API_PROVIDER,API_NAME,API_VERSION,CONTEXT) VALUES ('DEL', 'Delicious', '1.0.0','/deli'); + +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',500,100,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',501,101,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',500,102,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',502,103,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',501,104,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',503,105,'2012-03-05 12:10:11'); +INSERT INTO AM_SUBSCRIPTION ( TIER_ID , API_ID , APPLICATION_ID , LAST_ACCESSED ) VALUES ('T1',501,102,'2012-03-05 12:10:11'); + +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1000, 'SSDCHEJJ-AWUIS-232', 'PRODUCTION'); +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1001, 'a1b2c3d4', 'SANDBOX'); +INSERT INTO AM_SUBSCRIPTION_KEY_MAPPING (SUBSCRIPTION_ID, ACCESS_TOKEN, KEY_TYPE) VALUES (1002, 'p1q2r3s4', 'PRODUCTION'); + +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (100, 'CON1', 'PRODUCTION'); +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (100, 'CON2', 'SANDBOX'); +INSERT INTO AM_APPLICATION_KEY_MAPPING (APPLICATION_ID, CONSUMER_KEY, KEY_TYPE) VALUES (101, 'CON3', 'PRODUCTION'); + +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON1','MY PEN','2.0',0,'PRABATH'); +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON2','MY PEN','2.0',0,'PRABATH'); +INSERT INTO IDN_OAUTH_CONSUMER_APPS ( APP_NAME , CALLBACK_URL , CONSUMER_KEY , CONSUMER_SECRET ,OAUTH_VERSION , TENANT_ID , USERNAME ) VALUES (NULL,NULL,'CON3','MY PEN','2.0',0,'admin'); + +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('a1b2c3d4','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','SANDBOX','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('p1q2r3s4','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','PRODUCTION','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('test1','UDAYANGA','DEVELOPER','CON1',NULL,'2012-01-01','PRODUCTION','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('test2','UDAYANGA','DEVELOPER','CON2',NULL,'2012-01-01','SANDBOX','ACTIVE',1343714931875); +INSERT INTO IDN_OAUTH2_ACCESS_TOKEN ( ACCESS_TOKEN ,AUTHZ_USER , USER_TYPE , CONSUMER_KEY , REFRESH_TOKEN ,TIME_CREATED , TOKEN_SCOPE , TOKEN_STATE ,VALIDITY_PERIOD ) VALUES ('test3','UDAYANGA','DEVELOPER','CON3',NULL,'2012-01-01','PRODUCTION','ACTIVE',3600); + +SELECT * FROM AM_SUBSCRIBER; +SELECT * FROM AM_APPLICATION; +SELECT * FROM AM_SUBSCRIPTION; diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/h2.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/h2.sql new file mode 100644 index 00000000..1c509006 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/h2.sql @@ -0,0 +1,304 @@ +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR (255), + CONSUMER_SECRET VARCHAR (512), + USERNAME VARCHAR (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR (255), + OAUTH_VERSION VARCHAR (128), + CALLBACK_URL VARCHAR (1024), + GRANT_TYPES VARCHAR (1024), + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS APM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +); + +CREATE TABLE IF NOT EXISTS APM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES APM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +); +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER( + OWNER_ID INTEGER AUTO_INCREMENT, + OWNER_NAME VARCHAR(200) NOT NULL, + OWNER_EMAIL VARCHAR(300) NOT NULL, + OWNER_DESC VARCHAR(1500), + OWNER_SITE VARCHAR(200), + TENANT_ID INTEGER, + PRIMARY KEY(OWNER_ID), + UNIQUE (OWNER_NAME,OWNER_EMAIL,TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER_PROPERTY( + OWNER_PROP_ID INTEGER AUTO_INCREMENT, + OWNER_ID INTEGER NOT NULL, + NAME VARCHAR(200) NOT NULL, + VALUE VARCHAR(300) NOT NULL, + SHOW_IN_STORE BOOLEAN NOT NULL, + PRIMARY KEY(OWNER_PROP_ID), + FOREIGN KEY(OWNER_ID) REFERENCES APM_BUSINESS_OWNER(OWNER_ID) +); + + CREATE TABLE IF NOT EXISTS APM_APP ( + APP_ID INTEGER AUTO_INCREMENT, + APP_PROVIDER VARCHAR(256), + TENANT_ID INTEGER, + APP_NAME VARCHAR(256), + APP_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + TRACKING_CODE varchar(100), + VISIBLE_ROLES varchar(500), + UUID varchar(500), + SAML2_SSO_ISSUER varchar(500), + LOG_OUT_URL varchar(500), + APP_ALLOW_ANONYMOUS BOOLEAN NULL, + APP_ENDPOINT varchar(500), + TREAT_AS_SITE BOOLEAN NOT NULL, + PRIMARY KEY(APP_ID), + UNIQUE (APP_PROVIDER,APP_NAME,APP_VERSION,TRACKING_CODE,UUID) + ); + +CREATE TABLE IF NOT EXISTS APM_POLICY_GROUP +( + POLICY_GRP_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(256), + AUTH_SCHEME VARCHAR(50) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + USER_ROLES varchar(512) DEFAULT NULL, + URL_ALLOW_ANONYMOUS BOOLEAN DEFAULT FALSE, + DESCRIPTION VARCHAR(1000) NULL, + PRIMARY KEY (POLICY_GRP_ID) +); + +CREATE TABLE IF NOT EXISTS APM_POLICY_GROUP_MAPPING +( + POLICY_GRP_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + PRIMARY KEY (POLICY_GRP_ID,APP_ID) +); + +CREATE TABLE IF NOT EXISTS APM_APP_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + URL_PATTERN VARCHAR(512) NULL, + SKIP_THROTTLING BOOLEAN DEFAULT FALSE, + POLICY_GRP_ID INTEGER NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID), + PRIMARY KEY(URL_MAPPING_ID) +); + +CREATE TABLE IF NOT EXISTS APM_ENTITLEMENT_POLICY_PARTIAL ( + ENTITLEMENT_POLICY_PARTIAL_ID INTEGER AUTO_INCREMENT, + NAME varchar(256) DEFAULT NULL, + CONTENT varchar(2048) DEFAULT NULL, + SHARED BOOLEAN DEFAULT FALSE, + AUTHOR varchar(256) DEFAULT NULL, + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY(ENTITLEMENT_POLICY_PARTIAL_ID) +); + +CREATE TABLE IF NOT EXISTS APM_POLICY_GRP_PARTIAL_MAPPING ( + POLICY_GRP_ID INTEGER NOT NULL, + POLICY_PARTIAL_ID INTEGER NOT NULL, + EFFECT varchar(50), + POLICY_ID varchar(100) DEFAULT NULL, + FOREIGN KEY(POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP(POLICY_GRP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY(POLICY_PARTIAL_ID) REFERENCES APM_ENTITLEMENT_POLICY_PARTIAL(ENTITLEMENT_POLICY_PARTIAL_ID), + PRIMARY KEY(POLICY_GRP_ID, POLICY_PARTIAL_ID) +); + +CREATE TABLE IF NOT EXISTS APM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + SUBSCRIPTION_TYPE VARCHAR(50), + TIER_ID VARCHAR(50), + APP_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + TRUSTED_IDP VARCHAR(255) NULL, + SUBSCRIPTION_TIME TIMESTAMP NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES APM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE(APP_ID, APPLICATION_ID,SUBSCRIPTION_TYPE) +); + +CREATE TABLE IF NOT EXISTS APM_APP_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +); + +CREATE TABLE IF NOT EXISTS APM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +); + +CREATE TABLE IF NOT EXISTS APM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +); + +CREATE TABLE IF NOT EXISTS APM_API_CONSUMER_APPS ( + ID INTEGER AUTO_INCREMENT, + SAML2_SSO_ISSUER varchar(500), + APP_CONSUMER_KEY VARCHAR(512), + API_TOKEN_ENDPOINT VARCHAR (1024), + API_CONSUMER_KEY VARCHAR(512), + API_CONSUMER_SECRET VARCHAR(512), + APP_NAME VARCHAR(512), + PRIMARY KEY (ID, APP_CONSUMER_KEY), + FOREIGN KEY (SAML2_SSO_ISSUER) REFERENCES APM_APP(SAML2_SSO_ISSUER), + FOREIGN KEY (APP_CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS APM_APP_HITS ( +UUID VARCHAR(500) NOT NULL, +APP_NAME VARCHAR(200) NOT NULL, +VERSION VARCHAR(50), +CONTEXT VARCHAR(256) NOT NULL, +USER_ID VARCHAR(50) NOT NULL, +TENANT_ID INTEGER, +HIT_TIME TIMESTAMP NOT NULL, +PRIMARY KEY (UUID, USER_ID, TENANT_ID, HIT_TIME) +); + +CREATE TABLE IF NOT EXISTS APM_APP_JAVA_POLICY +( +JAVA_POLICY_ID INTEGER AUTO_INCREMENT, +DISPLAY_NAME VARCHAR(100) NOT NULL, +FULL_QUALIFI_NAME VARCHAR(256) NOT NULL, +DESCRIPTION VARCHAR(2500), +DISPLAY_ORDER_SEQ_NO INTEGER NOT NULL, +IS_MANDATORY BOOLEAN DEFAULT FALSE, +POLICY_PROPERTIES VARCHAR(512) NULL, +IS_GLOBAL BOOLEAN DEFAULT TRUE, +PRIMARY KEY(JAVA_POLICY_ID), +UNIQUE(FULL_QUALIFI_NAME,DISPLAY_ORDER_SEQ_NO) +); + + +CREATE TABLE IF NOT EXISTS APM_APP_JAVA_POLICY_MAPPING +( +JAVA_POLICY_ID INTEGER NOT NULL, +APP_ID INTEGER NOT NULL, +PRIMARY KEY (JAVA_POLICY_ID,APP_ID), +FOREIGN KEY (JAVA_POLICY_ID) REFERENCES APM_APP_JAVA_POLICY(JAVA_POLICY_ID) ON UPDATE CASCADE ON DELETE CASCADE, +FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS APM_EXTERNAL_STORES( + APP_STORE_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + PRIMARY KEY (APP_STORE_ID) +); + +CREATE TABLE IF NOT EXISTS APM_APP_DEFAULT_VERSION( + DEFAULT_VERSION_ID INTEGER AUTO_INCREMENT, + APP_NAME VARCHAR(256), + APP_PROVIDER VARCHAR(256), + DEFAULT_APP_VERSION VARCHAR(30), + PUBLISHED_DEFAULT_APP_VERSION VARCHAR(30), + TENANT_ID INTEGER, +PRIMARY KEY(DEFAULT_VERSION_ID) +); + +CREATE TABLE IF NOT EXISTS APM_FAVOURITE_APPS ( + ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + CREATED_TIME TIMESTAMP NOT NULL, + PRIMARY KEY (ID), + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + UNIQUE (TENANT_ID,USER_ID,APP_ID) +); + +CREATE TABLE IF NOT EXISTS APM_STORE_FAVOURITE_PAGE ( + ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID_OF_USER INTEGER NOT NULL, + TENANT_ID_OF_STORE INTEGER NOT NULL, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS APM_ONE_TIME_DOWNLOAD_LINK( + ID INTEGER AUTO_INCREMENT, + BINARY_FILE varchar(500) NOT NULL, + UUID varchar(500) NOT NULL, + IS_DOWNLOADED BOOLEAN NOT NULL, + USERNAME VARCHAR(255), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +); + + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, IS_GLOBAL ) +VALUES ('Reverse Proxy Handler','org.wso2.carbon.appmgt.gateway.handlers.proxy.ReverseProxyHandler','',1,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('SAML2 Authentication Handler','org.wso2.carbon.appmgt.gateway.handlers.security.authentication.SAML2AuthenticationHandler','',2,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Subscription Handler', 'org.wso2.carbon.appmgt.gateway.handlers.subscription.SubscriptionsHandler', '', 3,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Authorization Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.AuthorizationHandler','',4,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Entitlement Handler','org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.EntitlementHandler','',5,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, POLICY_PROPERTIES,IS_GLOBAL ) +VALUES ('API Throttle Handler','org.wso2.carbon.appmgt.gateway.handlers.throttling.APIThrottleHandler','',6,TRUE,'{ "id": "A", "policyKey": "gov:/appmgt/applicationdata/tiers.xml"}',TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Publish Statistics:','org.wso2.carbon.appmgt.usage.publisher.APPMgtUsageHandler','',7,FALSE,TRUE); + + +CREATE INDEX IDX_SUB_APP_ID ON APM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/mssql.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/mssql.sql new file mode 100644 index 00000000..6ebec919 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/mssql.sql @@ -0,0 +1,394 @@ +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[IDN_OAUTH_CONSUMER_APPS]') AND TYPE IN (N'U')) + CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER IDENTITY, + CONSUMER_KEY VARCHAR(512), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR(1024), + PRIMARY KEY (ID), + UNIQUE (CONSUMER_KEY) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_SUBSCRIBER]') AND TYPE IN (N'U')) + CREATE TABLE APM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER IDENTITY, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED DATETIME2(0) NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID, USER_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APPLICATION]') AND TYPE IN (N'U')) + CREATE TABLE APM_APPLICATION ( + APPLICATION_ID INTEGER IDENTITY, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + FOREIGN KEY (SUBSCRIBER_ID) REFERENCES APM_SUBSCRIBER (SUBSCRIBER_ID) ON UPDATE CASCADE, + PRIMARY KEY (APPLICATION_ID), + UNIQUE ( NAME, SUBSCRIBER_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_BUSINESS_OWNER') AND TYPE IN (N'U')) +CREATE TABLE APM_BUSINESS_OWNER( + OWNER_ID INTEGER IDENTITY, + OWNER_NAME VARCHAR(200) NOT NULL, + OWNER_EMAIL VARCHAR(300) NOT NULL, + OWNER_DESC VARCHAR(1500), + OWNER_SITE VARCHAR(200), + TENANT_ID INTEGER, + PRIMARY KEY(OWNER_ID), + UNIQUE (OWNER_NAME,OWNER_EMAIL,TENANT_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_BUSINESS_OWNER_PROPERTY') AND TYPE IN (N'U')) +CREATE TABLE APM_BUSINESS_OWNER_PROPERTY( + OWNER_PROP_ID INTEGER IDENTITY, + OWNER_ID INTEGER NOT NULL, + NAME VARCHAR(200) NOT NULL, + VALUE VARCHAR(300) NOT NULL, + SHOW_IN_STORE BIT NOT NULL, + PRIMARY KEY(OWNER_PROP_ID), + FOREIGN KEY(OWNER_ID) REFERENCES APM_BUSINESS_OWNER(OWNER_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP ( + APP_ID INTEGER IDENTITY, + APP_PROVIDER VARCHAR(256), + TENANT_ID INTEGER, + APP_NAME VARCHAR(256), + APP_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + TRACKING_CODE VARCHAR(100), + VISIBLE_ROLES VARCHAR(500), + UUID VARCHAR(500) NOT NULL, + SAML2_SSO_ISSUER VARCHAR(500), + LOG_OUT_URL VARCHAR(500), + APP_ALLOW_ANONYMOUS BIT NULL, + APP_ENDPOINT VARCHAR(500), + TREAT_AS_SITE BIT NOT NULL, + PRIMARY KEY (APP_ID), + UNIQUE (APP_PROVIDER, APP_NAME, APP_VERSION, TRACKING_CODE, UUID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_POLICY_GROUP]') AND TYPE IN (N'U')) + CREATE TABLE APM_POLICY_GROUP + ( + POLICY_GRP_ID INTEGER IDENTITY, + NAME VARCHAR(256), + AUTH_SCHEME VARCHAR(50) NULL, + THROTTLING_TIER VARCHAR(512) DEFAULT NULL, + USER_ROLES VARCHAR(512) DEFAULT NULL, + URL_ALLOW_ANONYMOUS BIT DEFAULT 0, + DESCRIPTION VARCHAR(1000) NULL, + PRIMARY KEY (POLICY_GRP_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_POLICY_GROUP_MAPPING]') AND TYPE IN (N'U')) + CREATE TABLE APM_POLICY_GROUP_MAPPING + ( + POLICY_GRP_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP (APP_ID) + ON UPDATE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID) + ON UPDATE CASCADE, + PRIMARY KEY (POLICY_GRP_ID, APP_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_URL_MAPPING]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP_URL_MAPPING ( + URL_MAPPING_ID INTEGER IDENTITY, + APP_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + URL_PATTERN VARCHAR(512) NULL, + SKIP_THROTTLING BIT DEFAULT 0, + POLICY_GRP_ID INTEGER NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP (APP_ID) + ON UPDATE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID), + PRIMARY KEY (URL_MAPPING_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_ENTITLEMENT_POLICY_PARTIAL]') AND TYPE IN (N'U')) + CREATE TABLE APM_ENTITLEMENT_POLICY_PARTIAL ( + ENTITLEMENT_POLICY_PARTIAL_ID INTEGER IDENTITY, + NAME VARCHAR(256) DEFAULT NULL, + CONTENT VARCHAR(2048) DEFAULT NULL, + SHARED BIT DEFAULT 0, + AUTHOR VARCHAR(256) DEFAULT NULL, + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY (ENTITLEMENT_POLICY_PARTIAL_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_POLICY_GRP_PARTIAL_MAPPING]') AND TYPE IN (N'U')) + CREATE TABLE APM_POLICY_GRP_PARTIAL_MAPPING ( + POLICY_GRP_ID INTEGER NOT NULL, + POLICY_PARTIAL_ID INTEGER NOT NULL, + EFFECT VARCHAR(50), + POLICY_ID VARCHAR(100) DEFAULT NULL, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID) + ON UPDATE CASCADE, + FOREIGN KEY (POLICY_PARTIAL_ID) REFERENCES APM_ENTITLEMENT_POLICY_PARTIAL (ENTITLEMENT_POLICY_PARTIAL_ID), + PRIMARY KEY (POLICY_GRP_ID, POLICY_PARTIAL_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_SUBSCRIPTION]') AND TYPE IN (N'U')) + CREATE TABLE APM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER IDENTITY, + SUBSCRIPTION_TYPE VARCHAR(50), + TIER_ID VARCHAR(50), + APP_ID INTEGER, + LAST_ACCESSED DATETIME2(0) NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + TRUSTED_IDP VARCHAR(255) NULL, + SUBSCRIPTION_TIME DATETIME2(0) NOT NULL, + FOREIGN KEY (APPLICATION_ID) REFERENCES APM_APPLICATION (APPLICATION_ID) + ON UPDATE CASCADE, + FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE (APP_ID, APPLICATION_ID, SUBSCRIPTION_TYPE) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_LC_EVENT]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP_LC_EVENT ( + EVENT_ID INTEGER IDENTITY, + APP_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATETIME2(0) NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP (APP_ID) + ON UPDATE CASCADE, + PRIMARY KEY (EVENT_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_TIER_PERMISSIONS]') AND TYPE IN (N'U')) + CREATE TABLE APM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER IDENTITY, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (TIER_PERMISSIONS_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_WORKFLOWS]') AND TYPE IN (N'U')) + CREATE TABLE APM_WORKFLOWS ( + WF_ID INTEGER IDENTITY, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME DATETIME2(0), + WF_UPDATED_TIME DATETIME2(0), + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_API_CONSUMER_APPS]') AND TYPE IN (N'U')) + CREATE TABLE APM_API_CONSUMER_APPS ( + ID INTEGER IDENTITY, + SAML2_SSO_ISSUER VARCHAR(500), + APP_CONSUMER_KEY VARCHAR(512), + API_TOKEN_ENDPOINT VARCHAR(1024), + API_CONSUMER_KEY VARCHAR(512), + API_CONSUMER_SECRET VARCHAR(512), + APP_NAME VARCHAR(512), + PRIMARY KEY (ID, APP_CONSUMER_KEY), + FOREIGN KEY (APP_CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS (CONSUMER_KEY) + ON UPDATE CASCADE); + +IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IDX_APM_APP_UUID' AND object_id = OBJECT_ID('APM_APP')) + CREATE INDEX IDX_APM_APP_UUID ON APM_APP (UUID); + +IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IDX_APM_SUBSCRIBER_USER_ID' AND object_id = OBJECT_ID('APM_SUBSCRIBER')) + CREATE INDEX IDX_APM_SUBSCRIBER_USER_ID ON APM_SUBSCRIBER (USER_ID); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_HITS]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP_HITS ( + UUID VARCHAR(500) NOT NULL, + APP_NAME VARCHAR(200) NOT NULL, + VERSION VARCHAR(50), + CONTEXT VARCHAR(256) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER, + HIT_TIME DATETIME2(0) NOT NULL, + PRIMARY KEY (UUID, USER_ID, TENANT_ID, HIT_TIME) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_JAVA_POLICY]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP_JAVA_POLICY + ( + JAVA_POLICY_ID INTEGER IDENTITY, + DISPLAY_NAME VARCHAR(100) NOT NULL, + FULL_QUALIFI_NAME VARCHAR(256) NOT NULL, + DESCRIPTION VARCHAR(2500), + DISPLAY_ORDER_SEQ_NO INTEGER NOT NULL, + IS_MANDATORY BIT DEFAULT 0, + POLICY_PROPERTIES VARCHAR(512) NULL, + IS_GLOBAL BIT DEFAULT 1, + PRIMARY KEY (JAVA_POLICY_ID), + UNIQUE (FULL_QUALIFI_NAME, DISPLAY_ORDER_SEQ_NO) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_JAVA_POLICY_MAPPING]') AND TYPE IN (N'U')) + CREATE TABLE APM_APP_JAVA_POLICY_MAPPING + ( + JAVA_POLICY_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + PRIMARY KEY (JAVA_POLICY_ID, APP_ID), + FOREIGN KEY (JAVA_POLICY_ID) REFERENCES APM_APP_JAVA_POLICY (JAVA_POLICY_ID) + ON UPDATE CASCADE, + FOREIGN KEY (APP_ID) REFERENCES APM_APP (APP_ID) + ON UPDATE CASCADE + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_EXTERNAL_STORES]') AND TYPE IN (N'U')) + CREATE TABLE APM_EXTERNAL_STORES ( + APP_STORE_ID INTEGER IDENTITY, + APP_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP (APP_ID) + ON UPDATE CASCADE, + PRIMARY KEY (APP_STORE_ID) + ); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_APP_DEFAULT_VERSION]') AND TYPE IN (N'U')) +CREATE TABLE APM_APP_DEFAULT_VERSION( + DEFAULT_VERSION_ID INTEGER IDENTITY, + APP_NAME VARCHAR(256), + APP_PROVIDER VARCHAR(256), + DEFAULT_APP_VERSION VARCHAR(30), + PUBLISHED_DEFAULT_APP_VERSION VARCHAR(30), + TENANT_ID INTEGER, +PRIMARY KEY(DEFAULT_VERSION_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_FAVOURITE_APPS]') AND TYPE IN (N'U')) +CREATE TABLE APM_FAVOURITE_APPS ( + ID INTEGER IDENTITY, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + CREATED_TIME DATETIME2(0) NOT NULL, + PRIMARY KEY (ID), + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + UNIQUE (TENANT_ID,USER_ID,APP_ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_STORE_FAVOURITE_PAGE]') AND TYPE IN (N'U')) +CREATE TABLE APM_STORE_FAVOURITE_PAGE ( + ID INTEGER IDENTITY, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID_OF_USER INTEGER NOT NULL, + TENANT_ID_OF_STORE INTEGER NOT NULL, + PRIMARY KEY (ID) +); + +IF NOT EXISTS(SELECT * + FROM SYS.OBJECTS + WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[APM_ONE_TIME_DOWNLOAD_LINK]') AND TYPE IN (N'U')) +CREATE TABLE APM_ONE_TIME_DOWNLOAD_LINK( + ID INTEGER IDENTITY, + BINARY_FILE varchar(500) NOT NULL, + UUID varchar(500) NOT NULL, + IS_DOWNLOADED BIT DEFAULT 0, + USERNAME VARCHAR(255), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + CREATED_TIME DATETIME2(0) NOT NULL, + PRIMARY KEY (ID) +); + +INSERT INTO APM_APP_JAVA_POLICY (DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO, IS_MANDATORY, IS_GLOBAL) +VALUES + ('Reverse Proxy Handler', 'org.wso2.carbon.appmgt.gateway.handlers.proxy.ReverseProxyHandler', '', 1, 1, 1); + +INSERT INTO APM_APP_JAVA_POLICY (DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO, IS_MANDATORY, IS_GLOBAL) +VALUES + ('SAML2 Authentication Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAML2AuthenticationHandler', + '', 2, 1, 1); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Subscription Handler', 'org.wso2.carbon.appmgt.gateway.handlers.subscription.SubscriptionsHandler', '', 3,1,1); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Authorization Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.AuthorizationHandler','',4,1,1); + +INSERT INTO APM_APP_JAVA_POLICY (DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO, IS_MANDATORY, IS_GLOBAL) +VALUES ('Entitlement Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.EntitlementHandler', '', 3, + 1, 1); + +INSERT INTO APM_APP_JAVA_POLICY (DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO, IS_MANDATORY, POLICY_PROPERTIES, IS_GLOBAL) +VALUES ('API Throttle Handler', 'org.wso2.carbon.appmgt.gateway.handlers.throttling.APIThrottleHandler', '', 4, 1, + '{ "id": "A", "policyKey": "gov:/appmgt/applicationdata/tiers.xml"}', 1); + +INSERT INTO APM_APP_JAVA_POLICY (DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO, IS_MANDATORY, IS_GLOBAL) +VALUES ('Publish Statistics:', 'org.wso2.carbon.appmgt.usage.publisher.APPMgtUsageHandler', '', 5, 0, 1); + + +CREATE INDEX IDX_SUB_APP_ID ON APM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/mysql.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/mysql.sql new file mode 100644 index 00000000..23db9793 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/mysql.sql @@ -0,0 +1,307 @@ +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER NOT NULL AUTO_INCREMENT, + CONSUMER_KEY VARCHAR(255), + CONSUMER_SECRET VARCHAR(512), + USERNAME VARCHAR(255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR(255), + OAUTH_VERSION VARCHAR(128), + CALLBACK_URL VARCHAR(1024), + GRANT_TYPES VARCHAR (1024), + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APPLICATION ( + APPLICATION_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES APM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER( + OWNER_ID INTEGER AUTO_INCREMENT, + OWNER_NAME VARCHAR(200) NOT NULL, + OWNER_EMAIL VARCHAR(300) NOT NULL, + OWNER_DESC VARCHAR(1500), + OWNER_SITE VARCHAR(200), + TENANT_ID INTEGER, + PRIMARY KEY(OWNER_ID), + UNIQUE (OWNER_NAME,OWNER_EMAIL,TENANT_ID) + +) ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER_PROPERTY( + OWNER_PROP_ID INTEGER AUTO_INCREMENT, + OWNER_ID INTEGER NOT NULL, + NAME VARCHAR(200) NOT NULL, + VALUE VARCHAR(300) NOT NULL, + SHOW_IN_STORE BOOLEAN NOT NULL, + PRIMARY KEY(OWNER_PROP_ID), + FOREIGN KEY(OWNER_ID) REFERENCES APM_BUSINESS_OWNER(OWNER_ID) +) ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APP ( + APP_ID INTEGER AUTO_INCREMENT, + APP_PROVIDER VARCHAR(256), + TENANT_ID INTEGER, + APP_NAME VARCHAR(256), + APP_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + TRACKING_CODE varchar(100), + VISIBLE_ROLES varchar(500), + UUID varchar(500) NOT NULL, + SAML2_SSO_ISSUER varchar(500), + LOG_OUT_URL varchar(500), + APP_ALLOW_ANONYMOUS BOOLEAN NULL, + APP_ENDPOINT varchar(500), + TREAT_AS_SITE BOOLEAN NOT NULL, + PRIMARY KEY(APP_ID), + UNIQUE (APP_PROVIDER,APP_NAME,APP_VERSION,TRACKING_CODE,UUID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_POLICY_GROUP +( + POLICY_GRP_ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(256), + AUTH_SCHEME VARCHAR(50) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + USER_ROLES varchar(512) DEFAULT NULL, + URL_ALLOW_ANONYMOUS BOOLEAN DEFAULT FALSE, + DESCRIPTION VARCHAR(1000) NULL, + PRIMARY KEY (POLICY_GRP_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_POLICY_GROUP_MAPPING +( + POLICY_GRP_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + PRIMARY KEY (POLICY_GRP_ID,APP_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APP_URL_MAPPING ( + URL_MAPPING_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + URL_PATTERN VARCHAR(512) NULL, + SKIP_THROTTLING BOOLEAN DEFAULT FALSE, + POLICY_GRP_ID INTEGER NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID), + PRIMARY KEY(URL_MAPPING_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_ENTITLEMENT_POLICY_PARTIAL ( + ENTITLEMENT_POLICY_PARTIAL_ID INTEGER AUTO_INCREMENT, + NAME varchar(256) DEFAULT NULL, + CONTENT varchar(2048) DEFAULT NULL, + SHARED BOOLEAN DEFAULT FALSE, + AUTHOR varchar(256) DEFAULT NULL, + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INTEGER NULL, + PRIMARY KEY(ENTITLEMENT_POLICY_PARTIAL_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_POLICY_GRP_PARTIAL_MAPPING ( + POLICY_GRP_ID INTEGER NOT NULL, + POLICY_PARTIAL_ID INTEGER NOT NULL, + EFFECT varchar(50), + POLICY_ID varchar(100) DEFAULT NULL, + FOREIGN KEY(POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP(POLICY_GRP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY(POLICY_PARTIAL_ID) REFERENCES APM_ENTITLEMENT_POLICY_PARTIAL(ENTITLEMENT_POLICY_PARTIAL_ID), + PRIMARY KEY(POLICY_GRP_ID, POLICY_PARTIAL_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER AUTO_INCREMENT, + SUBSCRIPTION_TYPE VARCHAR(50), + TIER_ID VARCHAR(50), + APP_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + TRUSTED_IDP VARCHAR(255) NULL, + SUBSCRIPTION_TIME TIMESTAMP NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES APM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE(APP_ID, APPLICATION_ID,SUBSCRIPTION_TYPE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APP_LC_EVENT ( + EVENT_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER AUTO_INCREMENT, + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_WORKFLOWS( + WF_ID INTEGER AUTO_INCREMENT, + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_API_CONSUMER_APPS ( + ID INTEGER AUTO_INCREMENT, + SAML2_SSO_ISSUER varchar(500), + APP_CONSUMER_KEY VARCHAR(512), + API_TOKEN_ENDPOINT VARCHAR (1024), + API_CONSUMER_KEY VARCHAR(512), + API_CONSUMER_SECRET VARCHAR(512), + APP_NAME VARCHAR(512), + PRIMARY KEY (ID, APP_CONSUMER_KEY), + FOREIGN KEY (APP_CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) ON UPDATE CASCADE +)ENGINE INNODB; + +CREATE INDEX IDX_APM_APP_UUID ON APM_APP (UUID); + +CREATE INDEX IDX_APM_SUBSCRIBER_USER_ID ON APM_SUBSCRIBER (USER_ID); + +CREATE TABLE IF NOT EXISTS APM_APP_HITS ( +UUID VARCHAR(500) NOT NULL, +APP_NAME VARCHAR(200) NOT NULL, +VERSION VARCHAR(50), +CONTEXT VARCHAR(256) NOT NULL, +USER_ID VARCHAR(50) NOT NULL, +TENANT_ID INTEGER, +HIT_TIME TIMESTAMP NOT NULL, +PRIMARY KEY (UUID, USER_ID, TENANT_ID, HIT_TIME) +) ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APP_JAVA_POLICY +( +JAVA_POLICY_ID INTEGER AUTO_INCREMENT, +DISPLAY_NAME VARCHAR(100) NOT NULL, +FULL_QUALIFI_NAME VARCHAR(256) NOT NULL, +DESCRIPTION VARCHAR(2500), +DISPLAY_ORDER_SEQ_NO INTEGER NOT NULL, +IS_MANDATORY BOOLEAN DEFAULT FALSE, +POLICY_PROPERTIES VARCHAR(512) NULL, +IS_GLOBAL BOOLEAN DEFAULT TRUE, +PRIMARY KEY(JAVA_POLICY_ID), +UNIQUE(FULL_QUALIFI_NAME,DISPLAY_ORDER_SEQ_NO) +)ENGINE INNODB; + + +CREATE TABLE IF NOT EXISTS APM_APP_JAVA_POLICY_MAPPING +( +JAVA_POLICY_ID INTEGER NOT NULL, +APP_ID INTEGER NOT NULL, +PRIMARY KEY (JAVA_POLICY_ID,APP_ID), +FOREIGN KEY (JAVA_POLICY_ID) REFERENCES APM_APP_JAVA_POLICY(JAVA_POLICY_ID) ON UPDATE CASCADE ON DELETE CASCADE, +FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_EXTERNAL_STORES ( + APP_STORE_ID INTEGER AUTO_INCREMENT, + APP_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON UPDATE CASCADE ON DELETE CASCADE, + PRIMARY KEY (APP_STORE_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_APP_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INTEGER AUTO_INCREMENT, + APP_NAME VARCHAR(256), + APP_PROVIDER VARCHAR(256), + DEFAULT_APP_VERSION VARCHAR(30), + PUBLISHED_DEFAULT_APP_VERSION VARCHAR(30), + TENANT_ID INTEGER, +PRIMARY KEY(DEFAULT_VERSION_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_FAVOURITE_APPS ( + ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (ID), + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + UNIQUE (TENANT_ID,USER_ID,APP_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_STORE_FAVOURITE_PAGE ( + ID INTEGER AUTO_INCREMENT, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID_OF_USER INTEGER NOT NULL, + TENANT_ID_OF_STORE INTEGER NOT NULL, + PRIMARY KEY (ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS APM_ONE_TIME_DOWNLOAD_LINK( + ID INTEGER AUTO_INCREMENT, + BINARY_FILE varchar(500) NOT NULL, + UUID varchar(500) NOT NULL, + IS_DOWNLOADED BOOLEAN NOT NULL, + USERNAME VARCHAR(255), + TENANT_ID INTEGER, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +)ENGINE INNODB; + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, IS_GLOBAL ) +VALUES ('Reverse Proxy Handler','org.wso2.carbon.appmgt.gateway.handlers.proxy.ReverseProxyHandler','',1,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('SAML2 Authentication Handler','org.wso2.carbon.appmgt.gateway.handlers.security.authentication.SAML2AuthenticationHandler','',2,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Subscription Handler', 'org.wso2.carbon.appmgt.gateway.handlers.subscription.SubscriptionsHandler', '', 3,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Authorization Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.AuthorizationHandler','',4,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Entitlement Handler','org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.EntitlementHandler','',5,TRUE,TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, POLICY_PROPERTIES,IS_GLOBAL ) +VALUES ('API Throttle Handler','org.wso2.carbon.appmgt.gateway.handlers.throttling.APIThrottleHandler','',6,TRUE,'{ "id": "A", "policyKey": "gov:/appmgt/applicationdata/tiers.xml"}',TRUE); + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Publish Statistics:','org.wso2.carbon.appmgt.usage.publisher.APPMgtUsageHandler','',7,FALSE,TRUE); + + +CREATE INDEX IDX_SUB_APP_ID ON APM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID); diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/oracle.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/oracle.sql new file mode 100644 index 00000000..018fef01 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/oracle.sql @@ -0,0 +1,625 @@ +declare + v_sql LONG; + sequence_sql LONG; + trigger_sql LONG; +begin + + v_sql:='CREATE TABLE IDN_OAUTH_CONSUMER_APPS ( + ID INTEGER, + CONSUMER_KEY VARCHAR2 (255), + CONSUMER_SECRET VARCHAR2 (512), + USERNAME VARCHAR2 (255), + TENANT_ID INTEGER DEFAULT 0, + USER_DOMAIN VARCHAR(50), + APP_NAME VARCHAR2 (255), + OAUTH_VERSION VARCHAR2 (128), + CALLBACK_URL VARCHAR2 (1024), + GRANT_TYPES VARCHAR (1024), + CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (CONSUMER_KEY), + PRIMARY KEY (ID))'; + + sequence_sql:='CREATE SEQUENCE IDN_OAUTH_CONSUMER_APPS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE'; + + trigger_sql:= 'CREATE OR REPLACE TRIGGER IDN_OAUTH_CONSUMER_APPS_TRIG + BEFORE INSERT + ON IDN_OAUTH_CONSUMER_APPS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT IDN_OAUTH_CONSUMER_APPS_SEQ.nextval INTO :NEW.ID FROM dual; + END'; + + execute immediate v_sql; + execute immediate sequence_sql; + execute immediate trigger_sql; + + EXCEPTION + WHEN OTHERS THEN + IF SQLCODE = -955 THEN + NULL; -- suppresses ORA-00955 exception + ELSE + RAISE; + END IF; +END; +/ + +CREATE TABLE APM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR2(256) NULL, + DATE_SUBSCRIBED TIMESTAMP NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +) +/ + +CREATE SEQUENCE APM_SUBSCRIBER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_SUBSCRIBER_TRG + BEFORE INSERT + ON APM_SUBSCRIBER + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_SUBSCRIBER_SEQ.nextval INTO :NEW.SUBSCRIBER_ID FROM dual; + END; +/ + +CREATE INDEX IDX_APM_SUBSCRIBER_USER_ID ON APM_SUBSCRIBER (USER_ID) +/ + +CREATE TABLE APM_APPLICATION ( + APPLICATION_ID INTEGER, + NAME VARCHAR2(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR2(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR2(512), + DESCRIPTION VARCHAR2(512), + APPLICATION_STATUS VARCHAR2(50) DEFAULT 'APPROVED', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES APM_SUBSCRIBER(SUBSCRIBER_ID), + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +) +/ + +CREATE SEQUENCE APM_APPLICATION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_APPLICATION_TRG + BEFORE INSERT + ON APM_APPLICATION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APPLICATION_SEQ.nextval INTO :NEW.APPLICATION_ID FROM dual; + END; +/ + +CREATE TABLE APM_BUSINESS_OWNER( + OWNER_ID INTEGER, + OWNER_NAME VARCHAR2(200) NOT NULL, + OWNER_EMAIL VARCHAR2(300) NOT NULL, + OWNER_DESC VARCHAR2(1500), + OWNER_SITE VARCHAR2(200), + TENANT_ID INTEGER, + PRIMARY KEY(OWNER_ID), + UNIQUE (OWNER_NAME,OWNER_EMAIL,TENANT_ID) +) +/ + +CREATE SEQUENCE APM_BUSINESS_OWNER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_BUSINESS_OWNER_TRG + BEFORE INSERT + ON APM_BUSINESS_OWNER + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_BUSINESS_OWNER_SEQ.nextval INTO :NEW.OWNER_ID FROM dual; + END; + / + +CREATE TABLE APM_BUSINESS_OWNER_PROPERTY( + OWNER_PROP_ID INTEGER NOT NULL, + OWNER_ID INTEGER NOT NULL, + NAME VARCHAR2(200) NOT NULL, + VALUE VARCHAR2(300) NOT NULL, + SHOW_IN_STORE NUMBER(1) NOT NULL, + PRIMARY KEY(OWNER_PROP_ID), + FOREIGN KEY(OWNER_ID) REFERENCES APM_BUSINESS_OWNER(OWNER_ID) +) +/ + +CREATE SEQUENCE APM_BUSINESS_OWNER_PROP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_BUSINESS_OWNER_PROP_TRG + BEFORE INSERT + ON APM_BUSINESS_OWNER_PROPERTY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_BUSINESS_OWNER_PROP_SEQ.nextval INTO :NEW.OWNER_PROP_ID FROM dual; + END; +/ + +CREATE TABLE APM_APP ( + APP_ID INTEGER, + APP_PROVIDER VARCHAR2(256), + TENANT_ID INTEGER, + APP_NAME VARCHAR2(256), + APP_VERSION VARCHAR2(30), + CONTEXT VARCHAR2(256), + TRACKING_CODE VARCHAR2(100), + VISIBLE_ROLES VARCHAR2(500), + UUID VARCHAR2(500) NOT NULL, + SAML2_SSO_ISSUER VARCHAR2(500), + LOG_OUT_URL VARCHAR2(500), + APP_ALLOW_ANONYMOUS NUMBER(1) NULL, + APP_ENDPOINT VARCHAR2(500), + TREAT_AS_SITE NUMBER(1) NOT NULL, + PRIMARY KEY(APP_ID), + UNIQUE (APP_PROVIDER,APP_NAME,APP_VERSION,TRACKING_CODE,UUID) +) +/ + +CREATE SEQUENCE APM_APP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_APP_TRG + BEFORE INSERT + ON APM_APP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APP_SEQ.nextval INTO :NEW.APP_ID FROM dual; + END; +/ + +CREATE INDEX IDX_APM_APP_UUID ON APM_APP (UUID) +/ + +CREATE TABLE APM_POLICY_GROUP +( + POLICY_GRP_ID INTEGER, + NAME VARCHAR2(256), + AUTH_SCHEME VARCHAR2(50) NULL, + THROTTLING_TIER VARCHAR2(512) DEFAULT NULL, + USER_ROLES VARCHAR2(512) DEFAULT NULL, + URL_ALLOW_ANONYMOUS NUMBER(1) DEFAULT 0, + DESCRIPTION VARCHAR2(1000) NULL, + PRIMARY KEY (POLICY_GRP_ID) +) +/ + +CREATE SEQUENCE APM_POLICY_GROUP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_POLICY_GROUP_TRG + BEFORE INSERT + ON APM_POLICY_GROUP + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_POLICY_GROUP_SEQ.nextval INTO :NEW.POLICY_GRP_ID FROM dual; + END; + / + +CREATE TABLE APM_POLICY_GROUP_MAPPING +( + POLICY_GRP_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID) ON DELETE CASCADE, + PRIMARY KEY (POLICY_GRP_ID,APP_ID) +) +/ + + +CREATE TABLE APM_APP_URL_MAPPING ( + URL_MAPPING_ID INTEGER, + APP_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR2(20) NULL, + URL_PATTERN VARCHAR2(512) NULL, + SKIP_THROTTLING NUMBER(1) DEFAULT 0, + POLICY_GRP_ID INTEGER NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + FOREIGN KEY (POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP (POLICY_GRP_ID), + PRIMARY KEY(URL_MAPPING_ID) +) +/ + + +CREATE SEQUENCE APM_APP_URL_MAPPING_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_APP_URL_MAPPING_TRG + BEFORE INSERT + ON APM_APP_URL_MAPPING + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APP_URL_MAPPING_SEQ.nextval INTO :NEW.URL_MAPPING_ID FROM dual; + END; + / + +CREATE TABLE APM_ENTITLEMENT_POLICY_PARTIAL ( + ENTITLEMENT_POLICY_PARTIAL_ID INTEGER, + NAME VARCHAR2(256) DEFAULT NULL, + CONTENT VARCHAR2(2048) DEFAULT NULL, + "SHARED" NUMBER(1) DEFAULT 0, + AUTHOR VARCHAR2(256) DEFAULT NULL, + DESCRIPTION VARCHAR2(1000) NULL, + TENANT_ID INT NULL, + PRIMARY KEY(ENTITLEMENT_POLICY_PARTIAL_ID) +) +/ + +-- Breaking the naming convention since the identifer name is too long. +CREATE SEQUENCE APM_ENTL_POLICY_PARTIAL_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +-- Breaking the naming convention since the identifer name is too long. +CREATE OR REPLACE TRIGGER APM_ENTL_POLICY_PARTIAL_TRG + BEFORE INSERT + ON APM_ENTITLEMENT_POLICY_PARTIAL + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_ENTL_POLICY_PARTIAL_SEQ.nextval INTO :NEW.ENTITLEMENT_POLICY_PARTIAL_ID FROM dual; + END; + / + +CREATE TABLE APM_POLICY_GRP_PARTIAL_MAPPING ( + POLICY_GRP_ID INTEGER NOT NULL, + POLICY_PARTIAL_ID INTEGER NOT NULL, + EFFECT VARCHAR2(50), + POLICY_ID VARCHAR2(100) DEFAULT NULL, + FOREIGN KEY(POLICY_GRP_ID) REFERENCES APM_POLICY_GROUP(POLICY_GRP_ID) ON DELETE CASCADE, + FOREIGN KEY(POLICY_PARTIAL_ID) REFERENCES APM_ENTITLEMENT_POLICY_PARTIAL(ENTITLEMENT_POLICY_PARTIAL_ID), + PRIMARY KEY(POLICY_GRP_ID, POLICY_PARTIAL_ID) +) +/ + +CREATE TABLE APM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER, + SUBSCRIPTION_TYPE VARCHAR2(50), + TIER_ID VARCHAR2(50), + APP_ID INTEGER, + LAST_ACCESSED TIMESTAMP NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR2(50), + TRUSTED_IDP VARCHAR2(255) NULL, + SUBSCRIPTION_TIME TIMESTAMP NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES APM_APPLICATION(APPLICATION_ID), + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID), + PRIMARY KEY (SUBSCRIPTION_ID), + UNIQUE(APP_ID, APPLICATION_ID,SUBSCRIPTION_TYPE) +) +/ + +CREATE SEQUENCE APM_SUBSCRIPTION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_SUBSCRIPTION_TRG + BEFORE INSERT + ON APM_SUBSCRIPTION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_SUBSCRIPTION_SEQ.nextval INTO :NEW.SUBSCRIPTION_ID FROM dual; + END; + / + +CREATE INDEX IDX_SUB_APP_ID ON APM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID) +/ + +CREATE TABLE APM_APP_LC_EVENT ( + EVENT_ID INTEGER, + APP_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR2(50), + NEW_STATE VARCHAR2(50) NOT NULL, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE TIMESTAMP NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID), + PRIMARY KEY (EVENT_ID) +) +/ + +CREATE SEQUENCE APM_APP_LC_EVENT_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_APP_LC_EVENT_TRG + BEFORE INSERT + ON APM_APP_LC_EVENT + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APP_LC_EVENT_SEQ.nextval INTO :NEW.EVENT_ID FROM dual; + END; + / + + +CREATE TABLE APM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER, + TIER VARCHAR2(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR2(50) NOT NULL, + ROLES VARCHAR2(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +) +/ + +CREATE SEQUENCE APM_TIER_PERMISSIONS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_TIER_PERMISSIONS_TRG + BEFORE INSERT + ON APM_TIER_PERMISSIONS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_TIER_PERMISSIONS_SEQ.nextval INTO :NEW.TIER_PERMISSIONS_ID FROM dual; + END; + / + +CREATE TABLE APM_WORKFLOWS( + WF_ID INTEGER, + WF_REFERENCE VARCHAR2(255) NOT NULL, + WF_TYPE VARCHAR2(255) NOT NULL, + WF_STATUS VARCHAR2(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP, + WF_STATUS_DESC VARCHAR2(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR2(255), + WF_EXTERNAL_REFERENCE VARCHAR2(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +) +/ + +CREATE SEQUENCE APM_WORKFLOWS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_WORKFLOWS_TRG + BEFORE INSERT + ON APM_WORKFLOWS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_WORKFLOWS_SEQ.nextval INTO :NEW.WF_ID FROM dual; + END; + / + + +-- TODO : Add Foreign key contraints for APP_CONSUMER_KEY --> IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) and (SAML2_SSO_ISSUER) --> APM_APP(SAML2_SSO_ISSUER) +CREATE TABLE APM_API_CONSUMER_APPS( + ID INTEGER, + SAML2_SSO_ISSUER VARCHAR2(500), + APP_CONSUMER_KEY VARCHAR2(512), + API_TOKEN_ENDPOINT VARCHAR2(1024), + API_CONSUMER_KEY VARCHAR2(512), + API_CONSUMER_SECRET VARCHAR2(512), + APP_NAME VARCHAR2(512), + PRIMARY KEY (ID, APP_CONSUMER_KEY) +) +/ + +CREATE SEQUENCE APM_API_CONSUMER_APPS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_API_CONSUMER_APPS_TRG + BEFORE INSERT + ON APM_API_CONSUMER_APPS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_API_CONSUMER_APPS_SEQ.nextval INTO :NEW.ID FROM dual; + END; + / + + + + +CREATE TABLE APM_APP_HITS ( + UUID VARCHAR2(500) NOT NULL, + APP_NAME VARCHAR2(200) NOT NULL, + VERSION VARCHAR2(50), + CONTEXT VARCHAR2(256) NOT NULL, + USER_ID VARCHAR2(50) NOT NULL, + TENANT_ID INTEGER, + HIT_TIME TIMESTAMP NOT NULL, + PRIMARY KEY (UUID, USER_ID, TENANT_ID, HIT_TIME) +) +/ + +CREATE TABLE APM_APP_JAVA_POLICY( + JAVA_POLICY_ID INTEGER, + DISPLAY_NAME VARCHAR2(100) NOT NULL, + FULL_QUALIFI_NAME VARCHAR2(256) NOT NULL, + DESCRIPTION VARCHAR2(2500), + DISPLAY_ORDER_SEQ_NO INTEGER NOT NULL, + IS_MANDATORY NUMBER(1) DEFAULT 0, + POLICY_PROPERTIES VARCHAR2(512) NULL, + IS_GLOBAL NUMBER(1) DEFAULT 1, + PRIMARY KEY(JAVA_POLICY_ID), + UNIQUE(FULL_QUALIFI_NAME,DISPLAY_ORDER_SEQ_NO) +) +/ + +CREATE SEQUENCE APM_APP_JAVA_POLICY_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_APP_JAVA_POLICY_TRG + BEFORE INSERT + ON APM_APP_JAVA_POLICY + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APP_JAVA_POLICY_SEQ.nextval INTO :NEW.JAVA_POLICY_ID FROM dual; + END; + / + +CREATE TABLE APM_APP_JAVA_POLICY_MAPPING( + JAVA_POLICY_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + PRIMARY KEY (JAVA_POLICY_ID,APP_ID), + FOREIGN KEY (JAVA_POLICY_ID) REFERENCES APM_APP_JAVA_POLICY(JAVA_POLICY_ID) ON DELETE CASCADE, + FOREIGN KEY (APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE +) +/ + +CREATE TABLE APM_EXTERNAL_STORES ( + APP_STORE_ID INTEGER, + APP_ID INTEGER, + STORE_ID VARCHAR2(255) NOT NULL, + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + PRIMARY KEY (APP_STORE_ID) +) +/ + +CREATE SEQUENCE APM_EXTERNAL_STORES_SEQ START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER APM_EXTERNAL_STORES_TRG + BEFORE INSERT + ON APM_EXTERNAL_STORES + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_EXTERNAL_STORES_SEQ.nextval INTO :NEW.APP_STORE_ID FROM dual; + END; +/ + +CREATE TABLE APM_APP_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INTEGER, + APP_NAME VARCHAR2(256), + APP_PROVIDER VARCHAR2(256), + DEFAULT_APP_VERSION VARCHAR2(30), + PUBLISHED_DEFAULT_APP_VERSION VARCHAR2(30), + TENANT_ID INTEGER, +PRIMARY KEY(DEFAULT_VERSION_ID) +) +/ + +CREATE SEQUENCE APM_APP_DEFAULT_VERSION_SEQ START WITH 1 INCREMENT BY 1 +/ + +CREATE OR REPLACE TRIGGER APM_APP_DEFAULT_VERSION_TRG + BEFORE INSERT + ON APM_APP_DEFAULT_VERSION + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_APP_DEFAULT_VERSION_SEQ.nextval INTO :NEW.DEFAULT_VERSION_ID FROM dual; + END; +/ + +CREATE TABLE APM_FAVOURITE_APPS ( + ID INTEGER , + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + APP_ID INTEGER NOT NULL, + CREATED_TIME DATE NOT NULL, + PRIMARY KEY (ID), + FOREIGN KEY(APP_ID) REFERENCES APM_APP(APP_ID) ON DELETE CASCADE, + UNIQUE (TENANT_ID,USER_ID,APP_ID) +) +/ + +CREATE SEQUENCE APM_FAVOURITE_APPS_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_FAVOURITE_APPS_TRG + BEFORE INSERT + ON APM_FAVOURITE_APPS + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_FAVOURITE_APPS_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +CREATE TABLE APM_STORE_FAVOURITE_PAGE ( + ID INTEGER , + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID_OF_USER INTEGER NOT NULL, + TENANT_ID_OF_STORE INTEGER NOT NULL, + PRIMARY KEY (ID) +) +/ + +CREATE SEQUENCE APM_STORE_FAVOURITE_PAGE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_STORE_FAVOURITE_PAGE_TRG + BEFORE INSERT + ON APM_STORE_FAVOURITE_PAGE + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_STORE_FAVOURITE_PAGE_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + +CREATE TABLE APM_ONE_TIME_DOWNLOAD_LINK ( + ID INTEGER, + BINARY_FILE VARCHAR(500) NOT NULL, + UUID VARCHAR(500) NOT NULL, + IS_DOWNLOADED NUMBER(1) NOT NULL, + USERNAME VARCHAR(255), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +) +/ + +CREATE SEQUENCE APM_ONE_TIME_DOWNLOAD_LINK_SEQ START WITH 1 INCREMENT BY 1 NOCACHE +/ + +CREATE OR REPLACE TRIGGER APM_ONE_TIME_DOWNLOAD_LINK_TRG + BEFORE INSERT + ON APM_ONE_TIME_DOWNLOAD_LINK + REFERENCING NEW AS NEW + FOR EACH ROW + BEGIN + SELECT APM_ONE_TIME_DOWNLOAD_LINK_SEQ.nextval INTO :NEW.ID FROM dual; + END; +/ + + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, IS_GLOBAL ) +VALUES ('Reverse Proxy Handler','org.wso2.carbon.appmgt.gateway.handlers.proxy.ReverseProxyHandler','',1,1,1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('SAML2 Authentication Handler','org.wso2.carbon.appmgt.gateway.handlers.security.authentication.SAML2AuthenticationHandler','',2,1,1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Subscription Handler', 'org.wso2.carbon.appmgt.gateway.handlers.subscription.SubscriptionsHandler','',3,1,1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Authorization Handler', 'org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.AuthorizationHandler','',4,1,1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Entitlement Handler','org.wso2.carbon.appmgt.gateway.handlers.security.entitlement.EntitlementHandler','',5,1,1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY, POLICY_PROPERTIES,IS_GLOBAL ) +VALUES ('API Throttle Handler','org.wso2.carbon.appmgt.gateway.handlers.throttling.APIThrottleHandler','',6,1,'{ "id": "A", "policyKey": "gov:/appmgt/applicationdata/tiers.xml"}',1) +/ + +INSERT INTO APM_APP_JAVA_POLICY(DISPLAY_NAME, FULL_QUALIFI_NAME, DESCRIPTION, DISPLAY_ORDER_SEQ_NO,IS_MANDATORY,IS_GLOBAL) +VALUES ('Publish Statistics:','org.wso2.carbon.appmgt.usage.publisher.APPMgtUsageHandler','',7,0,1) +/ + + diff --git a/modules/distribution/src/core/resources/dbscripts/appmgt/postgresql.sql b/modules/distribution/src/core/resources/dbscripts/appmgt/postgresql.sql new file mode 100644 index 00000000..6798fc83 --- /dev/null +++ b/modules/distribution/src/core/resources/dbscripts/appmgt/postgresql.sql @@ -0,0 +1,310 @@ +BEGIN TRANSACTION; + +CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( + PRODUCT_NAME VARCHAR (20), + PRIMARY KEY (PRODUCT_NAME) +) +; + +INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( + CONSUMER_KEY VARCHAR (512), + CONSUMER_SECRET VARCHAR (512), + USERNAME VARCHAR (255), + TENANT_ID INTEGER DEFAULT 0, + APP_NAME VARCHAR (255), + OAUTH_VERSION VARCHAR (128), + CALLBACK_URL VARCHAR (1024), + GRANT_TYPES VARCHAR (1024), + PRIMARY KEY (CONSUMER_KEY) +) +; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( + REQUEST_TOKEN VARCHAR (512), + REQUEST_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY VARCHAR (512), + CALLBACK_URL VARCHAR (1024), + SCOPE VARCHAR(2048), + AUTHORIZED VARCHAR (128), + OAUTH_VERIFIER VARCHAR (512), + AUTHZ_USER VARCHAR (512), + PRIMARY KEY (REQUEST_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR (512), + ACCESS_TOKEN_SECRET VARCHAR (512), + CONSUMER_KEY VARCHAR (512), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (512), + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( + AUTHORIZATION_CODE VARCHAR (512), + CONSUMER_KEY VARCHAR (512), + SCOPE VARCHAR(2048), + AUTHZ_USER VARCHAR (512), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + PRIMARY KEY (AUTHORIZATION_CODE), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +; + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( + ACCESS_TOKEN VARCHAR (255), + REFRESH_TOKEN VARCHAR (255), + CONSUMER_KEY VARCHAR (255), + AUTHZ_USER VARCHAR (255), + USER_TYPE VARCHAR (255), + TIME_CREATED TIMESTAMP, + VALIDITY_PERIOD BIGINT, + TOKEN_SCOPE VARCHAR (25), + TOKEN_STATE VARCHAR (25) DEFAULT 'ACTIVE', + TOKEN_STATE_ID VARCHAR (255) DEFAULT 'NONE', + PRIMARY KEY (ACCESS_TOKEN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +; + +CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( + USER_NAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + RP_URL VARCHAR(255) NOT NULL, + TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', + LAST_VISIT DATE NOT NULL, + VISIT_COUNT INTEGER DEFAULT 0, + DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', + PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) +) +; + +CREATE SEQUENCE AM_SUBSCRIBER_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_SUBSCRIBER ( + SUBSCRIBER_ID INTEGER DEFAULT nextval('am_subscriber_sequence'), + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL_ADDRESS VARCHAR(256) NULL, + DATE_SUBSCRIBED DATE NOT NULL, + PRIMARY KEY (SUBSCRIBER_ID), + UNIQUE (TENANT_ID,USER_ID) +) +; + +CREATE SEQUENCE AM_APPLICATION_SEQUENCE START WITH 1 INCREMENT BY 1 ; +CREATE TABLE IF NOT EXISTS AM_APPLICATION ( + APPLICATION_ID INTEGER DEFAULT nextval('am_application_sequence'), + NAME VARCHAR(100), + SUBSCRIBER_ID INTEGER, + APPLICATION_TIER VARCHAR(50) DEFAULT 'Unlimited', + CALLBACK_URL VARCHAR(512), + DESCRIPTION VARCHAR(512), + APPLICATION_STATUS VARCHAR(50) DEFAULT 'APPROVED', + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID), + UNIQUE (NAME,SUBSCRIBER_ID) +) +; + +CREATE SEQUENCE APM_BUSINESS_OWNER_SEQUENCE START WITH 1 INCREMENT BY 1 ; +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER( + OWNER_ID INTEGER DEFAULT nextval('apm_business_owner_sequence'), + OWNER_NAME VARCHAR(200) NOT NULL, + OWNER_EMAIL VARCHAR(300) NOT NULL, + OWNER_DESC VARCHAR(1500), + OWNER_SITE VARCHAR(200), + TENANT_ID INTEGER, + PRIMARY KEY(OWNER_ID), + UNIQUE (OWNER_NAME,OWNER_EMAIL,TENANT_ID) + +); + +CREATE SEQUENCE APM_BUSINESS_OWNER_PROPERTY_SEQUENCE START WITH 1 INCREMENT BY 1 ; +CREATE TABLE IF NOT EXISTS APM_BUSINESS_OWNER_PROPERTY( + OWNER_PROP_ID INTEGER DEFAULT nextval('apm_business_owner_property_sequence'), + OWNER_ID INTEGER NOT NULL, + NAME VARCHAR(200) NOT NULL, + VALUE VARCHAR(300) NOT NULL, + SHOW_IN_STORE BOOLEAN NOT NULL, + PRIMARY KEY(OWNER_PROP_ID), + FOREIGN KEY(OWNER_ID) REFERENCES APM_BUSINESS_OWNER(OWNER_ID) +); + +CREATE SEQUENCE APPMGR_APP_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APPMGR_APP ( + API_ID INTEGER DEFAULT nextval('appmgr_app_sequence'), + API_PROVIDER VARCHAR(256), + API_NAME VARCHAR(256), + API_VERSION VARCHAR(30), + CONTEXT VARCHAR(256), + PRIMARY KEY(API_ID), + UNIQUE (API_PROVIDER,API_NAME,API_VERSION) +) +; + +CREATE SEQUENCE APPMGR_APP_URL_MAPPING_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APPMGR_APP_URL_MAPPING ( + URL_MAPPING_ID INTEGER DEFAULT nextval('appmgr_app_url_mapping_sequence'), + API_ID INTEGER NOT NULL, + HTTP_METHOD VARCHAR(20) NULL, + AUTH_SCHEME VARCHAR(50) NULL, + URL_PATTERN VARCHAR(512) NULL, + THROTTLING_TIER varchar(512) DEFAULT NULL, + USER_ROLES varchar(512) DEFAULT NULL, + ENTITLEMENT_POLICY_ID varchar(512) DEFAULT NULL, + PRIMARY KEY(URL_MAPPING_ID) +) +; + +CREATE SEQUENCE AM_SUBSCRIPTION_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION ( + SUBSCRIPTION_ID INTEGER DEFAULT nextval('am_subscription_sequence'), + SUBSCRIPTION_TYPE VARCHAR(50), + TIER_ID VARCHAR(50), + API_ID INTEGER, + LAST_ACCESSED DATE NULL, + APPLICATION_ID INTEGER, + SUB_STATUS VARCHAR(50), + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(API_ID) REFERENCES APPMGR_APP(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (SUBSCRIPTION_ID) +) +; + +CREATE TABLE IF NOT EXISTS AM_SUBSCRIPTION_KEY_MAPPING ( + SUBSCRIPTION_ID INTEGER, + ACCESS_TOKEN VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(SUBSCRIPTION_ID) REFERENCES AM_SUBSCRIPTION(SUBSCRIPTION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(SUBSCRIPTION_ID,ACCESS_TOKEN) +) +; + +CREATE TABLE IF NOT EXISTS AM_APPLICATION_KEY_MAPPING ( + APPLICATION_ID INTEGER, + CONSUMER_KEY VARCHAR(512), + KEY_TYPE VARCHAR(512) NOT NULL, + FOREIGN KEY(APPLICATION_ID) REFERENCES AM_APPLICATION(APPLICATION_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY(APPLICATION_ID,CONSUMER_KEY) +) +; + +CREATE SEQUENCE APPMGR_APP_LC_EVENT_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APPMGR_APP_LC_EVENT ( + EVENT_ID INTEGER DEFAULT nextval('appmgr_app_lc_event_sequence'), + API_ID INTEGER NOT NULL, + PREVIOUS_STATE VARCHAR(50), + NEW_STATE VARCHAR(50) NOT NULL, + USER_ID VARCHAR(50) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EVENT_DATE DATE NOT NULL, + FOREIGN KEY(API_ID) REFERENCES APPMGR_APP(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (EVENT_ID) +) +; + +CREATE TABLE IF NOT EXISTS AM_APP_KEY_DOMAIN_MAPPING ( + CONSUMER_KEY VARCHAR(255), + AUTHZ_DOMAIN VARCHAR(255) DEFAULT 'ALL', + PRIMARY KEY (CONSUMER_KEY,AUTHZ_DOMAIN), + FOREIGN KEY (CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(CONSUMER_KEY) +) +; + +CREATE SEQUENCE APPMGR_APP_COMMENTS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APPMGR_APP_COMMENTS ( + COMMENT_ID INTEGER DEFAULT nextval('appmgr_app_comments_sequence'), + COMMENT_TEXT VARCHAR(512), + COMMENTED_USER VARCHAR(255), + DATE_COMMENTED DATE NOT NULL, + API_ID INTEGER NOT NULL, + FOREIGN KEY(API_ID) REFERENCES APPMGR_APP(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (COMMENT_ID) +) +; + +CREATE SEQUENCE AM_WORKFLOWS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_WORKFLOWS( + WF_ID INTEGER DEFAULT nextval('am_workflows_sequence'), + WF_REFERENCE VARCHAR(255) NOT NULL, + WF_TYPE VARCHAR(255) NOT NULL, + WF_STATUS VARCHAR(255) NOT NULL, + WF_CREATED_TIME TIMESTAMP, + WF_UPDATED_TIME TIMESTAMP, + WF_STATUS_DESC VARCHAR(1000), + TENANT_ID INTEGER, + TENANT_DOMAIN VARCHAR(255), + WF_EXTERNAL_REFERENCE VARCHAR(255) NOT NULL, + PRIMARY KEY (WF_ID), + UNIQUE (WF_EXTERNAL_REFERENCE) +) +; + +CREATE SEQUENCE APPMGR_APP_RATINGS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APPMGR_APP_RATINGS ( + RATING_ID INTEGER DEFAULT nextval('appmgr_app_ratings_sequence'), + API_ID INTEGER, + RATING INTEGER, + SUBSCRIBER_ID INTEGER, + FOREIGN KEY(API_ID) REFERENCES APPMGR_APP(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + FOREIGN KEY(SUBSCRIBER_ID) REFERENCES AM_SUBSCRIBER(SUBSCRIBER_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (RATING_ID) +) +; + +CREATE SEQUENCE AM_TIER_PERMISSIONS_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_TIER_PERMISSIONS ( + TIER_PERMISSIONS_ID INTEGER DEFAULT nextval('am_tier_permissions_sequence'), + TIER VARCHAR(50) NOT NULL, + PERMISSIONS_TYPE VARCHAR(50) NOT NULL, + ROLES VARCHAR(512) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY(TIER_PERMISSIONS_ID) +); + +CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( + SESSION_ID VARCHAR(255) NOT NULL, + USER_NAME VARCHAR(255) NOT NULL, + CREATED_TIME VARCHAR(255) NOT NULL, + LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, + PRIMARY KEY (SESSION_ID) + +) +; + +CREATE SEQUENCE AM_EXTERNAL_STORES_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS AM_EXTERNAL_STORES ( + APISTORE_ID INTEGER DEFAULT nextval('am_external_stores_sequence'), + API_ID INTEGER, + STORE_ID VARCHAR(255) NOT NULL, + STORE_DISPLAY_NAME VARCHAR(255) NOT NULL, + STORE_ENDPOINT VARCHAR(255) NOT NULL, + STORE_TYPE VARCHAR(255) NOT NULL, + FOREIGN KEY(API_ID) REFERENCES APPMGR_APP(API_ID) ON UPDATE CASCADE ON DELETE RESTRICT, + PRIMARY KEY (APISTORE_ID) +) +; + +CREATE SEQUENCE APM_APP_DEFAULT_VERSION_SEQUENCE START WITH 1 INCREMENT BY 1; +CREATE TABLE IF NOT EXISTS APM_APP_DEFAULT_VERSION ( + DEFAULT_VERSION_ID INTEGER DEFAULT nextval('apm_app_default_version_sequence'), + APP_NAME VARCHAR(256), + APP_PROVIDER VARCHAR(256), + DEFAULT_APP_VERSION VARCHAR(30), + PUBLISHED_DEFAULT_APP_VERSION VARCHAR(30), + TENANT_ID INTEGER, +PRIMARY KEY(DEFAULT_VERSION_ID) +) +; + +CREATE INDEX IDX_SUB_APP_ID ON AM_SUBSCRIPTION (APPLICATION_ID, SUBSCRIPTION_ID) +; +CREATE INDEX IDX_AT_CK_AU ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY, AUTHZ_USER, TOKEN_STATE, USER_TYPE); +commit; diff --git a/modules/distribution/src/core/resources/lifecycles/APILifeCycle.xml b/modules/distribution/src/core/resources/lifecycles/APILifeCycle.xml new file mode 100644 index 00000000..1818a7ad --- /dev/null +++ b/modules/distribution/src/core/resources/lifecycles/APILifeCycle.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/core/resources/styles/css/main.css b/modules/distribution/src/core/resources/styles/css/main.css new file mode 100644 index 00000000..58a0b304 --- /dev/null +++ b/modules/distribution/src/core/resources/styles/css/main.css @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* ---------------- template styles ------------------------- */ + +table#main-table td#header { + background-image:none !important; + border-bottom:1px solid #CCC; +} + +table#main-table td#menu-panel { + border-right: solid 1px #6F97CD; + /*background-image: url(../images/app-server-menu-panel-bg.gif);*/ + background-position: right top; + background-repeat: repeat-y; +} + + +/* ---------------- header styles ------------------ */ +div#header-div { + background-color:#222222; + background-image:none !important; +} + +div#header-div div.left-logo { + background-image: url(../images/logo.png); + width: 138px; + margin:12px 20px !important; +} + +div#header-div div.right-logo { + /*background-image: url( ../images/wsas-mgt-logo.gif);*/ + color: #FFF; + font-family:Arial; + font-size:12px; + padding:0px !important; + margin:18px !important; + +} + +div#header-div div.header-links { + margin-top:0px; + float:right !important; +} +div#header-div div.header-links div.right-links { + margin-right: 0px; + height: 35px; + padding-top: 0px; +} +div#header-div div.header-links div.right-links ul { + + background-position:left top; + background-repeat:repeat-x; + padding-top: 9px; + padding-bottom: 7px; +} + +/* ------------- menu styles ---------------------- */ +div#menu { +} + +div#menu ul.main { +} + +div#menu ul.main li { +} + +div#menu ul.main li.normal { +} + +div#menu ul.main li a.menu-home { + color: #0067B1; + background-image: none; + height: 30px; + line-height: 30px; +} + +div#menu ul.main li a.menu-home:hover { + color: #f47b20; + background-image: none; + background-color: #ffffff; +} + +div#menu ul.main li.menu-header { + /*background-image: url(../images/app-server-menu-header.png);*/ + background-image:none !important; + background-position: left bottom; + background-repeat: repeat-x; + + border-top: 1px solid #CCC; + border-bottom: 1px solid #CCC; + color:#502D16 !important; + height: 32px; + line-height: 32px; + background-color:#F3f3f3; + font-weight:bold; + text-transform:uppercase; +} + +div#menu ul.main li.menu-header img { + margin-right:-14px; + margin-top:7px; +} +div#menu ul.main li a.menu-default { + +} + +div#menu ul.main li a.menu-default:hover { + background-color: #ffffff; + border-bottom: solid 1px #CCC; + border-top: solid 1px #CCC; + color: #00447C; + +} + +div#menu ul.sub { +} +div#menu ul.main li.menu-disabled-link { + background-color: #E9EDF7; +} + +/* -------------- child no-01 styles -------------- */ + +div#menu ul.sub li.normal { + +} + +div#menu ul.sub li a.menu-default { +} + +/* ----------- child no-01 (disabled) styles ------------------- */ + +div#menu ul.sub li a.menu-disabled-link { +} + +div#menu ul.sub li a.menu-disabled-link:hover { +} + +/* -------------- child no-02 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li a.menu-default { + +} + +/* -------------- child no-03 styles -------------- */ + +div#menu ul.sub li.normal ul.sub li.normal ul.sub li a.menu-default { +} + +/* ------------- footer styles -------------------- */ + +div#footer-div div.footer-content div.poweredby { + /*background-image: url( ../images/axis2-powered.gif);*/ +} + +/* ---- login styles ----- */ + + +/* --------------- table styles -------------------- */ + +.tableOddRow{background-color: white;} +.tableEvenRow{background-color: #eeeffb;} + +.button:hover{ + /*background-image:url(../images/wsas-button-bg-hover.gif); + border:solid 1px #9D9FA1;*/ +} + +/* -------------- work area ---------------------- */ + +table#main-table td#middle-content { + background-color:none !important; + background:transparent !important; +} +div#middle { + background-color:#ffffff; +} +div#middle h2 { + margin-top:5px; +} +div#middle div#workArea { + background-color:none !important; + background:transparent !important; + padding:10px; +} +div#workArea table.styledLeft thead th { + /*background-image:url("../images/app-server-table-header.gif");*/ + background-image:none; + background-color: #efd7a5; + border-bottom:1px solid #CCC; + border-left:1px solid #CCC; + border-right:1px solid #CCC; + border-top:1px solid #CCC; + height:27px; + line-height:25px; + text-transform:uppercase; + font-weight:bold; +} + +div#workArea table.styledLeft .tableOddRow { + background-color:none !important; +} + +div#workArea table.styledLeft .tableEvenRow { + background-color:none !important; + background:none; +} + + +div#workArea table.styledLeft tbody tr td.middle-header { + /*background-image:url("../images/app-server-table-header.gif");*/ + border-bottom:1px solid #A7A9AC; + border-left:1px solid #cccccc; + border-right:1px solid #cccccc; + border-top:1px solid #cccccc; + height:22px; + line-height:22px; +} +div#workArea table.styledLeft tbody tr td.buttonRow { + /*background-image:url("../images/app-server-buttonRow-bg.gif");*/ + background-color: #F5F5F6; + padding-bottom:5px; + padding-top:5px; +} +.button { + /*background-image:url("../images/app-server-button-bg.gif");*/ + background-position:left bottom; + border:1px solid #666666; + padding:2px 5px; +} + +/** TEAGUE EDITS FOR JAGGERY SERVER ADMIN **/ + +div#header-div { + height: 52px !important; +} + +.left-logo img { + display:none !important; +} + +body { + /*background-image:url("../images/bg.png");*/ + font-family:Arial !important; +} + +div.right-links ul a { + +} +a { + color:#502D16 !important; +} + +a:hover { + color:#784421 !important; +} + +table#main-table td#menu-panel { + border-right: 1px solid #784421; +} + +div#middle h2 { + color:#502D16 !important; + font-weight:bold; + padding-bottom:10px; + border-bottom:1px solid #CCC !important; +} +div#features tr.feature td { + border-top:1px solid #CCC; +} + +div#features tr.feature-top td { + border-top:0px; +} +#main-table { + background-color:none !important; + +} + +#middle { + background:transparent !important; + background-color:none !important; +} + +/* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ diff --git a/modules/distribution/src/core/resources/styles/images/logo.png b/modules/distribution/src/core/resources/styles/images/logo.png new file mode 100644 index 00000000..deb024cd Binary files /dev/null and b/modules/distribution/src/core/resources/styles/images/logo.png differ diff --git a/modules/distribution/src/core/resources/synapse-configs/default/api/_AuthorizeAPI_.xml b/modules/distribution/src/core/resources/synapse-configs/default/api/_AuthorizeAPI_.xml new file mode 100644 index 00000000..458007b8 --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/api/_AuthorizeAPI_.xml @@ -0,0 +1,24 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/api/_RevokeAPI_.xml b/modules/distribution/src/core/resources/synapse-configs/default/api/_RevokeAPI_.xml new file mode 100644 index 00000000..f227eecf --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/api/_RevokeAPI_.xml @@ -0,0 +1,25 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/api/_TokenAPI_.xml b/modules/distribution/src/core/resources/synapse-configs/default/api/_TokenAPI_.xml new file mode 100644 index 00000000..eb85c584 --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/api/_TokenAPI_.xml @@ -0,0 +1,25 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/api/_UserInfoAPI_.xml b/modules/distribution/src/core/resources/synapse-configs/default/api/_UserInfoAPI_.xml new file mode 100644 index 00000000..3e649879 --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/api/_UserInfoAPI_.xml @@ -0,0 +1,24 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/imports/empty.txt b/modules/distribution/src/core/resources/synapse-configs/default/imports/empty.txt new file mode 100644 index 00000000..9583b46c --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/imports/empty.txt @@ -0,0 +1 @@ +empty file to commit diff --git a/modules/distribution/src/core/resources/synapse-configs/default/inbound-endpoints/empty.txt b/modules/distribution/src/core/resources/synapse-configs/default/inbound-endpoints/empty.txt new file mode 100644 index 00000000..9583b46c --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/inbound-endpoints/empty.txt @@ -0,0 +1 @@ +empty file to commit diff --git a/modules/distribution/src/core/resources/synapse-configs/default/local-entries/empty.txt b/modules/distribution/src/core/resources/synapse-configs/default/local-entries/empty.txt new file mode 100644 index 00000000..9583b46c --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/local-entries/empty.txt @@ -0,0 +1 @@ +empty file to commit diff --git a/modules/distribution/src/core/resources/synapse-configs/default/proxy-services/empty.txt b/modules/distribution/src/core/resources/synapse-configs/default/proxy-services/empty.txt new file mode 100644 index 00000000..9583b46c --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/proxy-services/empty.txt @@ -0,0 +1 @@ +empty file to commit diff --git a/modules/distribution/src/core/resources/synapse-configs/default/registry.xml b/modules/distribution/src/core/resources/synapse-configs/default/registry.xml new file mode 100644 index 00000000..5a7bd59b --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/registry.xml @@ -0,0 +1,26 @@ + + + + + + + 15000 + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/sequences/fault.xml b/modules/distribution/src/core/resources/synapse-configs/default/sequences/fault.xml new file mode 100644 index 00000000..693aa33a --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/sequences/fault.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/sequences/main.xml b/modules/distribution/src/core/resources/synapse-configs/default/sequences/main.xml new file mode 100644 index 00000000..cee12a07 --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/sequences/main.xml @@ -0,0 +1,37 @@ + + + + + + The main sequence for the message mediation + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/core/resources/synapse-configs/default/synapse.xml b/modules/distribution/src/core/resources/synapse-configs/default/synapse.xml new file mode 100755 index 00000000..2a55ba74 --- /dev/null +++ b/modules/distribution/src/core/resources/synapse-configs/default/synapse.xml @@ -0,0 +1,26 @@ + + + + + + + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/api#certificate-mgt#v1.0/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/api#certificate-mgt#v1.0/web.xml new file mode 100644 index 00000000..8facd4b1 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/api#certificate-mgt#v1.0/web.xml @@ -0,0 +1,118 @@ + + + + Certificate-Webapp + + JAX-WS/JAX-RS Certificate Management Endpoint + JAX-WS/JAX-RS Servlet + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + + swagger.security.filter + ApiAuthorizationFilterImpl + + 1 + + + CXFServlet + /* + + + 60 + + + + isAdminService + false + + + doAuthentication + true + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + + + CertificateMgt-Admin + /* + + + CONFIDENTIAL + + + + + ApiOriginFilter + org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.ApiOriginFilter + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + + ApiOriginFilter + /* + + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/api#identity#entitlement/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/api#identity#entitlement/web.xml new file mode 100644 index 00000000..ef693381 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/api#identity#entitlement/web.xml @@ -0,0 +1,127 @@ + + + + + + Entitlement-Service-Provider + + + + ApiOriginFilter + org.wso2.carbon.identity.entitlement.endpoint.filter.ApiOriginFilter + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + + ApiOriginFilter + /* + + + + EntitlementServlet + EntitlementServlet + Entitlement Endpoints + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + swagger.api.basepath + https://localhost:9443/entitlement + + + + + EntitlementServlet + /* + + + + 60 + + true + + + + + + secured services + /decision/* + + + + + + CONFIDENTIAL + + + + + org.wso2.carbon.identity.entitlement.endpoint.impl.ApplicationInitializer + + + + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/api#scep-mgt#v1.0/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/api#scep-mgt#v1.0/web.xml new file mode 100644 index 00000000..0dfb469c --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/api#scep-mgt#v1.0/web.xml @@ -0,0 +1,92 @@ + + + + Certificate-Webapp + + JAX-WS/JAX-RS Certificate Management Endpoint + JAX-WS/JAX-RS Servlet + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + + + CXFServlet + /* + + + 60 + + + + isAdminService + false + + + doAuthentication + true + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/api-application-registration/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/api-application-registration/web.xml new file mode 100644 index 00000000..0e2a3b23 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/api-application-registration/web.xml @@ -0,0 +1,103 @@ + + + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + CXFServlet + /* + + + isAdminService + false + + + doAuthentication + true + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + + ApiPermissionFilter + org.wso2.carbon.apimgt.application.extension.api.filter.ApiPermissionFilter + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + + ApiPermissionFilter + /* + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/authenticationendpoint/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/authenticationendpoint/web.xml new file mode 100644 index 00000000..466e8313 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/authenticationendpoint/web.xml @@ -0,0 +1,280 @@ + + + + + + + + + + + + + + + + + + + + + AccountRecoveryRESTEndpointURL + https://localhost:9443/t/tenant-domain/api/identity/user/v0.9/ + + + + + + displayScopes + true + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + HttpHeaderSecurityFilter + * + + + + AuthenticationEndpointFilter + + org.wso2.carbon.identity.application.authentication.endpoint.util.filter.AuthenticationEndpointFilter + + + + + AuthenticationEndpointFilter + /* + + + + + org.wso2.carbon.identity.application.authentication.endpoint.util.listener.AuthenticationEndpointContextListener + + + + + retry.do + /retry.jsp + + + + claims.do + /requested-claims.jsp + + + + oauth2_login.do + /login.jsp + + + + oauth2_authz.do + /oauth2_authz.jsp + + + + oauth2_consent.do + /oauth2_consent.jsp + + + + oauth2_logout_consent.do + /oauth2_logout_consent.jsp + + + + oauth2_logout.do + /logout.jsp + + + + oauth2_error.do + /oauth2_error.jsp + + + + samlsso_login.do + /login.jsp + + + + samlsso_logout.do + /logout.jsp + + + + samlsso_redirect.do + /login.jsp + + + + samlsso_notification.do + /samlsso_notification.jsp + + + + openid_login.do + /login.jsp + + + + openid_profile.do + /openid_profile.jsp + + + + passivests_login.do + /login.jsp + + + + tenantlistrefresher.do + /tenant_refresh_endpoint.jsp + + + + registration.do + /registration.jsp + + + + retry.do + /retry.do + + + + oauth2_login.do + /oauth2_login.do + + + + oauth2_authz.do + /oauth2_authz.do + + + + oauth2_consent.do + /oauth2_consent.do + + + + oauth2_logout_consent.do + /oauth2_logout_consent.do + + + + oauth2_logout.do + /oauth2_logout.do + + + + oauth2_error.do + /oauth2_error.do + + + + samlsso_login.do + /samlsso_login.do + + + + samlsso_logout.do + /samlsso_logout.do + + + + samlsso_redirect.do + /samlsso_redirect.do + + + + samlsso_notification.do + /samlsso_notification.do + + + + openid_login.do + /openid_login.do + + + + openid_profile.do + /openid_profile.do + + + + passivests_login.do + /passivests_login.do + + + + tenantlistrefresher.do + /tenantlistrefresher.do + + + + registration.do + /registration.do + + + + claims.do + /claims.do + + + + java.lang.Throwable + /generic-exception-response.jsp + + + + + true + + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/client-registration#v0.11/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/client-registration#v0.11/web.xml new file mode 100644 index 00000000..19b51c7a --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/client-registration#v0.11/web.xml @@ -0,0 +1,87 @@ + + + + +JAX-WS/JAX-RS Device Registration Agent Endpoint +JAX-WS/JAX-RS Servlet + + contextConfigLocation + WEB-INF/beans.xml + + + + org.springframework.web.context.ContextLoaderListener + + + + JAX-WS/JAX-RS Device Registration Agent Endpoint + JAX-WS/JAX-RS Servlet + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + 1 + + + CXFServlet + /* + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/oauth2/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/oauth2/web.xml new file mode 100644 index 00000000..02b4a9e4 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/oauth2/web.xml @@ -0,0 +1,100 @@ + + + + + + OAuth2 Endpoints + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + + + OAuth2Endpoints + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + + + + + + + OAuth2Endpoints + /* + + + + + true + + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/secured-websocket/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/secured-websocket/web.xml new file mode 100644 index 00000000..ce51b848 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/secured-websocket/web.xml @@ -0,0 +1,61 @@ + + + + + Output WebSocket + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + diff --git a/modules/distribution/src/core/resources/web-apps/web-xml/shindig/web.xml b/modules/distribution/src/core/resources/web-apps/web-xml/shindig/web.xml new file mode 100644 index 00000000..857a8334 --- /dev/null +++ b/modules/distribution/src/core/resources/web-apps/web-xml/shindig/web.xml @@ -0,0 +1,423 @@ + + + + Shindig + + + + + guice-modules + + org.apache.shindig.common.PropertiesModule: + org.apache.shindig.gadgets.DefaultGuiceModule: + org.apache.shindig.social.core.config.SocialApiGuiceModule: + org.apache.shindig.social.sample.SampleModule: + org.apache.shindig.gadgets.oauth.OAuthModule: + org.apache.shindig.gadgets.oauth2.OAuth2Module: + org.apache.shindig.gadgets.oauth2.OAuth2MessageModule: + org.apache.shindig.gadgets.oauth2.handler.OAuth2HandlerModule: + org.apache.shindig.gadgets.oauth2.persistence.sample.OAuth2PersistenceModule: + org.apache.shindig.common.cache.ehcache.EhCacheModule: + org.apache.shindig.sample.shiro.ShiroGuiceModule: + org.apache.shindig.sample.container.SampleContainerGuiceModule: + org.apache.shindig.extras.ShindigExtrasGuiceModule: + org.apache.shindig.gadgets.admin.GadgetAdminModule: + org.wso2.carbon.dashboard.shindig.features.WSO2ShindigFeaturesModule + + + + + + system.properties + + + + + + + HttpHeaderSecurityFilter + org.apache.catalina.filters.HttpHeaderSecurityFilter + + hstsEnabled + false + + + antiClickJackingOption + SAMEORIGIN + + + + + + ContentTypeBasedCachePreventionFilter + org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter + + patterns + text/html" ,application/json" ,text/plain + + + filterAction + enforce + + + httpHeaders + Cache-Control: no-store, no-cache, must-revalidate, private + + + + + HttpHeaderSecurityFilter + /* + + + + ContentTypeBasedCachePreventionFilter + /* + + + + HttpHeaderSecurityFilter + * + + + + hostFilter + org.apache.shindig.common.servlet.HostFilter + + + hostFilter + /gadgets/ifr + /gadgets/js/* + /gadgets/proxy/* + /gadgets/concat + /gadgets/makeRequest + /rpc/* + /rest/* + + + + ShiroFilter + org.apache.shiro.web.servlet.IniShiroFilter + + config + + + + + + + + authFilter + org.apache.shindig.auth.AuthenticationServletFilter + + + + etagFilter + org.apache.shindig.gadgets.servlet.ETagFilter + + + + + ShiroFilter + /oauth/authorize + + + + ShiroFilter + /oauth2/authorize + + + + ShiroFilter + *.jsp + + + + authFilter + /social/* + /gadgets/ifr + /gadgets/makeRequest + /gadgets/proxy + /gadgets/api/rpc/* + /gadgets/api/rest/* + /rpc/* + /rest/* + + + + etagFilter + * + + + + org.apache.shindig.common.servlet.GuiceServletContextListener + + + + + xml-to-html + + org.wso2.carbon.dashboard.shindig.extensions.WSO2GadgetRenderingServlet + + + + + accel + + org.apache.shindig.gadgets.servlet.HtmlAccelServlet + + + + + + proxy + + org.apache.shindig.gadgets.servlet.ProxyServlet + + + + + + makeRequest + + org.apache.shindig.gadgets.servlet.MakeRequestServlet + + + + + + concat + + org.apache.shindig.gadgets.servlet.ConcatProxyServlet + + + + + + oauthCallback + + org.apache.shindig.gadgets.servlet.OAuthCallbackServlet + + + + + + oauth2callback + + org.apache.shindig.gadgets.servlet.OAuth2CallbackServlet + + + + + + metadata + + org.apache.shindig.gadgets.servlet.RpcServlet + + + + + + js + org.apache.shindig.gadgets.servlet.JsServlet + + + + restapiServlet + + org.apache.shindig.protocol.DataServiceServlet + + + handlers + org.apache.shindig.handlers + + + + + + jsonRpcServlet + + org.apache.shindig.protocol.JsonRpcServlet + + + handlers + org.apache.shindig.handlers + + + + + + sampleOAuth + + org.apache.shindig.social.sample.oauth.SampleOAuthServlet + + + + + + OAuth2Servlet + + org.apache.shindig.social.core.oauth2.OAuth2Servlet + + + + + rpcSwf + + org.apache.shindig.gadgets.servlet.RpcSwfServlet + + + + + js + /gadgets/js/* + + + + proxy + /gadgets/proxy/* + + + + makeRequest + /gadgets/makeRequest + + + + jsonRpcServlet + /rpc/* + /gadgets/api/rpc/* + /social/rpc/* + + + + restapiServlet + /rest/* + /gadgets/api/rest/* + /social/rest/* + + + + concat + /gadgets/concat + + + + oauthCallback + /gadgets/oauthcallback + + + + oauth2callback + /gadgets/oauth2callback + + + + xml-to-html + /gadgets/ifr + + + + accel + /gadgets/accel + + + + metadata + /gadgets/metadata + + + + sampleOAuth + /oauth/* + + + + OAuth2Servlet + /oauth2/* + + + + rpcSwf + /xpc* + + + + 404 + /error-pages/error404.html + + + + 401 + /error-pages/error401.html + + + + 403 + /error-pages/error403.html + + + + 405 + /error-pages/error405.html + + + + 500 + /error-pages/error500.html + + diff --git a/modules/features/org.wso2.iot.core.styles.feature/pom.xml b/modules/features/org.wso2.iot.core.styles.feature/pom.xml new file mode 100644 index 00000000..2a9feb81 --- /dev/null +++ b/modules/features/org.wso2.iot.core.styles.feature/pom.xml @@ -0,0 +1,75 @@ + + + + + + + org.wso2.iot + wso2iot-features + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.iot.core.styles.feature + pom + WSO2 IoT - Core - Server Styles Feature + http://wso2.org + + + + org.wso2.iot + org.wso2.iot.core.admin.styles + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.iot.core.styles + ../../etc/feature.properties + + + org.wso2.carbon.p2.category.type:console + + + + + org.wso2.iot:org.wso2.iot.core.admin.styles + + + + + + + + + + diff --git a/modules/features/pom.xml b/modules/features/pom.xml new file mode 100644 index 00000000..af3eff91 --- /dev/null +++ b/modules/features/pom.xml @@ -0,0 +1,41 @@ + + + + + + + + org.wso2.iot + wso2iot-parent + 3.1.0-SNAPSHOT + ../../pom.xml + + + 4.0.0 + wso2iot-features + pom + WSO2 IoT Server - Features Module + http://wso2.org + + + org.wso2.iot.core.styles.feature + + + diff --git a/modules/p2-profile/analytics-profile/pom.xml b/modules/p2-profile/analytics-profile/pom.xml index 1cd27e0a..cbc1caef 100644 --- a/modules/p2-profile/analytics-profile/pom.xml +++ b/modules/p2-profile/analytics-profile/pom.xml @@ -56,6 +56,25 @@ + + 2-unpack-wso2carbon + test + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.kernel.version} + zip + true + target + + + + @@ -827,9 +846,16 @@ creating-required-resources - generate-resources + test + + + + + + + diff --git a/modules/p2-profile/broker-profile/pom.xml b/modules/p2-profile/broker-profile/pom.xml index ea0050d0..81c3078f 100644 --- a/modules/p2-profile/broker-profile/pom.xml +++ b/modules/p2-profile/broker-profile/pom.xml @@ -15,7 +15,8 @@ ~ limitations under the License. --> - + org.wso2.iot @@ -56,6 +57,25 @@ + + 2-unpack-wso2carbon + test + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.kernel.version} + zip + true + target + + + + @@ -189,7 +209,9 @@ file:${basedir}/target/p2-repo file:${basedir}/target/p2-repo - file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/wso2/components + + file:${basedir}/target/wso2carbon-core-${carbon.kernel.version}/wso2/components + broker-default @@ -312,7 +334,8 @@ ${analytics.shared.version} - org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.feature.group + org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.feature.group + ${carbon.device.mgt.plugin.version} @@ -326,6 +349,25 @@ maven-antrun-plugin 1.1 + + creating-required-resources + test + + + + + + + + + + + + + run + + package diff --git a/modules/p2-profile/iot-core-profile/pom.xml b/modules/p2-profile/iot-core-profile/pom.xml index 1945ccd6..cd9ecb14 100644 --- a/modules/p2-profile/iot-core-profile/pom.xml +++ b/modules/p2-profile/iot-core-profile/pom.xml @@ -57,6 +57,25 @@ + + 2-unpack-wso2carbon + test + + unpack + + + + + org.wso2.carbon + wso2carbon-core + ${carbon.kernel.version} + zip + true + target + + + + @@ -3836,6 +3855,12 @@ + + + + + + diff --git a/modules/scripts/mobile-qsg/pom.xml b/modules/scripts/mobile-qsg/pom.xml new file mode 100644 index 00000000..7c31b98b --- /dev/null +++ b/modules/scripts/mobile-qsg/pom.xml @@ -0,0 +1,159 @@ + + + + + + org.wso2.iot + wso2iot-scripts + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + mobile-qsg + 3.1.0-SNAPSHOT + WSO2 IoTs QSG Script + This includes the tools for IoTs Quick Start Guide + jar + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + maven-assembly-plugin + + + jar-with-dependencies + + ${project.artifactId} + false + + + true + lib/ + org.wso2.mdm.qsg.QSGExecutor + + + + + + package + + single + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + download-appm-store.war + prepare-package + + run + + + + + + + + + download-appm-publisher.war + prepare-package + + run + + + + + + + + + download-appm-ouath-webapp.war + prepare-package + + run + + + + + + + + + download-appm-ouath-core.jar + prepare-package + + run + + + + + + + + + + + ${project.artifactId} + + + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents.wso2 + httpcore + + + com.googlecode.json-simple.wso2 + json-simple + + + org.apache.httpcomponents + httpmime + + + commons-codec + commons-codec + + + + diff --git a/modules/scripts/mobile-qsg/resources/Readme.txt b/modules/scripts/mobile-qsg/resources/Readme.txt new file mode 100644 index 00000000..64ce0ece --- /dev/null +++ b/modules/scripts/mobile-qsg/resources/Readme.txt @@ -0,0 +1,7 @@ + IoTs 3.1.0 QSG Setup guide + +1. Start the WSO2 IoTS server +2. Navigate to /core/samples/mobile-qsg/ directory using the terminal. +3. Once server is started execute the mobile-qsg.sh script +4. Then login to the https://:9443/devicemgt/ and use the username,password as alex alex@IoTS, ++Note that for this sample we have configured above user from the script. If you want to run this script again you have to login as admin and remove the user alex, chris and role iotMobileUser from the IoT Server. \ No newline at end of file diff --git a/modules/scripts/mobile-qsg/resources/apps/android/catalog.apk b/modules/scripts/mobile-qsg/resources/apps/android/catalog.apk new file mode 100644 index 00000000..473f5805 Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/catalog.apk differ diff --git a/modules/scripts/mobile-qsg/resources/apps/android/images/banner.jpg b/modules/scripts/mobile-qsg/resources/apps/android/images/banner.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/images/banner.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/android/images/icon.jpg b/modules/scripts/mobile-qsg/resources/apps/android/images/icon.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/images/icon.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/android/images/screen1.jpg b/modules/scripts/mobile-qsg/resources/apps/android/images/screen1.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/images/screen1.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/android/images/screen2.jpg b/modules/scripts/mobile-qsg/resources/apps/android/images/screen2.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/images/screen2.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/android/images/screen3.jpg b/modules/scripts/mobile-qsg/resources/apps/android/images/screen3.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/android/images/screen3.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/PNDemo.ipa b/modules/scripts/mobile-qsg/resources/apps/ios/PNDemo.ipa new file mode 100644 index 00000000..01729c7c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/PNDemo.ipa differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/images/banner.jpg b/modules/scripts/mobile-qsg/resources/apps/ios/images/banner.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/images/banner.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/images/icon.jpg b/modules/scripts/mobile-qsg/resources/apps/ios/images/icon.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/images/icon.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/images/screen1.jpg b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen1.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen1.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/images/screen2.jpg b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen2.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen2.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/apps/ios/images/screen3.jpg b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen3.jpg new file mode 100644 index 00000000..002dea5c Binary files /dev/null and b/modules/scripts/mobile-qsg/resources/apps/ios/images/screen3.jpg differ diff --git a/modules/scripts/mobile-qsg/resources/config.properties b/modules/scripts/mobile-qsg/resources/config.properties new file mode 100644 index 00000000..6466eca3 --- /dev/null +++ b/modules/scripts/mobile-qsg/resources/config.properties @@ -0,0 +1,5 @@ +dcr-endpoint=https://localhost:9443/dynamic-client-web/register +oauth-endpoint=https://localhost:9443/oauth2/token +emm-host=https://localhost:9443 +username=admin +password=admin diff --git a/modules/scripts/mobile-qsg/resources/mobile-qsg.sh b/modules/scripts/mobile-qsg/resources/mobile-qsg.sh new file mode 100755 index 00000000..8c50b9ad --- /dev/null +++ b/modules/scripts/mobile-qsg/resources/mobile-qsg.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# product-iots qsg sample setup script + +echo "Starting wso2iots-3.0.0 QSG setup ..." +java -jar "mobile-qsg.jar" +echo "wso2iots-3.0.0 QSG setup completed." diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java new file mode 100644 index 00000000..ff5bda18 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.wso2.mdm.qsg.dto.EMMQSGConfig; +import org.wso2.mdm.qsg.dto.HTTPResponse; +import org.wso2.mdm.qsg.dto.MobileApplication; +import org.wso2.mdm.qsg.utils.Constants; +import org.wso2.mdm.qsg.utils.HTTPInvoker; +import org.wso2.mdm.qsg.utils.QSGUtils; + +import java.io.File; +import java.util.HashMap; + +/** + * This class holds the app-mgt related operations. + */ +public class AppOperations { + + private static String appmPublisherMobileBinariesUrl = "/api/appm/publisher/v1.1/apps/mobile/binaries"; + private static String appmPublisherResourcesUrl = "/api/appm/publisher/v1.1/apps/static-contents?appType=mobileapp"; + private static String appmPublisherAppsUrl = "/api/appm/publisher/v1.1/apps/mobileapp"; + + + public static MobileApplication uploadApplication(String platform, String appName, String appContentType) { + + String appUploadEndpoint = EMMQSGConfig.getInstance().getEmmHost() + appmPublisherMobileBinariesUrl; + String filePath = "apps" + File.separator + platform + File.separator + appName; + HTTPResponse httpResponse = HTTPInvoker.uploadFile(appUploadEndpoint, filePath, appContentType); + if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) { + JSONObject appMeta = null; + MobileApplication application = new MobileApplication(); + try { + appMeta = (JSONObject) new JSONParser().parse(httpResponse.getResponse()); + application.setPackageId((String) appMeta.get("package")); + application.setAppId(QSGUtils.getResourceId((String) appMeta.get("path"))); + application.setVersion((String) appMeta.get("version")); + application.setPlatform(platform); + } catch (ParseException e) { + e.printStackTrace(); + } + return application; + } + return null; + } + + public static MobileApplication getPublicApplication(String packageId, String version, String platform) { + MobileApplication application = new MobileApplication(); + application.setVersion(version); + application.setPackageId(packageId); + application.setPlatform(platform); + return application; + } + + private static String uploadAsset(String path) { + + String resUploadEndpoint = EMMQSGConfig.getInstance().getEmmHost() + appmPublisherResourcesUrl; + HTTPResponse httpResponse = HTTPInvoker.uploadFile(resUploadEndpoint, path, "image/jpeg"); + if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) { + JSONObject resp = null; + try { + resp = (JSONObject) new JSONParser().parse(httpResponse.getResponse()); + return (String) resp.get("id"); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return null; + } + + public static MobileApplication uploadAssets(String platform, MobileApplication application) { + + String assetDir = "apps" + File.separator + platform + File.separator + "images"; + //Upload the icon file + String imgFile = assetDir + File.separator + "icon.jpg"; + String uploadPath = uploadAsset(imgFile); + if (uploadPath != null && !uploadPath.isEmpty()) { + application.setIcon(uploadPath); + } else { + System.out.println("Unable to upload the app icon file."); + return null; + } + + //Upload the banner file + imgFile = assetDir + File.separator + "banner.jpg"; + uploadPath = uploadAsset(imgFile); + if (uploadPath != null && !uploadPath.isEmpty()) { + application.setBanner(uploadPath); + } else { + System.out.println("Unable to upload the app banner file."); + return null; + } + + //Upload the screenshot1 file + imgFile = assetDir + File.separator + "screen1.jpg"; + uploadPath = uploadAsset(imgFile); + if (uploadPath != null && !uploadPath.isEmpty()) { + application.setScreenshot1(uploadPath); + } else { + System.out.println("Unable to upload the app screenshot1 file."); + return null; + } + + //Upload the screenshot2 file + imgFile = assetDir + File.separator + "screen2.jpg"; + uploadPath = uploadAsset(imgFile); + if (uploadPath != null && !uploadPath.isEmpty()) { + application.setScreenshot2(uploadPath); + } else { + System.out.println("Unable to upload the app screenshot2 file."); + return null; + } + + //Upload the screenshot3 file + imgFile = assetDir + File.separator + "screen3.jpg"; + uploadPath = uploadAsset(imgFile); + if (uploadPath != null && !uploadPath.isEmpty()) { + application.setScreenshot3(uploadPath); + } else { + System.out.println("Unable to upload the app screenshot3 file."); + return null; + } + return application; + } + + public static boolean addApplication(String name, MobileApplication mblApp, boolean isEnterpriseApp) { + HashMap headers = new HashMap(); + + String appEndpoint = EMMQSGConfig.getInstance().getEmmHost() + appmPublisherAppsUrl; + //Set the application payload + JSONObject application = new JSONObject(); + application.put("name", name); + application.put("description", "Sample application"); + application.put("type", "enterprise"); + //Set appMeta data + JSONObject appMeta = new JSONObject(); + appMeta.put("package", mblApp.getPackageId()); + appMeta.put("version", mblApp.getVersion()); + if (isEnterpriseApp) { + application.put("marketType", "enterprise"); + appMeta.put("path", mblApp.getAppId()); + } else { + application.put("marketType", "public"); + } + application.put("provider", "admin"); + application.put("displayName", name); + application.put("category", "Business"); + application.put("thumbnailUrl", mblApp.getIcon()); + application.put("version", mblApp.getVersion()); + application.put("banner", mblApp.getBanner()); + application.put("platform", mblApp.getPlatform()); + application.put("appType", mblApp.getPlatform()); + //application.put("appUrL", mblApp.getAppId()); + application.put("mediaType", "application/vnd.wso2-mobileapp+xml"); + + //Set screenshots + JSONArray screenshots = new JSONArray(); + screenshots.add(mblApp.getScreenshot1()); + screenshots.add(mblApp.getScreenshot2()); + screenshots.add(mblApp.getScreenshot3()); + application.put("appmeta", appMeta); + application.put("screenshots", screenshots); + + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse + httpResponse = + HTTPInvoker.sendHTTPPostWithOAuthSecurity(appEndpoint, application.toJSONString(), headers); + if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) { + return true; + } + return false; + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java new file mode 100644 index 00000000..79339640 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.wso2.mdm.qsg.dto.EMMQSGConfig; +import org.wso2.mdm.qsg.dto.HTTPResponse; +import org.wso2.mdm.qsg.utils.Constants; +import org.wso2.mdm.qsg.utils.HTTPInvoker; + +import java.util.HashMap; + +/** + * This class holds the methods to create policies. + */ +public class PolicyOperations { + + public static boolean createPasscodePolicy(String policyName, String deviceType) { + HashMap headers = new HashMap(); + String policyEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/policies"; + //Set the policy payload + JSONObject policyData = new JSONObject(); + policyData.put("policyName", policyName); + policyData.put("description", "Passcode Policy"); + policyData.put("compliance", "enforce"); + policyData.put("ownershipType", "ANY"); + policyData.put("active", false); + JSONObject profile = new JSONObject(); + profile.put("profileName", "passcode"); + profile.put("deviceType", deviceType); + JSONArray featureList = new JSONArray(); + JSONObject feature = new JSONObject(); + feature.put("featureCode", "PASSCODE_POLICY"); + feature.put("deviceType", deviceType); + JSONObject featureContent = new JSONObject(); + featureContent.put("allowSimple", false); + featureContent.put("requireAlphanumeric", true); + featureContent.put("minLength", "5"); + featureContent.put("minComplexChars", "2"); + featureContent.put("maxPINAgeInDays", 7); + featureContent.put("pinHistory", 7); + featureContent.put("maxFailedAttempts", null); + feature.put("content", featureContent); + featureList.add(feature); + profile.put("profileFeaturesList", featureList); + JSONArray roles = new JSONArray(); + roles.add(Constants.EMM_USER_ROLE); + policyData.put("profile", profile); + policyData.put("roles", roles); + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse + httpResponse = HTTPInvoker + .sendHTTPPostWithOAuthSecurity(policyEndpoint, policyData.toJSONString(), headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) { + return true; + } + return false; + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java new file mode 100644 index 00000000..240e84b9 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg; + +import org.wso2.mdm.qsg.dto.MobileApplication; +import org.wso2.mdm.qsg.utils.Constants; +import org.wso2.mdm.qsg.utils.HTTPInvoker; +import org.wso2.mdm.qsg.utils.QSGUtils; + +import java.util.*; + +/** + * Main class of EMM-QSG module. This class will populate each sample scenario. + */ +public class QSGExecutor { + + private static String iotAdminUser= "chris"; + private static String iotAdminPassword = "chrisadmin"; + private static String iotAdminEmail = "chris@mobx.com"; + + private static String iotMobileUser = "alex"; + private static String iotMobileUserPassword = "alexuser"; + private static String roleName = "iotMobileUser"; + + public static void main(String[] args) { + boolean status = false; + + // prompt for the user's name + /* + Scanner scanner = new Scanner(System.in); + System.out.print("Enter your email address and press enter : "); + String email = scanner.next(); + if (!QSGUtils.isValidEmailAddress(email)) { + do { + System.out.print("Please enter a valid email address and press enter : "); + email = scanner.next(); + } while (!QSGUtils.isValidEmailAddress(email)); + } + */ + String email = "alex@example.com"; + + //Setup the OAuth token + String token = QSGUtils.getOAuthToken(); + if (token == null) { + System.out.println("Unable to get the OAuth token. Please check the config.properties file."); + System.exit(0); + } + HTTPInvoker.oAuthToken = token; + //Creates the admin user + + System.out.println("Creating users "); + status = UserOperations.createUser(iotAdminUser, iotAdminEmail, true); + if (!status) { + System.out.println("Unable to create the admin user. Please check the config.properties file."); + System.exit(0); + } + + status = UserOperations.changePassword(iotAdminUser, iotAdminPassword); + if (!status) { + System.out.println("Unable to change the password of the admin user. Terminating the IoTS QSG now."); + System.exit(0); + } + + //Creates the emm user + + status = UserOperations.createUser(iotMobileUser, email, false); + if (!status) { + System.out.println("Unable to create the iot user ryan. Terminating the IoTS QSG now."); + System.exit(0); + } + + status = UserOperations.changePassword(iotMobileUser, iotMobileUserPassword); + if (!status) { + System.out.println("Unable to change the password of the iot user. Terminating the IoTS QSG now."); + System.exit(0); + } + + //Creates the emm-user role + System.out.println("Creating iotMobileUser role"); + status = UserOperations.createRole(roleName, new String[] {iotMobileUser}); + if (!status) { + System.out.println("Unable to create the emm user role. Terminating the IoTs QSG now."); + System.exit(0); + } + + System.out.println("Adding sample policies "); + //Add the android policy + status = PolicyOperations.createPasscodePolicy("android-passcode-policy1", Constants.DeviceType.ANDROID); + if (!status) { + System.out.println("Unable to create the android passcode policy. Terminating the IoTS QSG now."); + System.exit(0); + } + //Add the windows policy + status = PolicyOperations.createPasscodePolicy("windows-passcode-policy1", Constants.DeviceType.WINDOWS); + if (!status) { + System.out.println("Unable to create the windows passcode policy. Terminating the IoTS QSG now."); + System.exit(0); + } + + + System.out.println("Upload the android application "); + //Upload the android application + MobileApplication application = AppOperations.uploadApplication(Constants.DeviceType.ANDROID, "catalog.apk", + "application/vnd.android.package-archive"); + if (application == null) { + System.out.println("Unable to upload the sample android application. Terminating the IoTS QSG now."); + System.exit(0); + } + //Upload the assets + application = AppOperations.uploadAssets(Constants.DeviceType.ANDROID, application); + if (application == null) { + System.out.println( + "Unable to upload the assets for sample android application. Terminating the IoTS QSG now."); + System.exit(0); + } + + System.out.println("Create the android application "); + //Create application entry in publisher + status = AppOperations.addApplication("Catalog", application, true); + if (!status) { + System.out.println("Unable to create the android mobile application. Terminating the IoTS QSG now."); + System.exit(0); + } + + + System.out.println("Upload the iOS application "); + //Add the iOS policy + status = PolicyOperations.createPasscodePolicy("ios-passcode-policy1", Constants.DeviceType.IOS); + if (!status) { + System.out.println("Unable to create the ios passcode policy. Terminating the IoTS QSG now."); + System.exit(0); + } + + //Upload the ios application + MobileApplication iOSApplication = AppOperations.uploadApplication(Constants.DeviceType.IOS, "PNDemo.ipa","application/octet-stream"); + iOSApplication.setVersion("1.0.0"); + //Upload the assets + iOSApplication = AppOperations.uploadAssets(Constants.DeviceType.IOS, iOSApplication); + if (iOSApplication == null) { + System.out.println( + "Unable to upload the assets for sample iOS application. Terminating the IoTS QSG now."); + System.exit(0); + } + + System.out.println("Create the iOS application "); + //Create application entry in publisher + status = AppOperations.addApplication("WSO2Con", iOSApplication, true); + if (!status) { + System.out.println("Unable to create the iOS mobile application. Terminating the IoTS QSG now."); + System.exit(0); + } + + System.out.println("Exit"); + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java new file mode 100644 index 00000000..947a7eae --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.wso2.mdm.qsg.dto.EMMQSGConfig; +import org.wso2.mdm.qsg.dto.HTTPResponse; +import org.wso2.mdm.qsg.utils.Constants; +import org.wso2.mdm.qsg.utils.HTTPInvoker; + +import java.util.HashMap; + +/** + * This class holds the user-mgt related operations like user-create, role-create and change-password. + */ +public class UserOperations { + + public static boolean createUser(String username, String email, boolean isAdmin) { + HashMap headers = new HashMap(); + String userEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/users"; + //Set the user payload + JSONObject userData = new JSONObject(); + userData.put("username", username); + userData.put("emailAddress", email); + JSONArray roles = new JSONArray(); + if (isAdmin) { + roles.add("admin"); + userData.put("firstname", "Chris"); + userData.put("lastname", "Admin"); + } else { + userData.put("password", "kimemmtrial"); + userData.put("firstname", "Alex"); + userData.put("lastname", "User"); + } + userData.put("roles", roles); + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse httpResponse = HTTPInvoker + .sendHTTPPostWithOAuthSecurity(userEndpoint, userData.toJSONString(), headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) { + return true; + } + return false; + } + + public static boolean changePassword(String username, String pwd) { + HashMap headers = new HashMap(); + String pwdEndpoint = + EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/admin/users/" + username + "/credentials"; + //Set the password payload + JSONObject pwdData = new JSONObject(); + pwdData.put("newPassword", pwd); + + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse httpResponse = + HTTPInvoker.sendHTTPPostWithOAuthSecurity(pwdEndpoint, pwdData.toJSONString(), headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) { + return true; + } + return false; + } + + private static String[] getUserPermissions() { + String permissions = "/permission/admin/device-mgt/certificates/manage," + + "/permission/admin/device-mgt/certificates/view," + + "/permission/admin/device-mgt/configurations/view," + + "/permission/admin/device-mgt/api," + + "/permission/admin/device-mgt/devices/enroll," + + "/permission/admin/device-mgt/devices/disenroll," + + "/permission/admin/device-mgt/devices/enroll/android," + + "/permission/admin/device-mgt/devices/enroll/ios," + + "/permission/admin/device-mgt/devices/owning-device," + + "/permission/admin/device-mgt/devices/owning-device/view," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/applications," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/blacklist-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/camera," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/change-lock-code," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/clear-password," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/encrypt," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/enterprise-wipe," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/info," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/install-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/location," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/lock," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/logcat," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/mute," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/password-policy," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/ring," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/reboot," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/send-notification," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/uninstall-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/update-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/unlock," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/upgrade," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/vpn," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/webclip," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/wifi," + + "/permission/admin/device-mgt/devices/owning-device/operations/android/wipe," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/airplay," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/apn," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/app-list," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/app-lock," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/app-to-per-app-vpn," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/cal-subscription," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/caldav," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/cellular," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/clear-passcode," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/device-info," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/email," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/enterprise-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/enterprise-wipe," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/get-restrictions," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/ldap," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/location," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/lock," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/notification," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/passcode-policy," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/per-app-vpn," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/profile-list," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/remove-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/remove-profile," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/restriction," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/ring," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/store-app," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/vpn," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/webclip," + + "/permission/admin/device-mgt/devices/owning-device/operations/ios/wifi," + + "/permission/admin/device-mgt/notifications/view," + + "/permission/admin/device-mgt/platform-configurations/view," + + "/permission/admin/device-mgt/policies/view," + + "/permission/admin/device-mgt/applications/manage," + + "/permission/admin/manage/mobileapp/create," + + "/permission/admin/manage/mobileapp/install," + + "/permission/admin/manage/resources/browse," + + "/permission/admin/manage/webapp/subscribe," + + "/permission/admin/manage/search/advanced-search," + + "/permission/admin/manage/search/resources," + + "/permission/admin/manage/resources/govern/mobileapp/list," + + "/permission/admin/login"; + return permissions.split(","); + } + + public static boolean createRole(String roleName, String[] users) { + HashMap headers = new HashMap(); + String roleEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/roles"; + //Set the role payload + JSONObject roleData = new JSONObject(); + roleData.put("roleName", roleName); + JSONArray perms = new JSONArray(); + String[] permissions = getUserPermissions(); + for (String perm : permissions) { + perms.add(perm); + } + roleData.put("permissions", perms); + JSONArray usrs = new JSONArray(); + for (String usr : users) { + usrs.add(usr); + } + roleData.put("permissions", perms); + roleData.put("users", usrs); + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse httpResponse = + HTTPInvoker.sendHTTPPostWithOAuthSecurity(roleEndpoint, roleData.toJSONString(), headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) { + return true; + } + return false; + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java new file mode 100644 index 00000000..9d8cdd81 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.dto; + +/** + * This holds the domain-model of client-credentials. + */ +public class ClientCredentials { + + private String clientKey; + private String clientSecret; + + public String getClientKey() { + return clientKey; + } + + public void setClientKey(String clientKey) { + this.clientKey = clientKey; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } +} \ No newline at end of file diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java new file mode 100644 index 00000000..8bd3abdd --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.dto; + +/** + * This holds the model object of EMM configuration. + */ +public class EMMQSGConfig { + + private String dcrEndPoint; + private String oauthEndPoint; + private String emmHost; + private String username; + private String password; + private static EMMQSGConfig instance = new EMMQSGConfig(); + + private EMMQSGConfig() { + + } + + public String getDcrEndPoint() { + return dcrEndPoint; + } + + public void setDcrEndPoint(String dcrEndPoint) { + this.dcrEndPoint = dcrEndPoint; + } + + public String getOauthEndPoint() { + return oauthEndPoint; + } + + public void setOauthEndPoint(String oauthEndPoint) { + this.oauthEndPoint = oauthEndPoint; + } + + public String getEmmHost() { + return emmHost; + } + + public void setEmmHost(String emmHost) { + this.emmHost = emmHost; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public static EMMQSGConfig getInstance() { + return instance; + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java new file mode 100644 index 00000000..2a5ed741 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.dto; + +/** + * This holds the domain-model of HTTP Response. + */ +public class HTTPResponse { + + private String response; + private int responseCode; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public int getResponseCode() { + return responseCode; + } + + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } +} \ No newline at end of file diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java new file mode 100644 index 00000000..4119a6fe --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.dto; + +/** + * This serves as the domain-model of MobileApplication related data. + */ +public class MobileApplication { + + private String appId; + private String packageId; + private String version; + private String icon; + private String banner; + private String screenshot1; + private String screenshot2; + private String screenshot3; + private String platform; + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public String getPackageId() { + return packageId; + } + + public void setPackageId(String packageId) { + this.packageId = packageId; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getBanner() { + return banner; + } + + public void setBanner(String banner) { + this.banner = banner; + } + + public String getScreenshot1() { + return screenshot1; + } + + public void setScreenshot1(String screenshot1) { + this.screenshot1 = screenshot1; + } + + public String getScreenshot2() { + return screenshot2; + } + + public void setScreenshot2(String screenshot2) { + this.screenshot2 = screenshot2; + } + + public String getScreenshot3() { + return screenshot3; + } + + public void setScreenshot3(String screenshot3) { + this.screenshot3 = screenshot3; + } +} diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java new file mode 100644 index 00000000..f5fb2789 --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.utils; + +/** + * This class defines the constants used by the EMm-QSG package. + */ +public final class Constants { + + public static final class DeviceType { + private DeviceType() { + throw new AssertionError(); + } + + public static final String ANDROID = "android"; + public static final String WINDOWS = "windows"; + public static final String IOS = "ios"; + } + + public static final class ContentType { + private ContentType() { + throw new AssertionError(); + } + + public static final String APPLICATION_JSON = "application/json"; + public static final String APPLICATION_URL_ENCODED = "application/x-www-form-urlencoded"; + } + + public static final class Header { + private Header() { + throw new AssertionError(); + } + + public static final String AUTH = "Authorization"; + public static final String CONTENT_TYPE = "Content-Type"; + } + + public static final class HTTPStatus { + private HTTPStatus() { + throw new AssertionError(); + } + + public static final int OK = 200; + public static final int CREATED = 201; + } + + public static final String UTF_8 = "utf-8"; + public static final String EMM_USER_ROLE = "emm-user"; +} \ No newline at end of file diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java new file mode 100644 index 00000000..733310be --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.utils; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.ContentBody; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.wso2.mdm.qsg.dto.HTTPResponse; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import java.io.*; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.List; + +/** + * This class provides the utility methods to make a HTTP request. + */ +public class HTTPInvoker { + + private static final String OAUTH_BEARER = "Bearer "; + public static String oAuthToken; + + private static HttpClient createHttpClient() + throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { + HttpClientBuilder b = HttpClientBuilder.create(); + + // setup a Trust Strategy that allows all certificates. + // + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + return true; + } + }).build(); + b.setSSLContext(sslContext); + //b.setSSLHostnameVerifier(new NoopHostnameVerifier()); + + // don't check Hostnames, either. + // -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken + HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; + + // here's the special part: + // -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; + // -- and create a Registry, to register it. + // + SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslSocketFactory) + .build(); + + // now, we create connection-manager using our Registry. + // -- allows multi-threaded use + PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + b.setConnectionManager(connMgr); + + // finally, build the HttpClient; + // -- done! + CloseableHttpClient client = b.build(); + return client; + } + + public static HTTPResponse sendHTTPPostWithURLParams(String url, List params, HashMap + headers) { + HttpPost post = null; + HttpResponse response = null; + CloseableHttpClient httpclient = null; + HTTPResponse httpResponse = new HTTPResponse(); + try { + httpclient = (CloseableHttpClient) createHttpClient(); + post = new HttpPost(url); + post.setEntity(new UrlEncodedFormEntity(params)); + for (String key : headers.keySet()) { + post.setHeader(key, headers.get(key)); + } + response = httpclient.execute(post); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + return httpResponse; + } + + public static HTTPResponse sendHTTPPost(String url, String payload, HashMap + headers) { + HttpPost post = null; + HttpResponse response = null; + HTTPResponse httpResponse = new HTTPResponse(); + CloseableHttpClient httpclient = null; + try { + httpclient = (CloseableHttpClient) createHttpClient(); + StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8); + post = new HttpPost(url); + post.setEntity(requestEntity); + for (String key : headers.keySet()) { + post.setHeader(key, headers.get(key)); + } + response = httpclient.execute(post); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return httpResponse; + } + + public static HTTPResponse sendHTTPPutWithOAuthSecurity(String url, String payload, HashMap + headers) { + HttpPut put = null; + HttpResponse response = null; + HTTPResponse httpResponse = new HTTPResponse(); + CloseableHttpClient httpclient = null; + try { + httpclient = (CloseableHttpClient) createHttpClient(); + StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8); + put = new HttpPut(url); + put.setEntity(requestEntity); + for (String key : headers.keySet()) { + put.setHeader(key, headers.get(key)); + } + put.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); + response = httpclient.execute(put); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return httpResponse; + } + + public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload, HashMap + headers) { + HttpPost post = null; + HttpResponse response = null; + HTTPResponse httpResponse = new HTTPResponse(); + CloseableHttpClient httpclient = null; + try { + httpclient = (CloseableHttpClient) createHttpClient(); + StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8); + post = new HttpPost(url); + post.setEntity(requestEntity); + for (String key : headers.keySet()) { + post.setHeader(key, headers.get(key)); + } + + post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); + response = httpclient.execute(post); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return httpResponse; + } + + public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, HttpEntity entity, HashMap + headers) { + HttpPost post = null; + HttpResponse response = null; + HTTPResponse httpResponse = new HTTPResponse(); + CloseableHttpClient httpclient = null; + try { + httpclient = (CloseableHttpClient) createHttpClient(); + post = new HttpPost(url); + post.setEntity(entity); + for (String key : headers.keySet()) { + post.setHeader(key, headers.get(key)); + } + post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); + response = httpclient.execute(post); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return httpResponse; + } + + public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) { + HttpPost post = null; + HttpResponse response = null; + HTTPResponse httpResponse = new HTTPResponse(); + CloseableHttpClient httpclient = null; + try { + httpclient = (CloseableHttpClient) createHttpClient(); + post = new HttpPost(url); + File file = new File(fileName); + + MultipartEntity mpEntity = new MultipartEntity(); + ContentBody cbFile = new FileBody(file, fileContentType); + mpEntity.addPart("file", cbFile); + post.setEntity(mpEntity); + post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); + //post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data"); + post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON); + response = httpclient.execute(post); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + BufferedReader rd = null; + try { + rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + } catch (IOException e) { + e.printStackTrace(); + } + + StringBuffer result = new StringBuffer(); + String line = ""; + try { + while ((line = rd.readLine()) != null) { + result.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); + httpResponse.setResponse(result.toString()); + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return httpResponse; + } +} \ No newline at end of file diff --git a/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java new file mode 100644 index 00000000..2372750b --- /dev/null +++ b/modules/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.mdm.qsg.utils; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.wso2.mdm.qsg.dto.ClientCredentials; +import org.wso2.mdm.qsg.dto.EMMQSGConfig; +import org.wso2.mdm.qsg.dto.HTTPResponse; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class holds the utility methods used by the EMM-QSG package. + */ +public class QSGUtils { + + public static EMMQSGConfig initConfig() { + Properties props = new Properties(); + InputStream input = null; + EMMQSGConfig emmConfig = null; + try { + input = new FileInputStream("config.properties"); + // load a properties file and set the properties + props.load(input); + emmConfig = EMMQSGConfig.getInstance(); + emmConfig.setEmmHost(props.getProperty("emm-host")); + emmConfig.setDcrEndPoint(props.getProperty("dcr-endpoint")); + emmConfig.setOauthEndPoint(props.getProperty("oauth-endpoint")); + emmConfig.setUsername(props.getProperty("username")); + emmConfig.setPassword(props.getProperty("password")); + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return emmConfig; + } + + private static ClientCredentials getClientCredentials() { + ClientCredentials clientCredentials = null; + HashMap headers = new HashMap(); + String dcrEndPoint = EMMQSGConfig.getInstance().getDcrEndPoint(); + //Set the DCR payload + JSONObject obj = new JSONObject(); + obj.put("owner", "admin"); + obj.put("clientName", "qsg"); + obj.put("grantType", "refresh_token password client_credentials"); + obj.put("tokenScope", "user:view,user:manage,user:admin:reset-password,role:view,role:manage,policy:view," + + "policy:manage,application:manage,appm:create,appm:publish,appm:update,appm:read"); + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON); + HTTPResponse httpResponse = HTTPInvoker.sendHTTPPost(dcrEndPoint, obj.toJSONString(), headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) { + try { + JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse()); + clientCredentials = new ClientCredentials(); + clientCredentials.setClientKey((String) jsonObject.get("client_id")); + clientCredentials.setClientSecret((String) jsonObject.get("client_secret")); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return clientCredentials; + } + + public static String getOAuthToken() { + QSGUtils.initConfig(); + ClientCredentials clientCredentials = getClientCredentials(); + String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret(); + String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes())); + HashMap headers = new HashMap(); + //Set the form params + List urlParameters = new ArrayList(); + urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername())); + urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword())); + urlParameters.add(new BasicNameValuePair("grant_type", "password")); + urlParameters.add(new BasicNameValuePair("scope", + "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " + + "application:manage appm:administration appm:create appm:publish appm:update appm:read")); + //Set the headers + headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED); + headers.put(Constants.Header.AUTH, authHeader); + HTTPResponse httpResponse = HTTPInvoker + .sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers); + if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) { + try { + JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse()); + return (String) jsonObject.get("access_token"); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return null; + } + + public static boolean isValidEmailAddress(String email) { + String emailPattern = + "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; + Pattern p = Pattern.compile(emailPattern); + Matcher m = p.matcher(email); + return m.matches(); + } + + public static String getResourceId(String resourcePath) { + return resourcePath.substring(resourcePath.lastIndexOf('/') + 1); + } +} diff --git a/modules/scripts/pom.xml b/modules/scripts/pom.xml new file mode 100644 index 00000000..8b0692a4 --- /dev/null +++ b/modules/scripts/pom.xml @@ -0,0 +1,38 @@ + + + + + + org.wso2.iot + wso2iot-parent + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + wso2iot-scripts + pom + WSO2 IoT - Core - Scripts + http://maven.apache.org + + + mobile-qsg + + + diff --git a/modules/tools/cdmf-devicetype-archetype/README.md b/modules/tools/cdmf-devicetype-archetype/README.md new file mode 100644 index 00000000..926825ed --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/README.md @@ -0,0 +1,89 @@ +# Install cdmf-devicetype-archetype + +First you need to download this maven archetype. To download + + git clone https://github.com/GPrathap/cdmf-devicetype-archetype.git + +To install this maven archetype into your local system, inside the cdmf-devicetype-archetype + + mvn clean install + +# Create sample device type plugin using cdmf-devicetype-archetype + +First download WOS2 IoT Server and copy the downloaded file to a preferred location and unzip it. The unzipped folder rename as IOTS_HOME. +To create new project go to this folder: IOTS_HOME/samples + + mvn archetype:generate -DarchetypeCatalog=local + +Then select the cdmf.devicetype:cdmf-devicetype-archetype as new archetype. + + jobs@jobs-ThinkPad-T530:~/wso2/IoT/m3/product/IOTS_HOME/samples$ + mvn archetype:generate -DarchetypeCatalog=local + [INFO] Scanning for projects... + [INFO] + [INFO] ------------------------------------------------------------------------ + [INFO] Building Maven Stub Project (No POM) 1 + [INFO] ------------------------------------------------------------------------ + [INFO] + [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom >>> + [INFO] + [INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom <<< + [INFO] + [INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom --- + [INFO] Generating project in Interactive mode + [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) + Choose archetype: + 1: local -> org.apache.synapse:synapse-package-archetype (This archetype can be used to create Maven projects that bundle a mediation + into a standalone distribution ready to be executed) + 2: local -> org.wso2.mdm:mdm-android-agent-archetype (Creates a MDM-Android agent project) + 3: local -> org.wso2.cdmf.devicetype:cdmf-devicetype-archetype (WSO2 CDMF Device Type Archetype) + Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 3 + + + Then you need to provide groupId, artifactId, version, packaging, name of your device type and name for sensor as shown below. + + Define value for property 'groupId': : org.homeautomation + Define value for property 'artifactId': : currentsensor + Define value for property 'version': 1.0-SNAPSHOT: : 1.0.0-SNAPSHOT + Define value for property 'package': org.homeautomation: : + Define value for property 'deviceType': : currentsensor + Define value for property 'nameOfTheSensor': : current + Confirm properties configuration: + groupId: org.homeautomation + artifactId: currentsensor + version: 1.0.0-SNAPSHOT + package: org.homeautomation + deviceType: currentsensor + nameOfTheSensor: current + + + +# Configure the device-deployer.xml file that is in the IoTS_HOME directory. + +Add the new module under the tag. + + + samples/currentsensor + + +Add the device type feature under the `` tag. + + org.homeautomation:org.homeautomation.currentsensor.feature:1.0.0-SNAPSHOT + + + +Add the device type feature group under the tag. + + + + org.homeautomation.currentsensor.feature.group + 1.0.0-SNAPSHOT + + + + +To deploy sample device type into IoT Server + + mvn clean install -f device-deployer.xml + +Note: This command should be executed place where `device-deployer.xml` is located diff --git a/modules/tools/cdmf-devicetype-archetype/pom.xml b/modules/tools/cdmf-devicetype-archetype/pom.xml new file mode 100644 index 00000000..dde30e71 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/pom.xml @@ -0,0 +1,65 @@ + + + + + org.wso2.iot + wso2iot-tools + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + iot-devicetype-archetype + 3.1.0-SNAPSHOT + WSO2 IoT - Device Type Archetype + WSO2 IoT Device Type Archetype + maven-archetype + + WSO2 Inc. + http://www.wso2.com + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + + org.apache.maven.archetype + archetype-packaging + ${archetype.packaging.version} + + + + + + maven-archetype-plugin + ${archetype.plugin.version} + + + + + + 2.4 + 2.4 + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 00000000..aef42d11 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + src/main/java/ + + **/*.java + + + + src/main/resources + + + src/test/resources + + + + + + + src/main/java/ + + **/*.java + + + + src/main/webapp + + **/*.xml + + + + src/main/resources + + + src/test/java/__groupId__.__rootArtifactId__.api + + + src/test/resources + + + + + + + src/assembly + + **/*.xml + + + + src/main/resources/ + + **/*.xml + **/*.properties + **/*.car + **/*.db + **/*.sql + **/*.json + **/*.inf + **/*.sh + **/*.hbs + **/*.py + **/*-view.js + **/*-graph.js + + + + src/main/resources/ + + **/*.png + **/*.js + **/*.css + + + + + + + + src/assembly + + **/*.xml + + + + src/main/resources/carbonapps + + **/*.* + + + + + + build.xml + + + + + + + + + + + + src/main/resources + + **/*.xml + **/*.properties + **/*.car + **/*.db + **/*.sql + **/*.json + **/*.inf + **/*.hbs + **/*.py + + + + src/main/resources/ + + **/*.png + **/*.js + **/*.sh + **/*.css + + + + + + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/build.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/build.xml new file mode 100644 index 00000000..be799706 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/build.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/pom.xml new file mode 100644 index 00000000..c15ef204 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/pom.xml @@ -0,0 +1,86 @@ + + + + ${groupId} + ${rootArtifactId}-component + ${version} + ../pom.xml + + 4.0.0 + ${artifactId} + ${version} + pom + ${artifactId} + http://wso2.org + + + + maven-clean-plugin + ${maven-clean-plugin.version} + + + auto-clean + initialize + + clean + + + + + + maven-antrun-plugin + ${wso2.maven.compiler.source} + + + process-resources + + + + + + + run + + + + + + maven-assembly-plugin + ${maven-assembly-plugin.version} + + ${project.artifactId}-${version} + false + + src/assembly/src.xml + + + + + create-archive + package + + single + + + + + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/assembly/src.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/assembly/src.xml new file mode 100644 index 00000000..a5a37501 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/assembly/src.xml @@ -0,0 +1,36 @@ + + + + src + + zip + + false + ${basedir}/src + + + ${basedir}/target/carbonapps + / + true + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/EventPublisher___nameOfTheSensor__.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/EventPublisher___nameOfTheSensor__.xml new file mode 100644 index 00000000..e94e4d8d --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/EventPublisher___nameOfTheSensor__.xml @@ -0,0 +1,25 @@ + + + + + + + + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/artifact.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/artifact.xml new file mode 100644 index 00000000..bdbf22a2 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventpublisher___nameOfTheSensor___1.0.0/artifact.xml @@ -0,0 +1,22 @@ + + + + + EventPublisher_${nameOfTheSensor}.xml + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/EventReceiver_mqtt___nameOfTheSensor__.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/EventReceiver_mqtt___nameOfTheSensor__.xml new file mode 100644 index 00000000..761036b0 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/EventReceiver_mqtt___nameOfTheSensor__.xml @@ -0,0 +1,32 @@ + + + + + carbon.super/${deviceType}/+/publisher + admin + device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2 + org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator + default + https://localhost:${carbon.https.port}/dynamic-client-web/register + tcp://${mqtt.broker.host}:${mqtt.broker.port} + true + + + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/artifact.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/artifact.xml new file mode 100644 index 00000000..ca3e0301 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventreceiver_mqtt___nameOfTheSensor___1.0.0/artifact.xml @@ -0,0 +1,22 @@ + + + + + EventReceiver_mqtt_${nameOfTheSensor}.xml + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/artifact.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/artifact.xml new file mode 100644 index 00000000..0877f658 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/artifact.xml @@ -0,0 +1,22 @@ + + + + + org_wso2_iot_devices_${nameOfTheSensor}.xml + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/org_wso2_iot_devices___nameOfTheSensor__.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/org_wso2_iot_devices___nameOfTheSensor__.xml new file mode 100644 index 00000000..22764126 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstore___nameOfTheSensor___1.0.0/org_wso2_iot_devices___nameOfTheSensor__.xml @@ -0,0 +1,62 @@ + + + + + + org.wso2.iot.devices.${nameOfTheSensor}:1.0.0 + + EVENT_STORE + + + meta_owner + true + true + false + STRING + + + meta_deviceType + true + true + false + STRING + + + meta_deviceId + true + true + false + STRING + + + meta_time + true + true + false + LONG + + + ${nameOfTheSensor} + false + false + false + FLOAT + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/artifact.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/artifact.xml new file mode 100644 index 00000000..5bc9ec1b --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/artifact.xml @@ -0,0 +1,23 @@ + + + + + org.wso2.iot.devices.${nameOfTheSensor}_1.0.0.json + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/org.wso2.iot.devices.__nameOfTheSensor___1.0.0.json b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/org.wso2.iot.devices.__nameOfTheSensor___1.0.0.json new file mode 100644 index 00000000..6d4e8a5c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Eventstream___nameOfTheSensor___1.0.0/org.wso2.iot.devices.__nameOfTheSensor___1.0.0.json @@ -0,0 +1,20 @@ +{ + "name": "org.wso2.iot.devices.${nameOfTheSensor}", + "version": "1.0.0", + "nickName": "${nameOfTheSensor}", + "description": "${nameOfTheSensor} data received from the Device", + "metaData": [ + {"name":"owner","type":"STRING"}, + {"name":"deviceType","type":"STRING"}, + {"name":"deviceId","type":"STRING"}, + {"name":"time","type":"LONG"} + ], + "payloadData": [ + { + "name": "${nameOfTheSensor}","type": "FLOAT" + } + ] +} + + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/__nameOfTheSensor___Script.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/__nameOfTheSensor___Script.xml new file mode 100644 index 00000000..b527e0cb --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/__nameOfTheSensor___Script.xml @@ -0,0 +1,28 @@ + + + + + IoTServer_Sensor_Script + + 0 * * * * ? + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/artifact.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/artifact.xml new file mode 100644 index 00000000..4304b82c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/Sparkscripts_1.0.0/artifact.xml @@ -0,0 +1,22 @@ + + + + + ${nameOfTheSensor}_Script.xml + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/artifacts.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/artifacts.xml new file mode 100644 index 00000000..b8f962f5 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/analytics/src/main/resources/carbonapps/__nameOfTheSensor__/artifacts.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml new file mode 100644 index 00000000..72b48405 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml @@ -0,0 +1,173 @@ + + + + + + ${groupId} + ${rootArtifactId}-component + ${version} + ../pom.xml + + 4.0.0 + ${project-base-package}.api + ${version} + war + ${project-base-package}.api + http://wso2.com + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + UTF-8 + ${maven.compiler.source} + ${maven.compiler.target} + + + + maven-war-plugin + ${maven-war-plugin.version} + + ${project-base-package}.api + + + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + provided + + + + + org.apache.httpcomponents + httpasyncclient + 4.1 + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot + provided + + + ${groupId} + ${project-base-package}.plugin + provided + + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics.data.publisher + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api + provided + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.extensions + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension + provided + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java new file mode 100644 index 00000000..8724a93c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package ${groupId}.${rootArtifactId}.api; + +import ${groupId}.${rootArtifactId}.api.dto.DeviceJSON; + +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Path; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.PUT; +import javax.ws.rs.DELETE; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + + +/** + * This is the controller API which is used to control agent side functionality + */ +@SuppressWarnings("NonJaxWsWebServices") +@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}") +@DeviceType(value = "${deviceType}") +public interface DeviceTypeService { + + /** + * @param agentInfo device owner,id and sensor value + * @return + */ + @Path("device/register") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/user/register"}) + Response registerDevice(final DeviceJSON agentInfo); + + /** + * @param deviceId unique identifier for given device type + * @param state change status of sensor: on/off + * @param response + */ + @Path("device/{deviceId}/change-status") + @POST + @Feature(code = "change-status", name = "Change status of sensor: on/off", + description = "Change status of sensor: on/off") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/change-status"}) + Response changeStatus(@PathParam("deviceId") String deviceId, + @QueryParam("state") String state, + @Context HttpServletResponse response); + + /** + * Retrieve Sensor data for the ${deviceType} + */ + @Path("device/stats/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/stats"}) + Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, + @QueryParam("to") long to); + + @Path("/device/{device_id}") + @DELETE + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/removeDevice"}) + Response removeDevice(@PathParam("device_id") String deviceId); + + @Path("/device/{device_id}") + @PUT + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) + Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); + + @Path("/device/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) + Response getDevice(@PathParam("device_id") String deviceId); + + @Path("/devices") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/devices"}) + Response getAllDevices(); + + @Path("/device/download") + @GET + @Produces("application/zip") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/download"}) + Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java new file mode 100644 index 00000000..e15d5203 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java @@ -0,0 +1,384 @@ +/* +* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package ${groupId}.${rootArtifactId}.api; + +import ${groupId}.${rootArtifactId}.api.dto.DeviceJSON; +import ${groupId}.${rootArtifactId}.api.dto.SensorRecord; +import ${groupId}.${rootArtifactId}.api.util.APIUtil; +import ${groupId}.${rootArtifactId}.api.util.ZipUtil; +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.api.DeviceTypeService; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.dataservice.commons.SORT; +import org.wso2.carbon.analytics.dataservice.commons.SortByField; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; +import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; +import org.wso2.carbon.device.mgt.iot.util.ZipArchive; +import org.wso2.carbon.identity.jwt.client.extension.JWTClient; +import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.user.api.UserStoreException; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Path; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.PUT; +import javax.ws.rs.DELETE; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +import java.util.UUID; +import java.util.Map; +import java.util.List; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Date; +import java.util.concurrent.ConcurrentHashMap; + + +/** + * This is the controller API which is used to control agent side functionality + */ +@SuppressWarnings("NonJaxWsWebServices") +@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}") +@DeviceType(value = "${deviceType}") +public class DeviceTypeServiceImpl implements DeviceTypeService { + + private static final String KEY_TYPE = "PRODUCTION"; + private static Log log = LogFactory.getLog(DeviceTypeService.class); + private static ApiApplicationKey apiApplicationKey; + private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); + + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } + + /** + * @param agentInfo device owner,id and sensor value + * @return + */ + @Path("device/register") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public Response registerDevice(final DeviceJSON agentInfo) { + String deviceId = agentInfo.deviceId; + if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { + deviceToIpMap.put(deviceId, agentInfo); + return Response.status(Response.Status.OK).build(); + } + return Response.status(Response.Status.NOT_ACCEPTABLE).build(); + } + + /** + * @param deviceId unique identifier for given device type + * @param state change status of sensor: on/off + * @param response + */ + @Path("device/{deviceId}/change-status") + @POST + @Feature(code = "change-status", name = "Change status of sensor: on/off", + description = "Change status of sensor: on/off") + public Response changeStatus(@PathParam("deviceId") String deviceId, + @QueryParam("state") String state, + @Context HttpServletResponse response) { + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + DeviceTypeConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + String sensorState = state.toUpperCase(); + if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals( + DeviceTypeConstants.STATE_OFF)) { + log.error("The requested state change should be either - 'ON' or 'OFF'"); + return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); + } + Map dynamicProperties = new HashMap<>(); + String publishTopic = APIUtil.getAuthenticatedUserTenantDomain() + + "/" + DeviceTypeConstants.DEVICE_TYPE + "/" + deviceId + "/command"; + dynamicProperties.put(DeviceTypeConstants.ADAPTER_TOPIC_PROPERTY, publishTopic); + APIUtil.getOutputEventAdapterService().publish(DeviceTypeConstants.MQTT_ADAPTER_NAME, + dynamicProperties, state); + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } + + /** + * Retrieve Sensor data for the + */ + @Path("device/stats/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, + @QueryParam("to") long to) { + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + String query = "deviceId:" + deviceId + " AND deviceType:" + + DeviceTypeConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; + String sensorTableName = DeviceTypeConstants.SENSOR_EVENT_TABLE; + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + DeviceTypeConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + if (sensorTableName != null) { + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField("time", SORT.ASC, false); + sortByFields.add(sortByField); + List sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields); + return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build(); + } + } catch (AnalyticsException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @Path("/device/{device_id}") + @DELETE + public Response removeDevice(@PathParam("device_id") String deviceId) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + @Path("/device/{device_id}") + @PUT + public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); + device.setDeviceIdentifier(deviceId); + device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); + device.setName(name); + device.setType(DeviceTypeConstants.DEVICE_TYPE); + boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device); + if (updated) { + return Response.ok().build(); + } else { + return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + @Path("/device/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getDevice(@PathParam("device_id") String deviceId) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); + return Response.ok().entity(device).build(); + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + @Path("/devices") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getAllDevices() { + try { + List userDevices = + APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser()); + ArrayList userDevicesforFirealarm = new ArrayList<>(); + for (Device device : userDevices) { + if (device.getType().equals(DeviceTypeConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + } + } + Device[] devices = userDevicesforFirealarm.toArray(new Device[]{}); + return Response.ok().entity(devices).build(); + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + + @Path("/device/download") + @GET + @Produces("application/zip") + public Response downloadSketch(@QueryParam("deviceName") String deviceName, + @QueryParam("sketchType") String sketchType) { + try { + ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); + Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); + response.status(Response.Status.OK); + response.type("application/zip"); + response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); + Response resp = response.build(); + zipFile.getZipFile().delete(); + return resp; + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + log.error(ex.getMessage(), ex); + return Response.status(500).entity(ex.getMessage()).build(); + } catch (JWTClientException ex) { + log.error(ex.getMessage(), ex); + return Response.status(500).entity(ex.getMessage()).build(); + } catch (APIManagerException ex) { + log.error(ex.getMessage(), ex); + return Response.status(500).entity(ex.getMessage()).build(); + } catch (IOException ex) { + log.error(ex.getMessage(), ex); + return Response.status(500).entity(ex.getMessage()).build(); + } catch (UserStoreException ex) { + log.error(ex.getMessage(), ex); + return Response.status(500).entity(ex.getMessage()).build(); + } + } + + private boolean register(String deviceId, String name) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + return false; + } + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + device.setName(name); + device.setType(DeviceTypeConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + if (added) { + APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser()); + } + return added; + } catch (DeviceManagementException e) { + log.error(e.getMessage(), e); + return false; + } + } + + private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) + throws DeviceManagementException, JWTClientException, APIManagerException, + UserStoreException { + //create new device id + String deviceId = shortUUID(); + if (apiApplicationKey == null) { + String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(); + applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain(); + APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); + String[] tags = {DeviceTypeConstants.DEVICE_TYPE}; + apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( + DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); + } + JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); + String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId; + AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), + apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes); + + //create token + String accessToken = accessTokenInfo.getAccessToken(); + String refreshToken = accessTokenInfo.getRefreshToken(); + boolean status = register(deviceId, deviceName); + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; + throw new DeviceManagementException(msg); + } + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, + deviceId, deviceName, accessToken, refreshToken); + return zipFile; + } +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java new file mode 100644 index 00000000..be3a86c0 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.dto; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * These information are sent by agent in each request to server + */ +@XmlRootElement +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) + public String owner; + @XmlElement(required = true) + public String deviceId; + @XmlElement(required = true) + public Float sensorValue; +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java new file mode 100644 index 00000000..d7656872 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.dto; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * This stores sensor event data for ${deviceType}. + */ +@XmlRootElement +@JsonIgnoreProperties(ignoreUnknown = true) +public class SensorRecord { + + @XmlElementWrapper(required = true, name = "values") + private Map values; + + /** + * The id. + */ + @XmlElement(required = false, name = "id") + private String id; + + /** + * Gets the values. + * @return the values + */ + public Map getValues() { + return values; + } + + /** + * Sets the values. + * @param values the values + */ + public void setValues(Map values) { + this.values = values; + } + + /** + * Gets the id. + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the id. + * @param id the new id + */ + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + List valueList = new ArrayList(); + for (Map.Entry entry : values.entrySet()) { + valueList.add(entry.getKey() + ":" + entry.getValue()); + } + return valueList.toString(); + + } + +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java new file mode 100644 index 00000000..84fbf846 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.exception; + +public class DeviceTypeException extends Exception { + + private static final long serialVersionUID = 2736466230451105441L; + + private String errorMessage; + + public DeviceTypeException(String msg, DeviceTypeException nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceTypeException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceTypeException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceTypeException() { + super(); + } + + public DeviceTypeException(Throwable cause) { + super(cause); + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java new file mode 100644 index 00000000..4d54030c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java @@ -0,0 +1,221 @@ +package ${groupId}.${rootArtifactId}.api.util; + +import ${groupId}.${rootArtifactId}.api.dto.SensorRecord; + +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils; +import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; +import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; +import org.wso2.carbon.analytics.dataservice.commons.SortByField; +import org.wso2.carbon.analytics.datasource.commons.Record; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.service.RealmService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class provides utility functions used by REST-API. + */ +public class APIUtil { + + private static Log log = LogFactory.getLog(APIUtil.class); + + public static String getAuthenticatedUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + public static DeviceManagementProviderService getDeviceManagementService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceManagementProviderService deviceManagementProviderService = + (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); + if (deviceManagementProviderService == null) { + String msg = "Device Management service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceManagementProviderService; + } + + public static APIManagementProviderService getAPIManagementProviderService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + APIManagementProviderService apiManagementProviderService = + (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null); + if (apiManagementProviderService == null) { + String msg = "API management provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return apiManagementProviderService; + } + + public static JWTClientManagerService getJWTClientManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = + (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "JWT Client manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } + + public static String getTenantDomainOftheUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return threadLocalCarbonContext.getTenantDomain(); + } + + public static UserStoreManager getUserStoreManager() { + RealmService realmService; + UserStoreManager userStoreManager; + try { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + if (realmService == null) { + String msg = "Realm service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + int tenantId = ctx.getTenantId(); + userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving current user store manager"; + log.error(msg, e); + throw new IllegalStateException(msg); + } + return userStoreManager; + } + + public static void registerApiAccessRoles(String user) { + UserStoreManager userStoreManager = null; + try { + userStoreManager = getUserStoreManager(); + String[] userList = new String[]{user}; + if (userStoreManager != null) { + String rolesOfUser[] = userStoreManager.getRoleListOfUser(user); + if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) { + userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION); + } else if (rolesOfUser != null && Arrays.asList(rolesOfUser).contains(Constants.DEFAULT_ROLE_NAME)) { + return; + } else { + userStoreManager.updateUserListOfRole(Constants.DEFAULT_ROLE_NAME, new String[0], userList); + } + } + } catch (UserStoreException e) { + log.error("Error while creating a role and adding a user for virtual_firealarm.", e); + } + } + + public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); + if (deviceAccessAuthorizationService == null) { + String msg = "Device Authorization service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceAccessAuthorizationService; + } + + public static List getAllEventsForDevice(String tableName, String query, + List sortByFields) throws AnalyticsException { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); + int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); + if (eventCount == 0) { + return null; + } + List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount, + sortByFields); + List recordIds = getRecordIds(resultEntries); + AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); + Map sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords( + analyticsDataAPI, response)); + List sortedSensorData = getSortedSensorData(sensorDatas, resultEntries); + return sortedSensorData; + } + + public static List getSortedSensorData(Map sensorDatas, + List searchResults) { + List sortedRecords = new ArrayList<>(); + for (SearchResultEntry searchResultEntry : searchResults) { + sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); + } + return sortedRecords; + } + + private static List getRecordIds(List searchResults) { + List ids = new ArrayList<>(); + for (SearchResultEntry searchResult : searchResults) { + ids.add(searchResult.getId()); + } + return ids; + } + + public static Map createSensorData(List records) { + Map sensorDatas = new HashMap<>(); + for (Record record : records) { + SensorRecord sensorData = createSensorData(record); + sensorDatas.put(sensorData.getId(), sensorData); + } + return sensorDatas; + } + + public static SensorRecord createSensorData(Record record) { + SensorRecord recordBean = new SensorRecord(); + recordBean.setId(record.getId()); + recordBean.setValues(record.getValues()); + return recordBean; + } + + public static AnalyticsDataAPI getAnalyticsDataAPI() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + AnalyticsDataAPI analyticsDataAPI = + (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); + if (analyticsDataAPI == null) { + String msg = "Analytics api service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return analyticsDataAPI; + } + + public static String getAuthenticatedUserTenantDomain() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return threadLocalCarbonContext.getTenantDomain(); + } + + public static OutputEventAdapterService getOutputEventAdapterService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + OutputEventAdapterService outputEventAdapterService = + (OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null); + if (outputEventAdapterService == null) { + String msg = "Device Authorization service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return outputEventAdapterService; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java new file mode 100644 index 00000000..86cc5bc0 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.util; + +import org.wso2.carbon.user.core.Permission; + +/** + * This hold the constants related to the device type. + */ +public class Constants { + + public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/${deviceType}/user"; + public static final String DEFAULT_ROLE_NAME = "${deviceType}_user"; + public static final Permission DEFAULT_PERMISSION[] + = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")}; +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ResponsePayload.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ResponsePayload.java new file mode 100644 index 00000000..f5c2998e --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ResponsePayload.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.util; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ResponsePayload { + + private int statusCode; + private String messageFromServer; + private Object responseContent; + + public static ResponsePayloadBuilder statusCode(int statusCode) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().statusCode(statusCode); + } + + public static ResponsePayloadBuilder messageFromServer( + String messageFromServer) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().messageFromServer(messageFromServer); + } + + public static ResponsePayloadBuilder responseContent(String responseContent) { + ResponsePayload message = new ResponsePayload(); + return message.getBuilder().responseContent(responseContent); + } + + @XmlElement + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + @XmlElement + public String getMessageFromServer() { + return messageFromServer; + } + + public void setMessageFromServer(String messageFromServer) { + this.messageFromServer = messageFromServer; + } + + @XmlElement + public Object getResponseContent() { + return responseContent; + } + + public void setResponseContent(Object responseContent) { + this.responseContent = responseContent; + } + + private ResponsePayloadBuilder getBuilder() { + return new ResponsePayloadBuilder(); + } + + public class ResponsePayloadBuilder { + + private int statusCode; + private String messageFromServer; + private Object responseContent; + + public ResponsePayloadBuilder statusCode(int statusCode) { + this.statusCode = statusCode; + return this; + } + + public ResponsePayloadBuilder messageFromServer(String messageFromServer) { + this.messageFromServer = messageFromServer; + return this; + } + + public ResponsePayloadBuilder responseContent(String responseContent) { + this.responseContent = responseContent; + return this; + } + + public ResponsePayload build() { + ResponsePayload payload = new ResponsePayload(); + payload.setStatusCode(statusCode); + payload.setMessageFromServer(messageFromServer); + payload.setResponseContent(responseContent); + return payload; + } + } + +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java new file mode 100644 index 00000000..df682a51 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.util; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; +import org.wso2.carbon.context.PrivilegedCarbonContext; + + +public class ServiceUtils { + private static final Log log = LogFactory.getLog(ServiceUtils.class); + + /** + * Sensor data are published to DAS + * + * @param deviceId unique identifier of the device + * @param sensorValue current value of sensor which is set at agent side + * @return + */ + public static boolean publishToDAS(String deviceId, float sensorValue) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); + String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; + Object payloadData[] = {sensorValue}; + try { + deviceAnalyticsService.publishEvent(DeviceTypeConstants.SENSOR_STREAM_DEFINITION, + DeviceTypeConstants.SENSOR_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData); + } catch (DataPublisherConfigurationException e) { + return false; + } + return true; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java new file mode 100644 index 00000000..ec72a87b --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.api.util; + +import ${groupId}.${rootArtifactId}.plugin.mqtt.MqttConfig; + +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.util.Utils; +import org.wso2.carbon.device.mgt.iot.util.ZipArchive; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * This is used to create a zip file that includes the necessary configuration required for the agent. + */ +public class ZipUtil { + + private static final String HTTPS_PORT_PROPERTY = "httpsPort"; + private static final String HTTP_PORT_PROPERTY = "httpPort"; + + private static final String LOCALHOST = "localhost"; + private static final String HTTPS_PROTOCOL_APPENDER = "https://"; + private static final String HTTP_PROTOCOL_APPENDER = "http://"; + + public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType, + String deviceId, String deviceName, String token, + String refreshToken) throws DeviceManagementException { + + String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; + String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" + + File.separator + deviceId; + String templateSketchPath = sketchFolder + File.separator + deviceType; + String iotServerIP; + + try { + iotServerIP = Utils.getServerUrl(); + String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); + String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); + String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; + String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort; + String apimEndpoint = httpsServerEP; + String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint(); + if (mqttEndpoint.contains(LOCALHOST)) { + mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP); + } + + Map contextParams = new HashMap<>(); + contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser()); + contextParams.put("DEVICE_OWNER", owner); + contextParams.put("DEVICE_ID", deviceId); + contextParams.put("DEVICE_NAME", deviceName); + contextParams.put("HTTPS_EP", httpsServerEP); + contextParams.put("HTTP_EP", httpServerEP); + contextParams.put("APIM_EP", apimEndpoint); + contextParams.put("MQTT_EP", mqttEndpoint); + contextParams.put("DEVICE_TOKEN", token); + contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); + + ZipArchive zipFile; + zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); + return zipFile; + } catch (IOException e) { + throw new DeviceManagementException("Zip File Creation Failed", e); + } + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 00000000..87c3aa3d --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,87 @@ + + + + + + + + + + Get device + /device-mgt/${deviceType}/user + /device/* + GET + ${deviceType}_user + + + Remove device + /device-mgt/${deviceType}/user + /device/* + DELETE + ${deviceType}_user + + + Download device + /device-mgt/${deviceType}/user + /device/download + GET + ${deviceType}_user + + + Update device + /device-mgt/${deviceType}/user + /device/* + POST + ${deviceType}_user + + + Get Devices + /device-mgt/${deviceType}/user + /device + GET + ${deviceType}_user + + + Register Device + /device-mgt/${deviceType}/user + /device/register + POST + ${deviceType}_device + + + Control Sensor + /device-mgt/${deviceType}/user + /device/*/change-status + POST + ${deviceType}_user + + + Get Stats + /device-mgt/${deviceType}/user + /device/stats/* + GET + ${deviceType}_device + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/webapp-classloading.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..a47a6891 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..e2641b15 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,46 @@ + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServlet + /* + + + isAdminService + false + + + doAuthentication + true + + + isSharedWithAllTenants + false + + + providerTenantDomain + carbon.super + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/pom.xml new file mode 100644 index 00000000..cf34e955 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/pom.xml @@ -0,0 +1,133 @@ + + + + + + ${groupId} + ${rootArtifactId}-component + ${version} + ../pom.xml + + 4.0.0 + ${version} + ${project-base-package}.plugin + bundle + ${project-base-package}.plugin + http://wso2.org + + + + org.apache.felix + maven-scr-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + UTF-8 + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.apache.felix + maven-bundle-plugin + ${org.apache.felix.version} + true + + + ${project-base-package}.plugin + ${project-base-package}.plugin + ${version} + IoT Server Impl Bundle + ${project-base-package}.plugin.internal + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.naming;resolution:=optional, + javax.sql;resolution:=optional, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.device.mgt.common, + org.wso2.carbon.device.mgt.iot.*, + org.wso2.carbon.device.mgt.extensions.feature.mgt.*, + org.wso2.carbon.utils.*, + org.wso2.carbon.event.output.adapter.core, + org.wso2.carbon.event.output.adapter.core.exception, + org.wso2.carbon.base, + org.wso2.carbon.core.util, + org.wso2.carbon.context, + org.wso2.carbon.core, + org.apache.commons.codec.binary + + + !${project-base-package}.plugin.internal, + ${project-base-package}.plugin.* + + + + + + + + + commons-codec.wso2 + commons-codec + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.extensions + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.wso2.carbon.analytics-common + org.wso2.carbon.event.output.adapter.core + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/constants/DeviceTypeConstants.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/constants/DeviceTypeConstants.java new file mode 100644 index 00000000..01ba3799 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/constants/DeviceTypeConstants.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.constants; + +import org.wso2.carbon.utils.CarbonUtils; +import java.io.File; + +public class DeviceTypeConstants { + public final static String DEVICE_TYPE = "${deviceType}"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "${deviceType}_DEVICE_ID"; + public final static String STATE_ON = "ON"; + public final static String STATE_OFF = "OFF"; + + //sensor events summerized table name + public static final String SENSOR_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_${nameOfTheSensor}"; + public static final String DATA_SOURCE_NAME = "jdbc/${deviceType}DM_DB"; + public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super"; + + //mqtt tranport related constants + public static final String MQTT_ADAPTER_NAME = "${nameOfTheSensor}_mqtt"; + public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt"; + public static final String ADAPTER_TOPIC_PROPERTY = "topic"; + public static final String MQTT_PORT = "\\$\\{mqtt.broker.port\\}"; + public static final String MQTT_BROKER_HOST = "\\$\\{mqtt.broker.host\\}"; + public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset"; + public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip"; + public static final int CARBON_DEFAULT_PORT_OFFSET = 0; + public static final int DEFAULT_MQTT_PORT = 1883; + public static final String SUBSCRIBED_TOPIC = "carbon.super/${deviceType}/+/publisher"; + public static final String CONTENT_TRANSFORMATION = "contentTransformer"; + public static final String CONTENT_VALIDATION = "contentValidator"; + public static final String RESOURCE = "resource"; + + public static final String USERNAME_PROPERTY_KEY = "username"; + public static final String DCR_PROPERTY_KEY = "dcrUrl"; + public static final String BROKER_URL_PROPERTY_KEY = "url"; + public static final String SCOPES_PROPERTY_KEY = "scopes"; + public static final String QOS_PROPERTY_KEY = "qos"; + public static final String CLIENT_ID_PROPERTY_KEY = "qos"; + public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession"; + public static final String TOPIC = "topic"; + + public final static String SENSOR_STREAM_DEFINITION = "org.wso2.iot.devices.${nameOfTheSensor}"; + public final static String SENSOR_STREAM_DEFINITION_VERSION = "1.0.0"; + + public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + + "mqtt.properties"; +} + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/exception/DeviceMgtPluginException.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/exception/DeviceMgtPluginException.java new file mode 100644 index 00000000..dff940aa --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/exception/DeviceMgtPluginException.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.exception; + +public class DeviceMgtPluginException extends Exception { + + private String errorMessage; + + public DeviceMgtPluginException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceMgtPluginException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceMgtPluginException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceMgtPluginException() { + super(); + } + + public DeviceMgtPluginException(Throwable cause) { + super(cause); + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManager.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManager.java new file mode 100644 index 00000000..28995b57 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManager.java @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO; +import ${groupId}.${rootArtifactId}.plugin.exception.DeviceMgtPluginException; +import ${groupId}.${rootArtifactId}.plugin.impl.feature.DeviceTypeFeatureManager; +import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the ${rootArtifactId} implementation of DeviceManagerService. + */ +public class DeviceTypeManager implements DeviceManager { + + private static final Log log = LogFactory.getLog(DeviceTypeManager.class); + private static final DeviceTypeDAO deviceTypeDAO = new DeviceTypeDAO(); + private FeatureManager featureManager = new DeviceTypeFeatureManager(); + + @Override + public FeatureManager getFeatureManager() { + return featureManager; + } + + @Override + public boolean saveConfiguration(TenantConfiguration tenantConfiguration) + throws DeviceManagementException { + //TODO implement this + return false; + } + + @Override + public TenantConfiguration getConfiguration() throws DeviceManagementException { + //TODO implement this + return null; + } + + @Override + public boolean enrollDevice(Device device) throws DeviceManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("Enrolling a new ${rootArtifactId} device : " + device.getDeviceIdentifier()); + } + DeviceTypeDAO.beginTransaction(); + status = deviceTypeDAO.getDeviceTypeDAO().addDevice(device); + DeviceTypeDAO.commitTransaction(); + } catch (DeviceMgtPluginException e) { + try { + DeviceTypeDAO.rollbackTransaction(); + } catch (DeviceMgtPluginException iotDAOEx) { + log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx); + } + String msg = "Error while enrolling the ${rootArtifactId} device : " + device.getDeviceIdentifier(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean modifyEnrollment(Device device) throws DeviceManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("Modifying the ${rootArtifactId} device enrollment data"); + } + DeviceTypeDAO.beginTransaction(); + status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device); + DeviceTypeDAO.commitTransaction(); + } catch (DeviceMgtPluginException e) { + try { + DeviceTypeDAO.rollbackTransaction(); + } catch (DeviceMgtPluginException iotDAOEx) { + String msg = "Error occurred while roll back the update device transaction :" + device.toString(); + log.warn(msg, iotDAOEx); + } + String msg = "Error while updating the enrollment of the ${rootArtifactId} device : " + + device.getDeviceIdentifier(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("Dis-enrolling ${rootArtifactId} device : " + deviceId); + } + DeviceTypeDAO.beginTransaction(); + status = deviceTypeDAO.getDeviceTypeDAO().deleteDevice(deviceId.getId()); + DeviceTypeDAO.commitTransaction(); + } catch (DeviceMgtPluginException e) { + try { + DeviceTypeDAO.rollbackTransaction(); + } catch (DeviceMgtPluginException iotDAOEx) { + String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString(); + log.warn(msg, iotDAOEx); + } + String msg = "Error while removing the ${rootArtifactId} device : " + deviceId.getId(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { + boolean isEnrolled = false; + try { + if (log.isDebugEnabled()) { + log.debug("Checking the enrollment of ${rootArtifactId} device : " + deviceId.getId()); + } + Device iotDevice = + deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId()); + if (iotDevice != null) { + isEnrolled = true; + } + } catch (DeviceMgtPluginException e) { + String msg = "Error while checking the enrollment status of ${rootArtifactId} device : " + + deviceId.getId(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return isEnrolled; + } + + @Override + public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { + return true; + } + + @Override + public boolean setActive(DeviceIdentifier deviceId, boolean status) + throws DeviceManagementException { + return true; + } + + @Override + public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { + Device device; + try { + if (log.isDebugEnabled()) { + log.debug("Getting the details of ${rootArtifactId} device : " + deviceId.getId()); + } + device = deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId()); + } catch (DeviceMgtPluginException e) { + String msg = "Error while fetching the ${rootArtifactId} device : " + deviceId.getId(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return device; + } + + @Override + public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) + throws DeviceManagementException { + return true; + } + + public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { + return false; + } + + @Override + public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, + EnrolmentInfo.Status status) throws DeviceManagementException { + return false; + } + + @Override + public License getLicense(String s) throws LicenseManagementException { + return null; + } + + @Override + public void addLicense(License license) throws LicenseManagementException { + + } + + @Override + public boolean requireDeviceAuthorization() { + return true; + } + + @Override + public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("updating the details of ${rootArtifactId} device : " + deviceIdentifier); + } + DeviceTypeDAO.beginTransaction(); + status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device); + DeviceTypeDAO.commitTransaction(); + } catch (DeviceMgtPluginException e) { + try { + DeviceTypeDAO.rollbackTransaction(); + } catch (DeviceMgtPluginException iotDAOEx) { + String msg = "Error occurred while roll back the update device info transaction :" + device.toString(); + log.warn(msg, iotDAOEx); + } + String msg = + "Error while updating the ${rootArtifactId} device : " + deviceIdentifier; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public List getAllDevices() throws DeviceManagementException { + List devices; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all ${rootArtifactId} devices"); + } + devices = deviceTypeDAO.getDeviceTypeDAO().getAllDevices(); + } catch (DeviceMgtPluginException e) { + String msg = "Error while fetching all ${rootArtifactId} devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManagerService.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManagerService.java new file mode 100644 index 00000000..1038f636 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/DeviceTypeManagerService.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; + +import java.util.List; + +public class DeviceTypeManagerService implements DeviceManagementService { + private DeviceManager deviceManager; + + @Override + public String getType() { + return DeviceTypeConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + this.deviceManager = new DeviceTypeManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public ProvisioningConfig getProvisioningConfig() { + return new ProvisioningConfig(DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false); + } + + @Override + public PushNotificationConfig getPushNotificationConfig() { + return null; + } + +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/DeviceTypeDAO.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/DeviceTypeDAO.java new file mode 100644 index 00000000..2092d615 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/DeviceTypeDAO.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.plugin.impl.dao.impl.DeviceTypeDAOImpl; +import ${groupId}.${rootArtifactId}.plugin.exception.DeviceMgtPluginException; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class DeviceTypeDAO { + + private static final Log log = LogFactory.getLog(DeviceTypeDAO.class); + static DataSource dataSource; // package local variable + private static ThreadLocal currentConnection = new ThreadLocal<>(); + + public DeviceTypeDAO() { + initDeviceTypeDAO(); + } + + public static void initDeviceTypeDAO() { + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME); + } catch (NamingException e) { + log.error("Error while looking up the data source: " + + DeviceTypeConstants.DATA_SOURCE_NAME); + } + } + + public static void beginTransaction() throws DeviceMgtPluginException { + try { + Connection conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new DeviceMgtPluginException("Error occurred while retrieving datasource connection", e); + } + } + + public static Connection getConnection() throws DeviceMgtPluginException { + if (currentConnection.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new DeviceMgtPluginException("Error occurred while retrieving data source connection", + e); + } + } + return currentConnection.get(); + } + + public static void commitTransaction() throws DeviceMgtPluginException { + try { + Connection conn = currentConnection.get(); + if (conn != null) { + conn.commit(); + } else { + if (log.isDebugEnabled()) { + log.debug("Datasource connection associated with the current thread is null, hence commit " + + "has not been attempted"); + } + } + } catch (SQLException e) { + throw new DeviceMgtPluginException("Error occurred while committing the transaction", e); + } finally { + closeConnection(); + } + } + + public static void closeConnection() throws DeviceMgtPluginException { + + Connection con = currentConnection.get(); + if (con != null) { + try { + con.close(); + } catch (SQLException e) { + log.error("Error occurred while close the connection"); + } + } + currentConnection.remove(); + } + + public static void rollbackTransaction() throws DeviceMgtPluginException { + try { + Connection conn = currentConnection.get(); + if (conn != null) { + conn.rollback(); + } else { + if (log.isDebugEnabled()) { + log.debug("Datasource connection associated with the current thread is null, hence rollback " + + "has not been attempted"); + } + } + } catch (SQLException e) { + throw new DeviceMgtPluginException("Error occurred while rollback the transaction", e); + } finally { + closeConnection(); + } + } + + public DeviceTypeDAOImpl getDeviceTypeDAO() { + return new DeviceTypeDAOImpl(); + } +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/impl/DeviceTypeDAOImpl.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/impl/DeviceTypeDAOImpl.java new file mode 100644 index 00000000..db5e4031 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/dao/impl/DeviceTypeDAOImpl.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.plugin.exception.DeviceMgtPluginException; +import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO; +import ${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeUtils; + +import org.wso2.carbon.device.mgt.common.Device; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implements IotDeviceDAO for ${deviceType} Devices. + */ +public class DeviceTypeDAOImpl { + + + private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class); + + public Device getDevice(String deviceId) throws DeviceMgtPluginException { + Connection conn = null; + PreparedStatement stmt = null; + Device iotDevice = null; + ResultSet resultSet = null; + try { + conn = DeviceTypeDAO.getConnection(); + String selectDBQuery = + "SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME" + + " FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, deviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new Device(); + iotDevice.setName(resultSet.getString( + DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME)); + if (log.isDebugEnabled()) { + log.debug("${deviceType} device " + deviceId + " data has been fetched from " + + "${deviceType} database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching ${deviceType} device : '" + deviceId + "'"; + log.error(msg, e); + throw new DeviceMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, resultSet); + DeviceTypeDAO.closeConnection(); + } + return iotDevice; + } + + public boolean addDevice(Device device) throws DeviceMgtPluginException { + boolean status = false; + Connection conn; + PreparedStatement stmt = null; + try { + conn = DeviceTypeDAO.getConnection(); + String createDBQuery = + "INSERT INTO ${deviceType}_DEVICE(${deviceType}_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; + stmt = conn.prepareStatement(createDBQuery); + stmt.setString(1, device.getDeviceIdentifier()); + stmt.setString(2, device.getName()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("${deviceType} device " + device.getDeviceIdentifier() + " data has been" + + " added to the ${deviceType} database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the ${deviceType} device '" + + device.getDeviceIdentifier() + "' to the ${deviceType} db."; + log.error(msg, e); + throw new DeviceMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + return status; + } + + public boolean updateDevice(Device device) throws DeviceMgtPluginException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = DeviceTypeDAO.getConnection(); + String updateDBQuery = + "UPDATE ${deviceType}_DEVICE SET DEVICE_NAME = ? WHERE ${deviceType}_DEVICE_ID = ?"; + stmt = conn.prepareStatement(updateDBQuery); + if (device.getProperties() == null) { + device.setProperties(new ArrayList()); + } + stmt.setString(1, device.getName()); + stmt.setString(2, device.getDeviceIdentifier()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("${deviceType} device " + device.getDeviceIdentifier() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the ${deviceType} device '" + + device.getDeviceIdentifier() + "' data."; + log.error(msg, e); + throw new DeviceMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + return status; + } + + public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = DeviceTypeDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, deviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("${deviceType} device " + deviceId + " data has deleted" + + " from the ${deviceType} database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting ${deviceType} device " + deviceId; + log.error(msg, e); + throw new DeviceMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, null); + } + return status; + } + + public List getAllDevices() throws DeviceMgtPluginException { + Connection conn = null; + PreparedStatement stmt = null; + ResultSet resultSet = null; + Device device; + List iotDevices = new ArrayList<>(); + try { + conn = DeviceTypeDAO.getConnection(); + String selectDBQuery = + "SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME " + + "FROM ${deviceType}_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + device = new Device(); + device.setDeviceIdentifier(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_ID)); + device.setName(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME)); + List propertyList = new ArrayList<>(); + device.setProperties(propertyList); + } + if (log.isDebugEnabled()) { + log.debug("All ${deviceType} device details have fetched from ${deviceType} database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all ${deviceType} device data'"; + log.error(msg, e); + throw new DeviceMgtPluginException(msg, e); + } finally { + DeviceTypeUtils.cleanupResources(stmt, resultSet); + DeviceTypeDAO.closeConnection(); + } + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/feature/DeviceTypeFeatureManager.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/feature/DeviceTypeFeatureManager.java new file mode 100644 index 00000000..ef22b52f --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/feature/DeviceTypeFeatureManager.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${groupId}.${rootArtifactId}.plugin.impl.feature; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager; + +import java.util.List; + +public class DeviceTypeFeatureManager implements FeatureManager { + @Override + public boolean addFeature(Feature feature) throws DeviceManagementException { + return false; + } + + @Override + public boolean addFeatures(List features) throws DeviceManagementException { + return false; + } + + @Override + public Feature getFeature(String name) throws DeviceManagementException { + GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance(); + return genericFeatureManager.getFeature(DeviceTypeConstants.DEVICE_TYPE, name); + } + + @Override + public List getFeatures() throws DeviceManagementException { + GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance(); + return genericFeatureManager.getFeatures(DeviceTypeConstants.DEVICE_TYPE); + } + + @Override + public boolean removeFeature(String name) throws DeviceManagementException { + return false; + } + + @Override + public boolean addSupportedFeaturesToDB() throws DeviceManagementException { + return false; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceSchemaInitializer.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceSchemaInitializer.java new file mode 100644 index 00000000..0b19f3bd --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceSchemaInitializer.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ${groupId}.${rootArtifactId}.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.dbcreator.DatabaseCreator; + +import javax.sql.DataSource; +import java.io.File; + +/** + * Provides methods for initializing the database script. + */ +public class DeviceSchemaInitializer extends DatabaseCreator{ + + private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class); + private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts" + + File.separator + "cdm" + File.separator + "plugins" + File.separator; + + public DeviceSchemaInitializer(DataSource dataSource) { + super(dataSource); + } + + @Override + protected String getDbScriptLocation(String databaseType) { + String scriptName = databaseType + ".sql"; + if (log.isDebugEnabled()) { + log.debug("Loading database script from :" + scriptName); + } + return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeStartupListener.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeStartupListener.java new file mode 100644 index 00000000..be6c243c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeStartupListener.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl.util; + +import ${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.core.ServerStartupObserver; + +import java.io.IOException; + +public class DeviceTypeStartupListener implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeStartupListener.class); + + @Override + public void completingServerStartup() { + } + + @Override + public void completedServerStartup() { + try { + DeviceTypeUtils.setupMqttOutputAdapter(); + } catch (IOException e) { + log.error("Failed to initialize the ${deviceType} output adapter", e); + } + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeUtils.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeUtils.java new file mode 100644 index 00000000..eb0252c9 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/impl/util/DeviceTypeUtils.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.impl.util; + +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.plugin.exception.DeviceMgtPluginException; +import ${groupId}.${rootArtifactId}.plugin.internal.DeviceTypeManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.util.Utils; +import org.wso2.carbon.event.output.adapter.core.MessageType; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Contains utility methods used by ${deviceType} plugin. + */ +public class DeviceTypeUtils { + + private static Log log = LogFactory.getLog(${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeUtils.class); + + public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing database connection", e); + } + } + } + + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + cleanupResources(null, stmt, rs); + } + + /** + * Creates the device management schema. + */ + public static void setupDeviceManagementSchema() throws DeviceMgtPluginException { + try { + Context ctx = new InitialContext(); + DataSource dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME); + DeviceSchemaInitializer initializer = + new DeviceSchemaInitializer(dataSource); + log.info("Initializing device management repository database schema"); + initializer.createRegistryDatabase(); + } catch (NamingException e) { + log.error("Error while looking up the data source: " + DeviceTypeConstants.DATA_SOURCE_NAME); + } catch (Exception e) { + throw new DeviceMgtPluginException("Error occurred while initializing Iot Device " + + "Management database schema", e); + } + } + + public static String replaceMqttProperty(String urlWithPlaceholders) { + String MQTT_BROKER_HOST = null; + String MQTT_PORT = null; + if(!DeviceTypeConstants.MQTT_BROKER_HOST.startsWith("$")){ + MQTT_BROKER_HOST = "\\$".concat(DeviceTypeConstants.MQTT_BROKER_HOST); + } + if(!DeviceTypeConstants.MQTT_PORT.startsWith("$")){ + MQTT_PORT = "\\$".concat(DeviceTypeConstants.MQTT_PORT); + } + urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders); + urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" + + (DeviceTypeConstants.DEFAULT_MQTT_PORT + getPortOffset())); + urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST, + System.getProperty(DeviceTypeConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost")); + return urlWithPlaceholders; + } + + private static int getPortOffset() { + ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); + String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty( + DeviceTypeConstants.CARBON_CONFIG_PORT_OFFSET)); + try { + if ((portOffset != null)) { + return Integer.parseInt(portOffset.trim()); + } else { + return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET; + } + } catch (NumberFormatException e) { + return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET; + } + } + + public static void setupMqttOutputAdapter() throws IOException { + OutputEventAdapterConfiguration outputEventAdapterConfiguration = + createMqttOutputEventAdapterConfiguration(DeviceTypeConstants.MQTT_ADAPTER_NAME, + DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT); + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true); + DeviceTypeManagementDataHolder.getInstance().getOutputEventAdapterService() + .create(outputEventAdapterConfiguration); + } catch (OutputEventAdapterException e) { + log.error("Unable to create Output Event Adapter : " + DeviceTypeConstants.MQTT_ADAPTER_NAME, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + /** + * Create Output Event Adapter Configuration for given configuration. + * + * @param name Output Event Adapter name + * @param type Output Event Adapter type + * @param msgFormat Output Event Adapter message format + * @return OutputEventAdapterConfiguration instance for given configuration + */ + private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type, + String msgFormat) throws IOException { + OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration(); + outputEventAdapterConfiguration.setName(name); + outputEventAdapterConfiguration.setType(type); + outputEventAdapterConfiguration.setMessageFormat(msgFormat); + File configFile = new File(DeviceTypeConstants.MQTT_CONFIG_LOCATION); + if (configFile.exists()) { + Map mqttAdapterProperties = new HashMap<>(); + InputStream propertyStream = configFile.toURI().toURL().openStream(); + Properties properties = new Properties(); + properties.load(propertyStream); + mqttAdapterProperties.put(DeviceTypeConstants.USERNAME_PROPERTY_KEY, properties.getProperty( + DeviceTypeConstants.USERNAME_PROPERTY_KEY)); + mqttAdapterProperties.put(DeviceTypeConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty( + properties.getProperty(DeviceTypeConstants.DCR_PROPERTY_KEY))); + mqttAdapterProperties.put(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty( + properties.getProperty(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY))); + mqttAdapterProperties.put(DeviceTypeConstants.SCOPES_PROPERTY_KEY, properties.getProperty( + DeviceTypeConstants.SCOPES_PROPERTY_KEY)); + mqttAdapterProperties.put(DeviceTypeConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty( + DeviceTypeConstants.CLEAR_SESSION_PROPERTY_KEY)); + mqttAdapterProperties.put(DeviceTypeConstants.QOS_PROPERTY_KEY, properties.getProperty( + DeviceTypeConstants.QOS_PROPERTY_KEY)); + mqttAdapterProperties.put(DeviceTypeConstants.CLIENT_ID_PROPERTY_KEY, ""); + mqttAdapterProperties.put(DeviceTypeConstants.RESOURCE, "output-event"); + outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties); + } + return outputEventAdapterConfiguration; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/DeviceTypeManagementDataHolder.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/DeviceTypeManagementDataHolder.java new file mode 100644 index 00000000..4caab566 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/DeviceTypeManagementDataHolder.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.internal; + +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; + +/** + * DataHolder class of fgfgt plugins component. + */ +public class DeviceTypeManagementDataHolder { + + private static DeviceTypeManagementDataHolder thisInstance = new DeviceTypeManagementDataHolder(); + private OutputEventAdapterService outputEventAdapterService; + + private DeviceTypeManagementDataHolder() { + } + + public static DeviceTypeManagementDataHolder getInstance() { + return thisInstance; + } + + public OutputEventAdapterService getOutputEventAdapterService() { + return outputEventAdapterService; + } + + public void setOutputEventAdapterService( + OutputEventAdapterService outputEventAdapterService) { + this.outputEventAdapterService = outputEventAdapterService; + } +} + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/ServiceComponent.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/ServiceComponent.java new file mode 100644 index 00000000..d675a0ed --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/internal/ServiceComponent.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.internal; + +import ${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeStartupListener; +import ${groupId}.${rootArtifactId}.plugin.exception.DeviceMgtPluginException; +import ${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeUtils; +import ${groupId}.${rootArtifactId}.plugin.impl.DeviceTypeManagerService; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; + +/** + * @scr.component name="${groupId}.${rootArtifactId}.plugin.internal.ServiceComponent" + * immediate="true" + * @scr.reference name="event.output.adapter.service" + * interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService" + * cardinality="1..1" + * policy="dynamic" + * bind="setOutputEventAdapterService" + * unbind="unsetOutputEventAdapterService" + */ + +public class ServiceComponent { + private static final Log log = LogFactory.getLog(ServiceComponent.class); + private ServiceRegistration serviceRegistration; + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating b Management Service Component"); + } + try { + DeviceTypeManagerService deviceTypeManagerService = new DeviceTypeManagerService(); + BundleContext bundleContext = ctx.getBundleContext(); + serviceRegistration = + bundleContext.registerService(DeviceManagementService.class.getName(), + deviceTypeManagerService, null); + bundleContext.registerService(ServerStartupObserver.class.getName(), new DeviceTypeStartupListener(), + null); + String setupOption = System.getProperty("setup"); + if (setupOption != null) { + if (log.isDebugEnabled()) { + log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " + + "to begin"); + } + try { + DeviceTypeUtils.setupDeviceManagementSchema(); + } catch (DeviceMgtPluginException e) { + log.error("Exception occurred while initializing device management database schema", e); + } + } + if (log.isDebugEnabled()) { + log.debug("b Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Current Sensor Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating b Management Service Component"); + } + try { + if (serviceRegistration != null) { + serviceRegistration.unregister(); + } + if (log.isDebugEnabled()) { + log.debug("Current Sensor Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Iot Device Management bundle", e); + } + } + + /** + * Initialize the Output EventAdapter Service dependency + * + * @param outputEventAdapterService Output EventAdapter Service reference + */ + protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) { + DeviceTypeManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService); + } + + /** + * De-reference the Output EventAdapter Service dependency. + */ + protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) { + DeviceTypeManagementDataHolder.getInstance().setOutputEventAdapterService(null); + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/mqtt/MqttConfig.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/mqtt/MqttConfig.java new file mode 100644 index 00000000..f5dbdb09 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/plugin/src/main/java/__groupId__/__rootArtifactId__/plugin/mqtt/MqttConfig.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package ${groupId}.${rootArtifactId}.plugin.mqtt; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.plugin.impl.util.DeviceTypeUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class MqttConfig { + + private static String brokerEndpoint; + + private static MqttConfig mqttConfig = new MqttConfig(); + private static final Log log = LogFactory.getLog(MqttConfig.class); + + private MqttConfig() { + File configFile = new File(DeviceTypeConstants.MQTT_CONFIG_LOCATION); + if (configFile.exists()) { + try { + InputStream propertyStream = configFile.toURI().toURL().openStream(); + Properties properties = new Properties(); + properties.load(propertyStream); + brokerEndpoint = DeviceTypeUtils.replaceMqttProperty( + properties.getProperty(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY)); + } catch (IOException e) { + log.error("Failed to read the mqtt.properties file" + e); + } + } + } + + public static MqttConfig getInstance() { + return mqttConfig; + } + + public String getBrokerEndpoint() { + return brokerEndpoint; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/pom.xml new file mode 100644 index 00000000..ef3153f1 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/pom.xml @@ -0,0 +1,50 @@ + + + + + ${groupId} + ${rootArtifactId} + ${version} + ../pom.xml + + 4.0.0 + ${version} + ${rootArtifactId}-component + pom + + + + + org.apache.felix + maven-scr-plugin + ${maven-scr-plugin.version} + + + generate-scr-scrdescriptor + + scr + + + + + + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/pom.xml new file mode 100644 index 00000000..bf0fb9a1 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/pom.xml @@ -0,0 +1,56 @@ + + + + + ${groupId} + ${rootArtifactId}-component + ${version} + ../pom.xml + + 4.0.0 + ${project-base-package}.ui + ${project-base-package}.ui + pom + + + + maven-assembly-plugin + ${maven-assembly-plugin.version} + + ${project.artifactId}-${version} + false + + src/assembly/src.xml + + + + + create-archive + package + + single + + + + + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/assembly/src.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/assembly/src.xml new file mode 100644 index 00000000..641802fe --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/assembly/src.xml @@ -0,0 +1,37 @@ + + + + + src + + zip + + false + ${basedir}/src + + + ${basedir}/src/main/resources/jaggeryapps/devicemgt + / + true + + + \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.hbs b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.hbs new file mode 100644 index 00000000..03cf0d59 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.hbs @@ -0,0 +1,25 @@ +{{#zone "topCss"}} + {{css "css/graph.css"}} +{{/zone}} + +
+
+ ${nameOfTheSensor} +
+
+
+
+
+
+
+
+
+
+ +{{#zone "bottomJs"}} + {{js "js/d3.min.js"}} + {{js "js/rickshaw.min.js"}} + {{js "js/moment.min.js"}} + {{js "js/devicetype-graph.js"}} +{{/zone}} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.js new file mode 100644 index 00000000..5336bc2c --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.js @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +function onRequest(context) { + var devices = context.unit.params.devices; + var deviceType = context.uriParams.deviceType; + var deviceId = request.getParameter("deviceId"); + + if (devices) { + return { + "devices": stringify(devices), + "backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/" + }; + } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { + var deviceModule = require("/app/modules/device.js").deviceModule; + var device = deviceModule.viewDevice(deviceType, deviceId); + if (device && device.status != "error") { + return { + "device": device, + "backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/" + deviceId + }; + } else { + response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); + exit(); + } + } +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.json b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.json new file mode 100644 index 00000000..688e9398 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/analytics-view.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/css/graph.css b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/css/graph.css new file mode 100644 index 00000000..9f357f2f --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/css/graph.css @@ -0,0 +1,470 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* graph */ + +.rickshaw_graph { + position: relative; +} + +.rickshaw_graph svg { + display: block; + overflow: hidden; +} + +/* ticks */ + +.rickshaw_graph .x_tick { + position: absolute; + top: 0; + bottom: 0; + width: 0; + border-left: 1px dotted rgba(0, 0, 0, 0.2); + pointer-events: none; +} + +.rickshaw_graph .x_tick .title { + position: absolute; + font-size: 12px; + font-family: Arial, sans-serif; + opacity: 0.5; + white-space: nowrap; + margin-left: 3px; + bottom: -20px; + height: auto; + border-bottom: none; +} + +/* annotations */ + +.rickshaw_annotation_timeline { + height: 1px; + border-top: 1px solid #e0e0e0; + margin-top: 10px; + position: relative; +} + +.rickshaw_annotation_timeline .annotation { + position: absolute; + height: 6px; + width: 6px; + margin-left: -2px; + top: -3px; + border-radius: 5px; + background-color: rgba(0, 0, 0, 0.25); +} + +.rickshaw_graph .annotation_line { + position: absolute; + top: 0; + bottom: -6px; + width: 0; + border-left: 2px solid rgba(0, 0, 0, 0.3); + display: none; +} + +.rickshaw_graph .annotation_line.active { + display: block; +} + +.rickshaw_graph .annotation_range { + background: rgba(0, 0, 0, 0.1); + display: none; + position: absolute; + top: 0; + bottom: -6px; +} + +.rickshaw_graph .annotation_range.active { + display: block; +} + +.rickshaw_graph .annotation_range.active.offscreen { + display: none; +} + +.rickshaw_annotation_timeline .annotation .content { + background: white; + color: black; + opacity: 0.9; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.8); + border-radius: 3px; + position: relative; + z-index: 20; + font-size: 12px; + padding: 6px 8px 8px; + top: 18px; + left: -11px; + width: 160px; + display: none; + cursor: pointer; +} + +.rickshaw_annotation_timeline .annotation .content:before { + content: "\25b2"; + position: absolute; + top: -11px; + color: white; + text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8); +} + +.rickshaw_annotation_timeline .annotation.active, +.rickshaw_annotation_timeline .annotation:hover { + background-color: rgba(0, 0, 0, 0.8); + cursor: none; +} + +.rickshaw_annotation_timeline .annotation .content:hover { + z-index: 50; +} + +.rickshaw_annotation_timeline .annotation.active .content { + display: block; +} + +.rickshaw_annotation_timeline .annotation:hover .content { + display: block; + z-index: 50; +} + +.rickshaw_graph .y_axis, +.rickshaw_graph .x_axis_d3 { + fill: none; +} + +.rickshaw_graph .y_ticks .tick line, +.rickshaw_graph .x_ticks_d3 .tick { + stroke: rgba(0, 0, 0, 0.16); + stroke-width: 2px; + shape-rendering: crisp-edges; + pointer-events: none; +} + +.rickshaw_graph .y_grid .tick, +.rickshaw_graph .x_grid_d3 .tick { + z-index: -1; + stroke: rgba(0, 0, 0, 0.20); + stroke-width: 1px; + stroke-dasharray: 1 1; +} + +.rickshaw_graph .y_grid .tick[data-y-value="0"] { + stroke-dasharray: 1 0; +} + +.rickshaw_graph .y_grid path, +.rickshaw_graph .x_grid_d3 path { + fill: none; + stroke: none; +} + +.rickshaw_graph .y_ticks path, +.rickshaw_graph .x_ticks_d3 path { + fill: none; + stroke: #808080; +} + +.rickshaw_graph .y_ticks text, +.rickshaw_graph .x_ticks_d3 text { + opacity: 0.5; + font-size: 12px; + pointer-events: none; +} + +.rickshaw_graph .x_tick.glow .title, +.rickshaw_graph .y_ticks.glow text { + fill: black; + color: black; + text-shadow: -1px 1px 0 rgba(255, 255, 255, 0.1), + 1px -1px 0 rgba(255, 255, 255, 0.1), + 1px 1px 0 rgba(255, 255, 255, 0.1), + 0 1px 0 rgba(255, 255, 255, 0.1), + 0 -1px 0 rgba(255, 255, 255, 0.1), + 1px 0 0 rgba(255, 255, 255, 0.1), + -1px 0 0 rgba(255, 255, 255, 0.1), + -1px -1px 0 rgba(255, 255, 255, 0.1); +} + +.rickshaw_graph .x_tick.inverse .title, +.rickshaw_graph .y_ticks.inverse text { + fill: white; + color: white; + text-shadow: -1px 1px 0 rgba(0, 0, 0, 0.8), + 1px -1px 0 rgba(0, 0, 0, 0.8), + 1px 1px 0 rgba(0, 0, 0, 0.8), + 0 1px 0 rgba(0, 0, 0, 0.8), + 0 -1px 0 rgba(0, 0, 0, 0.8), + 1px 0 0 rgba(0, 0, 0, 0.8), + -1px 0 0 rgba(0, 0, 0, 0.8), + -1px -1px 0 rgba(0, 0, 0, 0.8); +} + +.custom_rickshaw_graph { + position: relative; + left: 40px; +} + +.custom_y_axis { + position: absolute; + width: 40px; +} + +.custom_slider { + left: 40px; +} + +.custom_x_axis { + position: relative; + left: 40px; + height: 30px; + width: 97%; + top: 20px; + text-align: right; +} + +.chartWrapper { + padding-top: 50px; +} + +/*detail*/ + +.rickshaw_graph .detail { + pointer-events: none; + position: absolute; + top: 0; + z-index: 2; + background: rgba(0, 0, 0, 0.1); + bottom: 0; + width: 1px; + transition: opacity 0.25s linear; + -moz-transition: opacity 0.25s linear; + -o-transition: opacity 0.25s linear; + -webkit-transition: opacity 0.25s linear; +} + +.rickshaw_graph .detail.inactive { + opacity: 0; +} + +.rickshaw_graph .detail .item.active { + opacity: 1; +} + +.rickshaw_graph .detail .x_label { + font-family: Arial, sans-serif; + border-radius: 3px; + padding: 6px; + opacity: 0.5; + border: 1px solid #e0e0e0; + font-size: 12px; + position: absolute; + background: white; + white-space: nowrap; +} + +.rickshaw_graph .detail .x_label.left { + left: 0; +} + +.rickshaw_graph .detail .x_label.right { + right: 0; +} + +.rickshaw_graph .detail .item { + position: absolute; + z-index: 2; + border-radius: 3px; + padding: 0.25em; + font-size: 12px; + font-family: Arial, sans-serif; + opacity: 0; + background: rgba(0, 0, 0, 0.4); + color: white; + border: 1px solid rgba(0, 0, 0, 0.4); + margin-left: 1em; + margin-right: 1em; + margin-top: -1em; + white-space: nowrap; +} + +.rickshaw_graph .detail .item.left { + left: 0; +} + +.rickshaw_graph .detail .item.right { + right: 0; +} + +.rickshaw_graph .detail .item.active { + opacity: 1; + background: rgba(0, 0, 0, 0.8); +} + +.rickshaw_graph .detail .item:after { + position: absolute; + display: block; + width: 0; + height: 0; + + content: ""; + + border: 5px solid transparent; +} + +.rickshaw_graph .detail .item.left:after { + top: 1em; + left: -5px; + margin-top: -5px; + border-right-color: rgba(0, 0, 0, 0.8); + border-left-width: 0; +} + +.rickshaw_graph .detail .item.right:after { + top: 1em; + right: -5px; + margin-top: -5px; + border-left-color: rgba(0, 0, 0, 0.8); + border-right-width: 0; +} + +.rickshaw_graph .detail .dot { + width: 4px; + height: 4px; + margin-left: -3px; + margin-top: -3.5px; + border-radius: 5px; + position: absolute; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); + box-sizing: content-box; + -moz-box-sizing: content-box; + background: white; + border-width: 2px; + border-style: solid; + display: none; + background-clip: padding-box; +} + +.rickshaw_graph .detail .dot.active { + display: block; +} + +/*legend*/ +.rickshaw_legend { + font-family: Arial; + font-size: 12px; + color: white; + background: #404040; + display: inline-block; + padding: 12px 5px; + border-radius: 2px; + position: relative; + float: right; +} + +.rickshaw_legend:hover { + z-index: 10; +} + +.rickshaw_legend .swatch { + width: 10px; + height: 10px; + border: 1px solid rgba(0, 0, 0, 0.2); +} + +.rickshaw_legend .line { + clear: both; + line-height: 140%; + padding-right: 15px; +} + +.rickshaw_legend .line .swatch { + display: inline-block; + margin-right: 3px; + border-radius: 2px; +} + +.rickshaw_legend .label { + margin: 0; + white-space: nowrap; + display: inline; + font-size: inherit; + background-color: transparent; + color: inherit; + font-weight: normal; + line-height: normal; + padding: 0; + text-shadow: none; +} + +.rickshaw_legend .action:hover { + opacity: 0.6; +} + +.rickshaw_legend .action { + margin-right: 0.2em; + opacity: 0.2; + cursor: pointer; + font-size: 14px; +} + +.rickshaw_legend .line.disabled { + opacity: 0.4; +} + +.rickshaw_legend ul { + list-style-type: none; + padding: 0; + margin: 2px; + cursor: pointer; +} + +.rickshaw_legend li { + padding: 0 0 0 2px; + min-width: 80px; + white-space: nowrap; +} + +.rickshaw_legend li:hover { + background: rgba(255, 255, 255, 0.08); + border-radius: 3px; +} + +.rickshaw_legend li:active { + background: rgba(255, 255, 255, 0.2); + border-radius: 3px; +} + +.legend { + display: inline-block; + position: relative; + left: 8px; +} + +.legend_container { + float: right; + padding-right: 10px; + width: 0; + z-index: 1; + position: relative; + opacity: 0.7; +} + +.spaced { + margin-top: 20px !important; +} + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/d3.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/d3.min.js new file mode 100644 index 00000000..71f9715e --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/d3.min.js @@ -0,0 +1,9488 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +!function() { + var d3 = { + version: "3.5.2" + }; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; + try { + d3_array(d3_documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } + try { + d3_document.createElement("div").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; + } + d3.ascending = d3_ascending; + function d3_ascending(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + } + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + function d3_number(x) { + return x === null ? NaN : +x; + } + function d3_numeric(x) { + return !isNaN(x); + } + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; + } + return s; + }; + d3.mean = function(array, f) { + var s = 0, n = array.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; + } + if (j) return s / j; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + var numbers = [], n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); + } + if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); + }; + d3.variance = function(array, f) { + var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } + if (j > 1) return s / (j - 1); + }; + d3.deviation = function() { + var v = d3.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; + } + return lo; + } + }; + } + var d3_bisect = d3_bisector(d3_ascending); + d3.bisectLeft = d3_bisect.left; + d3.bisect = d3.bisectRight = d3_bisect.right; + d3.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); + }; + d3.shuffle = function(array, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array.length; + if (m < 2) i0 = 0; + } + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.zip = function() { + if (!(n = arguments.length)) return []; + for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { + for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { + zip[j] = arguments[j][i]; + } + } + return zips; + }; + function d3_zipLength(d) { + return d.length; + } + d3.transpose = function(matrix) { + return d3.zip.apply(d3, matrix); + }; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } + } + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } + } + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } + d3.map = function(object, f) { + var map = new d3_Map(); + if (object instanceof d3_Map) { + object.forEach(function(key, value) { + map.set(key, value); + }); + } else if (Array.isArray(object)) { + var i = -1, n = object.length, o; + if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); + } else { + for (var key in object) map.set(key, object[key]); + } + return map; + }; + function d3_Map() { + this._ = Object.create(null); + } + var d3_map_proto = "__proto__", d3_map_zero = "\x00"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value) { + return this._[d3_map_escape(key)] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; + } + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; + } + function d3_map_has(key) { + return d3_map_escape(key) in this._; + } + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; + } + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; + } + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; + } + function d3_map_empty() { + for (var key in this._) return false; + return true; + } + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() { + this._ = Object.create(null); + } + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } + }); + d3.behavior = {}; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; + } + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } + } + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; + } + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); + } + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; + } + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; + } + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; + } + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatcher = d3_documentElement.matches || d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3_selectionRoot; + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; + } + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; + } + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: "http://www.w3.org/1999/xhtml", + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0) { + prefix = name.slice(0, i); + name = name.slice(i + 1); + } + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; + } + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; + } + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; + } + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); + } + function d3_selection_classes(name) { + return (name + "").trim().split(/^|\s+/); + } + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; + } + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; + } + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name); + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); + return this; + } + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { + return this.ownerDocument.createElementNS(name.space, name.local); + } : function() { + return this.ownerDocument.createElementNS(this.namespaceURI, name); + }; + } + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); + } + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } + } + return value; + } + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.has(keyValue = key.call(node = group[i], node.__data__, i))) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues[i] = keyValue; + } + for (i = -1; ++i < m; ) { + if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } else if (node !== true) { + updateNodes[i] = node; + node.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.get(keyValues[i]) !== true) { + exitNodes[i] = group[i]; + } + } + } else { + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value); + } + } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; + } + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } + } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } + } + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; + } + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d3.select = function(node) { + var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + var d3_selectionRoot = d3.select(d3_documentElement); + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + } + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; + } + var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; + function d3_event_dragSuppress() { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect) { + var style = d3_documentElement.style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + var off = function() { + w.on(click, null); + }; + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; + } + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + } + d3.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); + } + } + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_behavior_dragMouseSubject, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_behavior_dragTouchSubject, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject()).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; + } else { + dragOffset = [ 0, 0 ]; + } + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx: dx, + dy: dy + }); + } + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged && d3.event.target === target); + dispatch({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + function d3_behavior_dragTouchId() { + return d3.event.changedTouches[0].identifier; + } + function d3_behavior_dragTouchSubject() { + return d3.event.target; + } + function d3_behavior_dragMouseSubject() { + return d3_window; + } + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + } + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; + var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; + function interpolate(t) { + var s = t * S; + if (dr) { + var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + } + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; + } + interpolate.duration = S * 1e3; + return interpolate; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { + g.each(function() { + var dispatch = event.of(this, arguments), view1 = view; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(dispatch); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); + return function(t) { + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k: k + }; + zoomed(dispatch); + }; + }).each("interrupt.zoom", function() { + zoomended(dispatch); + }).each("end.zoom", function() { + zoomended(dispatch); + }); + } else { + this.__chart__ = view; + zoomstarted(dispatch); + zoomed(dispatch); + zoomended(dispatch); + } + }); + }; + zoom.translate = function(_) { + if (!arguments.length) return [ view.x, view.y ]; + view = { + x: +_[0], + y: +_[1], + k: view.k + }; + rescale(); + return zoom; + }; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: +_ + }; + rescale(); + return zoom; + }; + zoom.scaleExtent = function(_) { + if (!arguments.length) return scaleExtent; + scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; + return zoom; + }; + zoom.center = function(_) { + if (!arguments.length) return center; + center = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.size = function(_) { + if (!arguments.length) return size; + size = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.duration = function(_) { + if (!arguments.length) return duration; + duration = +_; + return zoom; + }; + zoom.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + zoom.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + function location(p) { + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; + } + function point(l) { + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; + } + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d3.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" + }); + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }); + center0 = null; + } + function mousedowned() { + var that = this, target = d3.event.target, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d3.mouse(that), location0); + zoomed(dispatch); + } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged && d3.event.target === target); + zoomended(dispatch); + } + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d3.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d3.event.target; + d3.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; + } + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + d3.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); + } + } + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else translate0 = location(center0 = center || d3.mouse(this)), + d3_selection_interrupt.call(this), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ]; + var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); + d3.color = d3_color; + function d3_color() {} + d3_color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + } + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + } + d3.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + } + var d3_hclPrototype = d3_hcl.prototype = new d3_color(); + d3_hclPrototype.brighter = function(k) { + return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.darker = function(k) { + return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d3.lab = d3_lab; + function d3_lab(l, a, b) { + return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + } + var d3_lab_K = 18; + var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_lab.prototype = new d3_color(); + d3_labPrototype.brighter = function(k) { + return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + } + d3.rgb = d3_rgb; + function d3_rgb(r, g, b) { + return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + } + function d3_rgbNumber(value) { + return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, color; + m1 = /([a-z]+)\((.*)\)/i.exec(format); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } + + case "rgb": + { + return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + } + } + } + if (color = d3_rgb_names.get(format)) return rgb(color.r, color.g, color.b); + if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { + if (format.length === 4) { + r = (color & 3840) >> 4; + r = r >> 4 | r; + g = color & 240; + g = g >> 4 | g; + b = color & 15; + b = b << 4 | b; + } else if (format.length === 7) { + r = (color & 16711680) >> 16; + g = (color & 65280) >> 8; + b = color & 255; + } + } + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; + } else { + h = NaN; + s = l > 0 && l < 1 ? 0 : h; + } + return new d3_hsl(h, s, l); + } + function d3_rgb_lab(r, g, b) { + r = d3_rgb_xyz(r); + g = d3_rgb_xyz(g); + b = d3_rgb_xyz(b); + var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); + return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); + } + function d3_rgb_xyz(r) { + return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); + } + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + function d3_identity(d) { + return d; + } + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; + } + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); + } + } + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + function d3_xhrHasResponse(request) { + var type = request.responseType; + return type && type !== "text" ? request.response : request.responseText; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); + } + return text.slice(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); + } + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + f: false, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + }; + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(); + d3_timer_active = d3_timer_queueHead; + while (d3_timer_active) { + if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); + d3_timer_active = d3_timer_active.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.f) { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + } else { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } + } + d3_timer_queueTail = t0; + return time; + } + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { + var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = locale_grouping[j = (j + 1) % locale_grouping.length]; + } + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; + + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; + + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; + + case "b": + case "o": + case "x": + case "X": + if (symbol === "#") prefix = "0" + type.toLowerCase(); + + case "c": + exponent = false; + + case "d": + integer = true; + precision = 0; + break; + + case "s": + scale = -1; + type = "r"; + break; + } + if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; + if (type == "r" && !precision) type = "g"; + if (precision != null) { + if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); + } + type = d3_format_types.get(type) || d3_format_typeDefault; + var zcomma = zfill && comma; + return function(value) { + var fullSuffix = suffix; + if (integer && value % 1) return ""; + var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; + if (scale < 0) { + var unit = d3.formatPrefix(value, precision); + value = unit.scale(value); + fullSuffix = unit.symbol + suffix; + } else { + value *= scale; + } + value = type(value, precision); + var i = value.lastIndexOf("."), before, after; + if (i < 0) { + var j = exponent ? value.lastIndexOf("e") : -1; + if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); + } else { + before = value.substring(0, i); + after = locale_decimal + value.substring(i + 1); + } + if (!zfill && comma) before = formatGroup(before, Infinity); + var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; + if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); + negative += prefix; + value = before + after; + return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); + } + }); + function d3_format_typeDefault(x) { + return x + ""; + } + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + } + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); + } + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; + } + function ceil(date) { + step(date = local(new d3_date(date - 1)), 1); + return date; + } + function offset(date, k) { + step(date = new d3_date(+date), k); + return date; + } + function range(t0, t1, dt) { + var time = ceil(t0), times = []; + if (dt > 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); + } + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; + } + } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; + } + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; + } + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.slice(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.slice(j, i)); + return string.join(""); + } + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; + } + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + return d3_time_format; + } + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); + } + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + } + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; + } + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; + } + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; + } + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + } + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, + i + 5) : -1; + } + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); + } + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + } + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; + } + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; + } + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; + } + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; + } + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + } + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; + } + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; + } + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); + } + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } + } + var d3_geo_streamObjectType = { + Feature: function(feature, listener) { + d3_geo_streamGeometry(feature.geometry, listener); + }, + FeatureCollection: function(object, listener) { + var features = object.features, i = -1, n = features.length; + while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); + } + }; + var d3_geo_streamGeometryType = { + Sphere: function(object, listener) { + listener.sphere(); + }, + Point: function(object, listener) { + object = object.coordinates; + listener.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); + }, + LineString: function(object, listener) { + d3_geo_streamLine(object.coordinates, listener, 0); + }, + MultiLineString: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); + }, + Polygon: function(object, listener) { + d3_geo_streamPolygon(object.coordinates, listener); + }, + MultiPolygon: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); + }, + GeometryCollection: function(object, listener) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + } + }; + function d3_geo_streamLine(coordinates, listener, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + listener.lineStart(); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); + listener.lineEnd(); + } + function d3_geo_streamPolygon(coordinates, listener) { + var i = -1, n = coordinates.length; + listener.polygonStart(); + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); + listener.polygonEnd(); + } + d3.geo.area = function(object) { + d3_geo_areaSum = 0; + d3.geo.stream(object, d3_geo_area); + return d3_geo_areaSum; + }; + var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); + var d3_geo_area = { + sphere: function() { + d3_geo_areaSum += 4 * π; + }, + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_areaRingSum.reset(); + d3_geo_area.lineStart = d3_geo_areaRingStart; + }, + polygonEnd: function() { + var area = 2 * d3_geo_areaRingSum; + d3_geo_areaSum += area < 0 ? 4 * π + area : area; + d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + } + }; + function d3_geo_areaRingStart() { + var λ00, φ00, λ0, cosφ0, sinφ0; + d3_geo_area.point = function(λ, φ) { + d3_geo_area.point = nextPoint; + λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), + sinφ0 = Math.sin(φ); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + φ = φ * d3_radians / 2 + π / 4; + var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; + } + function d3_geo_cartesian(spherical) { + var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); + return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + } + function d3_geo_cartesianDot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + function linePoint(λ, φ) { + var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); + if (p0) { + var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); + d3_geo_cartesianNormalize(inflection); + inflection = d3_geo_spherical(inflection); + var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + if (antimeridian) { + if (λ < λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } else { + if (λ1 >= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } + } + } else { + point(λ, φ); + } + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); + } + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; + } + function d3_geo_centroidLineStart() { + var x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroid.point = nextPoint; + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_centroidLineEnd() { + d3_geo_centroid.point = d3_geo_centroidPoint; + } + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; + } + var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); + a.o = b; + subject.push(a); + clip.push(b); + a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); + b = new d3_geo_clipPolygonIntersection(p1, null, a, true); + a.o = b; + subject.push(a); + clip.push(b); + }); + clip.sort(compare); + d3_geo_clipPolygonLinkCircular(subject); + d3_geo_clipPolygonLinkCircular(clip); + if (!subject.length) return; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; + } + var start = subject[0], points, point; + while (1) { + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; + listener.lineStart(); + do { + current.v = current.o.v = true; + if (current.e) { + if (isSubject) { + for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.n.x, 1, listener); + } + current = current.n; + } else { + if (isSubject) { + points = current.p.z; + for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); + } + current = current.p; + } + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); + } + } + function d3_geo_clipPolygonLinkCircular(array) { + if (!(n = array.length)) return; + var n, i = 0, a = array[0], b; + while (++i < n) { + a.n = b = array[i]; + b.p = a; + a = b; + } + a.n = b = array[0]; + b.p = a; + } + function d3_geo_clipPolygonIntersection(point, points, other, entry) { + this.x = point; + this.z = points; + this.o = other; + this.e = entry; + this.v = false; + this.n = this.p = null; + } + function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { + return function(rotate, listener) { + var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + clip.point = pointRing; + clip.lineStart = ringStart; + clip.lineEnd = ringEnd; + segments = []; + polygon = []; + }, + polygonEnd: function() { + clip.point = point; + clip.lineStart = lineStart; + clip.lineEnd = lineEnd; + segments = d3.merge(segments); + var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); + if (segments.length) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); + } else if (clipStartInside) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (polygonStarted) listener.polygonEnd(), polygonStarted = false; + segments = polygon = null; + }, + sphere: function() { + listener.polygonStart(); + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + listener.polygonEnd(); + } + }; + function point(λ, φ) { + var point = rotate(λ, φ); + if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); + } + function pointLine(λ, φ) { + var point = rotate(λ, φ); + line.point(point[0], point[1]); + } + function lineStart() { + clip.point = pointLine; + line.lineStart(); + } + function lineEnd() { + clip.point = point; + line.lineEnd(); + } + var segments; + var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; + function pointRing(λ, φ) { + ring.push([ λ, φ ]); + var point = rotate(λ, φ); + ringListener.point(point[0], point[1]); + } + function ringStart() { + ringListener.lineStart(); + ring = []; + } + function ringEnd() { + pointRing(ring[0][0], ring[0][1]); + ringListener.lineEnd(); + var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; + ring.pop(); + polygon.push(ring); + ring = null; + if (!n) return; + if (clean & 1) { + segment = ringSegments[0]; + var n = segment.length - 1, i = -1, point; + if (n > 0) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); + } + return; + } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + } + return clip; + }; + } + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; + } + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; + } + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + } + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; + } + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + } + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); + } else { + listener.point(to[0], to[1]); + } + } + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); + polarAngle += antimeridian ? dλ + sdλ * τ : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } + } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + } + function d3_geo_clipCircle(radius) { + var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; + } + } + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line) { + var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; + } + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; + } + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; + } + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } + } + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; + } + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); + } + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); + } + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } + } else { + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } + } + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + } + function compare(a, b) { + return comparePoints(a.x, b.x); + } + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + } + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; + return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = ρ0 - y; + return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; + }; + return forward; + } + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; + } + }, lower48Point, alaskaPoint, hawaiiPoint; + function albersUsa(coordinates) { + var x = coordinates[0], y = coordinates[1]; + point = null; + (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); + return point; + } + albersUsa.invert = function(coordinates) { + var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; + return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); + } + }; + }; + albersUsa.precision = function(_) { + if (!arguments.length) return lower48.precision(); + lower48.precision(_); + alaska.precision(_); + hawaii.precision(_); + return albersUsa; + }; + albersUsa.scale = function(_) { + if (!arguments.length) return lower48.scale(); + lower48.scale(_); + alaska.scale(_ * .35); + hawaii.scale(_); + return albersUsa.translate(lower48.translate()); + }; + albersUsa.translate = function(_) { + if (!arguments.length) return lower48.translate(); + var k = lower48.scale(), x = +_[0], y = +_[1]; + lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; + alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + return albersUsa; + }; + return albersUsa.scale(1070); + }; + var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_pathAreaPolygon = 0; + d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; + }, + polygonEnd: function() { + d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); + } + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; + } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; + } + var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; + var d3_geo_pathBounds = { + point: d3_geo_pathBoundsPoint, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_pathBoundsPoint(x, y) { + if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; + if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; + } + } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); + } + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; + } + function pointLine(x, y) { + buffer.push("L", x, ",", y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + buffer.push("Z"); + } + return stream; + } + function d3_geo_pathBufferCircle(radius) { + return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; + } + var d3_geo_pathCentroid = { + point: d3_geo_pathCentroidPoint, + lineStart: d3_geo_pathCentroidLineStart, + lineEnd: d3_geo_pathCentroidLineEnd, + polygonStart: function() { + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; + }, + polygonEnd: function() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; + d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + } + }; + function d3_geo_pathCentroidPoint(x, y) { + d3_geo_centroidX0 += x; + d3_geo_centroidY0 += y; + ++d3_geo_centroidZ0; + } + function d3_geo_pathCentroidLineStart() { + var x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + } + function d3_geo_pathCentroidLineEnd() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + } + function d3_geo_pathCentroidRingStart() { + var x00, y00, x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + z = y0 * x - x0 * y; + d3_geo_centroidX2 += z * (x0 + x); + d3_geo_centroidY2 += z * (y0 + y); + d3_geo_centroidZ2 += z * 3; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + d3_geo_pathCentroid.lineEnd = function() { + nextPoint(x00, y00); + }; + } + function d3_geo_pathContext(context) { + var pointRadius = 4.5; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointRadius = _; + return stream; + }, + result: d3_noop + }; + function point(x, y) { + context.moveTo(x + pointRadius, y); + context.arc(x, y, pointRadius, 0, τ); + } + function pointLineStart(x, y) { + context.moveTo(x, y); + stream.point = pointLine; + } + function pointLine(x, y) { + context.lineTo(x, y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + context.closePath(); + } + return stream; + } + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); + } + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); + } + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; + } + }; + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + } + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); + } + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); + } + function lineEnd() { + resample.point = point; + stream.lineEnd(); + } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; + } + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; + } + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); + } + return resample; + } + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + } + } + } + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; + }; + return resample; + } + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); + } + return contextStream.result(); + } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; + } + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); + }); + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); + }; + } + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; + } + }; + }; + function d3_geo_transform(stream) { + this.stream = stream; + } + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); + } + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); + } + }; + } + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); + } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; + } + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + } + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); + } + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); + }; + } + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); + } + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; + } + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + } + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + } + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; + } + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; + } + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; + } + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] + }; + } + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); + }; + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; + } + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); + } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; + }); + }; + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + }; + }; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); + }; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); + }; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); + }; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); + }; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; + }; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; + }; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; + }; + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; + }); + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; + }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; + } + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; + } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + } + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + if (F > 0) { + if (φ < -halfπ + ε) φ = -halfπ + ε; + } else { + if (φ > halfπ - ε) φ = halfπ - ε; + } + var ρ = F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; + } + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; + }; + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; + }; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return rotate([ 0, 0, 90 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; + } + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; + } + return hull.slice(0, hs); + } + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; + } + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; + } + } + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; + } + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } + } + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; + } + }; + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } + } + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } + } + }); + return triangles; + }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); + }; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; + } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = xm; else x2 = xm; + if (below) y1 = ym; else y2 = ym; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - point[0], dy = y - point[1], distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; + } + } + var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; + + case 1: + find(node, xm, y1, x2, ym); + break; + + case 2: + find(node, x1, ym, xm, y2); + break; + + case 3: + find(node, xm, ym, x2, y2); + break; + } + } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); + }; + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } + } + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i: i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; + } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }); + } + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; + } + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; + } + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; + } + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; + } + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; + } + function d3_ease_quad(t) { + return t * t; + } + function d3_ease_cubic(t) { + return t * t * t; + } + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; + } + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); + } + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); + } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; + } + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; + }; + } + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); + }; + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; + } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; + } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; + } + return k; + } + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; + } + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 + }; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransform(a, b) { + var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; + if (ta[0] != tb[0] || ta[1] != tb[1]) { + s.push("translate(", null, ",", null, ")"); + q.push({ + i: 1, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: 3, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } else { + s.push(""); + } + if (ra != rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(s.pop() + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(s.pop() + "rotate(" + rb + ")"); + } + if (wa != wb) { + q.push({ + i: s.push(s.pop() + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(s.pop() + "skewX(" + wb + ")"); + } + if (ka[0] != kb[0] || ka[1] != kb[1]) { + n = s.push(s.pop() + "scale(", null, ",", null, ")"); + q.push({ + i: n - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: n - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] != 1 || kb[1] != 1) { + s.push(s.pop() + "scale(" + kb + ")"); + } + n = q.length; + return function(t) { + var i = -1, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + function d3_uninterpolateNumber(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return (x - a) / b; + }; + } + function d3_uninterpolateClamp(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return Math.max(0, Math.min(1, (x - a) / b)); + }; + } + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; + } + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; + } + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; + } + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; + } + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; + } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: (x - x0) / k + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); + } + } + } + if (sortChords) resort(); + } + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); + } + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad.point && dn && dn < chargeDistance2) { + var k = quad.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; + } + force.tick = function() { + if ((alpha *= .99) < .005) { + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight / (t.weight + s.weight)); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); + } + } + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; + } + } + event.tick({ + type: "tick", + alpha: alpha + }); + }; + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; + }; + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) alpha = x; else alpha = 0; + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + d3.timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, m = candidates.length, x; + while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); + } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; + } + function d3_layout_forceDragend(d) { + d.fixed &= ~6; + } + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; + } + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; + } + } + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function hierarchy(root) { + var stack = [ root ], nodes = [], node; + root.depth = 0; + while ((node = stack.pop()) != null) { + nodes.push(node); + if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { + var n, childs, child; + while (--n >= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; + } + if (value) node.value = 0; + node.children = childs; + } else { + if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; + delete node.children; + } + } + d3_layout_hierarchyVisitAfter(root, function(node) { + var childs, parent; + if (sort && (childs = node.children)) childs.sort(sort); + if (value && (parent = node.parent)) parent.value += node.value; + }); + return nodes; + } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + if (value) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; + } + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [ node ]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } + } + } + function d3_layout_hierarchyVisitAfter(node, callback) { + var nodes = [ node ], nodes2 = []; + while ((node = nodes.pop()) != null) { + nodes2.push(node); + if ((children = node.children) && (n = children.length)) { + var i = -1, n, children; + while (++i < n) nodes.push(children[i]); + } + } + while ((node = nodes2.pop()) != null) { + callback(node); + } + } + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie(data) { + var n = data.length, values = data.map(function(d, i) { + return +value.call(pie, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), k = (da - n * pa) / d3.sum(values), index = d3.range(n), arcs = [], v; + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie.value = function(_) { + if (!arguments.length) return value; + value = _; + return pie; + }; + pie.sort = function(_) { + if (!arguments.length) return sort; + sort = _; + return pie; + }; + pie.startAngle = function(_) { + if (!arguments.length) return startAngle; + startAngle = _; + return pie; + }; + pie.endAngle = function(_) { + if (!arguments.length) return endAngle; + endAngle = _; + return pie; + }; + pie.padAngle = function(_) { + if (!arguments.length) return padAngle; + padAngle = _; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } + } + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); + } + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; + } + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; + } + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } + } + } + return bins; + } + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r -= dr; + }); + } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; + } + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; + }; + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; + }; + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } + } + } + } + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); + } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); + } + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); + } + return nodes; + } + function wrapTree(root0) { + var root1 = { + A: null, + children: [ root0 ] + }, queue = [ root1 ], node1; + while ((node1 = queue.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i: i + }).a = child); + } + } + return root1.children[0]; + } + function firstWalk(v) { + var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; + } + } else if (w) { + v.z = w.z + separation(v._, w._); + } + v.parent.A = apportion(v, w, v.parent.A || siblings[0]); + } + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; + } + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; + } + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; + } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; + } + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; + } + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; + } + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; + } + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); + } + } + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; + } + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); + } + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } + } + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; + } + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); + } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; + } + } + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = 0; + root.y = 0; + root.dx = size[0]; + root.dy = size[1]; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; + } + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; + }; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; + }; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; + }; + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; + }; + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; + }; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; + }; + return d3_layout_hierarchyRebind(treemap, hierarchy); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } + return { + x: x, + y: y, + dx: dx, + dy: dy + }; + } + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; + }, + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; + } + }; + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; + } + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; + } + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; + } + function scale(x) { + return output(x); + } + scale.invert = function(y) { + return input(y); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); + }; + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); + }; + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); + }; + return rescale(); + } + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); + } + function d3_scale_linearNice(domain, m) { + return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + } + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; + } + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + } + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + if (format) { + var match = d3_format_re.exec(format); + match.shift(); + if (match[8] === "s") { + var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); + if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); + match[8] = "f"; + format = d3.format(match.join("")); + return function(d) { + return format(prefix.scale(d)) + prefix.symbol; + }; + } + if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); + format = match.join(""); + } else { + format = ",." + d3_scale_linearPrecision(range[2]) + "f"; + } + return d3.format(format); + } + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); + } + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); + } + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, + Math.floor), e; + return function(d) { + return d / pow(f(log(d) + e)) <= k ? format(d) : ""; + }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); + } + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); + }; + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; + } + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; + }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale; + }; + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, + 0) : (stop - start) / (domain.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; + }; + scale.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), + 0) : (stop - start) / (domain.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale; + }; + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; + }; + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; + }; + scale.rangeBand = function() { + return rangeBand; + }; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); + }; + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); + }; + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); + } + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; + } + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; + }; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); + }; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; + }; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; + } + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; + } + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; + }; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; + } + d3.svg = {}; + function d3_zero() { + return 0; + } + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); + } + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } + } else { + x0 = y0 = 0; + } + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if ((rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + if (x1 != null) { + var rc1 = Math.min(rc, (r1 - lc) / (kc + 1)), t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var rc0 = Math.min(rc, (r0 - lc) / (kc - 1)), t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + path.push("Z"); + return path.join(""); + } + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; + } + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; + }; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; + }; + arc.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc; + }; + arc.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc; + }; + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; + }; + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; + }; + arc.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc; + }; + arc.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; + } + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; + } + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; + } + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(r * r * d2 - D * D), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; + } + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.join("L"); + } + function d3_svg_lineLinearClosed(points) { + return d3_svg_lineLinear(points) + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); + } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); + } + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; + } + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; + } + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; + } + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id); + }; + d3_selectionPrototype.interrupt = function(name) { + return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, active; + if ((lock = this[ns]) && (active = lock[lock.active])) { + if (--lock.count) { + delete lock[lock.active]; + lock.active += .5; + } else { + delete this[ns]; + } + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; + } + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; + } + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection, name) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3_selectionRoot.transition(selection); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); + subgroup.push(subnode); + } + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_transition(subgroups, this.namespace, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) return this.node()[ns][id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node[ns][id].tween.remove(name); + } : function(node) { + node[ns][id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id, ns = groups.namespace; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node[ns][id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); + }; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; + } + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; + } + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node[ns][id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node[ns][id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } + } else { + d3_selection_each(this, function(node) { + var transition = node[ns][id]; + (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); + }); + } + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = node[ns][id0]; + d3_transitionNode(node, i, ns, id1, { + time: transition.time, + ease: transition.ease, + delay: transition.delay + transition.duration, + duration: transition.duration + }); + } + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id1); + }; + function d3_transitionNamespace(name) { + return name == null ? "__transition__" : "__transition_" + name + "__"; + } + function d3_transitionNode(node, i, ns, id, inherit) { + var lock = node[ns] || (node[ns] = { + active: 0, + count: 0 + }), transition = lock[id]; + if (!transition) { + var time = inherit.time; + transition = lock[id] = { + tween: new d3_Map(), + time: time, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + d3.timer(function(elapsed) { + var delay = transition.delay, duration, ease, timer = d3_timer_active, tweened = []; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + function start(elapsed) { + if (lock.active > id) return stop(); + var active = lock[lock.active]; + if (active) { + --lock.count; + delete lock[lock.active]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweened.push(value); + } + }); + ease = transition.ease; + duration = transition.duration; + d3.timer(function() { + timer.c = tick(elapsed || 1) ? d3_true : tick; + return 1; + }, 0, time); + } + function tick(elapsed) { + if (lock.active !== id) return 1; + var t = elapsed / duration, e = ease(t), n = tweened.length; + while (n > 0) { + tweened[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + return stop(); + } + } + function stop() { + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + }, 0, time); + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + } + lineEnter.attr(y2, sign * innerTickSize); + textEnter.attr(y1, sign * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); + } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = arguments; + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); + } + function d3_svg_axisY(selection, y0, y1) { + selection.attr("transform", function(d) { + var v0 = y0(d); + return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); + } + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); + } else { + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); + } + } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; + } else { + max = position; + } + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; + } + } + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); + } + } + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; + }; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } + } + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } + } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; + } + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; + } + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; + } + return brush; + }; + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; + } + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; + var d3_time_formatUtc = d3_time_format.utc; + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); + } + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; + }; + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); + }); + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); + }); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); + }; + scale.tickFormat = function() { + return format; + }; + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_time_scaleDate(t) { + return new Date(t); + } + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); + } + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); + } + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; + this.d3 = d3; +}(); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/devicetype-graph.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/devicetype-graph.js new file mode 100644 index 00000000..8babb6fb --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/devicetype-graph.js @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var palette = new Rickshaw.Color.Palette({scheme: "classic9"}); + +function drawGraph_${deviceType}(from, to) { + $("#y_axis").html(""); + $("#smoother").html(""); + $("#legend").html(""); + $("#chart").html(""); + $("#x_axis").html(""); + $("#slider").html(""); + + var devices = $("#details").data("devices"); + + var tzOffset = new Date().getTimezoneOffset() * 60; + + var chartWrapperElmId = "#div-chart"; + var graphWidth = $(chartWrapperElmId).width() - 50; + var graphConfig = { + element: document.getElementById("chart"), + width: graphWidth, + height: 400, + strokeWidth: 2, + renderer: 'line', + interpolation: "linear", + unstack: true, + stack: false, + xScale: d3.time.scale(), + padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2}, + series: [] + }; + + if (devices) { + for (var i = 0; i < devices.length; i++) { + graphConfig['series'].push( + { + 'color': palette.color(), + 'data': [{ + x: parseInt(new Date().getTime() / 1000), + y: 0 + }], + 'name': devices[i].name + }); + } + } else { + graphConfig['series'].push( + { + 'color': palette.color(), + 'data': [{ + x: parseInt(new Date().getTime() / 1000), + y: 0 + }], + 'name': $("#details").data("devicename") + }); + } + + var graph = new Rickshaw.Graph(graphConfig); + + graph.render(); + + var xAxis = new Rickshaw.Graph.Axis.Time({ + graph: graph + }); + + xAxis.render(); + + var yAxis = new Rickshaw.Graph.Axis.Y({ + graph: graph, + orientation: 'left', + element: document.getElementById("y_axis"), + width: 40, + height: 410 + }); + + yAxis.render(); + + var slider = new Rickshaw.Graph.RangeSlider.Preview({ + graph: graph, + element: document.getElementById("slider") + }); + + var legend = new Rickshaw.Graph.Legend({ + graph: graph, + element: document.getElementById('legend') + }); + + var hoverDetail = new Rickshaw.Graph.HoverDetail({ + graph: graph, + formatter: function (series, x, y) { + var date = '' + + moment.unix((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + ''; + var swatch = ''; + return swatch + series.name + ": " + parseInt(y) + '
' + date; + } + }); + + var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({ + graph: graph, + legend: legend + }); + + var order = new Rickshaw.Graph.Behavior.Series.Order({ + graph: graph, + legend: legend + }); + + var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({ + graph: graph, + legend: legend + }); + + var deviceIndex = 0; + + if (devices) { + getData(); + } else { + var backendApiUrl = $("#chart").data("backend-api-url") + "?from=" + from + "&to=" + to; + var successCallback = function (data) { + if (data) { + drawLineGraph(JSON.parse(data)); + } + }; + invokerUtil.get(backendApiUrl, successCallback, function (message) { + console.log(message); + }); + } + + function getData() { + if (deviceIndex >= devices.length) { + return; + } + var backendApiUrl = $("#chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier + + "?from=" + from + "&to=" + to; + var successCallback = function (data) { + if (data) { + drawLineGraph(JSON.parse(data)); + } + deviceIndex++; + getData(); + }; + invokerUtil.get(backendApiUrl, successCallback, function (message) { + console.log(message); + deviceIndex++; + getData(); + }); + } + + function drawLineGraph(data) { + if (data.length === 0 || data.length === undefined) { + return; + } + + var chartData = []; + for (var i = 0; i < data.length; i++) { + chartData.push( + { + x: parseInt(data[i].values.time) - tzOffset, + y: parseInt(data[i].values.${nameOfTheSensor}) + } + ); + } + + graphConfig.series[deviceIndex].data = chartData; + graph.update(); + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/moment.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/moment.min.js new file mode 100644 index 00000000..78e5aaad --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/moment.min.js @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! moment.js +//! version : 2.10.2 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com +!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return Ac.apply(null,arguments)}function b(a){Ac=a}function c(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}function e(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function f(a,b){var c,d=[];for(c=0;c0)for(c in Cc)d=Cc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function m(b){l(this,b),this._d=new Date(+b._d),Dc===!1&&(Dc=!0,a.updateOffset(this),Dc=!1)}function n(a){return a instanceof m||null!=a&&g(a,"_isAMomentObject")}function o(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function p(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&o(a[d])!==o(b[d]))&&g++;return g+f}function q(){}function r(a){return a?a.toLowerCase().replace("_","-"):a}function s(a){for(var b,c,d,e,f=0;f0;){if(d=t(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&p(e,c,!0)>=b-1)break;b--}f++}return null}function t(a){var b=null;if(!Ec[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Bc._abbr,require("./locale/"+a),u(b)}catch(c){}return Ec[a]}function u(a,b){var c;return a&&(c="undefined"==typeof b?w(a):v(a,b),c&&(Bc=c)),Bc._abbr}function v(a,b){return null!==b?(b.abbr=a,Ec[a]||(Ec[a]=new q),Ec[a].set(b),u(a),Ec[a]):(delete Ec[a],null)}function w(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Bc;if(!d(a)){if(b=t(a))return b;a=[a]}return s(a)}function x(a,b){var c=a.toLowerCase();Fc[c]=Fc[c+"s"]=Fc[b]=a}function y(a){return"string"==typeof a?Fc[a]||Fc[a.toLowerCase()]:void 0}function z(a){var b,c,d={};for(c in a)g(a,c)&&(b=y(c),b&&(d[b]=a[c]));return d}function A(b,c){return function(d){return null!=d?(C(this,b,d),a.updateOffset(this,c),this):B(this,b)}}function B(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function C(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function D(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=y(a),"function"==typeof this[a])return this[a](b);return this}function E(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.lengthb;b++)d[b]=Jc[d[b]]?Jc[d[b]]:G(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function I(a,b){return a.isValid()?(b=J(b,a.localeData()),Ic[b]||(Ic[b]=H(b)),Ic[b](a)):a.localeData().invalidDate()}function J(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Hc.lastIndex=0;d>=0&&Hc.test(a);)a=a.replace(Hc,c),Hc.lastIndex=0,d-=1;return a}function K(a,b,c){Yc[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function L(a,b){return g(Yc,a)?Yc[a](b._strict,b._locale):new RegExp(M(a))}function M(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function N(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=o(a)}),c=0;cd;d++){if(e=i([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function U(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),Q(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function V(b){return null!=b?(U(this,b),a.updateOffset(this,!0),this):B(this,"Month")}function W(){return Q(this.year(),this.month())}function X(a){var b,c=a._a;return c&&-2===a._pf.overflow&&(b=c[_c]<0||c[_c]>11?_c:c[ad]<1||c[ad]>Q(c[$c],c[_c])?ad:c[bd]<0||c[bd]>24||24===c[bd]&&(0!==c[cd]||0!==c[dd]||0!==c[ed])?bd:c[cd]<0||c[cd]>59?cd:c[dd]<0||c[dd]>59?dd:c[ed]<0||c[ed]>999?ed:-1,a._pf._overflowDayOfYear&&($c>b||b>ad)&&(b=ad),a._pf.overflow=b),a}function Y(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function Z(a,b){var c=!0;return h(function(){return c&&(Y(a),c=!1),b.apply(this,arguments)},b)}function $(a,b){hd[a]||(Y(b),hd[a]=!0)}function _(a){var b,c,d=a._i,e=id.exec(d);if(e){for(a._pf.iso=!0,b=0,c=jd.length;c>b;b++)if(jd[b][1].exec(d)){a._f=jd[b][0]+(e[6]||" ");break}for(b=0,c=kd.length;c>b;b++)if(kd[b][1].exec(d)){a._f+=kd[b][0];break}d.match(Vc)&&(a._f+="Z"),sa(a)}else a._isValid=!1}function aa(b){var c=ld.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(_(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ba(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function ca(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function da(a){return ea(a)?366:365}function ea(a){return a%4===0&&a%100!==0||a%400===0}function fa(){return ea(this.year())}function ga(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=za(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ha(a){return ga(a,this._week.dow,this._week.doy).week}function ia(){return this._week.dow}function ja(){return this._week.doy}function ka(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function la(a){var b=ga(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function ma(a,b,c,d,e){var f,g,h=ca(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:da(a-1)+g}}function na(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function oa(a,b,c){return null!=a?a:null!=b?b:c}function pa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function qa(a){var b,c,d,e,f=[];if(!a._d){for(d=pa(a),a._w&&null==a._a[ad]&&null==a._a[_c]&&ra(a),a._dayOfYear&&(e=oa(a._a[$c],d[$c]),a._dayOfYear>da(e)&&(a._pf._overflowDayOfYear=!0),c=ca(e,0,a._dayOfYear),a._a[_c]=c.getUTCMonth(),a._a[ad]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[bd]&&0===a._a[cd]&&0===a._a[dd]&&0===a._a[ed]&&(a._nextDay=!0,a._a[bd]=0),a._d=(a._useUTC?ca:ba).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[bd]=24)}}function ra(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=oa(b.GG,a._a[$c],ga(za(),1,4).year),d=oa(b.W,1),e=oa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=oa(b.gg,a._a[$c],ga(za(),f,g).year),d=oa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=ma(c,d,e,g,f),a._a[$c]=h.year,a._dayOfYear=h.dayOfYear}function sa(b){if(b._f===a.ISO_8601)return void _(b);b._a=[],b._pf.empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=J(b._f,b._locale).match(Gc)||[],c=0;c0&&b._pf.unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length),Jc[f]?(d?b._pf.empty=!1:b._pf.unusedTokens.push(f),P(f,d,b)):b._strict&&!d&&b._pf.unusedTokens.push(f);b._pf.charsLeftOver=i-j,h.length>0&&b._pf.unusedInput.push(h),b._pf.bigHour===!0&&b._a[bd]<=12&&(b._pf.bigHour=void 0),b._a[bd]=ta(b._locale,b._a[bd],b._meridiem),qa(b),X(b)}function ta(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function ua(a){var b,d,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;fg)&&(e=g,d=b));h(a,d||b)}function va(a){if(!a._d){var b=z(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],qa(a)}}function wa(a){var b,c=a._i,e=a._f;return a._locale=a._locale||w(a._l),null===c||void 0===e&&""===c?k({nullInput:!0}):("string"==typeof c&&(a._i=c=a._locale.preparse(c)),n(c)?new m(X(c)):(d(e)?ua(a):e?sa(a):xa(a),b=new m(X(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function xa(b){var c=b._i;void 0===c?b._d=new Date:e(c)?b._d=new Date(+c):"string"==typeof c?aa(b):d(c)?(b._a=f(c.slice(0),function(a){return parseInt(a,10)}),qa(b)):"object"==typeof c?va(b):"number"==typeof c?b._d=new Date(c):a.createFromInputFallback(b)}function ya(a,b,d,e,f){var g={};return"boolean"==typeof d&&(e=d,d=void 0),g._isAMomentObject=!0,g._useUTC=g._isUTC=f,g._l=d,g._i=a,g._f=b,g._strict=e,g._pf=c(),wa(g)}function za(a,b,c,d){return ya(a,b,c,d,!1)}function Aa(a,b){var c,e;if(1===b.length&&d(b[0])&&(b=b[0]),!b.length)return za();for(c=b[0],e=1;ea&&(a=-a,c="-"),c+E(~~(a/60),2)+b+E(~~a%60,2)})}function Ga(a){var b=(a||"").match(Vc)||[],c=b[b.length-1]||[],d=(c+"").match(qd)||["-",0,0],e=+(60*d[1])+o(d[2]);return"+"===d[0]?e:-e}function Ha(b,c){var d,f;return c._isUTC?(d=c.clone(),f=(n(b)||e(b)?+b:+za(b))-+d,d._d.setTime(+d._d+f),a.updateOffset(d,!1),d):za(b).local();return c._isUTC?za(b).zone(c._offset||0):za(b).local()}function Ia(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ja(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ga(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ia(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?Za(this,Ua(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ia(this)}function Ka(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function La(a){return this.utcOffset(0,a)}function Ma(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ia(this),"m")),this}function Na(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ga(this._i)),this}function Oa(a){return a=a?za(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Pa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Qa(){if(this._a){var a=this._isUTC?i(this._a):za(this._a);return this.isValid()&&p(this._a,a.toArray())>0}return!1}function Ra(){return!this._isUTC}function Sa(){return this._isUTC}function Ta(){return this._isUTC&&0===this._offset}function Ua(a,b){var c,d,e,f=a,h=null;return Ea(a)?f={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(f={},b?f[b]=a:f.milliseconds=a):(h=rd.exec(a))?(c="-"===h[1]?-1:1,f={y:0,d:o(h[ad])*c,h:o(h[bd])*c,m:o(h[cd])*c,s:o(h[dd])*c,ms:o(h[ed])*c}):(h=sd.exec(a))?(c="-"===h[1]?-1:1,f={y:Va(h[2],c),M:Va(h[3],c),d:Va(h[4],c),h:Va(h[5],c),m:Va(h[6],c),s:Va(h[7],c),w:Va(h[8],c)}):null==f?f={}:"object"==typeof f&&("from"in f||"to"in f)&&(e=Xa(za(f.from),za(f.to)),f={},f.ms=e.milliseconds,f.M=e.months),d=new Da(f),Ea(a)&&g(a,"_locale")&&(d._locale=a._locale),d}function Va(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Wa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Xa(a,b){var c;return b=Ha(b,a),a.isBefore(b)?c=Wa(a,b):(c=Wa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Ya(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||($(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ua(c,d),Za(this,e,a),this}}function Za(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&C(b,"Date",B(b,"Date")+g*d),h&&U(b,B(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function $a(a){var b=a||za(),c=Ha(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,za(b)))}function _a(){return new m(this)}function ab(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+this>+a):(c=n(a)?+a:+za(a),c<+this.clone().startOf(b))}function bb(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+a>+this):(c=n(a)?+a:+za(a),+this.clone().endOf(b)a?Math.ceil(a):Math.floor(a)}function fb(a,b,c){var d,e,f=Ha(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=y(b),"year"===b||"month"===b||"quarter"===b?(e=gb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:eb(e)}function gb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function hb(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function ib(){var a=this.clone().utc();return 0b;b++)if(this._weekdaysParse[b]||(c=za([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Jb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Eb(a,this.localeData()),this.add(a-b,"d")):b}function Kb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Lb(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Mb(a,b){F(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Nb(a,b){return b._meridiemParse}function Ob(a){return"p"===(a+"").toLowerCase().charAt(0)}function Pb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Qb(a){F(0,[a,3],0,"millisecond")}function Rb(){return this._isUTC?"UTC":""}function Sb(){return this._isUTC?"Coordinated Universal Time":""}function Tb(a){return za(1e3*a)}function Ub(){return za.apply(null,arguments).parseZone()}function Vb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Wb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function Xb(){return this._invalidDate}function Yb(a){return this._ordinal.replace("%d",a)}function Zb(a){return a}function $b(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function _b(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function ac(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function bc(a,b,c,d){var e=w(),f=i().set(d,b);return e[c](f,a)}function cc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return bc(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=bc(a,f,c,e);return g}function dc(a,b){return cc(a,b,"months",12,"month")}function ec(a,b){return cc(a,b,"monthsShort",12,"month")}function fc(a,b){return cc(a,b,"weekdays",7,"day")}function gc(a,b){return cc(a,b,"weekdaysShort",7,"day")}function hc(a,b){return cc(a,b,"weekdaysMin",7,"day")}function ic(){var a=this._data;return this._milliseconds=Od(this._milliseconds),this._days=Od(this._days),this._months=Od(this._months),a.milliseconds=Od(a.milliseconds),a.seconds=Od(a.seconds),a.minutes=Od(a.minutes),a.hours=Od(a.hours),a.months=Od(a.months),a.years=Od(a.years),this}function jc(a,b,c,d){var e=Ua(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function kc(a,b){return jc(this,a,b,1)}function lc(a,b){return jc(this,a,b,-1)}function mc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=eb(d/1e3),g.seconds=a%60,b=eb(a/60),g.minutes=b%60,c=eb(b/60),g.hours=c%24,e+=eb(c/24),h=eb(nc(e)),e-=eb(oc(h)),f+=eb(e/30),e%=30,h+=eb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function nc(a){return 400*a/146097}function oc(a){return 146097*a/400}function pc(a){var b,c,d=this._milliseconds;if(a=y(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*nc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(oc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 24*b*60+d/6e4;case"second":return 24*b*60*60+d/1e3;case"millisecond":return Math.floor(24*b*60*60*1e3)+d;default:throw new Error("Unknown unit "+a)}}function qc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*o(this._months/12)}function rc(a){return function(){return this.as(a)}}function sc(a){return a=y(a),this[a+"s"]()}function tc(a){return function(){return this._data[a]}}function uc(){return eb(this.days()/7)}function vc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function wc(a,b,c){var d=Ua(a).abs(),e=ce(d.as("s")),f=ce(d.as("m")),g=ce(d.as("h")),h=ce(d.as("d")),i=ce(d.as("M")),j=ce(d.as("y")),k=e0,k[4]=c,vc.apply(null,k)}function xc(a,b){return void 0===de[a]?!1:void 0===b?de[a]:(de[a]=b,!0)}function yc(a){var b=this.localeData(),c=wc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function zc(){var a=ee(this.years()),b=ee(this.months()),c=ee(this.days()),d=ee(this.hours()),e=ee(this.minutes()),f=ee(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Ac,Bc,Cc=a.momentProperties=[],Dc=!1,Ec={},Fc={},Gc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Hc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ic={},Jc={},Kc=/\d/,Lc=/\d\d/,Mc=/\d{3}/,Nc=/\d{4}/,Oc=/[+-]?\d{6}/,Pc=/\d\d?/,Qc=/\d{1,3}/,Rc=/\d{1,4}/,Sc=/[+-]?\d{1,6}/,Tc=/\d+/,Uc=/[+-]?\d+/,Vc=/Z|[+-]\d\d:?\d\d/gi,Wc=/[+-]?\d+(\.\d{1,3})?/,Xc=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Yc={},Zc={},$c=0,_c=1,ad=2,bd=3,cd=4,dd=5,ed=6;F("M",["MM",2],"Mo",function(){return this.month()+1}),F("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),F("MMMM",0,0,function(a){return this.localeData().months(this,a)}),x("month","M"),K("M",Pc),K("MM",Pc,Lc),K("MMM",Xc),K("MMMM",Xc),N(["M","MM"],function(a,b){b[_c]=o(a)-1}),N(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[_c]=e:c._pf.invalidMonth=a});var fd="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),gd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),hd={};a.suppressDeprecationWarnings=!1;var id=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,jd=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],kd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],ld=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=Z("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),F(0,["YY",2],0,function(){return this.year()%100}),F(0,["YYYY",4],0,"year"),F(0,["YYYYY",5],0,"year"),F(0,["YYYYYY",6,!0],0,"year"),x("year","y"),K("Y",Uc),K("YY",Pc,Lc),K("YYYY",Rc,Nc),K("YYYYY",Sc,Oc),K("YYYYYY",Sc,Oc),N(["YYYY","YYYYY","YYYYYY"],$c),N("YY",function(b,c){c[$c]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return o(a)+(o(a)>68?1900:2e3)};var md=A("FullYear",!1);F("w",["ww",2],"wo","week"),F("W",["WW",2],"Wo","isoWeek"),x("week","w"),x("isoWeek","W"),K("w",Pc),K("ww",Pc,Lc),K("W",Pc),K("WW",Pc,Lc),O(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=o(a)});var nd={dow:0,doy:6};F("DDD",["DDDD",3],"DDDo","dayOfYear"),x("dayOfYear","DDD"),K("DDD",Qc),K("DDDD",Mc),N(["DDD","DDDD"],function(a,b,c){c._dayOfYear=o(a)}),a.ISO_8601=function(){};var od=Z("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return this>a?this:a}),pd=Z("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return a>this?this:a});Fa("Z",":"),Fa("ZZ",""),K("Z",Vc),K("ZZ",Vc),N(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ga(a)});var qd=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var rd=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,sd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Ua.fn=Da.prototype;var td=Ya(1,"add"),ud=Ya(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var vd=Z("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});F(0,["gg",2],0,function(){return this.weekYear()%100}),F(0,["GG",2],0,function(){return this.isoWeekYear()%100}),xb("gggg","weekYear"),xb("ggggg","weekYear"),xb("GGGG","isoWeekYear"),xb("GGGGG","isoWeekYear"),x("weekYear","gg"),x("isoWeekYear","GG"),K("G",Uc),K("g",Uc),K("GG",Pc,Lc),K("gg",Pc,Lc),K("GGGG",Rc,Nc),K("gggg",Rc,Nc),K("GGGGG",Sc,Oc),K("ggggg",Sc,Oc),O(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=o(a)}),O(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),F("Q",0,0,"quarter"),x("quarter","Q"),K("Q",Kc),N("Q",function(a,b){b[_c]=3*(o(a)-1)}),F("D",["DD",2],"Do","date"),x("date","D"),K("D",Pc),K("DD",Pc,Lc),K("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),N(["D","DD"],ad),N("Do",function(a,b){b[ad]=o(a.match(Pc)[0],10)});var wd=A("Date",!0);F("d",0,"do","day"),F("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),F("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),F("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),F("e",0,0,"weekday"),F("E",0,0,"isoWeekday"),x("day","d"),x("weekday","e"),x("isoWeekday","E"),K("d",Pc),K("e",Pc),K("E",Pc),K("dd",Xc),K("ddd",Xc),K("dddd",Xc),O(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:c._pf.invalidWeekday=a}),O(["d","e","E"],function(a,b,c,d){b[d]=o(a)});var xd="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),yd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),zd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");F("H",["HH",2],0,"hour"),F("h",["hh",2],0,function(){return this.hours()%12||12}),Mb("a",!0),Mb("A",!1),x("hour","h"),K("a",Nb),K("A",Nb),K("H",Pc),K("h",Pc),K("HH",Pc,Lc),K("hh",Pc,Lc),N(["H","HH"],bd),N(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),N(["h","hh"],function(a,b,c){b[bd]=o(a),c._pf.bigHour=!0});var Ad=/[ap]\.?m?\.?/i,Bd=A("Hours",!0);F("m",["mm",2],0,"minute"),x("minute","m"),K("m",Pc),K("mm",Pc,Lc),N(["m","mm"],cd);var Cd=A("Minutes",!1);F("s",["ss",2],0,"second"),x("second","s"),K("s",Pc),K("ss",Pc,Lc),N(["s","ss"],dd);var Dd=A("Seconds",!1);F("S",0,0,function(){return~~(this.millisecond()/100)}),F(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Qb("SSS"),Qb("SSSS"),x("millisecond","ms"),K("S",Qc,Kc),K("SS",Qc,Lc),K("SSS",Qc,Mc),K("SSSS",Tc),N(["S","SS","SSS","SSSS"],function(a,b){b[ed]=o(1e3*("0."+a))});var Ed=A("Milliseconds",!1);F("z",0,0,"zoneAbbr"),F("zz",0,0,"zoneName");var Fd=m.prototype;Fd.add=td,Fd.calendar=$a,Fd.clone=_a,Fd.diff=fb,Fd.endOf=pb,Fd.format=jb,Fd.from=kb,Fd.fromNow=lb,Fd.get=D,Fd.invalidAt=wb,Fd.isAfter=ab,Fd.isBefore=bb,Fd.isBetween=cb,Fd.isSame=db,Fd.isValid=ub,Fd.lang=vd,Fd.locale=mb,Fd.localeData=nb,Fd.max=pd,Fd.min=od,Fd.parsingFlags=vb,Fd.set=D,Fd.startOf=ob,Fd.subtract=ud,Fd.toArray=tb,Fd.toDate=sb,Fd.toISOString=ib,Fd.toJSON=ib,Fd.toString=hb,Fd.unix=rb,Fd.valueOf=qb,Fd.year=md,Fd.isLeapYear=fa,Fd.weekYear=zb,Fd.isoWeekYear=Ab,Fd.quarter=Fd.quarters=Db,Fd.month=V,Fd.daysInMonth=W,Fd.week=Fd.weeks=ka,Fd.isoWeek=Fd.isoWeeks=la,Fd.weeksInYear=Cb,Fd.isoWeeksInYear=Bb,Fd.date=wd,Fd.day=Fd.days=Jb,Fd.weekday=Kb,Fd.isoWeekday=Lb,Fd.dayOfYear=na,Fd.hour=Fd.hours=Bd,Fd.minute=Fd.minutes=Cd,Fd.second=Fd.seconds=Dd,Fd.millisecond=Fd.milliseconds=Ed,Fd.utcOffset=Ja,Fd.utc=La,Fd.local=Ma,Fd.parseZone=Na,Fd.hasAlignedHourOffset=Oa,Fd.isDST=Pa,Fd.isDSTShifted=Qa,Fd.isLocal=Ra,Fd.isUtcOffset=Sa,Fd.isUtc=Ta,Fd.isUTC=Ta,Fd.zoneAbbr=Rb,Fd.zoneName=Sb,Fd.dates=Z("dates accessor is deprecated. Use date instead.",wd),Fd.months=Z("months accessor is deprecated. Use month instead",V),Fd.years=Z("years accessor is deprecated. Use year instead",md),Fd.zone=Z("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Ka);var Gd=Fd,Hd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Id={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Jd="Invalid date",Kd="%d",Ld=/\d{1,2}/,Md={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Nd=q.prototype;Nd._calendar=Hd,Nd.calendar=Vb,Nd._longDateFormat=Id,Nd.longDateFormat=Wb,Nd._invalidDate=Jd,Nd.invalidDate=Xb,Nd._ordinal=Kd,Nd.ordinal=Yb,Nd._ordinalParse=Ld, +Nd.preparse=Zb,Nd.postformat=Zb,Nd._relativeTime=Md,Nd.relativeTime=$b,Nd.pastFuture=_b,Nd.set=ac,Nd.months=R,Nd._months=fd,Nd.monthsShort=S,Nd._monthsShort=gd,Nd.monthsParse=T,Nd.week=ha,Nd._week=nd,Nd.firstDayOfYear=ja,Nd.firstDayOfWeek=ia,Nd.weekdays=Fb,Nd._weekdays=xd,Nd.weekdaysMin=Hb,Nd._weekdaysMin=zd,Nd.weekdaysShort=Gb,Nd._weekdaysShort=yd,Nd.weekdaysParse=Ib,Nd.isPM=Ob,Nd._meridiemParse=Ad,Nd.meridiem=Pb,u("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===o(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=Z("moment.lang is deprecated. Use moment.locale instead.",u),a.langData=Z("moment.langData is deprecated. Use moment.localeData instead.",w);var Od=Math.abs,Pd=rc("ms"),Qd=rc("s"),Rd=rc("m"),Sd=rc("h"),Td=rc("d"),Ud=rc("w"),Vd=rc("M"),Wd=rc("y"),Xd=tc("milliseconds"),Yd=tc("seconds"),Zd=tc("minutes"),$d=tc("hours"),_d=tc("days"),ae=tc("months"),be=tc("years"),ce=Math.round,de={s:45,m:45,h:22,d:26,M:11},ee=Math.abs,fe=Da.prototype;fe.abs=ic,fe.add=kc,fe.subtract=lc,fe.as=pc,fe.asMilliseconds=Pd,fe.asSeconds=Qd,fe.asMinutes=Rd,fe.asHours=Sd,fe.asDays=Td,fe.asWeeks=Ud,fe.asMonths=Vd,fe.asYears=Wd,fe.valueOf=qc,fe._bubble=mc,fe.get=sc,fe.milliseconds=Xd,fe.seconds=Yd,fe.minutes=Zd,fe.hours=$d,fe.days=_d,fe.weeks=uc,fe.months=ae,fe.years=be,fe.humanize=yc,fe.toISOString=zc,fe.toString=zc,fe.toJSON=zc,fe.locale=mb,fe.localeData=nb,fe.toIsoString=Z("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",zc),fe.lang=vd,F("X",0,0,"unix"),F("x",0,0,"valueOf"),K("x",Uc),K("X",Wc),N("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),N("x",function(a,b,c){c._d=new Date(o(a))}),a.version="2.10.2",b(za),a.fn=Gd,a.min=Ba,a.max=Ca,a.utc=i,a.unix=Tb,a.months=dc,a.isDate=e,a.locale=u,a.invalid=k,a.duration=Ua,a.isMoment=n,a.weekdays=fc,a.parseZone=Ub,a.localeData=w,a.isDuration=Ea,a.monthsShort=ec,a.weekdaysMin=hc,a.defineLocale=v,a.weekdaysShort=gc,a.normalizeUnits=y,a.relativeTimeThreshold=xc;var ge=a;return ge}); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/rickshaw.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/rickshaw.min.js new file mode 100644 index 00000000..be060e0b --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.analytics-view/public/js/rickshaw.min.js @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +(function(root,factory){if(typeof define==="function"&&define.amd){define(["d3.min"],function(d3){return root.Rickshaw=factory(d3)})}else if(typeof exports==="object"){module.exports=factory(require("d3"))}else{root.Rickshaw=factory(d3)}})(this,function(d3){var Rickshaw={namespace:function(namespace,obj){var parts=namespace.split(".");var parent=Rickshaw;for(var i=1,length=parts.length;i0){var x=s.data[0].x;var y=s.data[0].y;if(typeof x!="number"||typeof y!="number"&&y!==null){throw"x and y properties of points should be numbers instead of "+typeof x+" and "+typeof y}}if(s.data.length>=3){if(s.data[2].xthis.window.xMax)isInRange=false;return isInRange}return true};this.onUpdate=function(callback){this.updateCallbacks.push(callback)};this.onConfigure=function(callback){this.configureCallbacks.push(callback)};this.registerRenderer=function(renderer){this._renderers=this._renderers||{};this._renderers[renderer.name]=renderer};this.configure=function(args){this.config=this.config||{};if(args.width||args.height){this.setSize(args)}Rickshaw.keys(this.defaults).forEach(function(k){this.config[k]=k in args?args[k]:k in this?this[k]:this.defaults[k]},this);Rickshaw.keys(this.config).forEach(function(k){this[k]=this.config[k]},this);if("stack"in args)args.unstack=!args.stack;var renderer=args.renderer||this.renderer&&this.renderer.name||"stack";this.setRenderer(renderer,args);this.configureCallbacks.forEach(function(callback){callback(args)})};this.setRenderer=function(r,args){if(typeof r=="function"){this.renderer=new r({graph:self});this.registerRenderer(this.renderer)}else{if(!this._renderers[r]){throw"couldn't find renderer "+r}this.renderer=this._renderers[r]}if(typeof args=="object"){this.renderer.configure(args)}};this.setSize=function(args){args=args||{};if(typeof window!==undefined){var style=window.getComputedStyle(this.element,null);var elementWidth=parseInt(style.getPropertyValue("width"),10);var elementHeight=parseInt(style.getPropertyValue("height"),10)}this.width=args.width||elementWidth||400;this.height=args.height||elementHeight||250;this.vis&&this.vis.attr("width",this.width).attr("height",this.height)};this.initialize(args)};Rickshaw.namespace("Rickshaw.Fixtures.Color");Rickshaw.Fixtures.Color=function(){this.schemes={};this.schemes.spectrum14=["#ecb796","#dc8f70","#b2a470","#92875a","#716c49","#d2ed82","#bbe468","#a1d05d","#e7cbe6","#d8aad6","#a888c2","#9dc2d3","#649eb9","#387aa3"].reverse();this.schemes.spectrum2000=["#57306f","#514c76","#646583","#738394","#6b9c7d","#84b665","#a7ca50","#bfe746","#e2f528","#fff726","#ecdd00","#d4b11d","#de8800","#de4800","#c91515","#9a0000","#7b0429","#580839","#31082b"];this.schemes.spectrum2001=["#2f243f","#3c2c55","#4a3768","#565270","#6b6b7c","#72957f","#86ad6e","#a1bc5e","#b8d954","#d3e04e","#ccad2a","#cc8412","#c1521d","#ad3821","#8a1010","#681717","#531e1e","#3d1818","#320a1b"];this.schemes.classic9=["#423d4f","#4a6860","#848f39","#a2b73c","#ddcb53","#c5a32f","#7d5836","#963b20","#7c2626","#491d37","#2f254a"].reverse();this.schemes.httpStatus={503:"#ea5029",502:"#d23f14",500:"#bf3613",410:"#efacea",409:"#e291dc",403:"#f457e8",408:"#e121d2",401:"#b92dae",405:"#f47ceb",404:"#a82a9f",400:"#b263c6",301:"#6fa024",302:"#87c32b",307:"#a0d84c",304:"#28b55c",200:"#1a4f74",206:"#27839f",201:"#52adc9",202:"#7c979f",203:"#a5b8bd",204:"#c1cdd1"};this.schemes.colorwheel=["#b5b6a9","#858772","#785f43","#96557e","#4682b4","#65b9ac","#73c03a","#cb513a"].reverse();this.schemes.cool=["#5e9d2f","#73c03a","#4682b4","#7bc3b8","#a9884e","#c1b266","#a47493","#c09fb5"];this.schemes.munin=["#00cc00","#0066b3","#ff8000","#ffcc00","#330099","#990099","#ccff00","#ff0000","#808080","#008f00","#00487d","#b35a00","#b38f00","#6b006b","#8fb300","#b30000","#bebebe","#80ff80","#80c9ff","#ffc080","#ffe680","#aa80ff","#ee00cc","#ff8080","#666600","#ffbfff","#00ffcc","#cc6699","#999900"]};Rickshaw.namespace("Rickshaw.Fixtures.RandomData");Rickshaw.Fixtures.RandomData=function(timeInterval){var addData;timeInterval=timeInterval||1;var lastRandomValue=200;var timeBase=Math.floor((new Date).getTime()/1e3);this.addData=function(data){var randomValue=Math.random()*100+15+lastRandomValue;var index=data[0].length;var counter=1;data.forEach(function(series){var randomVariance=Math.random()*20;var v=randomValue/25+counter++ +(Math.cos(index*counter*11/960)+2)*15+(Math.cos(index/7)+2)*7+(Math.cos(index/17)+2)*1;series.push({x:index*timeInterval+timeBase,y:v+randomVariance})});lastRandomValue=randomValue*.85};this.removeData=function(data){data.forEach(function(series){series.shift()});timeBase+=timeInterval}};Rickshaw.namespace("Rickshaw.Fixtures.Time");Rickshaw.Fixtures.Time=function(){var self=this;this.months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];this.units=[{name:"decade",seconds:86400*365.25*10,formatter:function(d){return parseInt(d.getUTCFullYear()/10,10)*10}},{name:"year",seconds:86400*365.25,formatter:function(d){return d.getUTCFullYear()}},{name:"month",seconds:86400*30.5,formatter:function(d){return self.months[d.getUTCMonth()]}},{name:"week",seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:"day",seconds:86400,formatter:function(d){return d.getUTCDate()}},{name:"6 hour",seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:"hour",seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:"15 minute",seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:"minute",seconds:60,formatter:function(d){return d.getUTCMinutes()}},{name:"15 second",seconds:15,formatter:function(d){return d.getUTCSeconds()+"s"}},{name:"second",seconds:1,formatter:function(d){return d.getUTCSeconds()+"s"}},{name:"decisecond",seconds:1/10,formatter:function(d){return d.getUTCMilliseconds()+"ms"}},{name:"centisecond",seconds:1/100,formatter:function(d){return d.getUTCMilliseconds()+"ms"}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift()};this.formatDate=function(d){return d3.time.format("%b %e")(d)};this.formatTime=function(d){return d.toUTCString().match(/(\d+:\d+):/)[1]};this.ceil=function(time,unit){var date,floor,year;if(unit.name=="month"){date=new Date(time*1e3);floor=Date.UTC(date.getUTCFullYear(),date.getUTCMonth())/1e3;if(floor==time)return time;year=date.getUTCFullYear();var month=date.getUTCMonth();if(month==11){month=0;year=year+1}else{month+=1}return Date.UTC(year,month)/1e3}if(unit.name=="year"){date=new Date(time*1e3);floor=Date.UTC(date.getUTCFullYear(),0)/1e3;if(floor==time)return time;year=date.getUTCFullYear()+1;return Date.UTC(year,0)/1e3}return Math.ceil(time/unit.seconds)*unit.seconds}};Rickshaw.namespace("Rickshaw.Fixtures.Time.Local");Rickshaw.Fixtures.Time.Local=function(){var self=this;this.months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];this.units=[{name:"decade",seconds:86400*365.25*10,formatter:function(d){return parseInt(d.getFullYear()/10,10)*10}},{name:"year",seconds:86400*365.25,formatter:function(d){return d.getFullYear()}},{name:"month",seconds:86400*30.5,formatter:function(d){return self.months[d.getMonth()]}},{name:"week",seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:"day",seconds:86400,formatter:function(d){return d.getDate()}},{name:"6 hour",seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:"hour",seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:"15 minute",seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:"minute",seconds:60,formatter:function(d){return d.getMinutes()}},{name:"15 second",seconds:15,formatter:function(d){return d.getSeconds()+"s"}},{name:"second",seconds:1,formatter:function(d){return d.getSeconds()+"s"}},{name:"decisecond",seconds:1/10,formatter:function(d){return d.getMilliseconds()+"ms"}},{name:"centisecond",seconds:1/100,formatter:function(d){return d.getMilliseconds()+"ms"}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift()};this.formatDate=function(d){return d3.time.format("%b %e")(d)};this.formatTime=function(d){return d.toString().match(/(\d+:\d+):/)[1]};this.ceil=function(time,unit){var date,floor,year;if(unit.name=="day"){var nearFuture=new Date((time+unit.seconds-1)*1e3);var rounded=new Date(0);rounded.setMilliseconds(0);rounded.setSeconds(0);rounded.setMinutes(0);rounded.setHours(0);rounded.setDate(nearFuture.getDate());rounded.setMonth(nearFuture.getMonth());rounded.setFullYear(nearFuture.getFullYear());return rounded.getTime()/1e3}if(unit.name=="month"){date=new Date(time*1e3);floor=new Date(date.getFullYear(),date.getMonth()).getTime()/1e3;if(floor==time)return time;year=date.getFullYear();var month=date.getMonth();if(month==11){month=0;year=year+1}else{month+=1}return new Date(year,month).getTime()/1e3}if(unit.name=="year"){date=new Date(time*1e3);floor=new Date(date.getUTCFullYear(),0).getTime()/1e3;if(floor==time)return time;year=date.getFullYear()+1;return new Date(year,0).getTime()/1e3}return Math.ceil(time/unit.seconds)*unit.seconds}};Rickshaw.namespace("Rickshaw.Fixtures.Number");Rickshaw.Fixtures.Number.formatKMBT=function(y){var abs_y=Math.abs(y);if(abs_y>=1e12){return y/1e12+"T"}else if(abs_y>=1e9){return y/1e9+"B"}else if(abs_y>=1e6){return y/1e6+"M"}else if(abs_y>=1e3){return y/1e3+"K"}else if(abs_y<1&&y>0){return y.toFixed(2)}else if(abs_y===0){return""}else{return y}};Rickshaw.Fixtures.Number.formatBase1024KMGTP=function(y){var abs_y=Math.abs(y);if(abs_y>=0x4000000000000){return y/0x4000000000000+"P"}else if(abs_y>=1099511627776){return y/1099511627776+"T"}else if(abs_y>=1073741824){return y/1073741824+"G"}else if(abs_y>=1048576){return y/1048576+"M"}else if(abs_y>=1024){return y/1024+"K"}else if(abs_y<1&&y>0){return y.toFixed(2)}else if(abs_y===0){return""}else{return y}};Rickshaw.namespace("Rickshaw.Color.Palette");Rickshaw.Color.Palette=function(args){var color=new Rickshaw.Fixtures.Color;args=args||{};this.schemes={};this.scheme=color.schemes[args.scheme]||args.scheme||color.schemes.colorwheel;this.runningIndex=0;this.generatorIndex=0;if(args.interpolatedStopCount){var schemeCount=this.scheme.length-1;var i,j,scheme=[];for(i=0;iself.graph.x.range()[1]){if(annotation.element){annotation.line.classList.add("offscreen");annotation.element.style.display="none"}annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.add("offscreen")});return}if(!annotation.element){var element=annotation.element=document.createElement("div");element.classList.add("annotation");this.elements.timeline.appendChild(element);element.addEventListener("click",function(e){element.classList.toggle("active");annotation.line.classList.toggle("active");annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.toggle("active")})},false)}annotation.element.style.left=left+"px";annotation.element.style.display="block";annotation.boxes.forEach(function(box){var element=box.element;if(!element){element=box.element=document.createElement("div");element.classList.add("content");element.innerHTML=box.content;annotation.element.appendChild(element);annotation.line=document.createElement("div");annotation.line.classList.add("annotation_line");self.graph.element.appendChild(annotation.line);if(box.end){box.rangeElement=document.createElement("div");box.rangeElement.classList.add("annotation_range");self.graph.element.appendChild(box.rangeElement)}}if(box.end){var annotationRangeStart=left;var annotationRangeEnd=Math.min(self.graph.x(box.end),self.graph.x.range()[1]);if(annotationRangeStart>annotationRangeEnd){annotationRangeEnd=left;annotationRangeStart=Math.max(self.graph.x(box.end),self.graph.x.range()[0])}var annotationRangeWidth=annotationRangeEnd-annotationRangeStart;box.rangeElement.style.left=annotationRangeStart+"px";box.rangeElement.style.width=annotationRangeWidth+"px";box.rangeElement.classList.remove("offscreen")}annotation.line.classList.remove("offscreen");annotation.line.style.left=left+"px"})},this)};this.graph.onUpdate(function(){self.update()})};Rickshaw.namespace("Rickshaw.Graph.Axis.Time");Rickshaw.Graph.Axis.Time=function(args){var self=this;this.graph=args.graph;this.elements=[];this.ticksTreatment=args.ticksTreatment||"plain";this.fixedTimeUnit=args.timeUnit;var time=args.timeFixture||new Rickshaw.Fixtures.Time;this.appropriateTimeUnit=function(){var unit;var units=time.units;var domain=this.graph.x.domain();var rangeSeconds=domain[1]-domain[0];units.forEach(function(u){if(Math.floor(rangeSeconds/u.seconds)>=2){unit=unit||u}});return unit||time.units[time.units.length-1]};this.tickOffsets=function(){var domain=this.graph.x.domain();var unit=this.fixedTimeUnit||this.appropriateTimeUnit();var count=Math.ceil((domain[1]-domain[0])/unit.seconds);var runningTick=domain[0];var offsets=[];for(var i=0;iself.graph.x.range()[1])return;var element=document.createElement("div");element.style.left=self.graph.x(o.value)+"px";element.classList.add("x_tick");element.classList.add(self.ticksTreatment);var title=document.createElement("div");title.classList.add("title");title.innerHTML=o.unit.formatter(new Date(o.value*1e3));element.appendChild(title);self.graph.element.appendChild(element);self.elements.push(element)})};this.graph.onUpdate(function(){self.render()})};Rickshaw.namespace("Rickshaw.Graph.Axis.X");Rickshaw.Graph.Axis.X=function(args){var self=this;var berthRate=.1;this.initialize=function(args){this.graph=args.graph;this.orientation=args.orientation||"top";this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||"plain";if(args.element){this.element=args.element;this._discoverSize(args.element,args);this.vis=d3.select(args.element).append("svg:svg").attr("height",this.height).attr("width",this.width).attr("class","rickshaw_graph x_axis_d3");this.element=this.vis[0][0];this.element.style.position="relative";this.setSize({width:args.width,height:args.height})}else{this.vis=this.graph.vis}this.graph.onUpdate(function(){self.render()})};this.setSize=function(args){args=args||{};if(!this.element)return;this._discoverSize(this.element.parentNode,args);this.vis.attr("height",this.height).attr("width",this.width*(1+berthRate));var berth=Math.floor(this.width*berthRate/2);this.element.style.left=-1*berth+"px"};this.render=function(){if(this._renderWidth!==undefined&&this.graph.width!==this._renderWidth)this.setSize({auto:true});var axis=d3.svg.axis().scale(this.graph.x).orient(this.orientation);axis.tickFormat(args.tickFormat||function(x){return x});if(this.tickValues)axis.tickValues(this.tickValues);this.ticks=this.staticTicks||Math.floor(this.graph.width/this.pixelsPerTick);var berth=Math.floor(this.width*berthRate/2)||0;var transform;if(this.orientation=="top"){var yOffset=this.height||this.graph.height;transform="translate("+berth+","+yOffset+")"}else{transform="translate("+berth+", 0)"}if(this.element){this.vis.selectAll("*").remove()}this.vis.append("svg:g").attr("class",["x_ticks_d3",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));var gridSize=(this.orientation=="bottom"?1:-1)*this.graph.height;this.graph.vis.append("svg:g").attr("class","x_grid_d3").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize)).selectAll("text").each(function(){this.parentNode.setAttribute("data-x-value",this.textContent)});this._renderHeight=this.graph.height};this._discoverSize=function(element,args){if(typeof window!=="undefined"){var style=window.getComputedStyle(element,null);var elementHeight=parseInt(style.getPropertyValue("height"),10);if(!args.auto){var elementWidth=parseInt(style.getPropertyValue("width"),10)}}this.width=(args.width||elementWidth||this.graph.width)*(1+berthRate);this.height=args.height||elementHeight||40};this.initialize(args)};Rickshaw.namespace("Rickshaw.Graph.Axis.Y");Rickshaw.Graph.Axis.Y=Rickshaw.Class.create({initialize:function(args){this.graph=args.graph;this.orientation=args.orientation||"right";this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||"plain";this.tickFormat=args.tickFormat||function(y){return y};this.berthRate=.1;if(args.element){this.element=args.element;this.vis=d3.select(args.element).append("svg:svg").attr("class","rickshaw_graph y_axis");this.element=this.vis[0][0];this.element.style.position="relative";this.setSize({width:args.width,height:args.height})}else{this.vis=this.graph.vis}var self=this;this.graph.onUpdate(function(){self.render()})},setSize:function(args){args=args||{};if(!this.element)return;if(typeof window!=="undefined"){var style=window.getComputedStyle(this.element.parentNode,null);var elementWidth=parseInt(style.getPropertyValue("width"),10);if(!args.auto){var elementHeight=parseInt(style.getPropertyValue("height"),10)}}this.width=args.width||elementWidth||this.graph.width*this.berthRate;this.height=args.height||elementHeight||this.graph.height;this.vis.attr("width",this.width).attr("height",this.height*(1+this.berthRate));var berth=this.height*this.berthRate;if(this.orientation=="left"){this.element.style.top=-1*berth+"px"}},render:function(){if(this._renderHeight!==undefined&&this.graph.height!==this._renderHeight)this.setSize({auto:true});this.ticks=this.staticTicks||Math.floor(this.graph.height/this.pixelsPerTick);var axis=this._drawAxis(this.graph.y);this._drawGrid(axis);this._renderHeight=this.graph.height},_drawAxis:function(scale){var axis=d3.svg.axis().scale(scale).orient(this.orientation);axis.tickFormat(this.tickFormat);if(this.tickValues)axis.tickValues(this.tickValues);if(this.orientation=="left"){var berth=this.height*this.berthRate;var transform="translate("+this.width+", "+berth+")"}if(this.element){this.vis.selectAll("*").remove()}this.vis.append("svg:g").attr("class",["y_ticks",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));return axis},_drawGrid:function(axis){var gridSize=(this.orientation=="right"?1:-1)*this.graph.width;this.graph.vis.append("svg:g").attr("class","y_grid").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize)).selectAll("text").each(function(){this.parentNode.setAttribute("data-y-value",this.textContent) +})}});Rickshaw.namespace("Rickshaw.Graph.Axis.Y.Scaled");Rickshaw.Graph.Axis.Y.Scaled=Rickshaw.Class.create(Rickshaw.Graph.Axis.Y,{initialize:function($super,args){if(typeof args.scale==="undefined"){throw new Error("Scaled requires scale")}this.scale=args.scale;if(typeof args.grid==="undefined"){this.grid=true}else{this.grid=args.grid}$super(args)},_drawAxis:function($super,scale){var domain=this.scale.domain();var renderDomain=this.graph.renderer.domain().y;var extents=[Math.min.apply(Math,domain),Math.max.apply(Math,domain)];var extentMap=d3.scale.linear().domain([0,1]).range(extents);var adjExtents=[extentMap(renderDomain[0]),extentMap(renderDomain[1])];var adjustment=d3.scale.linear().domain(extents).range(adjExtents);var adjustedScale=this.scale.copy().domain(domain.map(adjustment)).range(scale.range());return $super(adjustedScale)},_drawGrid:function($super,axis){if(this.grid){$super(axis)}}});Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Highlight");Rickshaw.Graph.Behavior.Series.Highlight=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;var colorSafe={};var activeLine=null;var disabledColor=args.disabledColor||function(seriesColor){return d3.interpolateRgb(seriesColor,d3.rgb("#d8d8d8"))(.8).toString()};this.addHighlightEvents=function(l){l.element.addEventListener("mouseover",function(e){if(activeLine)return;else activeLine=l;self.legend.lines.forEach(function(line){if(l===line){if(self.graph.renderer.unstack&&(line.series.renderer?line.series.renderer.unstack:true)){var seriesIndex=self.graph.series.indexOf(line.series);line.originalIndex=seriesIndex;var series=self.graph.series.splice(seriesIndex,1)[0];self.graph.series.push(series)}return}colorSafe[line.series.name]=colorSafe[line.series.name]||line.series.color;line.series.color=disabledColor(line.series.color)});self.graph.update()},false);l.element.addEventListener("mouseout",function(e){if(!activeLine)return;else activeLine=null;self.legend.lines.forEach(function(line){if(l===line&&line.hasOwnProperty("originalIndex")){var series=self.graph.series.pop();self.graph.series.splice(line.originalIndex,0,series);delete line.originalIndex}if(colorSafe[line.series.name]){line.series.color=colorSafe[line.series.name]}});self.graph.update()},false)};if(this.legend){this.legend.lines.forEach(function(l){self.addHighlightEvents(l)})}};Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Order");Rickshaw.Graph.Behavior.Series.Order=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;if(typeof window.jQuery=="undefined"){throw"couldn't find jQuery at window.jQuery"}if(typeof window.jQuery.ui=="undefined"){throw"couldn't find jQuery UI at window.jQuery.ui"}jQuery(function(){jQuery(self.legend.list).sortable({containment:"parent",tolerance:"pointer",update:function(event,ui){var series=[];jQuery(self.legend.list).find("li").each(function(index,item){if(!item.series)return;series.push(item.series)});for(var i=self.graph.series.length-1;i>=0;i--){self.graph.series[i]=series.shift()}self.graph.update()}});jQuery(self.legend.list).disableSelection()});this.graph.onUpdate(function(){var h=window.getComputedStyle(self.legend.element).height;self.legend.element.style.height=h})};Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Toggle");Rickshaw.Graph.Behavior.Series.Toggle=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;this.addAnchor=function(line){var anchor=document.createElement("a");anchor.innerHTML="✔";anchor.classList.add("action");line.element.insertBefore(anchor,line.element.firstChild);anchor.onclick=function(e){if(line.series.disabled){line.series.enable();line.element.classList.remove("disabled")}else{if(this.graph.series.filter(function(s){return!s.disabled}).length<=1)return;line.series.disable();line.element.classList.add("disabled")}self.graph.update()}.bind(this);var label=line.element.getElementsByTagName("span")[0];label.onclick=function(e){var disableAllOtherLines=line.series.disabled;if(!disableAllOtherLines){for(var i=0;idomainX){dataIndex=Math.abs(domainX-data[i].x)0){alignables.forEach(function(el){el.classList.remove("left");el.classList.add("right")});var rightAlignError=this._calcLayoutError(alignables);if(rightAlignError>leftAlignError){alignables.forEach(function(el){el.classList.remove("right");el.classList.add("left")})}}if(typeof this.onRender=="function"){this.onRender(args)}},_calcLayoutError:function(alignables){var parentRect=this.element.parentNode.getBoundingClientRect();var error=0;var alignRight=alignables.forEach(function(el){var rect=el.getBoundingClientRect();if(!rect.width){return}if(rect.right>parentRect.right){error+=rect.right-parentRect.right}if(rect.left=self.previewWidth){frameAfterDrag[0]-=frameAfterDrag[1]-self.previewWidth;frameAfterDrag[1]=self.previewWidth}}self.graphs.forEach(function(graph){var domainScale=d3.scale.linear().interpolate(d3.interpolateNumber).domain([0,self.previewWidth]).range(graph.dataDomain());var windowAfterDrag=[domainScale(frameAfterDrag[0]),domainScale(frameAfterDrag[1])];self.slideCallbacks.forEach(function(callback){callback(graph,windowAfterDrag[0],windowAfterDrag[1])});if(frameAfterDrag[0]===0){windowAfterDrag[0]=undefined}if(frameAfterDrag[1]===self.previewWidth){windowAfterDrag[1]=undefined}graph.window.xMin=windowAfterDrag[0];graph.window.xMax=windowAfterDrag[1];graph.update()})}function onMousedown(){drag.target=d3.event.target;drag.start=self._getClientXFromEvent(d3.event,drag);self.frameBeforeDrag=self.currentFrame.slice();d3.event.preventDefault?d3.event.preventDefault():d3.event.returnValue=false;d3.select(document).on("mousemove.rickshaw_range_slider_preview",onMousemove);d3.select(document).on("mouseup.rickshaw_range_slider_preview",onMouseup);d3.select(document).on("touchmove.rickshaw_range_slider_preview",onMousemove);d3.select(document).on("touchend.rickshaw_range_slider_preview",onMouseup);d3.select(document).on("touchcancel.rickshaw_range_slider_preview",onMouseup)}function onMousedownLeftHandle(datum,index){drag.left=true;onMousedown()}function onMousedownRightHandle(datum,index){drag.right=true;onMousedown()}function onMousedownMiddleHandle(datum,index){drag.left=true;drag.right=true;drag.rigid=true;onMousedown()}function onMouseup(datum,index){d3.select(document).on("mousemove.rickshaw_range_slider_preview",null);d3.select(document).on("mouseup.rickshaw_range_slider_preview",null);d3.select(document).on("touchmove.rickshaw_range_slider_preview",null);d3.select(document).on("touchend.rickshaw_range_slider_preview",null);d3.select(document).on("touchcancel.rickshaw_range_slider_preview",null);delete self.frameBeforeDrag;drag.left=false;drag.right=false;drag.rigid=false}element.select("rect.left_handle").on("mousedown",onMousedownLeftHandle);element.select("rect.right_handle").on("mousedown",onMousedownRightHandle);element.select("rect.middle_handle").on("mousedown",onMousedownMiddleHandle);element.select("rect.left_handle").on("touchstart",onMousedownLeftHandle);element.select("rect.right_handle").on("touchstart",onMousedownRightHandle);element.select("rect.middle_handle").on("touchstart",onMousedownMiddleHandle)},_getClientXFromEvent:function(event,drag){switch(event.type){case"touchstart":case"touchmove":var touchList=event.changedTouches;var touch=null;for(var touchIndex=0;touchIndexyMax)yMax=y});if(!series.length)return;if(series[0].xxMax)xMax=series[series.length-1].x});xMin-=(xMax-xMin)*this.padding.left;xMax+=(xMax-xMin)*this.padding.right;yMin=this.graph.min==="auto"?yMin:this.graph.min||0;yMax=this.graph.max===undefined?yMax:this.graph.max;if(this.graph.min==="auto"||yMin<0){yMin-=(yMax-yMin)*this.padding.bottom}if(this.graph.max===undefined){yMax+=(yMax-yMin)*this.padding.top}return{x:[xMin,xMax],y:[yMin,yMax]}},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll("*").remove();var data=series.filter(function(s){return!s.disabled}).map(function(s){return s.stack});var pathNodes=vis.selectAll("path.path").data(data).enter().append("svg:path").classed("path",true).attr("d",this.seriesPathFactory());if(this.stroke){var strokeNodes=vis.selectAll("path.stroke").data(data).enter().append("svg:path").classed("stroke",true).attr("d",this.seriesStrokeFactory())}var i=0;series.forEach(function(series){if(series.disabled)return;series.path=pathNodes[0][i];if(this.stroke)series.stroke=strokeNodes[0][i];this._styleSeries(series);i++},this)},_styleSeries:function(series){var fill=this.fill?series.color:"none";var stroke=this.stroke?series.color:"none";series.path.setAttribute("fill",fill);series.path.setAttribute("stroke",stroke);series.path.setAttribute("stroke-width",this.strokeWidth);if(series.className){d3.select(series.path).classed(series.className,true)}if(series.className&&this.stroke){d3.select(series.stroke).classed(series.className,true)}},configure:function(args){args=args||{};Rickshaw.keys(this.defaults()).forEach(function(key){if(!args.hasOwnProperty(key)){this[key]=this[key]||this.graph[key]||this.defaults()[key];return}if(typeof this.defaults()[key]=="object"){Rickshaw.keys(this.defaults()[key]).forEach(function(k){this[key][k]=args[key][k]!==undefined?args[key][k]:this[key][k]!==undefined?this[key][k]:this.defaults()[key][k]},this)}else{this[key]=args[key]!==undefined?args[key]:this[key]!==undefined?this[key]:this.graph[key]!==undefined?this.graph[key]:this.defaults()[key]}},this)},setStrokeWidth:function(strokeWidth){if(strokeWidth!==undefined){this.strokeWidth=strokeWidth}},setTension:function(tension){if(tension!==undefined){this.tension=tension}}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Line");Rickshaw.Graph.Renderer.Line=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"line",defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:false,stroke:true})},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.line().x(function(d){return graph.x(d.x)}).y(function(d){return graph.y(d.y)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Stack");Rickshaw.Graph.Renderer.Stack=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"stack",defaults:function($super){return Rickshaw.extend($super(),{fill:true,stroke:false,unstack:false})},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.area().x(function(d){return graph.x(d.x)}).y0(function(d){return graph.y(d.y0)}).y1(function(d){return graph.y(d.y+d.y0)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Bar");Rickshaw.Graph.Renderer.Bar=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"bar",defaults:function($super){var defaults=Rickshaw.extend($super(),{gapSize:.05,unstack:false});delete defaults.tension;return defaults},initialize:function($super,args){args=args||{};this.gapSize=args.gapSize||this.gapSize;$super(args)},domain:function($super){var domain=$super();var frequentInterval=this._frequentInterval(this.graph.stackedData.slice(-1).shift());domain.x[1]+=Number(frequentInterval.magnitude);return domain},barWidth:function(series){var frequentInterval=this._frequentInterval(series.stack);var barWidth=this.graph.x.magnitude(frequentInterval.magnitude)*(1-this.gapSize);return barWidth},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll("*").remove();var barWidth=this.barWidth(series.active()[0]);var barXOffset=0;var activeSeriesCount=series.filter(function(s){return!s.disabled}).length;var seriesBarWidth=this.unstack?barWidth/activeSeriesCount:barWidth;var transform=function(d){var matrix=[1,0,0,d.y<0?-1:1,0,d.y<0?graph.y.magnitude(Math.abs(d.y))*2:0];return"matrix("+matrix.join(",")+")"};series.forEach(function(series){if(series.disabled)return;var barWidth=this.barWidth(series);var nodes=vis.selectAll("path").data(series.stack.filter(function(d){return d.y!==null})).enter().append("svg:rect").attr("x",function(d){return graph.x(d.x)+barXOffset}).attr("y",function(d){return graph.y(d.y0+Math.abs(d.y))*(d.y<0?-1:1)}).attr("width",seriesBarWidth).attr("height",function(d){return graph.y.magnitude(Math.abs(d.y))}).attr("transform",transform);Array.prototype.forEach.call(nodes[0],function(n){n.setAttribute("fill",series.color)});if(this.unstack)barXOffset+=seriesBarWidth},this)},_frequentInterval:function(data){var intervalCounts={};for(var i=0;i0){this[0].data.forEach(function(plot){item.data.push({x:plot.x,y:0})})}else if(item.data.length===0){item.data.push({x:this.timeBase-(this.timeInterval||0),y:0})}this.push(item);if(this.legend){this.legend.addLine(this.itemByName(item.name))}},addData:function(data,x){var index=this.getIndex();Rickshaw.keys(data).forEach(function(name){if(!this.itemByName(name)){this.addItem({name:name})}},this);this.forEach(function(item){item.data.push({x:x||(index*this.timeInterval||1)+this.timeBase,y:data[item.name]||0})},this)},getIndex:function(){return this[0]&&this[0].data&&this[0].data.length?this[0].data.length:0},itemByName:function(name){for(var i=0;i1;i--){this.currentSize+=1;this.currentIndex+=1;this.forEach(function(item){item.data.unshift({x:((i-1)*this.timeInterval||1)+this.timeBase,y:0,i:i})},this)}}},addData:function($super,data,x){$super(data,x);this.currentSize+=1;this.currentIndex+=1;if(this.maxDataPoints!==undefined){while(this.currentSize>this.maxDataPoints){this.dropData()}}},dropData:function(){this.forEach(function(item){item.data.splice(0,1)});this.currentSize-=1},getIndex:function(){return this.currentIndex}});return Rickshaw}); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.hbs b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.hbs new file mode 100644 index 00000000..e32cba43 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.hbs @@ -0,0 +1,68 @@ +{{#zone "topCss"}} + +{{/zone}} + +{{#zone "device-thumbnail"}} + +{{/zone}} + +{{#zone "device-opetations"}} +
+ Operations +
+
+ {{unit "iot.unit.device.operation-bar" device=device backendApiUri=backendApiUri autoCompleteParams=autoCompleteParams}} +
+{{/zone}} + +{{#zone "device-detail-properties"}} +
+ +
+
+ +
+
Device Statistics
+ {{unit "cdmf.unit.device.type.${deviceType}.realtime.analytics-view" device=device}} +
+
+
Operations Log
+
+ +
+
+ Not available yet +
+
+
+
+
+
+
+
+{{/zone}} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.js new file mode 100644 index 00000000..b0b65887 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.js @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +function onRequest(context) { + var log = new Log("device-view.js"); + var deviceType = context.uriParams.deviceType; + var deviceId = request.getParameter("id"); + var autoCompleteParams = [ + {"name" : "deviceId", "value" : deviceId} + ]; + + if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { + var deviceModule = require("/app/modules/device.js").deviceModule; + var device = deviceModule.viewDevice(deviceType, deviceId); + if (device && device.status != "error") { + return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/"+deviceType+"/", "autoCompleteParams" : autoCompleteParams}; + } else { + response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); + exit(); + } + } +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.json b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.json new file mode 100644 index 00000000..9eecd8f5 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/device-view.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/public/images/deviceType.png b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/public/images/deviceType.png new file mode 100644 index 00000000..766cd2ba Binary files /dev/null and b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.device-view/public/images/deviceType.png differ diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.hbs b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.hbs new file mode 100644 index 00000000..ad79ed4b --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.hbs @@ -0,0 +1,29 @@ +{{#zone "topCss"}} + {{css "css/graph.css"}} +{{/zone}} +
+
+
${nameOfTheSensor}
+
+
+
+
+
+
Time
+
+
+ + + + + View Device Analytics + + +{{#zone "bottomJs"}} + {{js "js/d3.min.js"}} + {{js "js/rickshaw.min.js"}} + {{js "js/moment.min.js"}} + {{js "js/socket.io.min.js"}} + {{js "js/device-stats.js"}} +{{/zone}} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.js new file mode 100644 index 00000000..78f6ab41 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.js @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +function onRequest(context) { + var log = new Log("stats.js"); + var device = context.unit.params.device; + var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); + var constants = require("/app/modules/constants.js"); + var websocketEndpoint = devicemgtProps["httpsURL"].replace("https", "wss"); + var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); + var token = ""; + if (tokenPair) { + token = tokenPair.accessToken; + } + websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.devices.${nameOfTheSensor}/1.0.0?" + + "token="+ token +"&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type; + return {"device": device, "websocketEndpoint" : websocketEndpoint}; +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.json b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.json new file mode 100644 index 00000000..688e9398 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/analytics-view.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/css/graph.css b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/css/graph.css new file mode 100644 index 00000000..7d0c9bba --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/css/graph.css @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* graph */ + +.rickshaw_graph { + position: relative; +} + +.rickshaw_graph svg { + display: block; + overflow: hidden; +} + +/* ticks */ + +.rickshaw_graph .x_tick { + position: absolute; + top: 0; + bottom: 0; + width: 0; + border-left: 1px dotted rgba(0, 0, 0, 0.2); + pointer-events: none; +} + +.rickshaw_graph .x_tick .title { + position: absolute; + font-size: 12px; + font-family: Arial, sans-serif; + opacity: 0.5; + white-space: nowrap; + margin-left: 3px; + bottom: -20px; + height: auto; + border-bottom: none; +} + +/* annotations */ + +.rickshaw_annotation_timeline { + height: 1px; + border-top: 1px solid #e0e0e0; + margin-top: 10px; + position: relative; +} + +.rickshaw_annotation_timeline .annotation { + position: absolute; + height: 6px; + width: 6px; + margin-left: -2px; + top: -3px; + border-radius: 5px; + background-color: rgba(0, 0, 0, 0.25); +} + +.rickshaw_graph .annotation_line { + position: absolute; + top: 0; + bottom: -6px; + width: 0; + border-left: 2px solid rgba(0, 0, 0, 0.3); + display: none; +} + +.rickshaw_graph .annotation_line.active { + display: block; +} + +.rickshaw_graph .annotation_range { + background: rgba(0, 0, 0, 0.1); + display: none; + position: absolute; + top: 0; + bottom: -6px; +} + +.rickshaw_graph .annotation_range.active { + display: block; +} + +.rickshaw_graph .annotation_range.active.offscreen { + display: none; +} + +.rickshaw_annotation_timeline .annotation .content { + background: white; + color: black; + opacity: 0.9; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.8); + border-radius: 3px; + position: relative; + z-index: 20; + font-size: 12px; + padding: 6px 8px 8px; + top: 18px; + left: -11px; + width: 160px; + display: none; + cursor: pointer; +} + +.rickshaw_annotation_timeline .annotation .content:before { + content: "\25b2"; + position: absolute; + top: -11px; + color: white; + text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8); +} + +.rickshaw_annotation_timeline .annotation.active, +.rickshaw_annotation_timeline .annotation:hover { + background-color: rgba(0, 0, 0, 0.8); + cursor: none; +} + +.rickshaw_annotation_timeline .annotation .content:hover { + z-index: 50; +} + +.rickshaw_annotation_timeline .annotation.active .content { + display: block; +} + +.rickshaw_annotation_timeline .annotation:hover .content { + display: block; + z-index: 50; +} + +.rickshaw_graph .y_axis, +.rickshaw_graph .x_axis_d3 { + fill: none; +} + +.rickshaw_graph .y_ticks .tick line, +.rickshaw_graph .x_ticks_d3 .tick { + stroke: rgba(0, 0, 0, 0.16); + stroke-width: 2px; + shape-rendering: crisp-edges; + pointer-events: none; +} + +.rickshaw_graph .y_grid .tick, +.rickshaw_graph .x_grid_d3 .tick { + z-index: -1; + stroke: rgba(0, 0, 0, 0.20); + stroke-width: 1px; + stroke-dasharray: 1 1; +} + +.rickshaw_graph .y_grid .tick[data-y-value="0"] { + stroke-dasharray: 1 0; +} + +.rickshaw_graph .y_grid path, +.rickshaw_graph .x_grid_d3 path { + fill: none; + stroke: none; +} + +.rickshaw_graph .y_ticks path, +.rickshaw_graph .x_ticks_d3 path { + fill: none; + stroke: #808080; +} + +.rickshaw_graph .y_ticks text, +.rickshaw_graph .x_ticks_d3 text { + opacity: 0.5; + font-size: 12px; + pointer-events: none; +} + +.rickshaw_graph .x_tick.glow .title, +.rickshaw_graph .y_ticks.glow text { + fill: black; + color: black; + text-shadow: -1px 1px 0 rgba(255, 255, 255, 0.1), + 1px -1px 0 rgba(255, 255, 255, 0.1), + 1px 1px 0 rgba(255, 255, 255, 0.1), + 0 1px 0 rgba(255, 255, 255, 0.1), + 0 -1px 0 rgba(255, 255, 255, 0.1), + 1px 0 0 rgba(255, 255, 255, 0.1), + -1px 0 0 rgba(255, 255, 255, 0.1), + -1px -1px 0 rgba(255, 255, 255, 0.1); +} + +.rickshaw_graph .x_tick.inverse .title, +.rickshaw_graph .y_ticks.inverse text { + fill: white; + color: white; + text-shadow: -1px 1px 0 rgba(0, 0, 0, 0.8), + 1px -1px 0 rgba(0, 0, 0, 0.8), + 1px 1px 0 rgba(0, 0, 0, 0.8), + 0 1px 0 rgba(0, 0, 0, 0.8), + 0 -1px 0 rgba(0, 0, 0, 0.8), + 1px 0 0 rgba(0, 0, 0, 0.8), + -1px 0 0 rgba(0, 0, 0, 0.8), + -1px -1px 0 rgba(0, 0, 0, 0.8); +} + +.custom_rickshaw_graph { + position: relative; + left: 40px; +} + +.custom_y_axis { + position: absolute; + width: 40px; + margin-top: -20px; +} + +.custom_slider { + left: 40px; +} + +.custom_x_axis { + position: relative; + left: 40px; + height: 30px; + width: 97%; + top: 20px; + text-align: right; +} + +.chartWrapper { + padding-top: 50px; +} + +/*detail*/ + +.rickshaw_graph .detail { + pointer-events: none; + position: absolute; + top: 0; + z-index: 2; + background: rgba(0, 0, 0, 0.1); + bottom: 0; + width: 1px; + transition: opacity 0.25s linear; + -moz-transition: opacity 0.25s linear; + -o-transition: opacity 0.25s linear; + -webkit-transition: opacity 0.25s linear; +} + +.rickshaw_graph .detail.inactive { + opacity: 0; +} + +.rickshaw_graph .detail .item.active { + opacity: 1; +} + +.rickshaw_graph .detail .x_label { + font-family: Arial, sans-serif; + border-radius: 3px; + padding: 6px; + opacity: 0.5; + border: 1px solid #e0e0e0; + font-size: 12px; + position: absolute; + background: white; + white-space: nowrap; +} + +.rickshaw_graph .detail .x_label.left { + left: 0; +} + +.rickshaw_graph .detail .x_label.right { + right: 0; +} + +.rickshaw_graph .detail .item { + position: absolute; + z-index: 2; + border-radius: 3px; + padding: 0.25em; + font-size: 12px; + font-family: Arial, sans-serif; + opacity: 0; + background: rgba(0, 0, 0, 0.4); + color: white; + border: 1px solid rgba(0, 0, 0, 0.4); + margin-left: 1em; + margin-right: 1em; + margin-top: -1em; + white-space: nowrap; +} + +.rickshaw_graph .detail .item.left { + left: 0; +} + +.rickshaw_graph .detail .item.right { + right: 0; +} + +.rickshaw_graph .detail .item.active { + opacity: 1; + background: rgba(0, 0, 0, 0.8); +} + +.rickshaw_graph .detail .item:after { + position: absolute; + display: block; + width: 0; + height: 0; + + content: ""; + + border: 5px solid transparent; +} + +.rickshaw_graph .detail .item.left:after { + top: 1em; + left: -5px; + margin-top: -5px; + border-right-color: rgba(0, 0, 0, 0.8); + border-left-width: 0; +} + +.rickshaw_graph .detail .item.right:after { + top: 1em; + right: -5px; + margin-top: -5px; + border-left-color: rgba(0, 0, 0, 0.8); + border-right-width: 0; +} + +.rickshaw_graph .detail .dot { + width: 4px; + height: 4px; + margin-left: -3px; + margin-top: -3.5px; + border-radius: 5px; + position: absolute; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); + box-sizing: content-box; + -moz-box-sizing: content-box; + background: white; + border-width: 2px; + border-style: solid; + display: none; + background-clip: padding-box; +} + +.rickshaw_graph .detail .dot.active { + display: block; +} + +/*legend*/ +.rickshaw_legend { + font-family: Arial; + font-size: 12px; + color: white; + background: #404040; + display: inline-block; + padding: 12px 5px; + border-radius: 2px; + position: relative; + float: right; +} + +.rickshaw_legend:hover { + z-index: 10; +} + +.rickshaw_legend .swatch { + width: 10px; + height: 10px; + border: 1px solid rgba(0, 0, 0, 0.2); +} + +.rickshaw_legend .line { + clear: both; + line-height: 140%; + padding-right: 15px; +} + +.rickshaw_legend .line .swatch { + display: inline-block; + margin-right: 3px; + border-radius: 2px; +} + +.rickshaw_legend .label { + margin: 0; + white-space: nowrap; + display: inline; + font-size: inherit; + background-color: transparent; + color: inherit; + font-weight: normal; + line-height: normal; + padding: 0; + text-shadow: none; +} + +.rickshaw_legend .action:hover { + opacity: 0.6; +} + +.rickshaw_legend .action { + margin-right: 0.2em; + opacity: 0.2; + cursor: pointer; + font-size: 14px; +} + +.rickshaw_legend .line.disabled { + opacity: 0.4; +} + +.rickshaw_legend ul { + list-style-type: none; + padding: 0; + margin: 2px; + cursor: pointer; +} + +.rickshaw_legend li { + padding: 0 0 0 2px; + min-width: 80px; + white-space: nowrap; +} + +.rickshaw_legend li:hover { + background: rgba(255, 255, 255, 0.08); + border-radius: 3px; +} + +.rickshaw_legend li:active { + background: rgba(255, 255, 255, 0.2); + border-radius: 3px; +} + +.legend { + display: inline-block; + position: relative; + left: 8px; +} + +.legend_container { + float: right; + padding-right: 10px; + width: 0; + z-index: 1; + position: relative; + opacity: 0.7; +} + +.spaced { + margin-top: 20px !important; +} + diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/d3.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/d3.min.js new file mode 100644 index 00000000..71f9715e --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/d3.min.js @@ -0,0 +1,9488 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +!function() { + var d3 = { + version: "3.5.2" + }; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; + try { + d3_array(d3_documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } + try { + d3_document.createElement("div").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; + } + d3.ascending = d3_ascending; + function d3_ascending(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + } + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + function d3_number(x) { + return x === null ? NaN : +x; + } + function d3_numeric(x) { + return !isNaN(x); + } + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; + } + return s; + }; + d3.mean = function(array, f) { + var s = 0, n = array.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; + } + if (j) return s / j; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + var numbers = [], n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); + } + if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); + }; + d3.variance = function(array, f) { + var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } + if (j > 1) return s / (j - 1); + }; + d3.deviation = function() { + var v = d3.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; + } + return lo; + } + }; + } + var d3_bisect = d3_bisector(d3_ascending); + d3.bisectLeft = d3_bisect.left; + d3.bisect = d3.bisectRight = d3_bisect.right; + d3.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); + }; + d3.shuffle = function(array, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array.length; + if (m < 2) i0 = 0; + } + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.zip = function() { + if (!(n = arguments.length)) return []; + for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { + for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { + zip[j] = arguments[j][i]; + } + } + return zips; + }; + function d3_zipLength(d) { + return d.length; + } + d3.transpose = function(matrix) { + return d3.zip.apply(d3, matrix); + }; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } + } + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } + } + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } + d3.map = function(object, f) { + var map = new d3_Map(); + if (object instanceof d3_Map) { + object.forEach(function(key, value) { + map.set(key, value); + }); + } else if (Array.isArray(object)) { + var i = -1, n = object.length, o; + if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); + } else { + for (var key in object) map.set(key, object[key]); + } + return map; + }; + function d3_Map() { + this._ = Object.create(null); + } + var d3_map_proto = "__proto__", d3_map_zero = "\x00"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value) { + return this._[d3_map_escape(key)] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; + } + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; + } + function d3_map_has(key) { + return d3_map_escape(key) in this._; + } + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; + } + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; + } + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; + } + function d3_map_empty() { + for (var key in this._) return false; + return true; + } + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() { + this._ = Object.create(null); + } + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } + }); + d3.behavior = {}; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; + } + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } + } + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; + } + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); + } + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; + } + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; + } + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; + } + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatcher = d3_documentElement.matches || d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3_selectionRoot; + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; + } + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; + } + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: "http://www.w3.org/1999/xhtml", + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0) { + prefix = name.slice(0, i); + name = name.slice(i + 1); + } + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; + } + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; + } + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; + } + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); + } + function d3_selection_classes(name) { + return (name + "").trim().split(/^|\s+/); + } + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; + } + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; + } + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name); + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); + return this; + } + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { + return this.ownerDocument.createElementNS(name.space, name.local); + } : function() { + return this.ownerDocument.createElementNS(this.namespaceURI, name); + }; + } + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); + } + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } + } + return value; + } + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.has(keyValue = key.call(node = group[i], node.__data__, i))) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues[i] = keyValue; + } + for (i = -1; ++i < m; ) { + if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } else if (node !== true) { + updateNodes[i] = node; + node.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.get(keyValues[i]) !== true) { + exitNodes[i] = group[i]; + } + } + } else { + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value); + } + } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; + } + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } + } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } + } + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; + } + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d3.select = function(node) { + var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + var d3_selectionRoot = d3.select(d3_documentElement); + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + } + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; + } + var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; + function d3_event_dragSuppress() { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect) { + var style = d3_documentElement.style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + var off = function() { + w.on(click, null); + }; + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; + } + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + } + d3.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); + } + } + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_behavior_dragMouseSubject, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_behavior_dragTouchSubject, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject()).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; + } else { + dragOffset = [ 0, 0 ]; + } + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx: dx, + dy: dy + }); + } + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged && d3.event.target === target); + dispatch({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + function d3_behavior_dragTouchId() { + return d3.event.changedTouches[0].identifier; + } + function d3_behavior_dragTouchSubject() { + return d3.event.target; + } + function d3_behavior_dragMouseSubject() { + return d3_window; + } + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + } + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; + var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; + function interpolate(t) { + var s = t * S; + if (dr) { + var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + } + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; + } + interpolate.duration = S * 1e3; + return interpolate; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { + g.each(function() { + var dispatch = event.of(this, arguments), view1 = view; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(dispatch); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); + return function(t) { + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k: k + }; + zoomed(dispatch); + }; + }).each("interrupt.zoom", function() { + zoomended(dispatch); + }).each("end.zoom", function() { + zoomended(dispatch); + }); + } else { + this.__chart__ = view; + zoomstarted(dispatch); + zoomed(dispatch); + zoomended(dispatch); + } + }); + }; + zoom.translate = function(_) { + if (!arguments.length) return [ view.x, view.y ]; + view = { + x: +_[0], + y: +_[1], + k: view.k + }; + rescale(); + return zoom; + }; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: +_ + }; + rescale(); + return zoom; + }; + zoom.scaleExtent = function(_) { + if (!arguments.length) return scaleExtent; + scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; + return zoom; + }; + zoom.center = function(_) { + if (!arguments.length) return center; + center = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.size = function(_) { + if (!arguments.length) return size; + size = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.duration = function(_) { + if (!arguments.length) return duration; + duration = +_; + return zoom; + }; + zoom.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + zoom.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + function location(p) { + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; + } + function point(l) { + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; + } + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d3.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" + }); + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }); + center0 = null; + } + function mousedowned() { + var that = this, target = d3.event.target, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d3.mouse(that), location0); + zoomed(dispatch); + } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged && d3.event.target === target); + zoomended(dispatch); + } + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d3.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d3.event.target; + d3.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; + } + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + d3.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); + } + } + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else translate0 = location(center0 = center || d3.mouse(this)), + d3_selection_interrupt.call(this), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ]; + var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); + d3.color = d3_color; + function d3_color() {} + d3_color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + } + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + } + d3.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + } + var d3_hclPrototype = d3_hcl.prototype = new d3_color(); + d3_hclPrototype.brighter = function(k) { + return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.darker = function(k) { + return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d3.lab = d3_lab; + function d3_lab(l, a, b) { + return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + } + var d3_lab_K = 18; + var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_lab.prototype = new d3_color(); + d3_labPrototype.brighter = function(k) { + return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + } + d3.rgb = d3_rgb; + function d3_rgb(r, g, b) { + return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + } + function d3_rgbNumber(value) { + return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, color; + m1 = /([a-z]+)\((.*)\)/i.exec(format); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } + + case "rgb": + { + return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + } + } + } + if (color = d3_rgb_names.get(format)) return rgb(color.r, color.g, color.b); + if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { + if (format.length === 4) { + r = (color & 3840) >> 4; + r = r >> 4 | r; + g = color & 240; + g = g >> 4 | g; + b = color & 15; + b = b << 4 | b; + } else if (format.length === 7) { + r = (color & 16711680) >> 16; + g = (color & 65280) >> 8; + b = color & 255; + } + } + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; + } else { + h = NaN; + s = l > 0 && l < 1 ? 0 : h; + } + return new d3_hsl(h, s, l); + } + function d3_rgb_lab(r, g, b) { + r = d3_rgb_xyz(r); + g = d3_rgb_xyz(g); + b = d3_rgb_xyz(b); + var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); + return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); + } + function d3_rgb_xyz(r) { + return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); + } + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + function d3_identity(d) { + return d; + } + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; + } + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); + } + } + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + function d3_xhrHasResponse(request) { + var type = request.responseType; + return type && type !== "text" ? request.response : request.responseText; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); + } + return text.slice(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); + } + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + f: false, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + }; + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(); + d3_timer_active = d3_timer_queueHead; + while (d3_timer_active) { + if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); + d3_timer_active = d3_timer_active.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.f) { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + } else { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } + } + d3_timer_queueTail = t0; + return time; + } + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { + var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = locale_grouping[j = (j + 1) % locale_grouping.length]; + } + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; + + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; + + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; + + case "b": + case "o": + case "x": + case "X": + if (symbol === "#") prefix = "0" + type.toLowerCase(); + + case "c": + exponent = false; + + case "d": + integer = true; + precision = 0; + break; + + case "s": + scale = -1; + type = "r"; + break; + } + if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; + if (type == "r" && !precision) type = "g"; + if (precision != null) { + if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); + } + type = d3_format_types.get(type) || d3_format_typeDefault; + var zcomma = zfill && comma; + return function(value) { + var fullSuffix = suffix; + if (integer && value % 1) return ""; + var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; + if (scale < 0) { + var unit = d3.formatPrefix(value, precision); + value = unit.scale(value); + fullSuffix = unit.symbol + suffix; + } else { + value *= scale; + } + value = type(value, precision); + var i = value.lastIndexOf("."), before, after; + if (i < 0) { + var j = exponent ? value.lastIndexOf("e") : -1; + if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); + } else { + before = value.substring(0, i); + after = locale_decimal + value.substring(i + 1); + } + if (!zfill && comma) before = formatGroup(before, Infinity); + var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; + if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); + negative += prefix; + value = before + after; + return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); + } + }); + function d3_format_typeDefault(x) { + return x + ""; + } + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + } + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); + } + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; + } + function ceil(date) { + step(date = local(new d3_date(date - 1)), 1); + return date; + } + function offset(date, k) { + step(date = new d3_date(+date), k); + return date; + } + function range(t0, t1, dt) { + var time = ceil(t0), times = []; + if (dt > 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); + } + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; + } + } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; + } + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; + } + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.slice(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.slice(j, i)); + return string.join(""); + } + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; + } + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + return d3_time_format; + } + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); + } + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + } + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; + } + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; + } + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; + } + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + } + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, + i + 5) : -1; + } + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); + } + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + } + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; + } + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; + } + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; + } + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; + } + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + } + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; + } + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; + } + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); + } + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } + } + var d3_geo_streamObjectType = { + Feature: function(feature, listener) { + d3_geo_streamGeometry(feature.geometry, listener); + }, + FeatureCollection: function(object, listener) { + var features = object.features, i = -1, n = features.length; + while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); + } + }; + var d3_geo_streamGeometryType = { + Sphere: function(object, listener) { + listener.sphere(); + }, + Point: function(object, listener) { + object = object.coordinates; + listener.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); + }, + LineString: function(object, listener) { + d3_geo_streamLine(object.coordinates, listener, 0); + }, + MultiLineString: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); + }, + Polygon: function(object, listener) { + d3_geo_streamPolygon(object.coordinates, listener); + }, + MultiPolygon: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); + }, + GeometryCollection: function(object, listener) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + } + }; + function d3_geo_streamLine(coordinates, listener, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + listener.lineStart(); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); + listener.lineEnd(); + } + function d3_geo_streamPolygon(coordinates, listener) { + var i = -1, n = coordinates.length; + listener.polygonStart(); + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); + listener.polygonEnd(); + } + d3.geo.area = function(object) { + d3_geo_areaSum = 0; + d3.geo.stream(object, d3_geo_area); + return d3_geo_areaSum; + }; + var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); + var d3_geo_area = { + sphere: function() { + d3_geo_areaSum += 4 * π; + }, + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_areaRingSum.reset(); + d3_geo_area.lineStart = d3_geo_areaRingStart; + }, + polygonEnd: function() { + var area = 2 * d3_geo_areaRingSum; + d3_geo_areaSum += area < 0 ? 4 * π + area : area; + d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + } + }; + function d3_geo_areaRingStart() { + var λ00, φ00, λ0, cosφ0, sinφ0; + d3_geo_area.point = function(λ, φ) { + d3_geo_area.point = nextPoint; + λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), + sinφ0 = Math.sin(φ); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + φ = φ * d3_radians / 2 + π / 4; + var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; + } + function d3_geo_cartesian(spherical) { + var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); + return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + } + function d3_geo_cartesianDot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + function linePoint(λ, φ) { + var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); + if (p0) { + var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); + d3_geo_cartesianNormalize(inflection); + inflection = d3_geo_spherical(inflection); + var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + if (antimeridian) { + if (λ < λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } else { + if (λ1 >= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } + } + } else { + point(λ, φ); + } + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); + } + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; + } + function d3_geo_centroidLineStart() { + var x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroid.point = nextPoint; + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_centroidLineEnd() { + d3_geo_centroid.point = d3_geo_centroidPoint; + } + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; + } + var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); + a.o = b; + subject.push(a); + clip.push(b); + a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); + b = new d3_geo_clipPolygonIntersection(p1, null, a, true); + a.o = b; + subject.push(a); + clip.push(b); + }); + clip.sort(compare); + d3_geo_clipPolygonLinkCircular(subject); + d3_geo_clipPolygonLinkCircular(clip); + if (!subject.length) return; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; + } + var start = subject[0], points, point; + while (1) { + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; + listener.lineStart(); + do { + current.v = current.o.v = true; + if (current.e) { + if (isSubject) { + for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.n.x, 1, listener); + } + current = current.n; + } else { + if (isSubject) { + points = current.p.z; + for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); + } + current = current.p; + } + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); + } + } + function d3_geo_clipPolygonLinkCircular(array) { + if (!(n = array.length)) return; + var n, i = 0, a = array[0], b; + while (++i < n) { + a.n = b = array[i]; + b.p = a; + a = b; + } + a.n = b = array[0]; + b.p = a; + } + function d3_geo_clipPolygonIntersection(point, points, other, entry) { + this.x = point; + this.z = points; + this.o = other; + this.e = entry; + this.v = false; + this.n = this.p = null; + } + function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { + return function(rotate, listener) { + var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + clip.point = pointRing; + clip.lineStart = ringStart; + clip.lineEnd = ringEnd; + segments = []; + polygon = []; + }, + polygonEnd: function() { + clip.point = point; + clip.lineStart = lineStart; + clip.lineEnd = lineEnd; + segments = d3.merge(segments); + var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); + if (segments.length) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); + } else if (clipStartInside) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (polygonStarted) listener.polygonEnd(), polygonStarted = false; + segments = polygon = null; + }, + sphere: function() { + listener.polygonStart(); + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + listener.polygonEnd(); + } + }; + function point(λ, φ) { + var point = rotate(λ, φ); + if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); + } + function pointLine(λ, φ) { + var point = rotate(λ, φ); + line.point(point[0], point[1]); + } + function lineStart() { + clip.point = pointLine; + line.lineStart(); + } + function lineEnd() { + clip.point = point; + line.lineEnd(); + } + var segments; + var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; + function pointRing(λ, φ) { + ring.push([ λ, φ ]); + var point = rotate(λ, φ); + ringListener.point(point[0], point[1]); + } + function ringStart() { + ringListener.lineStart(); + ring = []; + } + function ringEnd() { + pointRing(ring[0][0], ring[0][1]); + ringListener.lineEnd(); + var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; + ring.pop(); + polygon.push(ring); + ring = null; + if (!n) return; + if (clean & 1) { + segment = ringSegments[0]; + var n = segment.length - 1, i = -1, point; + if (n > 0) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); + } + return; + } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + } + return clip; + }; + } + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; + } + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; + } + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + } + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; + } + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + } + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); + } else { + listener.point(to[0], to[1]); + } + } + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); + polarAngle += antimeridian ? dλ + sdλ * τ : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } + } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + } + function d3_geo_clipCircle(radius) { + var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; + } + } + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line) { + var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; + } + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; + } + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; + } + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } + } + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; + } + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); + } + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); + } + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } + } else { + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } + } + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + } + function compare(a, b) { + return comparePoints(a.x, b.x); + } + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + } + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; + return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = ρ0 - y; + return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; + }; + return forward; + } + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; + } + }, lower48Point, alaskaPoint, hawaiiPoint; + function albersUsa(coordinates) { + var x = coordinates[0], y = coordinates[1]; + point = null; + (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); + return point; + } + albersUsa.invert = function(coordinates) { + var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; + return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); + } + }; + }; + albersUsa.precision = function(_) { + if (!arguments.length) return lower48.precision(); + lower48.precision(_); + alaska.precision(_); + hawaii.precision(_); + return albersUsa; + }; + albersUsa.scale = function(_) { + if (!arguments.length) return lower48.scale(); + lower48.scale(_); + alaska.scale(_ * .35); + hawaii.scale(_); + return albersUsa.translate(lower48.translate()); + }; + albersUsa.translate = function(_) { + if (!arguments.length) return lower48.translate(); + var k = lower48.scale(), x = +_[0], y = +_[1]; + lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; + alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + return albersUsa; + }; + return albersUsa.scale(1070); + }; + var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_pathAreaPolygon = 0; + d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; + }, + polygonEnd: function() { + d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); + } + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; + } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; + } + var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; + var d3_geo_pathBounds = { + point: d3_geo_pathBoundsPoint, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_pathBoundsPoint(x, y) { + if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; + if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; + } + } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); + } + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; + } + function pointLine(x, y) { + buffer.push("L", x, ",", y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + buffer.push("Z"); + } + return stream; + } + function d3_geo_pathBufferCircle(radius) { + return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; + } + var d3_geo_pathCentroid = { + point: d3_geo_pathCentroidPoint, + lineStart: d3_geo_pathCentroidLineStart, + lineEnd: d3_geo_pathCentroidLineEnd, + polygonStart: function() { + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; + }, + polygonEnd: function() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; + d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + } + }; + function d3_geo_pathCentroidPoint(x, y) { + d3_geo_centroidX0 += x; + d3_geo_centroidY0 += y; + ++d3_geo_centroidZ0; + } + function d3_geo_pathCentroidLineStart() { + var x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + } + function d3_geo_pathCentroidLineEnd() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + } + function d3_geo_pathCentroidRingStart() { + var x00, y00, x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + z = y0 * x - x0 * y; + d3_geo_centroidX2 += z * (x0 + x); + d3_geo_centroidY2 += z * (y0 + y); + d3_geo_centroidZ2 += z * 3; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + d3_geo_pathCentroid.lineEnd = function() { + nextPoint(x00, y00); + }; + } + function d3_geo_pathContext(context) { + var pointRadius = 4.5; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointRadius = _; + return stream; + }, + result: d3_noop + }; + function point(x, y) { + context.moveTo(x + pointRadius, y); + context.arc(x, y, pointRadius, 0, τ); + } + function pointLineStart(x, y) { + context.moveTo(x, y); + stream.point = pointLine; + } + function pointLine(x, y) { + context.lineTo(x, y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + context.closePath(); + } + return stream; + } + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); + } + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); + } + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; + } + }; + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + } + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); + } + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); + } + function lineEnd() { + resample.point = point; + stream.lineEnd(); + } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; + } + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; + } + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); + } + return resample; + } + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + } + } + } + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; + }; + return resample; + } + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); + } + return contextStream.result(); + } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; + } + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); + }); + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); + }; + } + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; + } + }; + }; + function d3_geo_transform(stream) { + this.stream = stream; + } + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); + } + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); + } + }; + } + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); + } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; + } + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + } + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); + } + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); + }; + } + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); + } + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; + } + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + } + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + } + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; + } + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; + } + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; + } + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] + }; + } + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); + }; + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; + } + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); + } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; + }); + }; + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + }; + }; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); + }; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); + }; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); + }; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); + }; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; + }; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; + }; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; + }; + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; + }); + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; + }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; + } + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; + } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + } + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + if (F > 0) { + if (φ < -halfπ + ε) φ = -halfπ + ε; + } else { + if (φ > halfπ - ε) φ = halfπ - ε; + } + var ρ = F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; + } + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; + }; + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; + }; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return rotate([ 0, 0, 90 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; + } + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; + } + return hull.slice(0, hs); + } + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; + } + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; + } + } + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; + } + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } + } + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; + } + }; + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } + } + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } + } + }); + return triangles; + }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); + }; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; + } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = xm; else x2 = xm; + if (below) y1 = ym; else y2 = ym; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - point[0], dy = y - point[1], distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; + } + } + var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; + + case 1: + find(node, xm, y1, x2, ym); + break; + + case 2: + find(node, x1, ym, xm, y2); + break; + + case 3: + find(node, xm, ym, x2, y2); + break; + } + } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); + }; + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } + } + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i: i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; + } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }); + } + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; + } + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; + } + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; + } + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; + } + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; + } + function d3_ease_quad(t) { + return t * t; + } + function d3_ease_cubic(t) { + return t * t * t; + } + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; + } + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); + } + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); + } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; + } + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; + }; + } + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); + }; + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; + } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; + } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; + } + return k; + } + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; + } + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 + }; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransform(a, b) { + var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; + if (ta[0] != tb[0] || ta[1] != tb[1]) { + s.push("translate(", null, ",", null, ")"); + q.push({ + i: 1, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: 3, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } else { + s.push(""); + } + if (ra != rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(s.pop() + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(s.pop() + "rotate(" + rb + ")"); + } + if (wa != wb) { + q.push({ + i: s.push(s.pop() + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(s.pop() + "skewX(" + wb + ")"); + } + if (ka[0] != kb[0] || ka[1] != kb[1]) { + n = s.push(s.pop() + "scale(", null, ",", null, ")"); + q.push({ + i: n - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: n - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] != 1 || kb[1] != 1) { + s.push(s.pop() + "scale(" + kb + ")"); + } + n = q.length; + return function(t) { + var i = -1, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + function d3_uninterpolateNumber(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return (x - a) / b; + }; + } + function d3_uninterpolateClamp(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return Math.max(0, Math.min(1, (x - a) / b)); + }; + } + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; + } + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; + } + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; + } + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; + } + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; + } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: (x - x0) / k + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); + } + } + } + if (sortChords) resort(); + } + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); + } + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad.point && dn && dn < chargeDistance2) { + var k = quad.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; + } + force.tick = function() { + if ((alpha *= .99) < .005) { + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight / (t.weight + s.weight)); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); + } + } + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; + } + } + event.tick({ + type: "tick", + alpha: alpha + }); + }; + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; + }; + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) alpha = x; else alpha = 0; + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + d3.timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, m = candidates.length, x; + while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); + } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; + } + function d3_layout_forceDragend(d) { + d.fixed &= ~6; + } + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; + } + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; + } + } + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function hierarchy(root) { + var stack = [ root ], nodes = [], node; + root.depth = 0; + while ((node = stack.pop()) != null) { + nodes.push(node); + if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { + var n, childs, child; + while (--n >= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; + } + if (value) node.value = 0; + node.children = childs; + } else { + if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; + delete node.children; + } + } + d3_layout_hierarchyVisitAfter(root, function(node) { + var childs, parent; + if (sort && (childs = node.children)) childs.sort(sort); + if (value && (parent = node.parent)) parent.value += node.value; + }); + return nodes; + } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + if (value) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; + } + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [ node ]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } + } + } + function d3_layout_hierarchyVisitAfter(node, callback) { + var nodes = [ node ], nodes2 = []; + while ((node = nodes.pop()) != null) { + nodes2.push(node); + if ((children = node.children) && (n = children.length)) { + var i = -1, n, children; + while (++i < n) nodes.push(children[i]); + } + } + while ((node = nodes2.pop()) != null) { + callback(node); + } + } + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie(data) { + var n = data.length, values = data.map(function(d, i) { + return +value.call(pie, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), k = (da - n * pa) / d3.sum(values), index = d3.range(n), arcs = [], v; + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie.value = function(_) { + if (!arguments.length) return value; + value = _; + return pie; + }; + pie.sort = function(_) { + if (!arguments.length) return sort; + sort = _; + return pie; + }; + pie.startAngle = function(_) { + if (!arguments.length) return startAngle; + startAngle = _; + return pie; + }; + pie.endAngle = function(_) { + if (!arguments.length) return endAngle; + endAngle = _; + return pie; + }; + pie.padAngle = function(_) { + if (!arguments.length) return padAngle; + padAngle = _; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } + } + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); + } + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; + } + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; + } + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } + } + } + return bins; + } + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r -= dr; + }); + } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; + } + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; + }; + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; + }; + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } + } + } + } + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); + } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); + } + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); + } + return nodes; + } + function wrapTree(root0) { + var root1 = { + A: null, + children: [ root0 ] + }, queue = [ root1 ], node1; + while ((node1 = queue.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i: i + }).a = child); + } + } + return root1.children[0]; + } + function firstWalk(v) { + var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; + } + } else if (w) { + v.z = w.z + separation(v._, w._); + } + v.parent.A = apportion(v, w, v.parent.A || siblings[0]); + } + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; + } + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; + } + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; + } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; + } + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; + } + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; + } + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; + } + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); + } + } + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; + } + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); + } + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } + } + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; + } + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); + } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; + } + } + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = 0; + root.y = 0; + root.dx = size[0]; + root.dy = size[1]; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; + } + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; + }; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; + }; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; + }; + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; + }; + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; + }; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; + }; + return d3_layout_hierarchyRebind(treemap, hierarchy); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } + return { + x: x, + y: y, + dx: dx, + dy: dy + }; + } + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; + }, + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; + } + }; + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; + } + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; + } + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; + } + function scale(x) { + return output(x); + } + scale.invert = function(y) { + return input(y); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); + }; + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); + }; + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); + }; + return rescale(); + } + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); + } + function d3_scale_linearNice(domain, m) { + return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + } + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; + } + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + } + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + if (format) { + var match = d3_format_re.exec(format); + match.shift(); + if (match[8] === "s") { + var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); + if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); + match[8] = "f"; + format = d3.format(match.join("")); + return function(d) { + return format(prefix.scale(d)) + prefix.symbol; + }; + } + if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); + format = match.join(""); + } else { + format = ",." + d3_scale_linearPrecision(range[2]) + "f"; + } + return d3.format(format); + } + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); + } + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); + } + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, + Math.floor), e; + return function(d) { + return d / pow(f(log(d) + e)) <= k ? format(d) : ""; + }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); + } + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); + }; + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; + } + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; + }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale; + }; + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, + 0) : (stop - start) / (domain.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; + }; + scale.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), + 0) : (stop - start) / (domain.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale; + }; + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; + }; + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; + }; + scale.rangeBand = function() { + return rangeBand; + }; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); + }; + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); + }; + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); + } + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; + } + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; + }; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); + }; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; + }; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; + } + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; + } + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; + }; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; + } + d3.svg = {}; + function d3_zero() { + return 0; + } + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); + } + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } + } else { + x0 = y0 = 0; + } + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if ((rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + if (x1 != null) { + var rc1 = Math.min(rc, (r1 - lc) / (kc + 1)), t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var rc0 = Math.min(rc, (r0 - lc) / (kc - 1)), t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + path.push("Z"); + return path.join(""); + } + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; + } + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; + }; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; + }; + arc.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc; + }; + arc.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc; + }; + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; + }; + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; + }; + arc.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc; + }; + arc.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; + } + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; + } + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; + } + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(r * r * d2 - D * D), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; + } + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.join("L"); + } + function d3_svg_lineLinearClosed(points) { + return d3_svg_lineLinear(points) + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); + } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); + } + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; + } + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; + } + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; + } + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id); + }; + d3_selectionPrototype.interrupt = function(name) { + return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, active; + if ((lock = this[ns]) && (active = lock[lock.active])) { + if (--lock.count) { + delete lock[lock.active]; + lock.active += .5; + } else { + delete this[ns]; + } + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; + } + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; + } + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection, name) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3_selectionRoot.transition(selection); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); + subgroup.push(subnode); + } + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_transition(subgroups, this.namespace, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) return this.node()[ns][id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node[ns][id].tween.remove(name); + } : function(node) { + node[ns][id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id, ns = groups.namespace; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node[ns][id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); + }; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; + } + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; + } + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node[ns][id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node[ns][id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } + } else { + d3_selection_each(this, function(node) { + var transition = node[ns][id]; + (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); + }); + } + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = node[ns][id0]; + d3_transitionNode(node, i, ns, id1, { + time: transition.time, + ease: transition.ease, + delay: transition.delay + transition.duration, + duration: transition.duration + }); + } + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id1); + }; + function d3_transitionNamespace(name) { + return name == null ? "__transition__" : "__transition_" + name + "__"; + } + function d3_transitionNode(node, i, ns, id, inherit) { + var lock = node[ns] || (node[ns] = { + active: 0, + count: 0 + }), transition = lock[id]; + if (!transition) { + var time = inherit.time; + transition = lock[id] = { + tween: new d3_Map(), + time: time, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + d3.timer(function(elapsed) { + var delay = transition.delay, duration, ease, timer = d3_timer_active, tweened = []; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + function start(elapsed) { + if (lock.active > id) return stop(); + var active = lock[lock.active]; + if (active) { + --lock.count; + delete lock[lock.active]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweened.push(value); + } + }); + ease = transition.ease; + duration = transition.duration; + d3.timer(function() { + timer.c = tick(elapsed || 1) ? d3_true : tick; + return 1; + }, 0, time); + } + function tick(elapsed) { + if (lock.active !== id) return 1; + var t = elapsed / duration, e = ease(t), n = tweened.length; + while (n > 0) { + tweened[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + return stop(); + } + } + function stop() { + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + }, 0, time); + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + } + lineEnter.attr(y2, sign * innerTickSize); + textEnter.attr(y1, sign * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); + } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = arguments; + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); + } + function d3_svg_axisY(selection, y0, y1) { + selection.attr("transform", function(d) { + var v0 = y0(d); + return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); + } + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); + } else { + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); + } + } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; + } else { + max = position; + } + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; + } + } + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); + } + } + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; + }; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } + } + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } + } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; + } + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; + } + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; + } + return brush; + }; + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; + } + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; + var d3_time_formatUtc = d3_time_format.utc; + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); + } + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; + }; + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); + }); + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); + }); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); + }; + scale.tickFormat = function() { + return format; + }; + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_time_scaleDate(t) { + return new Date(t); + } + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); + } + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); + } + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; + this.d3 = d3; +}(); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/device-stats.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/device-stats.js new file mode 100644 index 00000000..e3ea82f8 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/device-stats.js @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var ws; +var graph; +var chartData = []; +var palette = new Rickshaw.Color.Palette({scheme: "classic9"}); + +$(window).load(function () { + var tNow = new Date().getTime() / 1000; + for (var i = 0; i < 30; i++) { + chartData.push({ + x: tNow - (30 - i) * 15, + y: parseFloat(0) + }); + } + + graph = new Rickshaw.Graph({ + element: document.getElementById("chart"), + width: $("#div-chart").width() - 50, + height: 300, + renderer: "line", + padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2}, + xScale: d3.time.scale(), + series: [{ + 'color': palette.color(), + 'data': chartData, + 'name': "Temperature" + }] + }); + + graph.render(); + + var xAxis = new Rickshaw.Graph.Axis.Time({ + graph: graph + }); + + xAxis.render(); + + new Rickshaw.Graph.Axis.Y({ + graph: graph, + orientation: 'left', + height: 300, + tickFormat: Rickshaw.Fixtures.Number.formatKMBT, + element: document.getElementById('y_axis') + }); + + new Rickshaw.Graph.HoverDetail({ + graph: graph, + formatter: function (series, x, y) { + var date = '' + moment.unix(x*1000).format('Do MMM YYYY h:mm:ss a') + ''; + var swatch = ''; + return swatch + series.name + ": " + parseInt(y) + '
' + date; + } + }); + + var websocketUrl = $("#div-chart").data("websocketurl"); + connect(websocketUrl) +}); + +$(window).unload(function () { + disconnect(); +}); + +//websocket connection +function connect(target) { + if ('WebSocket' in window) { + ws = new WebSocket(target); + } else if ('MozWebSocket' in window) { + ws = new MozWebSocket(target); + } else { + console.log('WebSocket is not supported by this browser.'); + } + if (ws) { + ws.onmessage = function (event) { + var dataPoint = JSON.parse(event.data); + chartData.push({ + x: parseInt(dataPoint[4]) / 1000, + y: parseFloat(dataPoint[5]) + }); + chartData.shift(); + graph.update(); + }; + } +} + +function disconnect() { + if (ws != null) { + ws.close(); + ws = null; + } +} diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/moment.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/moment.min.js new file mode 100644 index 00000000..78e5aaad --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/moment.min.js @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! moment.js +//! version : 2.10.2 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com +!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return Ac.apply(null,arguments)}function b(a){Ac=a}function c(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}function e(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function f(a,b){var c,d=[];for(c=0;c0)for(c in Cc)d=Cc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function m(b){l(this,b),this._d=new Date(+b._d),Dc===!1&&(Dc=!0,a.updateOffset(this),Dc=!1)}function n(a){return a instanceof m||null!=a&&g(a,"_isAMomentObject")}function o(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function p(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&o(a[d])!==o(b[d]))&&g++;return g+f}function q(){}function r(a){return a?a.toLowerCase().replace("_","-"):a}function s(a){for(var b,c,d,e,f=0;f0;){if(d=t(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&p(e,c,!0)>=b-1)break;b--}f++}return null}function t(a){var b=null;if(!Ec[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Bc._abbr,require("./locale/"+a),u(b)}catch(c){}return Ec[a]}function u(a,b){var c;return a&&(c="undefined"==typeof b?w(a):v(a,b),c&&(Bc=c)),Bc._abbr}function v(a,b){return null!==b?(b.abbr=a,Ec[a]||(Ec[a]=new q),Ec[a].set(b),u(a),Ec[a]):(delete Ec[a],null)}function w(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Bc;if(!d(a)){if(b=t(a))return b;a=[a]}return s(a)}function x(a,b){var c=a.toLowerCase();Fc[c]=Fc[c+"s"]=Fc[b]=a}function y(a){return"string"==typeof a?Fc[a]||Fc[a.toLowerCase()]:void 0}function z(a){var b,c,d={};for(c in a)g(a,c)&&(b=y(c),b&&(d[b]=a[c]));return d}function A(b,c){return function(d){return null!=d?(C(this,b,d),a.updateOffset(this,c),this):B(this,b)}}function B(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function C(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function D(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=y(a),"function"==typeof this[a])return this[a](b);return this}function E(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.lengthb;b++)d[b]=Jc[d[b]]?Jc[d[b]]:G(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function I(a,b){return a.isValid()?(b=J(b,a.localeData()),Ic[b]||(Ic[b]=H(b)),Ic[b](a)):a.localeData().invalidDate()}function J(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Hc.lastIndex=0;d>=0&&Hc.test(a);)a=a.replace(Hc,c),Hc.lastIndex=0,d-=1;return a}function K(a,b,c){Yc[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function L(a,b){return g(Yc,a)?Yc[a](b._strict,b._locale):new RegExp(M(a))}function M(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function N(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=o(a)}),c=0;cd;d++){if(e=i([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function U(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),Q(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function V(b){return null!=b?(U(this,b),a.updateOffset(this,!0),this):B(this,"Month")}function W(){return Q(this.year(),this.month())}function X(a){var b,c=a._a;return c&&-2===a._pf.overflow&&(b=c[_c]<0||c[_c]>11?_c:c[ad]<1||c[ad]>Q(c[$c],c[_c])?ad:c[bd]<0||c[bd]>24||24===c[bd]&&(0!==c[cd]||0!==c[dd]||0!==c[ed])?bd:c[cd]<0||c[cd]>59?cd:c[dd]<0||c[dd]>59?dd:c[ed]<0||c[ed]>999?ed:-1,a._pf._overflowDayOfYear&&($c>b||b>ad)&&(b=ad),a._pf.overflow=b),a}function Y(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function Z(a,b){var c=!0;return h(function(){return c&&(Y(a),c=!1),b.apply(this,arguments)},b)}function $(a,b){hd[a]||(Y(b),hd[a]=!0)}function _(a){var b,c,d=a._i,e=id.exec(d);if(e){for(a._pf.iso=!0,b=0,c=jd.length;c>b;b++)if(jd[b][1].exec(d)){a._f=jd[b][0]+(e[6]||" ");break}for(b=0,c=kd.length;c>b;b++)if(kd[b][1].exec(d)){a._f+=kd[b][0];break}d.match(Vc)&&(a._f+="Z"),sa(a)}else a._isValid=!1}function aa(b){var c=ld.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(_(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ba(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function ca(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function da(a){return ea(a)?366:365}function ea(a){return a%4===0&&a%100!==0||a%400===0}function fa(){return ea(this.year())}function ga(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=za(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ha(a){return ga(a,this._week.dow,this._week.doy).week}function ia(){return this._week.dow}function ja(){return this._week.doy}function ka(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function la(a){var b=ga(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function ma(a,b,c,d,e){var f,g,h=ca(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:da(a-1)+g}}function na(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function oa(a,b,c){return null!=a?a:null!=b?b:c}function pa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function qa(a){var b,c,d,e,f=[];if(!a._d){for(d=pa(a),a._w&&null==a._a[ad]&&null==a._a[_c]&&ra(a),a._dayOfYear&&(e=oa(a._a[$c],d[$c]),a._dayOfYear>da(e)&&(a._pf._overflowDayOfYear=!0),c=ca(e,0,a._dayOfYear),a._a[_c]=c.getUTCMonth(),a._a[ad]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[bd]&&0===a._a[cd]&&0===a._a[dd]&&0===a._a[ed]&&(a._nextDay=!0,a._a[bd]=0),a._d=(a._useUTC?ca:ba).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[bd]=24)}}function ra(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=oa(b.GG,a._a[$c],ga(za(),1,4).year),d=oa(b.W,1),e=oa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=oa(b.gg,a._a[$c],ga(za(),f,g).year),d=oa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=ma(c,d,e,g,f),a._a[$c]=h.year,a._dayOfYear=h.dayOfYear}function sa(b){if(b._f===a.ISO_8601)return void _(b);b._a=[],b._pf.empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=J(b._f,b._locale).match(Gc)||[],c=0;c0&&b._pf.unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length),Jc[f]?(d?b._pf.empty=!1:b._pf.unusedTokens.push(f),P(f,d,b)):b._strict&&!d&&b._pf.unusedTokens.push(f);b._pf.charsLeftOver=i-j,h.length>0&&b._pf.unusedInput.push(h),b._pf.bigHour===!0&&b._a[bd]<=12&&(b._pf.bigHour=void 0),b._a[bd]=ta(b._locale,b._a[bd],b._meridiem),qa(b),X(b)}function ta(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function ua(a){var b,d,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;fg)&&(e=g,d=b));h(a,d||b)}function va(a){if(!a._d){var b=z(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],qa(a)}}function wa(a){var b,c=a._i,e=a._f;return a._locale=a._locale||w(a._l),null===c||void 0===e&&""===c?k({nullInput:!0}):("string"==typeof c&&(a._i=c=a._locale.preparse(c)),n(c)?new m(X(c)):(d(e)?ua(a):e?sa(a):xa(a),b=new m(X(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function xa(b){var c=b._i;void 0===c?b._d=new Date:e(c)?b._d=new Date(+c):"string"==typeof c?aa(b):d(c)?(b._a=f(c.slice(0),function(a){return parseInt(a,10)}),qa(b)):"object"==typeof c?va(b):"number"==typeof c?b._d=new Date(c):a.createFromInputFallback(b)}function ya(a,b,d,e,f){var g={};return"boolean"==typeof d&&(e=d,d=void 0),g._isAMomentObject=!0,g._useUTC=g._isUTC=f,g._l=d,g._i=a,g._f=b,g._strict=e,g._pf=c(),wa(g)}function za(a,b,c,d){return ya(a,b,c,d,!1)}function Aa(a,b){var c,e;if(1===b.length&&d(b[0])&&(b=b[0]),!b.length)return za();for(c=b[0],e=1;ea&&(a=-a,c="-"),c+E(~~(a/60),2)+b+E(~~a%60,2)})}function Ga(a){var b=(a||"").match(Vc)||[],c=b[b.length-1]||[],d=(c+"").match(qd)||["-",0,0],e=+(60*d[1])+o(d[2]);return"+"===d[0]?e:-e}function Ha(b,c){var d,f;return c._isUTC?(d=c.clone(),f=(n(b)||e(b)?+b:+za(b))-+d,d._d.setTime(+d._d+f),a.updateOffset(d,!1),d):za(b).local();return c._isUTC?za(b).zone(c._offset||0):za(b).local()}function Ia(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ja(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ga(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ia(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?Za(this,Ua(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ia(this)}function Ka(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function La(a){return this.utcOffset(0,a)}function Ma(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ia(this),"m")),this}function Na(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ga(this._i)),this}function Oa(a){return a=a?za(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Pa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Qa(){if(this._a){var a=this._isUTC?i(this._a):za(this._a);return this.isValid()&&p(this._a,a.toArray())>0}return!1}function Ra(){return!this._isUTC}function Sa(){return this._isUTC}function Ta(){return this._isUTC&&0===this._offset}function Ua(a,b){var c,d,e,f=a,h=null;return Ea(a)?f={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(f={},b?f[b]=a:f.milliseconds=a):(h=rd.exec(a))?(c="-"===h[1]?-1:1,f={y:0,d:o(h[ad])*c,h:o(h[bd])*c,m:o(h[cd])*c,s:o(h[dd])*c,ms:o(h[ed])*c}):(h=sd.exec(a))?(c="-"===h[1]?-1:1,f={y:Va(h[2],c),M:Va(h[3],c),d:Va(h[4],c),h:Va(h[5],c),m:Va(h[6],c),s:Va(h[7],c),w:Va(h[8],c)}):null==f?f={}:"object"==typeof f&&("from"in f||"to"in f)&&(e=Xa(za(f.from),za(f.to)),f={},f.ms=e.milliseconds,f.M=e.months),d=new Da(f),Ea(a)&&g(a,"_locale")&&(d._locale=a._locale),d}function Va(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Wa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Xa(a,b){var c;return b=Ha(b,a),a.isBefore(b)?c=Wa(a,b):(c=Wa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Ya(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||($(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ua(c,d),Za(this,e,a),this}}function Za(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&C(b,"Date",B(b,"Date")+g*d),h&&U(b,B(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function $a(a){var b=a||za(),c=Ha(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,za(b)))}function _a(){return new m(this)}function ab(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+this>+a):(c=n(a)?+a:+za(a),c<+this.clone().startOf(b))}function bb(a,b){var c;return b=y("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=n(a)?a:za(a),+a>+this):(c=n(a)?+a:+za(a),+this.clone().endOf(b)a?Math.ceil(a):Math.floor(a)}function fb(a,b,c){var d,e,f=Ha(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=y(b),"year"===b||"month"===b||"quarter"===b?(e=gb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:eb(e)}function gb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function hb(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function ib(){var a=this.clone().utc();return 0b;b++)if(this._weekdaysParse[b]||(c=za([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Jb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Eb(a,this.localeData()),this.add(a-b,"d")):b}function Kb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Lb(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Mb(a,b){F(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Nb(a,b){return b._meridiemParse}function Ob(a){return"p"===(a+"").toLowerCase().charAt(0)}function Pb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Qb(a){F(0,[a,3],0,"millisecond")}function Rb(){return this._isUTC?"UTC":""}function Sb(){return this._isUTC?"Coordinated Universal Time":""}function Tb(a){return za(1e3*a)}function Ub(){return za.apply(null,arguments).parseZone()}function Vb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Wb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function Xb(){return this._invalidDate}function Yb(a){return this._ordinal.replace("%d",a)}function Zb(a){return a}function $b(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function _b(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function ac(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function bc(a,b,c,d){var e=w(),f=i().set(d,b);return e[c](f,a)}function cc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return bc(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=bc(a,f,c,e);return g}function dc(a,b){return cc(a,b,"months",12,"month")}function ec(a,b){return cc(a,b,"monthsShort",12,"month")}function fc(a,b){return cc(a,b,"weekdays",7,"day")}function gc(a,b){return cc(a,b,"weekdaysShort",7,"day")}function hc(a,b){return cc(a,b,"weekdaysMin",7,"day")}function ic(){var a=this._data;return this._milliseconds=Od(this._milliseconds),this._days=Od(this._days),this._months=Od(this._months),a.milliseconds=Od(a.milliseconds),a.seconds=Od(a.seconds),a.minutes=Od(a.minutes),a.hours=Od(a.hours),a.months=Od(a.months),a.years=Od(a.years),this}function jc(a,b,c,d){var e=Ua(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function kc(a,b){return jc(this,a,b,1)}function lc(a,b){return jc(this,a,b,-1)}function mc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=eb(d/1e3),g.seconds=a%60,b=eb(a/60),g.minutes=b%60,c=eb(b/60),g.hours=c%24,e+=eb(c/24),h=eb(nc(e)),e-=eb(oc(h)),f+=eb(e/30),e%=30,h+=eb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function nc(a){return 400*a/146097}function oc(a){return 146097*a/400}function pc(a){var b,c,d=this._milliseconds;if(a=y(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*nc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(oc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 24*b*60+d/6e4;case"second":return 24*b*60*60+d/1e3;case"millisecond":return Math.floor(24*b*60*60*1e3)+d;default:throw new Error("Unknown unit "+a)}}function qc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*o(this._months/12)}function rc(a){return function(){return this.as(a)}}function sc(a){return a=y(a),this[a+"s"]()}function tc(a){return function(){return this._data[a]}}function uc(){return eb(this.days()/7)}function vc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function wc(a,b,c){var d=Ua(a).abs(),e=ce(d.as("s")),f=ce(d.as("m")),g=ce(d.as("h")),h=ce(d.as("d")),i=ce(d.as("M")),j=ce(d.as("y")),k=e0,k[4]=c,vc.apply(null,k)}function xc(a,b){return void 0===de[a]?!1:void 0===b?de[a]:(de[a]=b,!0)}function yc(a){var b=this.localeData(),c=wc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function zc(){var a=ee(this.years()),b=ee(this.months()),c=ee(this.days()),d=ee(this.hours()),e=ee(this.minutes()),f=ee(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Ac,Bc,Cc=a.momentProperties=[],Dc=!1,Ec={},Fc={},Gc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Hc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ic={},Jc={},Kc=/\d/,Lc=/\d\d/,Mc=/\d{3}/,Nc=/\d{4}/,Oc=/[+-]?\d{6}/,Pc=/\d\d?/,Qc=/\d{1,3}/,Rc=/\d{1,4}/,Sc=/[+-]?\d{1,6}/,Tc=/\d+/,Uc=/[+-]?\d+/,Vc=/Z|[+-]\d\d:?\d\d/gi,Wc=/[+-]?\d+(\.\d{1,3})?/,Xc=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Yc={},Zc={},$c=0,_c=1,ad=2,bd=3,cd=4,dd=5,ed=6;F("M",["MM",2],"Mo",function(){return this.month()+1}),F("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),F("MMMM",0,0,function(a){return this.localeData().months(this,a)}),x("month","M"),K("M",Pc),K("MM",Pc,Lc),K("MMM",Xc),K("MMMM",Xc),N(["M","MM"],function(a,b){b[_c]=o(a)-1}),N(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[_c]=e:c._pf.invalidMonth=a});var fd="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),gd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),hd={};a.suppressDeprecationWarnings=!1;var id=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,jd=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],kd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],ld=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=Z("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),F(0,["YY",2],0,function(){return this.year()%100}),F(0,["YYYY",4],0,"year"),F(0,["YYYYY",5],0,"year"),F(0,["YYYYYY",6,!0],0,"year"),x("year","y"),K("Y",Uc),K("YY",Pc,Lc),K("YYYY",Rc,Nc),K("YYYYY",Sc,Oc),K("YYYYYY",Sc,Oc),N(["YYYY","YYYYY","YYYYYY"],$c),N("YY",function(b,c){c[$c]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return o(a)+(o(a)>68?1900:2e3)};var md=A("FullYear",!1);F("w",["ww",2],"wo","week"),F("W",["WW",2],"Wo","isoWeek"),x("week","w"),x("isoWeek","W"),K("w",Pc),K("ww",Pc,Lc),K("W",Pc),K("WW",Pc,Lc),O(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=o(a)});var nd={dow:0,doy:6};F("DDD",["DDDD",3],"DDDo","dayOfYear"),x("dayOfYear","DDD"),K("DDD",Qc),K("DDDD",Mc),N(["DDD","DDDD"],function(a,b,c){c._dayOfYear=o(a)}),a.ISO_8601=function(){};var od=Z("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return this>a?this:a}),pd=Z("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=za.apply(null,arguments);return a>this?this:a});Fa("Z",":"),Fa("ZZ",""),K("Z",Vc),K("ZZ",Vc),N(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ga(a)});var qd=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var rd=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,sd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Ua.fn=Da.prototype;var td=Ya(1,"add"),ud=Ya(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var vd=Z("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});F(0,["gg",2],0,function(){return this.weekYear()%100}),F(0,["GG",2],0,function(){return this.isoWeekYear()%100}),xb("gggg","weekYear"),xb("ggggg","weekYear"),xb("GGGG","isoWeekYear"),xb("GGGGG","isoWeekYear"),x("weekYear","gg"),x("isoWeekYear","GG"),K("G",Uc),K("g",Uc),K("GG",Pc,Lc),K("gg",Pc,Lc),K("GGGG",Rc,Nc),K("gggg",Rc,Nc),K("GGGGG",Sc,Oc),K("ggggg",Sc,Oc),O(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=o(a)}),O(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),F("Q",0,0,"quarter"),x("quarter","Q"),K("Q",Kc),N("Q",function(a,b){b[_c]=3*(o(a)-1)}),F("D",["DD",2],"Do","date"),x("date","D"),K("D",Pc),K("DD",Pc,Lc),K("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),N(["D","DD"],ad),N("Do",function(a,b){b[ad]=o(a.match(Pc)[0],10)});var wd=A("Date",!0);F("d",0,"do","day"),F("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),F("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),F("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),F("e",0,0,"weekday"),F("E",0,0,"isoWeekday"),x("day","d"),x("weekday","e"),x("isoWeekday","E"),K("d",Pc),K("e",Pc),K("E",Pc),K("dd",Xc),K("ddd",Xc),K("dddd",Xc),O(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:c._pf.invalidWeekday=a}),O(["d","e","E"],function(a,b,c,d){b[d]=o(a)});var xd="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),yd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),zd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");F("H",["HH",2],0,"hour"),F("h",["hh",2],0,function(){return this.hours()%12||12}),Mb("a",!0),Mb("A",!1),x("hour","h"),K("a",Nb),K("A",Nb),K("H",Pc),K("h",Pc),K("HH",Pc,Lc),K("hh",Pc,Lc),N(["H","HH"],bd),N(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),N(["h","hh"],function(a,b,c){b[bd]=o(a),c._pf.bigHour=!0});var Ad=/[ap]\.?m?\.?/i,Bd=A("Hours",!0);F("m",["mm",2],0,"minute"),x("minute","m"),K("m",Pc),K("mm",Pc,Lc),N(["m","mm"],cd);var Cd=A("Minutes",!1);F("s",["ss",2],0,"second"),x("second","s"),K("s",Pc),K("ss",Pc,Lc),N(["s","ss"],dd);var Dd=A("Seconds",!1);F("S",0,0,function(){return~~(this.millisecond()/100)}),F(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Qb("SSS"),Qb("SSSS"),x("millisecond","ms"),K("S",Qc,Kc),K("SS",Qc,Lc),K("SSS",Qc,Mc),K("SSSS",Tc),N(["S","SS","SSS","SSSS"],function(a,b){b[ed]=o(1e3*("0."+a))});var Ed=A("Milliseconds",!1);F("z",0,0,"zoneAbbr"),F("zz",0,0,"zoneName");var Fd=m.prototype;Fd.add=td,Fd.calendar=$a,Fd.clone=_a,Fd.diff=fb,Fd.endOf=pb,Fd.format=jb,Fd.from=kb,Fd.fromNow=lb,Fd.get=D,Fd.invalidAt=wb,Fd.isAfter=ab,Fd.isBefore=bb,Fd.isBetween=cb,Fd.isSame=db,Fd.isValid=ub,Fd.lang=vd,Fd.locale=mb,Fd.localeData=nb,Fd.max=pd,Fd.min=od,Fd.parsingFlags=vb,Fd.set=D,Fd.startOf=ob,Fd.subtract=ud,Fd.toArray=tb,Fd.toDate=sb,Fd.toISOString=ib,Fd.toJSON=ib,Fd.toString=hb,Fd.unix=rb,Fd.valueOf=qb,Fd.year=md,Fd.isLeapYear=fa,Fd.weekYear=zb,Fd.isoWeekYear=Ab,Fd.quarter=Fd.quarters=Db,Fd.month=V,Fd.daysInMonth=W,Fd.week=Fd.weeks=ka,Fd.isoWeek=Fd.isoWeeks=la,Fd.weeksInYear=Cb,Fd.isoWeeksInYear=Bb,Fd.date=wd,Fd.day=Fd.days=Jb,Fd.weekday=Kb,Fd.isoWeekday=Lb,Fd.dayOfYear=na,Fd.hour=Fd.hours=Bd,Fd.minute=Fd.minutes=Cd,Fd.second=Fd.seconds=Dd,Fd.millisecond=Fd.milliseconds=Ed,Fd.utcOffset=Ja,Fd.utc=La,Fd.local=Ma,Fd.parseZone=Na,Fd.hasAlignedHourOffset=Oa,Fd.isDST=Pa,Fd.isDSTShifted=Qa,Fd.isLocal=Ra,Fd.isUtcOffset=Sa,Fd.isUtc=Ta,Fd.isUTC=Ta,Fd.zoneAbbr=Rb,Fd.zoneName=Sb,Fd.dates=Z("dates accessor is deprecated. Use date instead.",wd),Fd.months=Z("months accessor is deprecated. Use month instead",V),Fd.years=Z("years accessor is deprecated. Use year instead",md),Fd.zone=Z("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Ka);var Gd=Fd,Hd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Id={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Jd="Invalid date",Kd="%d",Ld=/\d{1,2}/,Md={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Nd=q.prototype;Nd._calendar=Hd,Nd.calendar=Vb,Nd._longDateFormat=Id,Nd.longDateFormat=Wb,Nd._invalidDate=Jd,Nd.invalidDate=Xb,Nd._ordinal=Kd,Nd.ordinal=Yb,Nd._ordinalParse=Ld, +Nd.preparse=Zb,Nd.postformat=Zb,Nd._relativeTime=Md,Nd.relativeTime=$b,Nd.pastFuture=_b,Nd.set=ac,Nd.months=R,Nd._months=fd,Nd.monthsShort=S,Nd._monthsShort=gd,Nd.monthsParse=T,Nd.week=ha,Nd._week=nd,Nd.firstDayOfYear=ja,Nd.firstDayOfWeek=ia,Nd.weekdays=Fb,Nd._weekdays=xd,Nd.weekdaysMin=Hb,Nd._weekdaysMin=zd,Nd.weekdaysShort=Gb,Nd._weekdaysShort=yd,Nd.weekdaysParse=Ib,Nd.isPM=Ob,Nd._meridiemParse=Ad,Nd.meridiem=Pb,u("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===o(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=Z("moment.lang is deprecated. Use moment.locale instead.",u),a.langData=Z("moment.langData is deprecated. Use moment.localeData instead.",w);var Od=Math.abs,Pd=rc("ms"),Qd=rc("s"),Rd=rc("m"),Sd=rc("h"),Td=rc("d"),Ud=rc("w"),Vd=rc("M"),Wd=rc("y"),Xd=tc("milliseconds"),Yd=tc("seconds"),Zd=tc("minutes"),$d=tc("hours"),_d=tc("days"),ae=tc("months"),be=tc("years"),ce=Math.round,de={s:45,m:45,h:22,d:26,M:11},ee=Math.abs,fe=Da.prototype;fe.abs=ic,fe.add=kc,fe.subtract=lc,fe.as=pc,fe.asMilliseconds=Pd,fe.asSeconds=Qd,fe.asMinutes=Rd,fe.asHours=Sd,fe.asDays=Td,fe.asWeeks=Ud,fe.asMonths=Vd,fe.asYears=Wd,fe.valueOf=qc,fe._bubble=mc,fe.get=sc,fe.milliseconds=Xd,fe.seconds=Yd,fe.minutes=Zd,fe.hours=$d,fe.days=_d,fe.weeks=uc,fe.months=ae,fe.years=be,fe.humanize=yc,fe.toISOString=zc,fe.toString=zc,fe.toJSON=zc,fe.locale=mb,fe.localeData=nb,fe.toIsoString=Z("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",zc),fe.lang=vd,F("X",0,0,"unix"),F("x",0,0,"valueOf"),K("x",Uc),K("X",Wc),N("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),N("x",function(a,b,c){c._d=new Date(o(a))}),a.version="2.10.2",b(za),a.fn=Gd,a.min=Ba,a.max=Ca,a.utc=i,a.unix=Tb,a.months=dc,a.isDate=e,a.locale=u,a.invalid=k,a.duration=Ua,a.isMoment=n,a.weekdays=fc,a.parseZone=Ub,a.localeData=w,a.isDuration=Ea,a.monthsShort=ec,a.weekdaysMin=hc,a.defineLocale=v,a.weekdaysShort=gc,a.normalizeUnits=y,a.relativeTimeThreshold=xc;var ge=a;return ge}); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/rickshaw.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/rickshaw.min.js new file mode 100644 index 00000000..be060e0b --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/rickshaw.min.js @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +(function(root,factory){if(typeof define==="function"&&define.amd){define(["d3.min"],function(d3){return root.Rickshaw=factory(d3)})}else if(typeof exports==="object"){module.exports=factory(require("d3"))}else{root.Rickshaw=factory(d3)}})(this,function(d3){var Rickshaw={namespace:function(namespace,obj){var parts=namespace.split(".");var parent=Rickshaw;for(var i=1,length=parts.length;i0){var x=s.data[0].x;var y=s.data[0].y;if(typeof x!="number"||typeof y!="number"&&y!==null){throw"x and y properties of points should be numbers instead of "+typeof x+" and "+typeof y}}if(s.data.length>=3){if(s.data[2].xthis.window.xMax)isInRange=false;return isInRange}return true};this.onUpdate=function(callback){this.updateCallbacks.push(callback)};this.onConfigure=function(callback){this.configureCallbacks.push(callback)};this.registerRenderer=function(renderer){this._renderers=this._renderers||{};this._renderers[renderer.name]=renderer};this.configure=function(args){this.config=this.config||{};if(args.width||args.height){this.setSize(args)}Rickshaw.keys(this.defaults).forEach(function(k){this.config[k]=k in args?args[k]:k in this?this[k]:this.defaults[k]},this);Rickshaw.keys(this.config).forEach(function(k){this[k]=this.config[k]},this);if("stack"in args)args.unstack=!args.stack;var renderer=args.renderer||this.renderer&&this.renderer.name||"stack";this.setRenderer(renderer,args);this.configureCallbacks.forEach(function(callback){callback(args)})};this.setRenderer=function(r,args){if(typeof r=="function"){this.renderer=new r({graph:self});this.registerRenderer(this.renderer)}else{if(!this._renderers[r]){throw"couldn't find renderer "+r}this.renderer=this._renderers[r]}if(typeof args=="object"){this.renderer.configure(args)}};this.setSize=function(args){args=args||{};if(typeof window!==undefined){var style=window.getComputedStyle(this.element,null);var elementWidth=parseInt(style.getPropertyValue("width"),10);var elementHeight=parseInt(style.getPropertyValue("height"),10)}this.width=args.width||elementWidth||400;this.height=args.height||elementHeight||250;this.vis&&this.vis.attr("width",this.width).attr("height",this.height)};this.initialize(args)};Rickshaw.namespace("Rickshaw.Fixtures.Color");Rickshaw.Fixtures.Color=function(){this.schemes={};this.schemes.spectrum14=["#ecb796","#dc8f70","#b2a470","#92875a","#716c49","#d2ed82","#bbe468","#a1d05d","#e7cbe6","#d8aad6","#a888c2","#9dc2d3","#649eb9","#387aa3"].reverse();this.schemes.spectrum2000=["#57306f","#514c76","#646583","#738394","#6b9c7d","#84b665","#a7ca50","#bfe746","#e2f528","#fff726","#ecdd00","#d4b11d","#de8800","#de4800","#c91515","#9a0000","#7b0429","#580839","#31082b"];this.schemes.spectrum2001=["#2f243f","#3c2c55","#4a3768","#565270","#6b6b7c","#72957f","#86ad6e","#a1bc5e","#b8d954","#d3e04e","#ccad2a","#cc8412","#c1521d","#ad3821","#8a1010","#681717","#531e1e","#3d1818","#320a1b"];this.schemes.classic9=["#423d4f","#4a6860","#848f39","#a2b73c","#ddcb53","#c5a32f","#7d5836","#963b20","#7c2626","#491d37","#2f254a"].reverse();this.schemes.httpStatus={503:"#ea5029",502:"#d23f14",500:"#bf3613",410:"#efacea",409:"#e291dc",403:"#f457e8",408:"#e121d2",401:"#b92dae",405:"#f47ceb",404:"#a82a9f",400:"#b263c6",301:"#6fa024",302:"#87c32b",307:"#a0d84c",304:"#28b55c",200:"#1a4f74",206:"#27839f",201:"#52adc9",202:"#7c979f",203:"#a5b8bd",204:"#c1cdd1"};this.schemes.colorwheel=["#b5b6a9","#858772","#785f43","#96557e","#4682b4","#65b9ac","#73c03a","#cb513a"].reverse();this.schemes.cool=["#5e9d2f","#73c03a","#4682b4","#7bc3b8","#a9884e","#c1b266","#a47493","#c09fb5"];this.schemes.munin=["#00cc00","#0066b3","#ff8000","#ffcc00","#330099","#990099","#ccff00","#ff0000","#808080","#008f00","#00487d","#b35a00","#b38f00","#6b006b","#8fb300","#b30000","#bebebe","#80ff80","#80c9ff","#ffc080","#ffe680","#aa80ff","#ee00cc","#ff8080","#666600","#ffbfff","#00ffcc","#cc6699","#999900"]};Rickshaw.namespace("Rickshaw.Fixtures.RandomData");Rickshaw.Fixtures.RandomData=function(timeInterval){var addData;timeInterval=timeInterval||1;var lastRandomValue=200;var timeBase=Math.floor((new Date).getTime()/1e3);this.addData=function(data){var randomValue=Math.random()*100+15+lastRandomValue;var index=data[0].length;var counter=1;data.forEach(function(series){var randomVariance=Math.random()*20;var v=randomValue/25+counter++ +(Math.cos(index*counter*11/960)+2)*15+(Math.cos(index/7)+2)*7+(Math.cos(index/17)+2)*1;series.push({x:index*timeInterval+timeBase,y:v+randomVariance})});lastRandomValue=randomValue*.85};this.removeData=function(data){data.forEach(function(series){series.shift()});timeBase+=timeInterval}};Rickshaw.namespace("Rickshaw.Fixtures.Time");Rickshaw.Fixtures.Time=function(){var self=this;this.months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];this.units=[{name:"decade",seconds:86400*365.25*10,formatter:function(d){return parseInt(d.getUTCFullYear()/10,10)*10}},{name:"year",seconds:86400*365.25,formatter:function(d){return d.getUTCFullYear()}},{name:"month",seconds:86400*30.5,formatter:function(d){return self.months[d.getUTCMonth()]}},{name:"week",seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:"day",seconds:86400,formatter:function(d){return d.getUTCDate()}},{name:"6 hour",seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:"hour",seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:"15 minute",seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:"minute",seconds:60,formatter:function(d){return d.getUTCMinutes()}},{name:"15 second",seconds:15,formatter:function(d){return d.getUTCSeconds()+"s"}},{name:"second",seconds:1,formatter:function(d){return d.getUTCSeconds()+"s"}},{name:"decisecond",seconds:1/10,formatter:function(d){return d.getUTCMilliseconds()+"ms"}},{name:"centisecond",seconds:1/100,formatter:function(d){return d.getUTCMilliseconds()+"ms"}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift()};this.formatDate=function(d){return d3.time.format("%b %e")(d)};this.formatTime=function(d){return d.toUTCString().match(/(\d+:\d+):/)[1]};this.ceil=function(time,unit){var date,floor,year;if(unit.name=="month"){date=new Date(time*1e3);floor=Date.UTC(date.getUTCFullYear(),date.getUTCMonth())/1e3;if(floor==time)return time;year=date.getUTCFullYear();var month=date.getUTCMonth();if(month==11){month=0;year=year+1}else{month+=1}return Date.UTC(year,month)/1e3}if(unit.name=="year"){date=new Date(time*1e3);floor=Date.UTC(date.getUTCFullYear(),0)/1e3;if(floor==time)return time;year=date.getUTCFullYear()+1;return Date.UTC(year,0)/1e3}return Math.ceil(time/unit.seconds)*unit.seconds}};Rickshaw.namespace("Rickshaw.Fixtures.Time.Local");Rickshaw.Fixtures.Time.Local=function(){var self=this;this.months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];this.units=[{name:"decade",seconds:86400*365.25*10,formatter:function(d){return parseInt(d.getFullYear()/10,10)*10}},{name:"year",seconds:86400*365.25,formatter:function(d){return d.getFullYear()}},{name:"month",seconds:86400*30.5,formatter:function(d){return self.months[d.getMonth()]}},{name:"week",seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:"day",seconds:86400,formatter:function(d){return d.getDate()}},{name:"6 hour",seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:"hour",seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:"15 minute",seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:"minute",seconds:60,formatter:function(d){return d.getMinutes()}},{name:"15 second",seconds:15,formatter:function(d){return d.getSeconds()+"s"}},{name:"second",seconds:1,formatter:function(d){return d.getSeconds()+"s"}},{name:"decisecond",seconds:1/10,formatter:function(d){return d.getMilliseconds()+"ms"}},{name:"centisecond",seconds:1/100,formatter:function(d){return d.getMilliseconds()+"ms"}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift()};this.formatDate=function(d){return d3.time.format("%b %e")(d)};this.formatTime=function(d){return d.toString().match(/(\d+:\d+):/)[1]};this.ceil=function(time,unit){var date,floor,year;if(unit.name=="day"){var nearFuture=new Date((time+unit.seconds-1)*1e3);var rounded=new Date(0);rounded.setMilliseconds(0);rounded.setSeconds(0);rounded.setMinutes(0);rounded.setHours(0);rounded.setDate(nearFuture.getDate());rounded.setMonth(nearFuture.getMonth());rounded.setFullYear(nearFuture.getFullYear());return rounded.getTime()/1e3}if(unit.name=="month"){date=new Date(time*1e3);floor=new Date(date.getFullYear(),date.getMonth()).getTime()/1e3;if(floor==time)return time;year=date.getFullYear();var month=date.getMonth();if(month==11){month=0;year=year+1}else{month+=1}return new Date(year,month).getTime()/1e3}if(unit.name=="year"){date=new Date(time*1e3);floor=new Date(date.getUTCFullYear(),0).getTime()/1e3;if(floor==time)return time;year=date.getFullYear()+1;return new Date(year,0).getTime()/1e3}return Math.ceil(time/unit.seconds)*unit.seconds}};Rickshaw.namespace("Rickshaw.Fixtures.Number");Rickshaw.Fixtures.Number.formatKMBT=function(y){var abs_y=Math.abs(y);if(abs_y>=1e12){return y/1e12+"T"}else if(abs_y>=1e9){return y/1e9+"B"}else if(abs_y>=1e6){return y/1e6+"M"}else if(abs_y>=1e3){return y/1e3+"K"}else if(abs_y<1&&y>0){return y.toFixed(2)}else if(abs_y===0){return""}else{return y}};Rickshaw.Fixtures.Number.formatBase1024KMGTP=function(y){var abs_y=Math.abs(y);if(abs_y>=0x4000000000000){return y/0x4000000000000+"P"}else if(abs_y>=1099511627776){return y/1099511627776+"T"}else if(abs_y>=1073741824){return y/1073741824+"G"}else if(abs_y>=1048576){return y/1048576+"M"}else if(abs_y>=1024){return y/1024+"K"}else if(abs_y<1&&y>0){return y.toFixed(2)}else if(abs_y===0){return""}else{return y}};Rickshaw.namespace("Rickshaw.Color.Palette");Rickshaw.Color.Palette=function(args){var color=new Rickshaw.Fixtures.Color;args=args||{};this.schemes={};this.scheme=color.schemes[args.scheme]||args.scheme||color.schemes.colorwheel;this.runningIndex=0;this.generatorIndex=0;if(args.interpolatedStopCount){var schemeCount=this.scheme.length-1;var i,j,scheme=[];for(i=0;iself.graph.x.range()[1]){if(annotation.element){annotation.line.classList.add("offscreen");annotation.element.style.display="none"}annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.add("offscreen")});return}if(!annotation.element){var element=annotation.element=document.createElement("div");element.classList.add("annotation");this.elements.timeline.appendChild(element);element.addEventListener("click",function(e){element.classList.toggle("active");annotation.line.classList.toggle("active");annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.toggle("active")})},false)}annotation.element.style.left=left+"px";annotation.element.style.display="block";annotation.boxes.forEach(function(box){var element=box.element;if(!element){element=box.element=document.createElement("div");element.classList.add("content");element.innerHTML=box.content;annotation.element.appendChild(element);annotation.line=document.createElement("div");annotation.line.classList.add("annotation_line");self.graph.element.appendChild(annotation.line);if(box.end){box.rangeElement=document.createElement("div");box.rangeElement.classList.add("annotation_range");self.graph.element.appendChild(box.rangeElement)}}if(box.end){var annotationRangeStart=left;var annotationRangeEnd=Math.min(self.graph.x(box.end),self.graph.x.range()[1]);if(annotationRangeStart>annotationRangeEnd){annotationRangeEnd=left;annotationRangeStart=Math.max(self.graph.x(box.end),self.graph.x.range()[0])}var annotationRangeWidth=annotationRangeEnd-annotationRangeStart;box.rangeElement.style.left=annotationRangeStart+"px";box.rangeElement.style.width=annotationRangeWidth+"px";box.rangeElement.classList.remove("offscreen")}annotation.line.classList.remove("offscreen");annotation.line.style.left=left+"px"})},this)};this.graph.onUpdate(function(){self.update()})};Rickshaw.namespace("Rickshaw.Graph.Axis.Time");Rickshaw.Graph.Axis.Time=function(args){var self=this;this.graph=args.graph;this.elements=[];this.ticksTreatment=args.ticksTreatment||"plain";this.fixedTimeUnit=args.timeUnit;var time=args.timeFixture||new Rickshaw.Fixtures.Time;this.appropriateTimeUnit=function(){var unit;var units=time.units;var domain=this.graph.x.domain();var rangeSeconds=domain[1]-domain[0];units.forEach(function(u){if(Math.floor(rangeSeconds/u.seconds)>=2){unit=unit||u}});return unit||time.units[time.units.length-1]};this.tickOffsets=function(){var domain=this.graph.x.domain();var unit=this.fixedTimeUnit||this.appropriateTimeUnit();var count=Math.ceil((domain[1]-domain[0])/unit.seconds);var runningTick=domain[0];var offsets=[];for(var i=0;iself.graph.x.range()[1])return;var element=document.createElement("div");element.style.left=self.graph.x(o.value)+"px";element.classList.add("x_tick");element.classList.add(self.ticksTreatment);var title=document.createElement("div");title.classList.add("title");title.innerHTML=o.unit.formatter(new Date(o.value*1e3));element.appendChild(title);self.graph.element.appendChild(element);self.elements.push(element)})};this.graph.onUpdate(function(){self.render()})};Rickshaw.namespace("Rickshaw.Graph.Axis.X");Rickshaw.Graph.Axis.X=function(args){var self=this;var berthRate=.1;this.initialize=function(args){this.graph=args.graph;this.orientation=args.orientation||"top";this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||"plain";if(args.element){this.element=args.element;this._discoverSize(args.element,args);this.vis=d3.select(args.element).append("svg:svg").attr("height",this.height).attr("width",this.width).attr("class","rickshaw_graph x_axis_d3");this.element=this.vis[0][0];this.element.style.position="relative";this.setSize({width:args.width,height:args.height})}else{this.vis=this.graph.vis}this.graph.onUpdate(function(){self.render()})};this.setSize=function(args){args=args||{};if(!this.element)return;this._discoverSize(this.element.parentNode,args);this.vis.attr("height",this.height).attr("width",this.width*(1+berthRate));var berth=Math.floor(this.width*berthRate/2);this.element.style.left=-1*berth+"px"};this.render=function(){if(this._renderWidth!==undefined&&this.graph.width!==this._renderWidth)this.setSize({auto:true});var axis=d3.svg.axis().scale(this.graph.x).orient(this.orientation);axis.tickFormat(args.tickFormat||function(x){return x});if(this.tickValues)axis.tickValues(this.tickValues);this.ticks=this.staticTicks||Math.floor(this.graph.width/this.pixelsPerTick);var berth=Math.floor(this.width*berthRate/2)||0;var transform;if(this.orientation=="top"){var yOffset=this.height||this.graph.height;transform="translate("+berth+","+yOffset+")"}else{transform="translate("+berth+", 0)"}if(this.element){this.vis.selectAll("*").remove()}this.vis.append("svg:g").attr("class",["x_ticks_d3",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));var gridSize=(this.orientation=="bottom"?1:-1)*this.graph.height;this.graph.vis.append("svg:g").attr("class","x_grid_d3").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize)).selectAll("text").each(function(){this.parentNode.setAttribute("data-x-value",this.textContent)});this._renderHeight=this.graph.height};this._discoverSize=function(element,args){if(typeof window!=="undefined"){var style=window.getComputedStyle(element,null);var elementHeight=parseInt(style.getPropertyValue("height"),10);if(!args.auto){var elementWidth=parseInt(style.getPropertyValue("width"),10)}}this.width=(args.width||elementWidth||this.graph.width)*(1+berthRate);this.height=args.height||elementHeight||40};this.initialize(args)};Rickshaw.namespace("Rickshaw.Graph.Axis.Y");Rickshaw.Graph.Axis.Y=Rickshaw.Class.create({initialize:function(args){this.graph=args.graph;this.orientation=args.orientation||"right";this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||"plain";this.tickFormat=args.tickFormat||function(y){return y};this.berthRate=.1;if(args.element){this.element=args.element;this.vis=d3.select(args.element).append("svg:svg").attr("class","rickshaw_graph y_axis");this.element=this.vis[0][0];this.element.style.position="relative";this.setSize({width:args.width,height:args.height})}else{this.vis=this.graph.vis}var self=this;this.graph.onUpdate(function(){self.render()})},setSize:function(args){args=args||{};if(!this.element)return;if(typeof window!=="undefined"){var style=window.getComputedStyle(this.element.parentNode,null);var elementWidth=parseInt(style.getPropertyValue("width"),10);if(!args.auto){var elementHeight=parseInt(style.getPropertyValue("height"),10)}}this.width=args.width||elementWidth||this.graph.width*this.berthRate;this.height=args.height||elementHeight||this.graph.height;this.vis.attr("width",this.width).attr("height",this.height*(1+this.berthRate));var berth=this.height*this.berthRate;if(this.orientation=="left"){this.element.style.top=-1*berth+"px"}},render:function(){if(this._renderHeight!==undefined&&this.graph.height!==this._renderHeight)this.setSize({auto:true});this.ticks=this.staticTicks||Math.floor(this.graph.height/this.pixelsPerTick);var axis=this._drawAxis(this.graph.y);this._drawGrid(axis);this._renderHeight=this.graph.height},_drawAxis:function(scale){var axis=d3.svg.axis().scale(scale).orient(this.orientation);axis.tickFormat(this.tickFormat);if(this.tickValues)axis.tickValues(this.tickValues);if(this.orientation=="left"){var berth=this.height*this.berthRate;var transform="translate("+this.width+", "+berth+")"}if(this.element){this.vis.selectAll("*").remove()}this.vis.append("svg:g").attr("class",["y_ticks",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));return axis},_drawGrid:function(axis){var gridSize=(this.orientation=="right"?1:-1)*this.graph.width;this.graph.vis.append("svg:g").attr("class","y_grid").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize)).selectAll("text").each(function(){this.parentNode.setAttribute("data-y-value",this.textContent) +})}});Rickshaw.namespace("Rickshaw.Graph.Axis.Y.Scaled");Rickshaw.Graph.Axis.Y.Scaled=Rickshaw.Class.create(Rickshaw.Graph.Axis.Y,{initialize:function($super,args){if(typeof args.scale==="undefined"){throw new Error("Scaled requires scale")}this.scale=args.scale;if(typeof args.grid==="undefined"){this.grid=true}else{this.grid=args.grid}$super(args)},_drawAxis:function($super,scale){var domain=this.scale.domain();var renderDomain=this.graph.renderer.domain().y;var extents=[Math.min.apply(Math,domain),Math.max.apply(Math,domain)];var extentMap=d3.scale.linear().domain([0,1]).range(extents);var adjExtents=[extentMap(renderDomain[0]),extentMap(renderDomain[1])];var adjustment=d3.scale.linear().domain(extents).range(adjExtents);var adjustedScale=this.scale.copy().domain(domain.map(adjustment)).range(scale.range());return $super(adjustedScale)},_drawGrid:function($super,axis){if(this.grid){$super(axis)}}});Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Highlight");Rickshaw.Graph.Behavior.Series.Highlight=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;var colorSafe={};var activeLine=null;var disabledColor=args.disabledColor||function(seriesColor){return d3.interpolateRgb(seriesColor,d3.rgb("#d8d8d8"))(.8).toString()};this.addHighlightEvents=function(l){l.element.addEventListener("mouseover",function(e){if(activeLine)return;else activeLine=l;self.legend.lines.forEach(function(line){if(l===line){if(self.graph.renderer.unstack&&(line.series.renderer?line.series.renderer.unstack:true)){var seriesIndex=self.graph.series.indexOf(line.series);line.originalIndex=seriesIndex;var series=self.graph.series.splice(seriesIndex,1)[0];self.graph.series.push(series)}return}colorSafe[line.series.name]=colorSafe[line.series.name]||line.series.color;line.series.color=disabledColor(line.series.color)});self.graph.update()},false);l.element.addEventListener("mouseout",function(e){if(!activeLine)return;else activeLine=null;self.legend.lines.forEach(function(line){if(l===line&&line.hasOwnProperty("originalIndex")){var series=self.graph.series.pop();self.graph.series.splice(line.originalIndex,0,series);delete line.originalIndex}if(colorSafe[line.series.name]){line.series.color=colorSafe[line.series.name]}});self.graph.update()},false)};if(this.legend){this.legend.lines.forEach(function(l){self.addHighlightEvents(l)})}};Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Order");Rickshaw.Graph.Behavior.Series.Order=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;if(typeof window.jQuery=="undefined"){throw"couldn't find jQuery at window.jQuery"}if(typeof window.jQuery.ui=="undefined"){throw"couldn't find jQuery UI at window.jQuery.ui"}jQuery(function(){jQuery(self.legend.list).sortable({containment:"parent",tolerance:"pointer",update:function(event,ui){var series=[];jQuery(self.legend.list).find("li").each(function(index,item){if(!item.series)return;series.push(item.series)});for(var i=self.graph.series.length-1;i>=0;i--){self.graph.series[i]=series.shift()}self.graph.update()}});jQuery(self.legend.list).disableSelection()});this.graph.onUpdate(function(){var h=window.getComputedStyle(self.legend.element).height;self.legend.element.style.height=h})};Rickshaw.namespace("Rickshaw.Graph.Behavior.Series.Toggle");Rickshaw.Graph.Behavior.Series.Toggle=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;this.addAnchor=function(line){var anchor=document.createElement("a");anchor.innerHTML="✔";anchor.classList.add("action");line.element.insertBefore(anchor,line.element.firstChild);anchor.onclick=function(e){if(line.series.disabled){line.series.enable();line.element.classList.remove("disabled")}else{if(this.graph.series.filter(function(s){return!s.disabled}).length<=1)return;line.series.disable();line.element.classList.add("disabled")}self.graph.update()}.bind(this);var label=line.element.getElementsByTagName("span")[0];label.onclick=function(e){var disableAllOtherLines=line.series.disabled;if(!disableAllOtherLines){for(var i=0;idomainX){dataIndex=Math.abs(domainX-data[i].x)0){alignables.forEach(function(el){el.classList.remove("left");el.classList.add("right")});var rightAlignError=this._calcLayoutError(alignables);if(rightAlignError>leftAlignError){alignables.forEach(function(el){el.classList.remove("right");el.classList.add("left")})}}if(typeof this.onRender=="function"){this.onRender(args)}},_calcLayoutError:function(alignables){var parentRect=this.element.parentNode.getBoundingClientRect();var error=0;var alignRight=alignables.forEach(function(el){var rect=el.getBoundingClientRect();if(!rect.width){return}if(rect.right>parentRect.right){error+=rect.right-parentRect.right}if(rect.left=self.previewWidth){frameAfterDrag[0]-=frameAfterDrag[1]-self.previewWidth;frameAfterDrag[1]=self.previewWidth}}self.graphs.forEach(function(graph){var domainScale=d3.scale.linear().interpolate(d3.interpolateNumber).domain([0,self.previewWidth]).range(graph.dataDomain());var windowAfterDrag=[domainScale(frameAfterDrag[0]),domainScale(frameAfterDrag[1])];self.slideCallbacks.forEach(function(callback){callback(graph,windowAfterDrag[0],windowAfterDrag[1])});if(frameAfterDrag[0]===0){windowAfterDrag[0]=undefined}if(frameAfterDrag[1]===self.previewWidth){windowAfterDrag[1]=undefined}graph.window.xMin=windowAfterDrag[0];graph.window.xMax=windowAfterDrag[1];graph.update()})}function onMousedown(){drag.target=d3.event.target;drag.start=self._getClientXFromEvent(d3.event,drag);self.frameBeforeDrag=self.currentFrame.slice();d3.event.preventDefault?d3.event.preventDefault():d3.event.returnValue=false;d3.select(document).on("mousemove.rickshaw_range_slider_preview",onMousemove);d3.select(document).on("mouseup.rickshaw_range_slider_preview",onMouseup);d3.select(document).on("touchmove.rickshaw_range_slider_preview",onMousemove);d3.select(document).on("touchend.rickshaw_range_slider_preview",onMouseup);d3.select(document).on("touchcancel.rickshaw_range_slider_preview",onMouseup)}function onMousedownLeftHandle(datum,index){drag.left=true;onMousedown()}function onMousedownRightHandle(datum,index){drag.right=true;onMousedown()}function onMousedownMiddleHandle(datum,index){drag.left=true;drag.right=true;drag.rigid=true;onMousedown()}function onMouseup(datum,index){d3.select(document).on("mousemove.rickshaw_range_slider_preview",null);d3.select(document).on("mouseup.rickshaw_range_slider_preview",null);d3.select(document).on("touchmove.rickshaw_range_slider_preview",null);d3.select(document).on("touchend.rickshaw_range_slider_preview",null);d3.select(document).on("touchcancel.rickshaw_range_slider_preview",null);delete self.frameBeforeDrag;drag.left=false;drag.right=false;drag.rigid=false}element.select("rect.left_handle").on("mousedown",onMousedownLeftHandle);element.select("rect.right_handle").on("mousedown",onMousedownRightHandle);element.select("rect.middle_handle").on("mousedown",onMousedownMiddleHandle);element.select("rect.left_handle").on("touchstart",onMousedownLeftHandle);element.select("rect.right_handle").on("touchstart",onMousedownRightHandle);element.select("rect.middle_handle").on("touchstart",onMousedownMiddleHandle)},_getClientXFromEvent:function(event,drag){switch(event.type){case"touchstart":case"touchmove":var touchList=event.changedTouches;var touch=null;for(var touchIndex=0;touchIndexyMax)yMax=y});if(!series.length)return;if(series[0].xxMax)xMax=series[series.length-1].x});xMin-=(xMax-xMin)*this.padding.left;xMax+=(xMax-xMin)*this.padding.right;yMin=this.graph.min==="auto"?yMin:this.graph.min||0;yMax=this.graph.max===undefined?yMax:this.graph.max;if(this.graph.min==="auto"||yMin<0){yMin-=(yMax-yMin)*this.padding.bottom}if(this.graph.max===undefined){yMax+=(yMax-yMin)*this.padding.top}return{x:[xMin,xMax],y:[yMin,yMax]}},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll("*").remove();var data=series.filter(function(s){return!s.disabled}).map(function(s){return s.stack});var pathNodes=vis.selectAll("path.path").data(data).enter().append("svg:path").classed("path",true).attr("d",this.seriesPathFactory());if(this.stroke){var strokeNodes=vis.selectAll("path.stroke").data(data).enter().append("svg:path").classed("stroke",true).attr("d",this.seriesStrokeFactory())}var i=0;series.forEach(function(series){if(series.disabled)return;series.path=pathNodes[0][i];if(this.stroke)series.stroke=strokeNodes[0][i];this._styleSeries(series);i++},this)},_styleSeries:function(series){var fill=this.fill?series.color:"none";var stroke=this.stroke?series.color:"none";series.path.setAttribute("fill",fill);series.path.setAttribute("stroke",stroke);series.path.setAttribute("stroke-width",this.strokeWidth);if(series.className){d3.select(series.path).classed(series.className,true)}if(series.className&&this.stroke){d3.select(series.stroke).classed(series.className,true)}},configure:function(args){args=args||{};Rickshaw.keys(this.defaults()).forEach(function(key){if(!args.hasOwnProperty(key)){this[key]=this[key]||this.graph[key]||this.defaults()[key];return}if(typeof this.defaults()[key]=="object"){Rickshaw.keys(this.defaults()[key]).forEach(function(k){this[key][k]=args[key][k]!==undefined?args[key][k]:this[key][k]!==undefined?this[key][k]:this.defaults()[key][k]},this)}else{this[key]=args[key]!==undefined?args[key]:this[key]!==undefined?this[key]:this.graph[key]!==undefined?this.graph[key]:this.defaults()[key]}},this)},setStrokeWidth:function(strokeWidth){if(strokeWidth!==undefined){this.strokeWidth=strokeWidth}},setTension:function(tension){if(tension!==undefined){this.tension=tension}}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Line");Rickshaw.Graph.Renderer.Line=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"line",defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:false,stroke:true})},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.line().x(function(d){return graph.x(d.x)}).y(function(d){return graph.y(d.y)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Stack");Rickshaw.Graph.Renderer.Stack=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"stack",defaults:function($super){return Rickshaw.extend($super(),{fill:true,stroke:false,unstack:false})},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.area().x(function(d){return graph.x(d.x)}).y0(function(d){return graph.y(d.y0)}).y1(function(d){return graph.y(d.y+d.y0)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory}});Rickshaw.namespace("Rickshaw.Graph.Renderer.Bar");Rickshaw.Graph.Renderer.Bar=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:"bar",defaults:function($super){var defaults=Rickshaw.extend($super(),{gapSize:.05,unstack:false});delete defaults.tension;return defaults},initialize:function($super,args){args=args||{};this.gapSize=args.gapSize||this.gapSize;$super(args)},domain:function($super){var domain=$super();var frequentInterval=this._frequentInterval(this.graph.stackedData.slice(-1).shift());domain.x[1]+=Number(frequentInterval.magnitude);return domain},barWidth:function(series){var frequentInterval=this._frequentInterval(series.stack);var barWidth=this.graph.x.magnitude(frequentInterval.magnitude)*(1-this.gapSize);return barWidth},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll("*").remove();var barWidth=this.barWidth(series.active()[0]);var barXOffset=0;var activeSeriesCount=series.filter(function(s){return!s.disabled}).length;var seriesBarWidth=this.unstack?barWidth/activeSeriesCount:barWidth;var transform=function(d){var matrix=[1,0,0,d.y<0?-1:1,0,d.y<0?graph.y.magnitude(Math.abs(d.y))*2:0];return"matrix("+matrix.join(",")+")"};series.forEach(function(series){if(series.disabled)return;var barWidth=this.barWidth(series);var nodes=vis.selectAll("path").data(series.stack.filter(function(d){return d.y!==null})).enter().append("svg:rect").attr("x",function(d){return graph.x(d.x)+barXOffset}).attr("y",function(d){return graph.y(d.y0+Math.abs(d.y))*(d.y<0?-1:1)}).attr("width",seriesBarWidth).attr("height",function(d){return graph.y.magnitude(Math.abs(d.y))}).attr("transform",transform);Array.prototype.forEach.call(nodes[0],function(n){n.setAttribute("fill",series.color)});if(this.unstack)barXOffset+=seriesBarWidth},this)},_frequentInterval:function(data){var intervalCounts={};for(var i=0;i0){this[0].data.forEach(function(plot){item.data.push({x:plot.x,y:0})})}else if(item.data.length===0){item.data.push({x:this.timeBase-(this.timeInterval||0),y:0})}this.push(item);if(this.legend){this.legend.addLine(this.itemByName(item.name))}},addData:function(data,x){var index=this.getIndex();Rickshaw.keys(data).forEach(function(name){if(!this.itemByName(name)){this.addItem({name:name})}},this);this.forEach(function(item){item.data.push({x:x||(index*this.timeInterval||1)+this.timeBase,y:data[item.name]||0})},this)},getIndex:function(){return this[0]&&this[0].data&&this[0].data.length?this[0].data.length:0},itemByName:function(name){for(var i=0;i1;i--){this.currentSize+=1;this.currentIndex+=1;this.forEach(function(item){item.data.unshift({x:((i-1)*this.timeInterval||1)+this.timeBase,y:0,i:i})},this)}}},addData:function($super,data,x){$super(data,x);this.currentSize+=1;this.currentIndex+=1;if(this.maxDataPoints!==undefined){while(this.currentSize>this.maxDataPoints){this.dropData()}}},dropData:function(){this.forEach(function(item){item.data.splice(0,1)});this.currentSize-=1},getIndex:function(){return this.currentIndex}});return Rickshaw}); \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/socket.io.min.js b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/socket.io.min.js new file mode 100644 index 00000000..7e870c98 --- /dev/null +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.__deviceType__.realtime.analytics-view/public/js/socket.io.min.js @@ -0,0 +1,2 @@ +/*! Socket.IO.min.js build:0.9.16, production. Copyright(c) 2011 LearnBoost MIT Licensed */ +var io="undefined"==typeof module?{}:module.exports;(function(){(function(a,b){var c=a;c.version="0.9.16",c.protocol=1,c.transports=[],c.j=[],c.sockets={},c.connect=function(a,d){var e=c.util.parseUri(a),f,g;b&&b.location&&(e.protocol=e.protocol||b.location.protocol.slice(0,-1),e.host=e.host||(b.document?b.document.domain:b.location.hostname),e.port=e.port||b.location.port),f=c.util.uniqueUri(e);var h={host:e.host,secure:"https"==e.protocol,port:e.port||("https"==e.protocol?443:80),query:e.query||""};c.util.merge(h,d);if(h["force new connection"]||!c.sockets[f])g=new c.Socket(h);return!h["force new connection"]&&g&&(c.sockets[f]=g),g=g||c.sockets[f],g.of(e.path.length>1?e.path:"")}})("object"==typeof module?module.exports:this.io={},this),function(a,b){var c=a.util={},d=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];c.parseUri=function(a){var b=d.exec(a||""),c={},f=14;while(f--)c[e[f]]=b[f]||"";return c},c.uniqueUri=function(a){var c=a.protocol,d=a.host,e=a.port;return"document"in b?(d=d||document.domain,e=e||(c=="https"&&document.location.protocol!=="https:"?443:document.location.port)):(d=d||"localhost",!e&&c=="https"&&(e=443)),(c||"http")+"://"+d+":"+(e||80)},c.query=function(a,b){var d=c.chunkQuery(a||""),e=[];c.merge(d,c.chunkQuery(b||""));for(var f in d)d.hasOwnProperty(f)&&e.push(f+"="+d[f]);return e.length?"?"+e.join("&"):""},c.chunkQuery=function(a){var b={},c=a.split("&"),d=0,e=c.length,f;for(;db.length?a:b,f=a.length>b.length?b:a;for(var g=0,h=f.length;g0&&a.splice(0,1)[0]!=c.transport.name);a.length?h(a):c.publish("connect_failed")}}},c.options["connect timeout"]))})}c.sessionid=d,c.closeTimeout=f*1e3,c.heartbeatTimeout=e*1e3,c.transports||(c.transports=c.origTransports=g?b.util.intersect(g.split(","),c.options.transports):c.options.transports),c.setHeartbeatTimeout(),h(c.transports),c.once("connect",function(){clearTimeout(c.connectTimeoutTimer),a&&typeof a=="function"&&a()})}),this},d.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);if(this.transport&&!this.transport.heartbeats())return;var a=this;this.heartbeatTimeoutTimer=setTimeout(function(){a.transport.onClose()},this.heartbeatTimeout)},d.prototype.packet=function(a){return this.connected&&!this.doBuffer?this.transport.packet(a):this.buffer.push(a),this},d.prototype.setBuffer=function(a){this.doBuffer=a,!a&&this.connected&&this.buffer.length&&(this.options.manualFlush||this.flushBuffer())},d.prototype.flushBuffer=function(){this.transport.payload(this.buffer),this.buffer=[]},d.prototype.disconnect=function(){if(this.connected||this.connecting)this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted");return this},d.prototype.disconnectSync=function(){var a=b.util.request(),c=["http"+(this.options.secure?"s":"")+":/",this.options.host+":"+this.options.port,this.options.resource,b.protocol,"",this.sessionid].join("/")+"/?disconnect=1";a.open("GET",c,!1),a.send(null),this.onDisconnect("booted")},d.prototype.isXDomain=function(){var a=c.location.port||("https:"==c.location.protocol?443:80);return this.options.host!==c.location.hostname||this.options.port!=a},d.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},d.prototype.onOpen=function(){this.open=!0},d.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},d.prototype.onPacket=function(a){this.of(a.endpoint).onPacket(a)},d.prototype.onError=function(a){a&&a.advice&&a.advice==="reconnect"&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",a&&a.reason?a.reason:a)},d.prototype.onDisconnect=function(a){var b=this.connected,c=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1;if(b||c)this.transport.close(),this.transport.clearTimeouts(),b&&(this.publish("disconnect",a),"booted"!=a&&this.options.reconnect&&!this.reconnecting&&this.reconnect())},d.prototype.reconnect=function(){function e(){if(a.connected){for(var b in a.namespaces)a.namespaces.hasOwnProperty(b)&&""!==b&&a.namespaces[b].packet({type:"connect"});a.publish("reconnect",a.transport.name,a.reconnectionAttempts)}clearTimeout(a.reconnectionTimer),a.removeListener("connect_failed",f),a.removeListener("connect",f),a.reconnecting=!1,delete a.reconnectionAttempts,delete a.reconnectionDelay,delete a.reconnectionTimer,delete a.redoTransports,a.options["try multiple transports"]=c}function f(){if(!a.reconnecting)return;if(a.connected)return e();if(a.connecting&&a.reconnecting)return a.reconnectionTimer=setTimeout(f,1e3);a.reconnectionAttempts++>=b?a.redoTransports?(a.publish("reconnect_failed"),e()):(a.on("connect_failed",f),a.options["try multiple transports"]=!0,a.transports=a.origTransports,a.transport=a.getTransport(),a.redoTransports=!0,a.connect()):(a.reconnectionDelay=10:!1},c.xdomainCheck=function(){return!0},typeof window!="undefined"&&(WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=!0),b.transports.push("flashsocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window)var swfobject=function(){function A(){if(t)return;try{var a=i.getElementsByTagName("body")[0].appendChild(Q("span"));a.parentNode.removeChild(a)}catch(b){return}t=!0;var c=l.length;for(var d=0;d0)for(var c=0;c0){var g=P(d);if(g)if(S(m[c].swfVersion)&&!(y.wk&&y.wk<312))U(d,!0),e&&(f.success=!0,f.ref=G(d),e(f));else if(m[c].expressInstall&&H()){var h={};h.data=m[c].expressInstall,h.width=g.getAttribute("width")||"0",h.height=g.getAttribute("height")||"0",g.getAttribute("class")&&(h.styleclass=g.getAttribute("class")),g.getAttribute("align")&&(h.align=g.getAttribute("align"));var i={},j=g.getElementsByTagName("param"),k=j.length;for(var l=0;l');h.outerHTML='"+k+"",n[n.length]=c.id,g=P(c.id)}else{var m=Q(b);m.setAttribute("type",e);for(var o in c)c[o]!=Object.prototype[o]&&(o.toLowerCase()=="styleclass"?m.setAttribute("class",c[o]):o.toLowerCase()!="classid"&&m.setAttribute(o,c[o]));for(var p in d)d[p]!=Object.prototype[p]&&p.toLowerCase()!="movie"&&M(m,p,d[p]);h.parentNode.replaceChild(m,h),g=m}}return g}function M(a,b,c){var d=Q("param");d.setAttribute("name",b),d.setAttribute("value",c),a.appendChild(d)}function N(a){var b=P(a);b&&b.nodeName=="OBJECT"&&(y.ie&&y.win?(b.style.display="none",function(){b.readyState==4?O(a):setTimeout(arguments.callee,10)}()):b.parentNode.removeChild(b))}function O(a){var b=P(a);if(b){for(var c in b)typeof b[c]=="function"&&(b[c]=null);b.parentNode.removeChild(b)}}function P(a){var b=null;try{b=i.getElementById(a)}catch(c){}return b}function Q(a){return i.createElement(a)}function R(a,b,c){a.attachEvent(b,c),o[o.length]=[a,b,c]}function S(a){var b=y.pv,c=a.split(".");return c[0]=parseInt(c[0],10),c[1]=parseInt(c[1],10)||0,c[2]=parseInt(c[2],10)||0,b[0]>c[0]||b[0]==c[0]&&b[1]>c[1]||b[0]==c[0]&&b[1]==c[1]&&b[2]>=c[2]?!0:!1}function T(c,d,e,f){if(y.ie&&y.mac)return;var g=i.getElementsByTagName("head")[0];if(!g)return;var h=e&&typeof e=="string"?e:"screen";f&&(v=null,w=null);if(!v||w!=h){var j=Q("style");j.setAttribute("type","text/css"),j.setAttribute("media",h),v=g.appendChild(j),y.ie&&y.win&&typeof i.styleSheets!=a&&i.styleSheets.length>0&&(v=i.styleSheets[i.styleSheets.length-1]),w=h}y.ie&&y.win?v&&typeof v.addRule==b&&v.addRule(c,d):v&&typeof i.createTextNode!=a&&v.appendChild(i.createTextNode(c+" {"+d+"}"))}function U(a,b){if(!x)return;var c=b?"visible":"hidden";t&&P(a)?P(a).style.visibility=c:T("#"+a,"visibility:"+c)}function V(b){var c=/[\\\"<>\.;]/,d=c.exec(b)!=null;return d&&typeof encodeURIComponent!=a?encodeURIComponent(b):b}var a="undefined",b="object",c="Shockwave Flash",d="ShockwaveFlash.ShockwaveFlash",e="application/x-shockwave-flash",f="SWFObjectExprInst",g="onreadystatechange",h=window,i=document,j=navigator,k=!1,l=[D],m=[],n=[],o=[],p,q,r,s,t=!1,u=!1,v,w,x=!0,y=function(){var f=typeof i.getElementById!=a&&typeof i.getElementsByTagName!=a&&typeof i.createElement!=a,g=j.userAgent.toLowerCase(),l=j.platform.toLowerCase(),m=l?/win/.test(l):/win/.test(g),n=l?/mac/.test(l):/mac/.test(g),o=/webkit/.test(g)?parseFloat(g.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,p=!1,q=[0,0,0],r=null;if(typeof j.plugins!=a&&typeof j.plugins[c]==b)r=j.plugins[c].description,r&&(typeof j.mimeTypes==a||!j.mimeTypes[e]||!!j.mimeTypes[e].enabledPlugin)&&(k=!0,p=!1,r=r.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),q[0]=parseInt(r.replace(/^(.*)\..*$/,"$1"),10),q[1]=parseInt(r.replace(/^.*\.(.*)\s.*$/,"$1"),10),q[2]=/[a-zA-Z]/.test(r)?parseInt(r.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0);else if(typeof h[["Active"].concat("Object").join("X")]!=a)try{var s=new(window[["Active"].concat("Object").join("X")])(d);s&&(r=s.GetVariable("$version"),r&&(p=!0,r=r.split(" ")[1].split(","),q=[parseInt(r[0],10),parseInt(r[1],10),parseInt(r[2],10)]))}catch(t){}return{w3:f,pv:q,wk:o,ie:p,win:m,mac:n}}(),z=function(){if(!y.w3)return;(typeof i.readyState!=a&&i.readyState=="complete"||typeof i.readyState==a&&(i.getElementsByTagName("body")[0]||i.body))&&A(),t||(typeof i.addEventListener!=a&&i.addEventListener("DOMContentLoaded",A,!1),y.ie&&y.win&&(i.attachEvent(g,function(){i.readyState=="complete"&&(i.detachEvent(g,arguments.callee),A())}),h==top&&function(){if(t)return;try{i.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,0);return}A()}()),y.wk&&function(){if(t)return;if(!/loaded|complete/.test(i.readyState)){setTimeout(arguments.callee,0);return}A()}(),C(A))}(),W=function(){y.ie&&y.win&&window.attachEvent("onunload",function(){var a=o.length;for(var b=0;b= 10.0.0 is required.");return}location.protocol=="file:"&&a.error("WARNING: web-socket-js doesn't work in file:///... URL unless you set Flash Security Settings properly. Open the page via Web server i.e. http://..."),WebSocket=function(a,b,c,d,e){var f=this;f.__id=WebSocket.__nextId++,WebSocket.__instances[f.__id]=f,f.readyState=WebSocket.CONNECTING,f.bufferedAmount=0,f.__events={},b?typeof b=="string"&&(b=[b]):b=[],setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(f.__id,a,b,c||null,d||0,e||null)})},0)},WebSocket.prototype.send=function(a){if(this.readyState==WebSocket.CONNECTING)throw"INVALID_STATE_ERR: Web Socket connection has not been established";var b=WebSocket.__flash.send(this.__id,encodeURIComponent(a));return b<0?!0:(this.bufferedAmount+=b,!1)},WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING)return;this.readyState=WebSocket.CLOSING,WebSocket.__flash.close(this.__id)},WebSocket.prototype.addEventListener=function(a,b,c){a in this.__events||(this.__events[a]=[]),this.__events[a].push(b)},WebSocket.prototype.removeEventListener=function(a,b,c){if(!(a in this.__events))return;var d=this.__events[a];for(var e=d.length-1;e>=0;--e)if(d[e]===b){d.splice(e,1);break}},WebSocket.prototype.dispatchEvent=function(a){var b=this.__events[a.type]||[];for(var c=0;c"),this.doc.close(),this.doc.parentWindow.s=this;var a=this.doc.createElement("div");a.className="socketio",this.doc.body.appendChild(a),this.iframe=this.doc.createElement("iframe"),a.appendChild(this.iframe);var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date));this.iframe.src=this.prepareUrl()+d,b.util.on(window,"unload",function(){c.destroy()})},c.prototype._=function(a,b){a=a.replace(/\\\//g,"/"),this.onData(a);try{var c=b.getElementsByTagName("script")[0];c.parentNode.removeChild(c)}catch(d){}},c.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(a){}this.doc=null,this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,CollectGarbage()}},c.prototype.close=function(){return this.destroy(),b.Transport.XHR.prototype.close.call(this)},c.check=function(a){if(typeof window!="undefined"&&["Active"].concat("Object").join("X")in window)try{var c=new(window[["Active"].concat("Object").join("X")])("htmlfile");return c&&b.Transport.XHR.check(a)}catch(d){}return!1},c.xdomainCheck=function(){return!1},b.transports.push("htmlfile")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(){b.Transport.XHR.apply(this,arguments)}function e(){}a["xhr-polling"]=d,b.util.inherit(d,b.Transport.XHR),b.util.merge(d,b.Transport.XHR),d.prototype.name="xhr-polling",d.prototype.heartbeats=function(){return!1},d.prototype.open=function(){var a=this;return b.Transport.XHR.prototype.open.call(a),!1},d.prototype.get=function(){function b(){this.readyState==4&&(this.onreadystatechange=e,this.status==200?(a.onData(this.responseText),a.get()):a.onClose())}function d(){this.onload=e,this.onerror=e,a.retryCounter=1,a.onData(this.responseText),a.get()}function f(){a.retryCounter++,!a.retryCounter||a.retryCounter>3?a.onClose():a.get()}if(!this.isOpen)return;var a=this;this.xhr=this.request(),c.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=d,this.xhr.onerror=f):this.xhr.onreadystatechange=b,this.xhr.send(null)},d.prototype.onClose=function(){b.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=e;try{this.xhr.abort()}catch(a){}this.xhr=null}},d.prototype.ready=function(a,c){var d=this;b.util.defer(function(){c.call(d)})},b.transports.push("xhr-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b,c){function e(a){b.Transport["xhr-polling"].apply(this,arguments),this.index=b.j.length;var c=this;b.j.push(function(a){c._(a)})}var d=c.document&&"MozAppearance"in c.document.documentElement.style;a["jsonp-polling"]=e,b.util.inherit(e,b.Transport["xhr-polling"]),e.prototype.name="jsonp-polling",e.prototype.post=function(a){function i(){j(),c.socket.setBuffer(!1)}function j(){c.iframe&&c.form.removeChild(c.iframe);try{h=document.createElement('